cli.mjs 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873
  1. import { createRequire as __prettierCreateRequire } from "module";
  2. import { fileURLToPath as __prettierFileUrlToPath } from "url";
  3. import { dirname as __prettierDirname } from "path";
  4. const require = __prettierCreateRequire(import.meta.url);
  5. const __filename = __prettierFileUrlToPath(import.meta.url);
  6. const __dirname = __prettierDirname(__filename);
  7. var __create = Object.create;
  8. var __defProp = Object.defineProperty;
  9. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  10. var __getOwnPropNames = Object.getOwnPropertyNames;
  11. var __getProtoOf = Object.getPrototypeOf;
  12. var __hasOwnProp = Object.prototype.hasOwnProperty;
  13. var __typeError = (msg) => {
  14. throw TypeError(msg);
  15. };
  16. var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  17. get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  18. }) : x)(function(x) {
  19. if (typeof require !== "undefined") return require.apply(this, arguments);
  20. throw Error('Dynamic require of "' + x + '" is not supported');
  21. });
  22. var __commonJS = (cb, mod) => function __require2() {
  23. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  24. };
  25. var __copyProps = (to, from, except, desc) => {
  26. if (from && typeof from === "object" || typeof from === "function") {
  27. for (let key of __getOwnPropNames(from))
  28. if (!__hasOwnProp.call(to, key) && key !== except)
  29. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  30. }
  31. return to;
  32. };
  33. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  34. // If the importer is in node compatibility mode or this is not an ESM
  35. // file that has been converted to a CommonJS file using a Babel-
  36. // compatible transform (i.e. "__esModule" has not been set), then set
  37. // "default" to the CommonJS "module.exports" for node compatibility.
  38. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  39. mod
  40. ));
  41. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  42. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  43. var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  44. var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
  45. // node_modules/dashify/index.js
  46. var require_dashify = __commonJS({
  47. "node_modules/dashify/index.js"(exports, module) {
  48. "use strict";
  49. module.exports = (str, options) => {
  50. if (typeof str !== "string") throw new TypeError("expected a string");
  51. return str.trim().replace(/([a-z])([A-Z])/g, "$1-$2").replace(/\W/g, (m) => /[À-ž]/.test(m) ? m : "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, (m) => options && options.condense ? "-" : m).toLowerCase();
  52. };
  53. }
  54. });
  55. // node_modules/minimist/index.js
  56. var require_minimist = __commonJS({
  57. "node_modules/minimist/index.js"(exports, module) {
  58. "use strict";
  59. function hasKey(obj, keys2) {
  60. var o = obj;
  61. keys2.slice(0, -1).forEach(function(key2) {
  62. o = o[key2] || {};
  63. });
  64. var key = keys2[keys2.length - 1];
  65. return key in o;
  66. }
  67. function isNumber(x) {
  68. if (typeof x === "number") {
  69. return true;
  70. }
  71. if (/^0x[0-9a-f]+$/i.test(x)) {
  72. return true;
  73. }
  74. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  75. }
  76. function isConstructorOrProto(obj, key) {
  77. return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
  78. }
  79. module.exports = function(args, opts) {
  80. if (!opts) {
  81. opts = {};
  82. }
  83. var flags = {
  84. bools: {},
  85. strings: {},
  86. unknownFn: null
  87. };
  88. if (typeof opts.unknown === "function") {
  89. flags.unknownFn = opts.unknown;
  90. }
  91. if (typeof opts.boolean === "boolean" && opts.boolean) {
  92. flags.allBools = true;
  93. } else {
  94. [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
  95. flags.bools[key2] = true;
  96. });
  97. }
  98. var aliases = {};
  99. function aliasIsBoolean(key2) {
  100. return aliases[key2].some(function(x) {
  101. return flags.bools[x];
  102. });
  103. }
  104. Object.keys(opts.alias || {}).forEach(function(key2) {
  105. aliases[key2] = [].concat(opts.alias[key2]);
  106. aliases[key2].forEach(function(x) {
  107. aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
  108. return x !== y;
  109. }));
  110. });
  111. });
  112. [].concat(opts.string).filter(Boolean).forEach(function(key2) {
  113. flags.strings[key2] = true;
  114. if (aliases[key2]) {
  115. [].concat(aliases[key2]).forEach(function(k) {
  116. flags.strings[k] = true;
  117. });
  118. }
  119. });
  120. var defaults = opts.default || {};
  121. var argv = { _: [] };
  122. function argDefined(key2, arg2) {
  123. return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
  124. }
  125. function setKey(obj, keys2, value2) {
  126. var o = obj;
  127. for (var i2 = 0; i2 < keys2.length - 1; i2++) {
  128. var key2 = keys2[i2];
  129. if (isConstructorOrProto(o, key2)) {
  130. return;
  131. }
  132. if (o[key2] === void 0) {
  133. o[key2] = {};
  134. }
  135. if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) {
  136. o[key2] = {};
  137. }
  138. if (o[key2] === Array.prototype) {
  139. o[key2] = [];
  140. }
  141. o = o[key2];
  142. }
  143. var lastKey = keys2[keys2.length - 1];
  144. if (isConstructorOrProto(o, lastKey)) {
  145. return;
  146. }
  147. if (o === Object.prototype || o === Number.prototype || o === String.prototype) {
  148. o = {};
  149. }
  150. if (o === Array.prototype) {
  151. o = [];
  152. }
  153. if (o[lastKey] === void 0 || flags.bools[lastKey] || typeof o[lastKey] === "boolean") {
  154. o[lastKey] = value2;
  155. } else if (Array.isArray(o[lastKey])) {
  156. o[lastKey].push(value2);
  157. } else {
  158. o[lastKey] = [o[lastKey], value2];
  159. }
  160. }
  161. function setArg(key2, val, arg2) {
  162. if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
  163. if (flags.unknownFn(arg2) === false) {
  164. return;
  165. }
  166. }
  167. var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val;
  168. setKey(argv, key2.split("."), value2);
  169. (aliases[key2] || []).forEach(function(x) {
  170. setKey(argv, x.split("."), value2);
  171. });
  172. }
  173. Object.keys(flags.bools).forEach(function(key2) {
  174. setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
  175. });
  176. var notFlags = [];
  177. if (args.indexOf("--") !== -1) {
  178. notFlags = args.slice(args.indexOf("--") + 1);
  179. args = args.slice(0, args.indexOf("--"));
  180. }
  181. for (var i = 0; i < args.length; i++) {
  182. var arg = args[i];
  183. var key;
  184. var next;
  185. if (/^--.+=/.test(arg)) {
  186. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  187. key = m[1];
  188. var value = m[2];
  189. if (flags.bools[key]) {
  190. value = value !== "false";
  191. }
  192. setArg(key, value, arg);
  193. } else if (/^--no-.+/.test(arg)) {
  194. key = arg.match(/^--no-(.+)/)[1];
  195. setArg(key, false, arg);
  196. } else if (/^--.+/.test(arg)) {
  197. key = arg.match(/^--(.+)/)[1];
  198. next = args[i + 1];
  199. if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  200. setArg(key, next, arg);
  201. i += 1;
  202. } else if (/^(true|false)$/.test(next)) {
  203. setArg(key, next === "true", arg);
  204. i += 1;
  205. } else {
  206. setArg(key, flags.strings[key] ? "" : true, arg);
  207. }
  208. } else if (/^-[^-]+/.test(arg)) {
  209. var letters = arg.slice(1, -1).split("");
  210. var broken = false;
  211. for (var j = 0; j < letters.length; j++) {
  212. next = arg.slice(j + 2);
  213. if (next === "-") {
  214. setArg(letters[j], next, arg);
  215. continue;
  216. }
  217. if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") {
  218. setArg(letters[j], next.slice(1), arg);
  219. broken = true;
  220. break;
  221. }
  222. if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  223. setArg(letters[j], next, arg);
  224. broken = true;
  225. break;
  226. }
  227. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  228. setArg(letters[j], arg.slice(j + 2), arg);
  229. broken = true;
  230. break;
  231. } else {
  232. setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
  233. }
  234. }
  235. key = arg.slice(-1)[0];
  236. if (!broken && key !== "-") {
  237. if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  238. setArg(key, args[i + 1], arg);
  239. i += 1;
  240. } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
  241. setArg(key, args[i + 1] === "true", arg);
  242. i += 1;
  243. } else {
  244. setArg(key, flags.strings[key] ? "" : true, arg);
  245. }
  246. }
  247. } else {
  248. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  249. argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));
  250. }
  251. if (opts.stopEarly) {
  252. argv._.push.apply(argv._, args.slice(i + 1));
  253. break;
  254. }
  255. }
  256. }
  257. Object.keys(defaults).forEach(function(k) {
  258. if (!hasKey(argv, k.split("."))) {
  259. setKey(argv, k.split("."), defaults[k]);
  260. (aliases[k] || []).forEach(function(x) {
  261. setKey(argv, x.split("."), defaults[k]);
  262. });
  263. }
  264. });
  265. if (opts["--"]) {
  266. argv["--"] = notFlags.slice();
  267. } else {
  268. notFlags.forEach(function(k) {
  269. argv._.push(k);
  270. });
  271. }
  272. return argv;
  273. };
  274. }
  275. });
  276. // node_modules/fast-json-stable-stringify/index.js
  277. var require_fast_json_stable_stringify = __commonJS({
  278. "node_modules/fast-json-stable-stringify/index.js"(exports, module) {
  279. "use strict";
  280. module.exports = function(data, opts) {
  281. if (!opts) opts = {};
  282. if (typeof opts === "function") opts = { cmp: opts };
  283. var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false;
  284. var cmp = opts.cmp && /* @__PURE__ */ function(f) {
  285. return function(node) {
  286. return function(a, b) {
  287. var aobj = { key: a, value: node[a] };
  288. var bobj = { key: b, value: node[b] };
  289. return f(aobj, bobj);
  290. };
  291. };
  292. }(opts.cmp);
  293. var seen = [];
  294. return function stringify5(node) {
  295. if (node && node.toJSON && typeof node.toJSON === "function") {
  296. node = node.toJSON();
  297. }
  298. if (node === void 0) return;
  299. if (typeof node == "number") return isFinite(node) ? "" + node : "null";
  300. if (typeof node !== "object") return JSON.stringify(node);
  301. var i, out;
  302. if (Array.isArray(node)) {
  303. out = "[";
  304. for (i = 0; i < node.length; i++) {
  305. if (i) out += ",";
  306. out += stringify5(node[i]) || "null";
  307. }
  308. return out + "]";
  309. }
  310. if (node === null) return "null";
  311. if (seen.indexOf(node) !== -1) {
  312. if (cycles) return JSON.stringify("__cycle__");
  313. throw new TypeError("Converting circular structure to JSON");
  314. }
  315. var seenIndex = seen.push(node) - 1;
  316. var keys2 = Object.keys(node).sort(cmp && cmp(node));
  317. out = "";
  318. for (i = 0; i < keys2.length; i++) {
  319. var key = keys2[i];
  320. var value = stringify5(node[key]);
  321. if (!value) continue;
  322. if (out) out += ",";
  323. out += JSON.stringify(key) + ":" + value;
  324. }
  325. seen.splice(seenIndex, 1);
  326. return "{" + out + "}";
  327. }(data);
  328. };
  329. }
  330. });
  331. // node_modules/common-path-prefix/index.js
  332. var require_common_path_prefix = __commonJS({
  333. "node_modules/common-path-prefix/index.js"(exports, module) {
  334. "use strict";
  335. var { sep: DEFAULT_SEPARATOR } = __require("path");
  336. var determineSeparator = (paths) => {
  337. for (const path12 of paths) {
  338. const match = /(\/|\\)/.exec(path12);
  339. if (match !== null) return match[0];
  340. }
  341. return DEFAULT_SEPARATOR;
  342. };
  343. module.exports = function commonPathPrefix2(paths, sep = determineSeparator(paths)) {
  344. const [first = "", ...remaining] = paths;
  345. if (first === "" || remaining.length === 0) return "";
  346. const parts = first.split(sep);
  347. let endOfPrefix = parts.length;
  348. for (const path12 of remaining) {
  349. const compare = path12.split(sep);
  350. for (let i = 0; i < endOfPrefix; i++) {
  351. if (compare[i] !== parts[i]) {
  352. endOfPrefix = i;
  353. }
  354. }
  355. if (endOfPrefix === 0) return "";
  356. }
  357. const prefix = parts.slice(0, endOfPrefix).join(sep);
  358. return prefix.endsWith(sep) ? prefix : prefix + sep;
  359. };
  360. }
  361. });
  362. // src/cli/index.js
  363. import * as prettier2 from "../index.mjs";
  364. // scripts/build/shims/at.js
  365. var at = (isOptionalObject, object2, index) => {
  366. if (isOptionalObject && (object2 === void 0 || object2 === null)) {
  367. return;
  368. }
  369. if (Array.isArray(object2) || typeof object2 === "string") {
  370. return object2[index < 0 ? object2.length + index : index];
  371. }
  372. return object2.at(index);
  373. };
  374. var at_default = at;
  375. // src/cli/options/get-context-options.js
  376. var import_dashify = __toESM(require_dashify(), 1);
  377. import { getSupportInfo } from "../index.mjs";
  378. // src/cli/cli-options.evaluate.js
  379. var cli_options_evaluate_default = {
  380. "cache": {
  381. "default": false,
  382. "description": "Only format changed files. Cannot use with --stdin-filepath.",
  383. "type": "boolean"
  384. },
  385. "cacheLocation": {
  386. "description": "Path to the cache file.",
  387. "type": "path"
  388. },
  389. "cacheStrategy": {
  390. "choices": [
  391. {
  392. "description": "Use the file metadata such as timestamps as cache keys",
  393. "value": "metadata"
  394. },
  395. {
  396. "description": "Use the file content as cache keys",
  397. "value": "content"
  398. }
  399. ],
  400. "description": "Strategy for the cache to use for detecting changed files.",
  401. "type": "choice"
  402. },
  403. "check": {
  404. "alias": "c",
  405. "category": "Output",
  406. "description": "Check if the given files are formatted, print a human-friendly summary\nmessage and paths to unformatted files (see also --list-different).",
  407. "type": "boolean"
  408. },
  409. "color": {
  410. "default": true,
  411. "description": "Colorize error messages.",
  412. "oppositeDescription": "Do not colorize error messages.",
  413. "type": "boolean"
  414. },
  415. "config": {
  416. "category": "Config",
  417. "description": "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
  418. "exception": (value) => value === false,
  419. "oppositeDescription": "Do not look for a configuration file.",
  420. "type": "path"
  421. },
  422. "configPrecedence": {
  423. "category": "Config",
  424. "choices": [
  425. {
  426. "description": "CLI options take precedence over config file",
  427. "value": "cli-override"
  428. },
  429. {
  430. "description": "Config file take precedence over CLI options",
  431. "value": "file-override"
  432. },
  433. {
  434. "description": "If a config file is found will evaluate it and ignore other CLI options.\nIf no config file is found CLI options will evaluate as normal.",
  435. "value": "prefer-file"
  436. }
  437. ],
  438. "default": "cli-override",
  439. "description": "Define in which order config files and CLI options should be evaluated.",
  440. "type": "choice"
  441. },
  442. "debugBenchmark": {
  443. "type": "boolean"
  444. },
  445. "debugCheck": {
  446. "type": "boolean"
  447. },
  448. "debugPrintAst": {
  449. "type": "boolean"
  450. },
  451. "debugPrintComments": {
  452. "type": "boolean"
  453. },
  454. "debugPrintDoc": {
  455. "type": "boolean"
  456. },
  457. "debugRepeat": {
  458. "default": 0,
  459. "type": "int"
  460. },
  461. "editorconfig": {
  462. "category": "Config",
  463. "default": true,
  464. "description": "Take .editorconfig into account when parsing configuration.",
  465. "oppositeDescription": "Don't take .editorconfig into account when parsing configuration.",
  466. "type": "boolean"
  467. },
  468. "errorOnUnmatchedPattern": {
  469. "oppositeDescription": "Prevent errors when pattern is unmatched.",
  470. "type": "boolean"
  471. },
  472. "fileInfo": {
  473. "description": "Extract the following info (as JSON) for a given file path. Reported fields:\n* ignored (boolean) - true if file path is filtered by --ignore-path\n* inferredParser (string | null) - name of parser inferred from file path",
  474. "type": "path"
  475. },
  476. "findConfigPath": {
  477. "category": "Config",
  478. "description": "Find and print the path to a configuration file for the given input file.",
  479. "type": "path"
  480. },
  481. "help": {
  482. "alias": "h",
  483. "description": "Show CLI usage, or details about the given flag.\nExample: --help write",
  484. "exception": (value) => value === "",
  485. "type": "flag"
  486. },
  487. "ignorePath": {
  488. "array": true,
  489. "category": "Config",
  490. "default": [
  491. {
  492. "value": [
  493. ".gitignore",
  494. ".prettierignore"
  495. ]
  496. }
  497. ],
  498. "description": "Path to a file with patterns describing files to ignore.\nMultiple values are accepted.",
  499. "type": "path"
  500. },
  501. "ignoreUnknown": {
  502. "alias": "u",
  503. "description": "Ignore unknown files.",
  504. "type": "boolean"
  505. },
  506. "listDifferent": {
  507. "alias": "l",
  508. "category": "Output",
  509. "description": "Print the names of files that are different from Prettier's formatting (see also --check).",
  510. "type": "boolean"
  511. },
  512. "logLevel": {
  513. "choices": [
  514. "silent",
  515. "error",
  516. "warn",
  517. "log",
  518. "debug"
  519. ],
  520. "default": "log",
  521. "description": "What level of logs to report.",
  522. "type": "choice"
  523. },
  524. "supportInfo": {
  525. "description": "Print support information as JSON.",
  526. "type": "boolean"
  527. },
  528. "version": {
  529. "alias": "v",
  530. "description": "Print Prettier version.",
  531. "type": "boolean"
  532. },
  533. "withNodeModules": {
  534. "category": "Config",
  535. "description": "Process files inside 'node_modules' directory.",
  536. "type": "boolean"
  537. },
  538. "write": {
  539. "alias": "w",
  540. "category": "Output",
  541. "description": "Edit files in-place. (Beware!)",
  542. "type": "boolean"
  543. }
  544. };
  545. // src/cli/prettier-internal.js
  546. import { __internal as sharedWithCli } from "../index.mjs";
  547. var {
  548. errors,
  549. optionCategories,
  550. createIsIgnoredFunction,
  551. formatOptionsHiddenDefaults,
  552. normalizeOptions,
  553. getSupportInfoWithoutPlugins,
  554. normalizeOptionSettings,
  555. vnopts,
  556. fastGlob,
  557. createTwoFilesPatch,
  558. mockable
  559. } = sharedWithCli;
  560. // src/cli/options/get-context-options.js
  561. var detailedCliOptions = normalizeOptionSettings(cli_options_evaluate_default).map(
  562. (option) => normalizeDetailedOption(option)
  563. );
  564. function apiOptionToCliOption(apiOption) {
  565. const cliOption = {
  566. ...apiOption,
  567. description: apiOption.cliDescription ?? apiOption.description,
  568. category: apiOption.cliCategory ?? optionCategories.CATEGORY_FORMAT,
  569. forwardToApi: apiOption.name
  570. };
  571. if (apiOption.deprecated) {
  572. delete cliOption.forwardToApi;
  573. delete cliOption.description;
  574. delete cliOption.oppositeDescription;
  575. cliOption.deprecated = true;
  576. }
  577. return normalizeDetailedOption(cliOption);
  578. }
  579. function normalizeDetailedOption(option) {
  580. var _a;
  581. return {
  582. category: optionCategories.CATEGORY_OTHER,
  583. ...option,
  584. name: option.cliName ?? (0, import_dashify.default)(option.name),
  585. choices: (_a = option.choices) == null ? void 0 : _a.map((choice) => {
  586. const newChoice = {
  587. description: "",
  588. deprecated: false,
  589. ...typeof choice === "object" ? choice : { value: choice }
  590. };
  591. if (newChoice.value === true) {
  592. newChoice.value = "";
  593. }
  594. return newChoice;
  595. })
  596. };
  597. }
  598. function supportInfoToContextOptions({ options: supportOptions, languages }) {
  599. const detailedOptions = [
  600. ...detailedCliOptions,
  601. ...supportOptions.map((apiOption) => apiOptionToCliOption(apiOption))
  602. ];
  603. return {
  604. supportOptions,
  605. languages,
  606. detailedOptions
  607. };
  608. }
  609. async function getContextOptions(plugins) {
  610. const supportInfo = await getSupportInfo({
  611. showDeprecated: true,
  612. plugins
  613. });
  614. return supportInfoToContextOptions(supportInfo);
  615. }
  616. function getContextOptionsWithoutPlugins() {
  617. const supportInfo = getSupportInfoWithoutPlugins();
  618. return supportInfoToContextOptions(supportInfo);
  619. }
  620. // scripts/build/shims/string-replace-all.js
  621. var stringReplaceAll = (isOptionalObject, original, pattern, replacement) => {
  622. if (isOptionalObject && (original === void 0 || original === null)) {
  623. return;
  624. }
  625. if (original.replaceAll) {
  626. return original.replaceAll(pattern, replacement);
  627. }
  628. if (pattern.global) {
  629. return original.replace(pattern, replacement);
  630. }
  631. return original.split(pattern).join(replacement);
  632. };
  633. var string_replace_all_default = stringReplaceAll;
  634. // node_modules/camelcase/index.js
  635. var UPPERCASE = /[\p{Lu}]/u;
  636. var LOWERCASE = /[\p{Ll}]/u;
  637. var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
  638. var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
  639. var SEPARATORS = /[_.\- ]+/;
  640. var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
  641. var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
  642. var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
  643. var preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  644. let isLastCharLower = false;
  645. let isLastCharUpper = false;
  646. let isLastLastCharUpper = false;
  647. let isLastLastCharPreserved = false;
  648. for (let index = 0; index < string.length; index++) {
  649. const character = string[index];
  650. isLastLastCharPreserved = index > 2 ? string[index - 3] === "-" : true;
  651. if (isLastCharLower && UPPERCASE.test(character)) {
  652. string = string.slice(0, index) + "-" + string.slice(index);
  653. isLastCharLower = false;
  654. isLastLastCharUpper = isLastCharUpper;
  655. isLastCharUpper = true;
  656. index++;
  657. } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
  658. string = string.slice(0, index - 1) + "-" + string.slice(index - 1);
  659. isLastLastCharUpper = isLastCharUpper;
  660. isLastCharUpper = false;
  661. isLastCharLower = true;
  662. } else {
  663. isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
  664. isLastLastCharUpper = isLastCharUpper;
  665. isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
  666. }
  667. }
  668. return string;
  669. };
  670. var preserveConsecutiveUppercase = (input, toLowerCase) => {
  671. LEADING_CAPITAL.lastIndex = 0;
  672. return string_replace_all_default(
  673. /* isOptionalObject */
  674. false,
  675. input,
  676. LEADING_CAPITAL,
  677. (match) => toLowerCase(match)
  678. );
  679. };
  680. var postProcess = (input, toUpperCase) => {
  681. SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
  682. NUMBERS_AND_IDENTIFIER.lastIndex = 0;
  683. return string_replace_all_default(
  684. /* isOptionalObject */
  685. false,
  686. string_replace_all_default(
  687. /* isOptionalObject */
  688. false,
  689. input,
  690. NUMBERS_AND_IDENTIFIER,
  691. (match, pattern, offset) => ["_", "-"].includes(input.charAt(offset + match.length)) ? match : toUpperCase(match)
  692. ),
  693. SEPARATORS_AND_IDENTIFIER,
  694. (_2, identifier) => toUpperCase(identifier)
  695. );
  696. };
  697. function camelCase(input, options) {
  698. if (!(typeof input === "string" || Array.isArray(input))) {
  699. throw new TypeError("Expected the input to be `string | string[]`");
  700. }
  701. options = {
  702. pascalCase: false,
  703. preserveConsecutiveUppercase: false,
  704. ...options
  705. };
  706. if (Array.isArray(input)) {
  707. input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
  708. } else {
  709. input = input.trim();
  710. }
  711. if (input.length === 0) {
  712. return "";
  713. }
  714. const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
  715. const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
  716. if (input.length === 1) {
  717. if (SEPARATORS.test(input)) {
  718. return "";
  719. }
  720. return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
  721. }
  722. const hasUpperCase = input !== toLowerCase(input);
  723. if (hasUpperCase) {
  724. input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
  725. }
  726. input = input.replace(LEADING_SEPARATORS, "");
  727. input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  728. if (options.pascalCase) {
  729. input = toUpperCase(input.charAt(0)) + input.slice(1);
  730. }
  731. return postProcess(input, toUpperCase);
  732. }
  733. // src/cli/utils.js
  734. import fs from "fs/promises";
  735. import path from "path";
  736. // node_modules/sdbm/index.js
  737. function sdbm(string) {
  738. let hash2 = 0;
  739. for (let i = 0; i < string.length; i++) {
  740. hash2 = string.charCodeAt(i) + (hash2 << 6) + (hash2 << 16) - hash2;
  741. }
  742. return hash2 >>> 0;
  743. }
  744. // src/cli/utils.js
  745. import { __internal as sharedWithCli2 } from "../index.mjs";
  746. var printToScreen = console.log.bind(console);
  747. function groupBy(array2, iteratee) {
  748. const result = /* @__PURE__ */ Object.create(null);
  749. for (const value of array2) {
  750. const key = iteratee(value);
  751. if (Array.isArray(result[key])) {
  752. result[key].push(value);
  753. } else {
  754. result[key] = [value];
  755. }
  756. }
  757. return result;
  758. }
  759. function pick(object2, keys2) {
  760. const entries = keys2.map((key) => [key, object2[key]]);
  761. return Object.fromEntries(entries);
  762. }
  763. function createHash(source) {
  764. return String(sdbm(source));
  765. }
  766. async function statSafe(filePath) {
  767. try {
  768. return await fs.stat(filePath);
  769. } catch (error) {
  770. if (error.code !== "ENOENT") {
  771. throw error;
  772. }
  773. }
  774. }
  775. async function lstatSafe(filePath) {
  776. try {
  777. return await fs.lstat(filePath);
  778. } catch (error) {
  779. if (error.code !== "ENOENT") {
  780. throw error;
  781. }
  782. }
  783. }
  784. function isJson(value) {
  785. try {
  786. JSON.parse(value);
  787. return true;
  788. } catch {
  789. return false;
  790. }
  791. }
  792. var normalizeToPosix = path.sep === "\\" ? (filepath) => string_replace_all_default(
  793. /* isOptionalObject */
  794. false,
  795. filepath,
  796. "\\",
  797. "/"
  798. ) : (filepath) => filepath;
  799. var { omit } = sharedWithCli2.utils;
  800. // src/cli/options/create-minimist-options.js
  801. function createMinimistOptions(detailedOptions) {
  802. const booleanNames = [];
  803. const stringNames = [];
  804. const defaultValues = {};
  805. for (const option of detailedOptions) {
  806. const { name, alias, type } = option;
  807. const names = type === "boolean" ? booleanNames : stringNames;
  808. names.push(name);
  809. if (alias) {
  810. names.push(alias);
  811. }
  812. if (!option.deprecated && (!option.forwardToApi || name === "plugin") && option.default !== void 0) {
  813. defaultValues[option.name] = option.default;
  814. }
  815. }
  816. return {
  817. // we use vnopts' AliasSchema to handle aliases for better error messages
  818. alias: {},
  819. boolean: booleanNames,
  820. string: stringNames,
  821. default: defaultValues
  822. };
  823. }
  824. // src/cli/options/minimist.js
  825. var import_minimist = __toESM(require_minimist(), 1);
  826. var PLACEHOLDER = null;
  827. function minimistParse(args, options) {
  828. const boolean = options.boolean ?? [];
  829. const defaults = options.default ?? {};
  830. const booleanWithoutDefault = boolean.filter((key) => !(key in defaults));
  831. const newDefaults = {
  832. ...defaults,
  833. ...Object.fromEntries(
  834. booleanWithoutDefault.map((key) => [key, PLACEHOLDER])
  835. )
  836. };
  837. const parsed = (0, import_minimist.default)(args, { ...options, default: newDefaults });
  838. return Object.fromEntries(
  839. Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER)
  840. );
  841. }
  842. // node_modules/chalk/source/vendor/ansi-styles/index.js
  843. var ANSI_BACKGROUND_OFFSET = 10;
  844. var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
  845. var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
  846. var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
  847. var styles = {
  848. modifier: {
  849. reset: [0, 0],
  850. // 21 isn't widely supported and 22 does the same thing
  851. bold: [1, 22],
  852. dim: [2, 22],
  853. italic: [3, 23],
  854. underline: [4, 24],
  855. overline: [53, 55],
  856. inverse: [7, 27],
  857. hidden: [8, 28],
  858. strikethrough: [9, 29]
  859. },
  860. color: {
  861. black: [30, 39],
  862. red: [31, 39],
  863. green: [32, 39],
  864. yellow: [33, 39],
  865. blue: [34, 39],
  866. magenta: [35, 39],
  867. cyan: [36, 39],
  868. white: [37, 39],
  869. // Bright color
  870. blackBright: [90, 39],
  871. gray: [90, 39],
  872. // Alias of `blackBright`
  873. grey: [90, 39],
  874. // Alias of `blackBright`
  875. redBright: [91, 39],
  876. greenBright: [92, 39],
  877. yellowBright: [93, 39],
  878. blueBright: [94, 39],
  879. magentaBright: [95, 39],
  880. cyanBright: [96, 39],
  881. whiteBright: [97, 39]
  882. },
  883. bgColor: {
  884. bgBlack: [40, 49],
  885. bgRed: [41, 49],
  886. bgGreen: [42, 49],
  887. bgYellow: [43, 49],
  888. bgBlue: [44, 49],
  889. bgMagenta: [45, 49],
  890. bgCyan: [46, 49],
  891. bgWhite: [47, 49],
  892. // Bright color
  893. bgBlackBright: [100, 49],
  894. bgGray: [100, 49],
  895. // Alias of `bgBlackBright`
  896. bgGrey: [100, 49],
  897. // Alias of `bgBlackBright`
  898. bgRedBright: [101, 49],
  899. bgGreenBright: [102, 49],
  900. bgYellowBright: [103, 49],
  901. bgBlueBright: [104, 49],
  902. bgMagentaBright: [105, 49],
  903. bgCyanBright: [106, 49],
  904. bgWhiteBright: [107, 49]
  905. }
  906. };
  907. var modifierNames = Object.keys(styles.modifier);
  908. var foregroundColorNames = Object.keys(styles.color);
  909. var backgroundColorNames = Object.keys(styles.bgColor);
  910. var colorNames = [...foregroundColorNames, ...backgroundColorNames];
  911. function assembleStyles() {
  912. const codes = /* @__PURE__ */ new Map();
  913. for (const [groupName, group] of Object.entries(styles)) {
  914. for (const [styleName, style] of Object.entries(group)) {
  915. styles[styleName] = {
  916. open: `\x1B[${style[0]}m`,
  917. close: `\x1B[${style[1]}m`
  918. };
  919. group[styleName] = styles[styleName];
  920. codes.set(style[0], style[1]);
  921. }
  922. Object.defineProperty(styles, groupName, {
  923. value: group,
  924. enumerable: false
  925. });
  926. }
  927. Object.defineProperty(styles, "codes", {
  928. value: codes,
  929. enumerable: false
  930. });
  931. styles.color.close = "\x1B[39m";
  932. styles.bgColor.close = "\x1B[49m";
  933. styles.color.ansi = wrapAnsi16();
  934. styles.color.ansi256 = wrapAnsi256();
  935. styles.color.ansi16m = wrapAnsi16m();
  936. styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  937. styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  938. styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  939. Object.defineProperties(styles, {
  940. rgbToAnsi256: {
  941. value(red, green, blue) {
  942. if (red === green && green === blue) {
  943. if (red < 8) {
  944. return 16;
  945. }
  946. if (red > 248) {
  947. return 231;
  948. }
  949. return Math.round((red - 8) / 247 * 24) + 232;
  950. }
  951. return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
  952. },
  953. enumerable: false
  954. },
  955. hexToRgb: {
  956. value(hex) {
  957. const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
  958. if (!matches) {
  959. return [0, 0, 0];
  960. }
  961. let [colorString] = matches;
  962. if (colorString.length === 3) {
  963. colorString = [...colorString].map((character) => character + character).join("");
  964. }
  965. const integer = Number.parseInt(colorString, 16);
  966. return [
  967. /* eslint-disable no-bitwise */
  968. integer >> 16 & 255,
  969. integer >> 8 & 255,
  970. integer & 255
  971. /* eslint-enable no-bitwise */
  972. ];
  973. },
  974. enumerable: false
  975. },
  976. hexToAnsi256: {
  977. value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
  978. enumerable: false
  979. },
  980. ansi256ToAnsi: {
  981. value(code) {
  982. if (code < 8) {
  983. return 30 + code;
  984. }
  985. if (code < 16) {
  986. return 90 + (code - 8);
  987. }
  988. let red;
  989. let green;
  990. let blue;
  991. if (code >= 232) {
  992. red = ((code - 232) * 10 + 8) / 255;
  993. green = red;
  994. blue = red;
  995. } else {
  996. code -= 16;
  997. const remainder = code % 36;
  998. red = Math.floor(code / 36) / 5;
  999. green = Math.floor(remainder / 6) / 5;
  1000. blue = remainder % 6 / 5;
  1001. }
  1002. const value = Math.max(red, green, blue) * 2;
  1003. if (value === 0) {
  1004. return 30;
  1005. }
  1006. let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
  1007. if (value === 2) {
  1008. result += 60;
  1009. }
  1010. return result;
  1011. },
  1012. enumerable: false
  1013. },
  1014. rgbToAnsi: {
  1015. value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
  1016. enumerable: false
  1017. },
  1018. hexToAnsi: {
  1019. value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
  1020. enumerable: false
  1021. }
  1022. });
  1023. return styles;
  1024. }
  1025. var ansiStyles = assembleStyles();
  1026. var ansi_styles_default = ansiStyles;
  1027. // node_modules/chalk/source/vendor/supports-color/index.js
  1028. import process2 from "process";
  1029. import os from "os";
  1030. import tty from "tty";
  1031. function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
  1032. const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  1033. const position = argv.indexOf(prefix + flag);
  1034. const terminatorPosition = argv.indexOf("--");
  1035. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  1036. }
  1037. var { env } = process2;
  1038. var flagForceColor;
  1039. if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  1040. flagForceColor = 0;
  1041. } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  1042. flagForceColor = 1;
  1043. }
  1044. function envForceColor() {
  1045. if ("FORCE_COLOR" in env) {
  1046. if (env.FORCE_COLOR === "true") {
  1047. return 1;
  1048. }
  1049. if (env.FORCE_COLOR === "false") {
  1050. return 0;
  1051. }
  1052. return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  1053. }
  1054. }
  1055. function translateLevel(level) {
  1056. if (level === 0) {
  1057. return false;
  1058. }
  1059. return {
  1060. level,
  1061. hasBasic: true,
  1062. has256: level >= 2,
  1063. has16m: level >= 3
  1064. };
  1065. }
  1066. function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  1067. const noFlagForceColor = envForceColor();
  1068. if (noFlagForceColor !== void 0) {
  1069. flagForceColor = noFlagForceColor;
  1070. }
  1071. const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  1072. if (forceColor === 0) {
  1073. return 0;
  1074. }
  1075. if (sniffFlags) {
  1076. if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
  1077. return 3;
  1078. }
  1079. if (hasFlag("color=256")) {
  1080. return 2;
  1081. }
  1082. }
  1083. if ("TF_BUILD" in env && "AGENT_NAME" in env) {
  1084. return 1;
  1085. }
  1086. if (haveStream && !streamIsTTY && forceColor === void 0) {
  1087. return 0;
  1088. }
  1089. const min = forceColor || 0;
  1090. if (env.TERM === "dumb") {
  1091. return min;
  1092. }
  1093. if (process2.platform === "win32") {
  1094. const osRelease = os.release().split(".");
  1095. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  1096. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  1097. }
  1098. return 1;
  1099. }
  1100. if ("CI" in env) {
  1101. if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
  1102. return 3;
  1103. }
  1104. if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
  1105. return 1;
  1106. }
  1107. return min;
  1108. }
  1109. if ("TEAMCITY_VERSION" in env) {
  1110. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  1111. }
  1112. if (env.COLORTERM === "truecolor") {
  1113. return 3;
  1114. }
  1115. if (env.TERM === "xterm-kitty") {
  1116. return 3;
  1117. }
  1118. if ("TERM_PROGRAM" in env) {
  1119. const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  1120. switch (env.TERM_PROGRAM) {
  1121. case "iTerm.app": {
  1122. return version2 >= 3 ? 3 : 2;
  1123. }
  1124. case "Apple_Terminal": {
  1125. return 2;
  1126. }
  1127. }
  1128. }
  1129. if (/-256(color)?$/i.test(env.TERM)) {
  1130. return 2;
  1131. }
  1132. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  1133. return 1;
  1134. }
  1135. if ("COLORTERM" in env) {
  1136. return 1;
  1137. }
  1138. return min;
  1139. }
  1140. function createSupportsColor(stream, options = {}) {
  1141. const level = _supportsColor(stream, {
  1142. streamIsTTY: stream && stream.isTTY,
  1143. ...options
  1144. });
  1145. return translateLevel(level);
  1146. }
  1147. var supportsColor = {
  1148. stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
  1149. stderr: createSupportsColor({ isTTY: tty.isatty(2) })
  1150. };
  1151. var supports_color_default = supportsColor;
  1152. // node_modules/chalk/source/utilities.js
  1153. function stringReplaceAll2(string, substring, replacer) {
  1154. let index = string.indexOf(substring);
  1155. if (index === -1) {
  1156. return string;
  1157. }
  1158. const substringLength = substring.length;
  1159. let endIndex = 0;
  1160. let returnValue = "";
  1161. do {
  1162. returnValue += string.slice(endIndex, index) + substring + replacer;
  1163. endIndex = index + substringLength;
  1164. index = string.indexOf(substring, endIndex);
  1165. } while (index !== -1);
  1166. returnValue += string.slice(endIndex);
  1167. return returnValue;
  1168. }
  1169. function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
  1170. let endIndex = 0;
  1171. let returnValue = "";
  1172. do {
  1173. const gotCR = string[index - 1] === "\r";
  1174. returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
  1175. endIndex = index + 1;
  1176. index = string.indexOf("\n", endIndex);
  1177. } while (index !== -1);
  1178. returnValue += string.slice(endIndex);
  1179. return returnValue;
  1180. }
  1181. // node_modules/chalk/source/index.js
  1182. var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
  1183. var GENERATOR = Symbol("GENERATOR");
  1184. var STYLER = Symbol("STYLER");
  1185. var IS_EMPTY = Symbol("IS_EMPTY");
  1186. var levelMapping = [
  1187. "ansi",
  1188. "ansi",
  1189. "ansi256",
  1190. "ansi16m"
  1191. ];
  1192. var styles2 = /* @__PURE__ */ Object.create(null);
  1193. var applyOptions = (object2, options = {}) => {
  1194. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  1195. throw new Error("The `level` option should be an integer from 0 to 3");
  1196. }
  1197. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  1198. object2.level = options.level === void 0 ? colorLevel : options.level;
  1199. };
  1200. var chalkFactory = (options) => {
  1201. const chalk2 = (...strings) => strings.join(" ");
  1202. applyOptions(chalk2, options);
  1203. Object.setPrototypeOf(chalk2, createChalk.prototype);
  1204. return chalk2;
  1205. };
  1206. function createChalk(options) {
  1207. return chalkFactory(options);
  1208. }
  1209. Object.setPrototypeOf(createChalk.prototype, Function.prototype);
  1210. for (const [styleName, style] of Object.entries(ansi_styles_default)) {
  1211. styles2[styleName] = {
  1212. get() {
  1213. const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
  1214. Object.defineProperty(this, styleName, { value: builder });
  1215. return builder;
  1216. }
  1217. };
  1218. }
  1219. styles2.visible = {
  1220. get() {
  1221. const builder = createBuilder(this, this[STYLER], true);
  1222. Object.defineProperty(this, "visible", { value: builder });
  1223. return builder;
  1224. }
  1225. };
  1226. var getModelAnsi = (model, level, type, ...arguments_) => {
  1227. if (model === "rgb") {
  1228. if (level === "ansi16m") {
  1229. return ansi_styles_default[type].ansi16m(...arguments_);
  1230. }
  1231. if (level === "ansi256") {
  1232. return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
  1233. }
  1234. return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
  1235. }
  1236. if (model === "hex") {
  1237. return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
  1238. }
  1239. return ansi_styles_default[type][model](...arguments_);
  1240. };
  1241. var usedModels = ["rgb", "hex", "ansi256"];
  1242. for (const model of usedModels) {
  1243. styles2[model] = {
  1244. get() {
  1245. const { level } = this;
  1246. return function(...arguments_) {
  1247. const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
  1248. return createBuilder(this, styler, this[IS_EMPTY]);
  1249. };
  1250. }
  1251. };
  1252. const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  1253. styles2[bgModel] = {
  1254. get() {
  1255. const { level } = this;
  1256. return function(...arguments_) {
  1257. const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
  1258. return createBuilder(this, styler, this[IS_EMPTY]);
  1259. };
  1260. }
  1261. };
  1262. }
  1263. var proto = Object.defineProperties(() => {
  1264. }, {
  1265. ...styles2,
  1266. level: {
  1267. enumerable: true,
  1268. get() {
  1269. return this[GENERATOR].level;
  1270. },
  1271. set(level) {
  1272. this[GENERATOR].level = level;
  1273. }
  1274. }
  1275. });
  1276. var createStyler = (open, close, parent) => {
  1277. let openAll;
  1278. let closeAll;
  1279. if (parent === void 0) {
  1280. openAll = open;
  1281. closeAll = close;
  1282. } else {
  1283. openAll = parent.openAll + open;
  1284. closeAll = close + parent.closeAll;
  1285. }
  1286. return {
  1287. open,
  1288. close,
  1289. openAll,
  1290. closeAll,
  1291. parent
  1292. };
  1293. };
  1294. var createBuilder = (self, _styler, _isEmpty) => {
  1295. const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
  1296. Object.setPrototypeOf(builder, proto);
  1297. builder[GENERATOR] = self;
  1298. builder[STYLER] = _styler;
  1299. builder[IS_EMPTY] = _isEmpty;
  1300. return builder;
  1301. };
  1302. var applyStyle = (self, string) => {
  1303. if (self.level <= 0 || !string) {
  1304. return self[IS_EMPTY] ? "" : string;
  1305. }
  1306. let styler = self[STYLER];
  1307. if (styler === void 0) {
  1308. return string;
  1309. }
  1310. const { openAll, closeAll } = styler;
  1311. if (string.includes("\x1B")) {
  1312. while (styler !== void 0) {
  1313. string = stringReplaceAll2(string, styler.close, styler.open);
  1314. styler = styler.parent;
  1315. }
  1316. }
  1317. const lfIndex = string.indexOf("\n");
  1318. if (lfIndex !== -1) {
  1319. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  1320. }
  1321. return openAll + string + closeAll;
  1322. };
  1323. Object.defineProperties(createChalk.prototype, styles2);
  1324. var chalk = createChalk();
  1325. var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
  1326. var source_default = chalk;
  1327. // node_modules/leven/index.js
  1328. var array = [];
  1329. var characterCodeCache = [];
  1330. function leven(first, second) {
  1331. if (first === second) {
  1332. return 0;
  1333. }
  1334. const swap = first;
  1335. if (first.length > second.length) {
  1336. first = second;
  1337. second = swap;
  1338. }
  1339. let firstLength = first.length;
  1340. let secondLength = second.length;
  1341. while (firstLength > 0 && first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength)) {
  1342. firstLength--;
  1343. secondLength--;
  1344. }
  1345. let start = 0;
  1346. while (start < firstLength && first.charCodeAt(start) === second.charCodeAt(start)) {
  1347. start++;
  1348. }
  1349. firstLength -= start;
  1350. secondLength -= start;
  1351. if (firstLength === 0) {
  1352. return secondLength;
  1353. }
  1354. let bCharacterCode;
  1355. let result;
  1356. let temporary;
  1357. let temporary2;
  1358. let index = 0;
  1359. let index2 = 0;
  1360. while (index < firstLength) {
  1361. characterCodeCache[index] = first.charCodeAt(start + index);
  1362. array[index] = ++index;
  1363. }
  1364. while (index2 < secondLength) {
  1365. bCharacterCode = second.charCodeAt(start + index2);
  1366. temporary = index2++;
  1367. result = index2;
  1368. for (index = 0; index < firstLength; index++) {
  1369. temporary2 = bCharacterCode === characterCodeCache[index] ? temporary : temporary + 1;
  1370. temporary = array[index];
  1371. result = array[index] = temporary > result ? temporary2 > result ? result + 1 : temporary2 : temporary2 > temporary ? temporary + 1 : temporary2;
  1372. }
  1373. }
  1374. return result;
  1375. }
  1376. // src/cli/options/normalize-cli-options.js
  1377. var descriptor = {
  1378. key: (key) => key.length === 1 ? `-${key}` : `--${key}`,
  1379. value: (value) => vnopts.apiDescriptor.value(value),
  1380. pair: ({ key, value }) => value === false ? `--no-${key}` : value === true ? descriptor.key(key) : value === "" ? `${descriptor.key(key)} without an argument` : `${descriptor.key(key)}=${value}`
  1381. };
  1382. var _flags;
  1383. var FlagSchema = class extends vnopts.ChoiceSchema {
  1384. constructor({ name, flags }) {
  1385. super({ name, choices: flags });
  1386. __privateAdd(this, _flags, []);
  1387. __privateSet(this, _flags, [...flags].sort());
  1388. }
  1389. preprocess(value, utils) {
  1390. if (typeof value === "string" && value.length > 0 && !__privateGet(this, _flags).includes(value)) {
  1391. const suggestion = __privateGet(this, _flags).find((flag) => leven(flag, value) < 3);
  1392. if (suggestion) {
  1393. utils.logger.warn(
  1394. [
  1395. `Unknown flag ${source_default.yellow(utils.descriptor.value(value))},`,
  1396. `did you mean ${source_default.blue(utils.descriptor.value(suggestion))}?`
  1397. ].join(" ")
  1398. );
  1399. return suggestion;
  1400. }
  1401. }
  1402. return value;
  1403. }
  1404. expected() {
  1405. return "a flag";
  1406. }
  1407. };
  1408. _flags = new WeakMap();
  1409. function normalizeCliOptions(options, optionInfos, opts) {
  1410. return normalizeOptions(options, optionInfos, {
  1411. ...opts,
  1412. isCLI: true,
  1413. FlagSchema,
  1414. descriptor
  1415. });
  1416. }
  1417. var normalize_cli_options_default = normalizeCliOptions;
  1418. // src/cli/options/parse-cli-arguments.js
  1419. function parseArgv(rawArguments, detailedOptions, logger, keys2) {
  1420. var _a;
  1421. const minimistOptions = createMinimistOptions(detailedOptions);
  1422. let argv = minimistParse(rawArguments, minimistOptions);
  1423. if (keys2) {
  1424. detailedOptions = detailedOptions.filter(
  1425. (option) => keys2.includes(option.name)
  1426. );
  1427. argv = pick(argv, keys2);
  1428. }
  1429. const normalized = normalize_cli_options_default(argv, detailedOptions, { logger });
  1430. return {
  1431. ...Object.fromEntries(
  1432. Object.entries(normalized).map(([key, value]) => {
  1433. const option = detailedOptions.find(({ name }) => name === key) || {};
  1434. return [option.forwardToApi || camelCase(key), value];
  1435. })
  1436. ),
  1437. _: (_a = normalized._) == null ? void 0 : _a.map(String),
  1438. get __raw() {
  1439. return argv;
  1440. }
  1441. };
  1442. }
  1443. var { detailedOptions: detailedOptionsWithoutPlugins } = getContextOptionsWithoutPlugins();
  1444. function parseArgvWithoutPlugins(rawArguments, logger, keys2) {
  1445. return parseArgv(
  1446. rawArguments,
  1447. detailedOptionsWithoutPlugins,
  1448. logger,
  1449. typeof keys2 === "string" ? [keys2] : keys2
  1450. );
  1451. }
  1452. // src/cli/context.js
  1453. var _stack;
  1454. var Context = class {
  1455. constructor({ rawArguments, logger }) {
  1456. __privateAdd(this, _stack, []);
  1457. this.rawArguments = rawArguments;
  1458. this.logger = logger;
  1459. }
  1460. async init() {
  1461. const { rawArguments, logger } = this;
  1462. const { plugins } = parseArgvWithoutPlugins(rawArguments, logger, [
  1463. "plugin"
  1464. ]);
  1465. await this.pushContextPlugins(plugins);
  1466. const argv = parseArgv(rawArguments, this.detailedOptions, logger);
  1467. this.argv = argv;
  1468. this.filePatterns = argv._;
  1469. }
  1470. /**
  1471. * @param {string[]} plugins
  1472. */
  1473. async pushContextPlugins(plugins) {
  1474. const options = await getContextOptions(plugins);
  1475. __privateGet(this, _stack).push(options);
  1476. Object.assign(this, options);
  1477. }
  1478. popContextPlugins() {
  1479. __privateGet(this, _stack).pop();
  1480. Object.assign(this, at_default(
  1481. /* isOptionalObject */
  1482. false,
  1483. __privateGet(this, _stack),
  1484. -1
  1485. ));
  1486. }
  1487. // eslint-disable-next-line getter-return
  1488. get performanceTestFlag() {
  1489. const { debugBenchmark, debugRepeat } = this.argv;
  1490. if (debugBenchmark) {
  1491. return {
  1492. name: "--debug-benchmark",
  1493. debugBenchmark: true
  1494. };
  1495. }
  1496. if (debugRepeat > 0) {
  1497. return {
  1498. name: "--debug-repeat",
  1499. debugRepeat
  1500. };
  1501. }
  1502. const { PRETTIER_PERF_REPEAT } = process.env;
  1503. if (PRETTIER_PERF_REPEAT && /^\d+$/u.test(PRETTIER_PERF_REPEAT)) {
  1504. return {
  1505. name: "PRETTIER_PERF_REPEAT (environment variable)",
  1506. debugRepeat: Number(PRETTIER_PERF_REPEAT)
  1507. };
  1508. }
  1509. }
  1510. };
  1511. _stack = new WeakMap();
  1512. var context_default = Context;
  1513. // src/cli/file-info.js
  1514. var import_fast_json_stable_stringify = __toESM(require_fast_json_stable_stringify(), 1);
  1515. import { format, getFileInfo } from "../index.mjs";
  1516. async function logFileInfoOrDie(context) {
  1517. const {
  1518. fileInfo: file,
  1519. ignorePath,
  1520. withNodeModules,
  1521. plugins,
  1522. config
  1523. } = context.argv;
  1524. const fileInfo = await getFileInfo(file, {
  1525. ignorePath,
  1526. withNodeModules,
  1527. plugins,
  1528. resolveConfig: config !== false
  1529. });
  1530. printToScreen(await format((0, import_fast_json_stable_stringify.default)(fileInfo), { parser: "json" }));
  1531. }
  1532. var file_info_default = logFileInfoOrDie;
  1533. // src/cli/find-config-path.js
  1534. import path2 from "path";
  1535. import { resolveConfigFile } from "../index.mjs";
  1536. async function logResolvedConfigPathOrDie(context) {
  1537. const file = context.argv.findConfigPath;
  1538. const configFile = await resolveConfigFile(file);
  1539. if (configFile) {
  1540. printToScreen(normalizeToPosix(path2.relative(process.cwd(), configFile)));
  1541. } else {
  1542. throw new Error(`Can not find configure file for "${file}".`);
  1543. }
  1544. }
  1545. var find_config_path_default = logResolvedConfigPathOrDie;
  1546. // src/cli/format.js
  1547. import fs8 from "fs/promises";
  1548. import path11 from "path";
  1549. import * as prettier from "../index.mjs";
  1550. // src/cli/expand-patterns.js
  1551. import path3 from "path";
  1552. async function* expandPatterns(context) {
  1553. const seen = /* @__PURE__ */ new Set();
  1554. let noResults = true;
  1555. for await (const { filePath, ignoreUnknown, error } of expandPatternsInternal(
  1556. context
  1557. )) {
  1558. noResults = false;
  1559. if (error) {
  1560. yield { error };
  1561. continue;
  1562. }
  1563. const filename = path3.resolve(filePath);
  1564. if (seen.has(filename)) {
  1565. continue;
  1566. }
  1567. seen.add(filename);
  1568. yield { filename, ignoreUnknown };
  1569. }
  1570. if (noResults && context.argv.errorOnUnmatchedPattern !== false) {
  1571. yield {
  1572. error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
  1573. };
  1574. }
  1575. }
  1576. async function* expandPatternsInternal(context) {
  1577. const silentlyIgnoredDirs = [".git", ".sl", ".svn", ".hg", ".jj"];
  1578. if (context.argv.withNodeModules !== true) {
  1579. silentlyIgnoredDirs.push("node_modules");
  1580. }
  1581. const globOptions = {
  1582. dot: true,
  1583. ignore: silentlyIgnoredDirs.map((dir) => "**/" + dir),
  1584. followSymbolicLinks: false
  1585. };
  1586. const cwd2 = process.cwd();
  1587. const entries = [];
  1588. for (const pattern of context.filePatterns) {
  1589. const absolutePath = path3.resolve(cwd2, pattern);
  1590. if (containsIgnoredPathSegment(absolutePath, cwd2, silentlyIgnoredDirs)) {
  1591. continue;
  1592. }
  1593. const stat = await lstatSafe(absolutePath);
  1594. if (stat) {
  1595. if (stat.isSymbolicLink()) {
  1596. if (context.argv.errorOnUnmatchedPattern !== false) {
  1597. yield {
  1598. error: `Explicitly specified pattern "${pattern}" is a symbolic link.`
  1599. };
  1600. } else {
  1601. context.logger.debug(
  1602. `Skipping pattern "${pattern}", as it is a symbolic link.`
  1603. );
  1604. }
  1605. } else if (stat.isFile()) {
  1606. entries.push({
  1607. type: "file",
  1608. glob: escapePathForGlob(fixWindowsSlashes(pattern)),
  1609. input: pattern
  1610. });
  1611. } else if (stat.isDirectory()) {
  1612. const relativePath = path3.relative(cwd2, absolutePath) || ".";
  1613. const prefix = escapePathForGlob(fixWindowsSlashes(relativePath));
  1614. entries.push({
  1615. type: "dir",
  1616. glob: `${prefix}/**/*`,
  1617. input: pattern,
  1618. ignoreUnknown: true
  1619. });
  1620. }
  1621. } else if (pattern[0] === "!") {
  1622. globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
  1623. } else {
  1624. entries.push({
  1625. type: "glob",
  1626. glob: fixWindowsSlashes(pattern),
  1627. input: pattern
  1628. });
  1629. }
  1630. }
  1631. for (const { type, glob, input, ignoreUnknown } of entries) {
  1632. let result;
  1633. try {
  1634. result = await fastGlob(glob, globOptions);
  1635. } catch ({ message }) {
  1636. yield {
  1637. error: `${errorMessages.globError[type]}: "${input}".
  1638. ${message}`
  1639. };
  1640. continue;
  1641. }
  1642. if (result.length === 0) {
  1643. if (context.argv.errorOnUnmatchedPattern !== false) {
  1644. yield { error: `${errorMessages.emptyResults[type]}: "${input}".` };
  1645. }
  1646. } else {
  1647. yield* sortPaths(result).map((filePath) => ({ filePath, ignoreUnknown }));
  1648. }
  1649. }
  1650. }
  1651. var errorMessages = {
  1652. globError: {
  1653. file: "Unable to resolve file",
  1654. dir: "Unable to expand directory",
  1655. glob: "Unable to expand glob pattern"
  1656. },
  1657. emptyResults: {
  1658. file: "Explicitly specified file was ignored due to negative glob patterns",
  1659. dir: "No supported files were found in the directory",
  1660. glob: "No files matching the pattern were found"
  1661. }
  1662. };
  1663. function containsIgnoredPathSegment(absolutePath, cwd2, ignoredDirectories) {
  1664. return path3.relative(cwd2, absolutePath).split(path3.sep).some((dir) => ignoredDirectories.includes(dir));
  1665. }
  1666. function sortPaths(paths) {
  1667. return paths.sort((a, b) => a.localeCompare(b));
  1668. }
  1669. function escapePathForGlob(path12) {
  1670. return string_replace_all_default(
  1671. /* isOptionalObject */
  1672. false,
  1673. string_replace_all_default(
  1674. /* isOptionalObject */
  1675. false,
  1676. fastGlob.escapePath(
  1677. string_replace_all_default(
  1678. /* isOptionalObject */
  1679. false,
  1680. path12,
  1681. "\\",
  1682. "\0"
  1683. )
  1684. // Workaround for fast-glob#262 (part 1)
  1685. ),
  1686. String.raw`\!`,
  1687. "@(!)"
  1688. ),
  1689. "\0",
  1690. String.raw`@(\\)`
  1691. );
  1692. }
  1693. var fixWindowsSlashes = normalizeToPosix;
  1694. // src/cli/find-cache-file.js
  1695. import fs4 from "fs/promises";
  1696. import os2 from "os";
  1697. import path8 from "path";
  1698. // node_modules/find-cache-dir/index.js
  1699. var import_common_path_prefix = __toESM(require_common_path_prefix(), 1);
  1700. import process4 from "process";
  1701. import path7 from "path";
  1702. import fs3 from "fs";
  1703. // node_modules/pkg-dir/index.js
  1704. import path6 from "path";
  1705. // node_modules/pkg-dir/node_modules/find-up/index.js
  1706. import path5 from "path";
  1707. import { fileURLToPath as fileURLToPath2 } from "url";
  1708. // node_modules/locate-path/index.js
  1709. import process3 from "process";
  1710. import path4 from "path";
  1711. import fs2, { promises as fsPromises } from "fs";
  1712. import { fileURLToPath } from "url";
  1713. var typeMappings = {
  1714. directory: "isDirectory",
  1715. file: "isFile"
  1716. };
  1717. function checkType(type) {
  1718. if (Object.hasOwnProperty.call(typeMappings, type)) {
  1719. return;
  1720. }
  1721. throw new Error(`Invalid type specified: ${type}`);
  1722. }
  1723. var matchType = (type, stat) => stat[typeMappings[type]]();
  1724. var toPath = (urlOrPath) => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  1725. function locatePathSync(paths, {
  1726. cwd: cwd2 = process3.cwd(),
  1727. type = "file",
  1728. allowSymlinks = true
  1729. } = {}) {
  1730. checkType(type);
  1731. cwd2 = toPath(cwd2);
  1732. const statFunction = allowSymlinks ? fs2.statSync : fs2.lstatSync;
  1733. for (const path_ of paths) {
  1734. try {
  1735. const stat = statFunction(path4.resolve(cwd2, path_), {
  1736. throwIfNoEntry: false
  1737. });
  1738. if (!stat) {
  1739. continue;
  1740. }
  1741. if (matchType(type, stat)) {
  1742. return path_;
  1743. }
  1744. } catch {
  1745. }
  1746. }
  1747. }
  1748. // node_modules/pkg-dir/node_modules/find-up/index.js
  1749. var toPath2 = (urlOrPath) => urlOrPath instanceof URL ? fileURLToPath2(urlOrPath) : urlOrPath;
  1750. var findUpStop = Symbol("findUpStop");
  1751. function findUpMultipleSync(name, options = {}) {
  1752. let directory = path5.resolve(toPath2(options.cwd) || "");
  1753. const { root } = path5.parse(directory);
  1754. const stopAt = options.stopAt || root;
  1755. const limit = options.limit || Number.POSITIVE_INFINITY;
  1756. const paths = [name].flat();
  1757. const runMatcher = (locateOptions) => {
  1758. if (typeof name !== "function") {
  1759. return locatePathSync(paths, locateOptions);
  1760. }
  1761. const foundPath = name(locateOptions.cwd);
  1762. if (typeof foundPath === "string") {
  1763. return locatePathSync([foundPath], locateOptions);
  1764. }
  1765. return foundPath;
  1766. };
  1767. const matches = [];
  1768. while (true) {
  1769. const foundPath = runMatcher({ ...options, cwd: directory });
  1770. if (foundPath === findUpStop) {
  1771. break;
  1772. }
  1773. if (foundPath) {
  1774. matches.push(path5.resolve(directory, foundPath));
  1775. }
  1776. if (directory === stopAt || matches.length >= limit) {
  1777. break;
  1778. }
  1779. directory = path5.dirname(directory);
  1780. }
  1781. return matches;
  1782. }
  1783. function findUpSync(name, options = {}) {
  1784. const matches = findUpMultipleSync(name, { ...options, limit: 1 });
  1785. return matches[0];
  1786. }
  1787. // node_modules/pkg-dir/index.js
  1788. function packageDirectorySync({ cwd: cwd2 } = {}) {
  1789. const filePath = findUpSync("package.json", { cwd: cwd2 });
  1790. return filePath && path6.dirname(filePath);
  1791. }
  1792. // node_modules/find-cache-dir/index.js
  1793. var { env: env2, cwd } = process4;
  1794. var isWritable = (path12) => {
  1795. try {
  1796. fs3.accessSync(path12, fs3.constants.W_OK);
  1797. return true;
  1798. } catch {
  1799. return false;
  1800. }
  1801. };
  1802. function useDirectory(directory, options) {
  1803. if (options.create) {
  1804. fs3.mkdirSync(directory, { recursive: true });
  1805. }
  1806. return directory;
  1807. }
  1808. function getNodeModuleDirectory(directory) {
  1809. const nodeModules = path7.join(directory, "node_modules");
  1810. if (!isWritable(nodeModules) && (fs3.existsSync(nodeModules) || !isWritable(path7.join(directory)))) {
  1811. return;
  1812. }
  1813. return nodeModules;
  1814. }
  1815. function findCacheDirectory(options = {}) {
  1816. if (env2.CACHE_DIR && !["true", "false", "1", "0"].includes(env2.CACHE_DIR)) {
  1817. return useDirectory(path7.join(env2.CACHE_DIR, options.name), options);
  1818. }
  1819. let { cwd: directory = cwd(), files } = options;
  1820. if (files) {
  1821. if (!Array.isArray(files)) {
  1822. throw new TypeError(`Expected \`files\` option to be an array, got \`${typeof files}\`.`);
  1823. }
  1824. directory = (0, import_common_path_prefix.default)(files.map((file) => path7.resolve(directory, file)));
  1825. }
  1826. directory = packageDirectorySync({ cwd: directory });
  1827. if (!directory) {
  1828. return;
  1829. }
  1830. const nodeModules = getNodeModuleDirectory(directory);
  1831. if (!nodeModules) {
  1832. return;
  1833. }
  1834. return useDirectory(path7.join(directory, "node_modules", ".cache", options.name), options);
  1835. }
  1836. // src/cli/find-cache-file.js
  1837. function findDefaultCacheFile() {
  1838. const cacheDir = findCacheDirectory({ name: "prettier", create: true }) || os2.tmpdir();
  1839. const cacheFilePath = path8.join(cacheDir, ".prettier-cache");
  1840. return cacheFilePath;
  1841. }
  1842. async function findCacheFileFromOption(cacheLocation) {
  1843. const cacheFile = path8.resolve(cacheLocation);
  1844. const stat = await statSafe(cacheFile);
  1845. if (stat) {
  1846. if (stat.isDirectory()) {
  1847. throw new Error(
  1848. `Resolved --cache-location '${cacheFile}' is a directory`
  1849. );
  1850. }
  1851. const data = await fs4.readFile(cacheFile, "utf8");
  1852. if (!isJson(data)) {
  1853. throw new Error(`'${cacheFile}' isn't a valid JSON file`);
  1854. }
  1855. }
  1856. return cacheFile;
  1857. }
  1858. async function findCacheFile(cacheLocation) {
  1859. if (!cacheLocation) {
  1860. return findDefaultCacheFile();
  1861. }
  1862. const cacheFile = await findCacheFileFromOption(cacheLocation);
  1863. return cacheFile;
  1864. }
  1865. var find_cache_file_default = findCacheFile;
  1866. // src/cli/format-results-cache.js
  1867. var import_fast_json_stable_stringify2 = __toESM(require_fast_json_stable_stringify(), 1);
  1868. import fs7 from "fs";
  1869. // node_modules/file-entry-cache/dist/index.js
  1870. import crypto2 from "crypto";
  1871. import fs6 from "fs";
  1872. import path10 from "path";
  1873. // node_modules/file-entry-cache/node_modules/flat-cache/dist/index.js
  1874. import path9 from "path";
  1875. import fs5 from "fs";
  1876. // node_modules/hookified/dist/node/index.js
  1877. var Eventified = class {
  1878. _eventListeners;
  1879. _maxListeners;
  1880. constructor() {
  1881. this._eventListeners = /* @__PURE__ */ new Map();
  1882. this._maxListeners = 100;
  1883. }
  1884. /**
  1885. * Adds a handler function for a specific event that will run only once
  1886. * @param {string | symbol} eventName
  1887. * @param {EventListener} listener
  1888. * @returns {IEventEmitter} returns the instance of the class for chaining
  1889. */
  1890. once(eventName, listener) {
  1891. const onceListener = (...arguments_) => {
  1892. this.off(eventName, onceListener);
  1893. listener(...arguments_);
  1894. };
  1895. this.on(eventName, onceListener);
  1896. return this;
  1897. }
  1898. /**
  1899. * Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
  1900. * @param {string} eventName The event name. Not required
  1901. * @returns {number} The number of listeners
  1902. */
  1903. listenerCount(eventName) {
  1904. if (!eventName) {
  1905. return this.getAllListeners().length;
  1906. }
  1907. const listeners = this._eventListeners.get(eventName);
  1908. return listeners ? listeners.length : 0;
  1909. }
  1910. /**
  1911. * Gets an array of event names
  1912. * @returns {Array<string | symbol>} An array of event names
  1913. */
  1914. eventNames() {
  1915. return Array.from(this._eventListeners.keys());
  1916. }
  1917. /**
  1918. * Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
  1919. * @param {string} [event] (Optional) The event name
  1920. * @returns {EventListener[]} An array of listeners
  1921. */
  1922. rawListeners(event) {
  1923. if (!event) {
  1924. return this.getAllListeners();
  1925. }
  1926. return this._eventListeners.get(event) ?? [];
  1927. }
  1928. /**
  1929. * Prepends a listener to the beginning of the listeners array for the specified event
  1930. * @param {string | symbol} eventName
  1931. * @param {EventListener} listener
  1932. * @returns {IEventEmitter} returns the instance of the class for chaining
  1933. */
  1934. prependListener(eventName, listener) {
  1935. const listeners = this._eventListeners.get(eventName) ?? [];
  1936. listeners.unshift(listener);
  1937. this._eventListeners.set(eventName, listeners);
  1938. return this;
  1939. }
  1940. /**
  1941. * Prepends a one-time listener to the beginning of the listeners array for the specified event
  1942. * @param {string | symbol} eventName
  1943. * @param {EventListener} listener
  1944. * @returns {IEventEmitter} returns the instance of the class for chaining
  1945. */
  1946. prependOnceListener(eventName, listener) {
  1947. const onceListener = (...arguments_) => {
  1948. this.off(eventName, onceListener);
  1949. listener(...arguments_);
  1950. };
  1951. this.prependListener(eventName, onceListener);
  1952. return this;
  1953. }
  1954. /**
  1955. * Gets the maximum number of listeners that can be added for a single event
  1956. * @returns {number} The maximum number of listeners
  1957. */
  1958. maxListeners() {
  1959. return this._maxListeners;
  1960. }
  1961. /**
  1962. * Adds a listener for a specific event. It is an alias for the on() method
  1963. * @param {string | symbol} event
  1964. * @param {EventListener} listener
  1965. * @returns {IEventEmitter} returns the instance of the class for chaining
  1966. */
  1967. addListener(event, listener) {
  1968. this.on(event, listener);
  1969. return this;
  1970. }
  1971. /**
  1972. * Adds a listener for a specific event
  1973. * @param {string | symbol} event
  1974. * @param {EventListener} listener
  1975. * @returns {IEventEmitter} returns the instance of the class for chaining
  1976. */
  1977. on(event, listener) {
  1978. if (!this._eventListeners.has(event)) {
  1979. this._eventListeners.set(event, []);
  1980. }
  1981. const listeners = this._eventListeners.get(event);
  1982. if (listeners) {
  1983. if (listeners.length >= this._maxListeners) {
  1984. console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${listeners.length + 1} ${event} listeners added. Use setMaxListeners() to increase limit.`);
  1985. }
  1986. listeners.push(listener);
  1987. }
  1988. return this;
  1989. }
  1990. /**
  1991. * Removes a listener for a specific event. It is an alias for the off() method
  1992. * @param {string | symbol} event
  1993. * @param {EventListener} listener
  1994. * @returns {IEventEmitter} returns the instance of the class for chaining
  1995. */
  1996. removeListener(event, listener) {
  1997. this.off(event, listener);
  1998. return this;
  1999. }
  2000. /**
  2001. * Removes a listener for a specific event
  2002. * @param {string | symbol} event
  2003. * @param {EventListener} listener
  2004. * @returns {IEventEmitter} returns the instance of the class for chaining
  2005. */
  2006. off(event, listener) {
  2007. const listeners = this._eventListeners.get(event) ?? [];
  2008. const index = listeners.indexOf(listener);
  2009. if (index !== -1) {
  2010. listeners.splice(index, 1);
  2011. }
  2012. if (listeners.length === 0) {
  2013. this._eventListeners.delete(event);
  2014. }
  2015. return this;
  2016. }
  2017. /**
  2018. * Calls all listeners for a specific event
  2019. * @param {string | symbol} event
  2020. * @param arguments_ The arguments to pass to the listeners
  2021. * @returns {boolean} Returns true if the event had listeners, false otherwise
  2022. */
  2023. emit(event, ...arguments_) {
  2024. let result = false;
  2025. const listeners = this._eventListeners.get(event);
  2026. if (listeners && listeners.length > 0) {
  2027. for (const listener of listeners) {
  2028. listener(...arguments_);
  2029. result = true;
  2030. }
  2031. }
  2032. return result;
  2033. }
  2034. /**
  2035. * Gets all listeners for a specific event. If no event is provided, it returns all listeners
  2036. * @param {string} [event] (Optional) The event name
  2037. * @returns {EventListener[]} An array of listeners
  2038. */
  2039. listeners(event) {
  2040. return this._eventListeners.get(event) ?? [];
  2041. }
  2042. /**
  2043. * Removes all listeners for a specific event. If no event is provided, it removes all listeners
  2044. * @param {string} [event] (Optional) The event name
  2045. * @returns {IEventEmitter} returns the instance of the class for chaining
  2046. */
  2047. removeAllListeners(event) {
  2048. if (event) {
  2049. this._eventListeners.delete(event);
  2050. } else {
  2051. this._eventListeners.clear();
  2052. }
  2053. return this;
  2054. }
  2055. /**
  2056. * Sets the maximum number of listeners that can be added for a single event
  2057. * @param {number} n The maximum number of listeners
  2058. * @returns {void}
  2059. */
  2060. setMaxListeners(n) {
  2061. this._maxListeners = n;
  2062. for (const listeners of this._eventListeners.values()) {
  2063. if (listeners.length > n) {
  2064. listeners.splice(n);
  2065. }
  2066. }
  2067. }
  2068. /**
  2069. * Gets all listeners
  2070. * @returns {EventListener[]} An array of listeners
  2071. */
  2072. getAllListeners() {
  2073. let result = new Array();
  2074. for (const listeners of this._eventListeners.values()) {
  2075. result = result.concat(listeners);
  2076. }
  2077. return result;
  2078. }
  2079. };
  2080. var Hookified = class extends Eventified {
  2081. _hooks;
  2082. _throwHookErrors = false;
  2083. constructor(options) {
  2084. super();
  2085. this._hooks = /* @__PURE__ */ new Map();
  2086. if ((options == null ? void 0 : options.throwHookErrors) !== void 0) {
  2087. this._throwHookErrors = options.throwHookErrors;
  2088. }
  2089. }
  2090. /**
  2091. * Gets all hooks
  2092. * @returns {Map<string, Hook[]>}
  2093. */
  2094. get hooks() {
  2095. return this._hooks;
  2096. }
  2097. /**
  2098. * Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
  2099. * @returns {boolean}
  2100. */
  2101. get throwHookErrors() {
  2102. return this._throwHookErrors;
  2103. }
  2104. /**
  2105. * Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
  2106. * @param {boolean} value
  2107. */
  2108. set throwHookErrors(value) {
  2109. this._throwHookErrors = value;
  2110. }
  2111. /**
  2112. * Adds a handler function for a specific event
  2113. * @param {string} event
  2114. * @param {Hook} handler - this can be async or sync
  2115. * @returns {void}
  2116. */
  2117. onHook(event, handler) {
  2118. const eventHandlers = this._hooks.get(event);
  2119. if (eventHandlers) {
  2120. eventHandlers.push(handler);
  2121. } else {
  2122. this._hooks.set(event, [handler]);
  2123. }
  2124. }
  2125. /**
  2126. * Adds a handler function for a specific event that runs before all other handlers
  2127. * @param {string} event
  2128. * @param {Hook} handler - this can be async or sync
  2129. * @returns {void}
  2130. */
  2131. prependHook(event, handler) {
  2132. const eventHandlers = this._hooks.get(event);
  2133. if (eventHandlers) {
  2134. eventHandlers.unshift(handler);
  2135. } else {
  2136. this._hooks.set(event, [handler]);
  2137. }
  2138. }
  2139. /**
  2140. * Adds a handler that only executes once for a specific event before all other handlers
  2141. * @param event
  2142. * @param handler
  2143. */
  2144. prependOnceHook(event, handler) {
  2145. const hook = async (...arguments_) => {
  2146. this.removeHook(event, hook);
  2147. return handler(...arguments_);
  2148. };
  2149. this.prependHook(event, hook);
  2150. }
  2151. /**
  2152. * Adds a handler that only executes once for a specific event
  2153. * @param event
  2154. * @param handler
  2155. */
  2156. onceHook(event, handler) {
  2157. const hook = async (...arguments_) => {
  2158. this.removeHook(event, hook);
  2159. return handler(...arguments_);
  2160. };
  2161. this.onHook(event, hook);
  2162. }
  2163. /**
  2164. * Removes a handler function for a specific event
  2165. * @param {string} event
  2166. * @param {Hook} handler
  2167. * @returns {void}
  2168. */
  2169. removeHook(event, handler) {
  2170. const eventHandlers = this._hooks.get(event);
  2171. if (eventHandlers) {
  2172. const index = eventHandlers.indexOf(handler);
  2173. if (index !== -1) {
  2174. eventHandlers.splice(index, 1);
  2175. }
  2176. }
  2177. }
  2178. /**
  2179. * Calls all handlers for a specific event
  2180. * @param {string} event
  2181. * @param {T[]} arguments_
  2182. * @returns {Promise<void>}
  2183. */
  2184. async hook(event, ...arguments_) {
  2185. const eventHandlers = this._hooks.get(event);
  2186. if (eventHandlers) {
  2187. for (const handler of eventHandlers) {
  2188. try {
  2189. await handler(...arguments_);
  2190. } catch (error) {
  2191. const message = `${event}: ${error.message}`;
  2192. this.emit("error", new Error(message));
  2193. if (this._throwHookErrors) {
  2194. throw new Error(message);
  2195. }
  2196. }
  2197. }
  2198. }
  2199. }
  2200. /**
  2201. * Gets all hooks for a specific event
  2202. * @param {string} event
  2203. * @returns {Hook[]}
  2204. */
  2205. getHooks(event) {
  2206. return this._hooks.get(event);
  2207. }
  2208. /**
  2209. * Removes all hooks
  2210. * @returns {void}
  2211. */
  2212. clearHooks() {
  2213. this._hooks.clear();
  2214. }
  2215. };
  2216. // node_modules/cacheable/dist/index.js
  2217. import * as crypto from "crypto";
  2218. var structuredClone = globalThis.structuredClone ?? ((value) => JSON.parse(JSON.stringify(value)));
  2219. var shorthandToMilliseconds = (shorthand) => {
  2220. let milliseconds;
  2221. if (shorthand === void 0) {
  2222. return void 0;
  2223. }
  2224. if (typeof shorthand === "number") {
  2225. milliseconds = shorthand;
  2226. } else if (typeof shorthand === "string") {
  2227. shorthand = shorthand.trim();
  2228. if (Number.isNaN(Number(shorthand))) {
  2229. const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
  2230. if (!match) {
  2231. throw new Error(
  2232. `Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`
  2233. );
  2234. }
  2235. const [, value, unit] = match;
  2236. const numericValue = Number.parseFloat(value);
  2237. const unitLower = unit.toLowerCase();
  2238. switch (unitLower) {
  2239. case "ms": {
  2240. milliseconds = numericValue;
  2241. break;
  2242. }
  2243. case "s": {
  2244. milliseconds = numericValue * 1e3;
  2245. break;
  2246. }
  2247. case "m": {
  2248. milliseconds = numericValue * 1e3 * 60;
  2249. break;
  2250. }
  2251. case "h": {
  2252. milliseconds = numericValue * 1e3 * 60 * 60;
  2253. break;
  2254. }
  2255. case "hr": {
  2256. milliseconds = numericValue * 1e3 * 60 * 60;
  2257. break;
  2258. }
  2259. case "d": {
  2260. milliseconds = numericValue * 1e3 * 60 * 60 * 24;
  2261. break;
  2262. }
  2263. /* c8 ignore next 3 */
  2264. default: {
  2265. milliseconds = Number(shorthand);
  2266. }
  2267. }
  2268. } else {
  2269. milliseconds = Number(shorthand);
  2270. }
  2271. } else {
  2272. throw new TypeError("Time must be a string or a number.");
  2273. }
  2274. return milliseconds;
  2275. };
  2276. var shorthandToTime = (shorthand, fromDate) => {
  2277. fromDate || (fromDate = /* @__PURE__ */ new Date());
  2278. const milliseconds = shorthandToMilliseconds(shorthand);
  2279. if (milliseconds === void 0) {
  2280. return fromDate.getTime();
  2281. }
  2282. return fromDate.getTime() + milliseconds;
  2283. };
  2284. function hash(object2, algorithm = "sha256") {
  2285. const objectString = JSON.stringify(object2);
  2286. if (!crypto.getHashes().includes(algorithm)) {
  2287. throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
  2288. }
  2289. const hasher = crypto.createHash(algorithm);
  2290. hasher.update(objectString);
  2291. return hasher.digest("hex");
  2292. }
  2293. function wrapSync(function_, options) {
  2294. const { ttl, keyPrefix, cache } = options;
  2295. return function(...arguments_) {
  2296. const cacheKey = createWrapKey(function_, arguments_, keyPrefix);
  2297. let value = cache.get(cacheKey);
  2298. if (value === void 0) {
  2299. try {
  2300. value = function_(...arguments_);
  2301. cache.set(cacheKey, value, ttl);
  2302. } catch (error) {
  2303. cache.emit("error", error);
  2304. if (options.cacheErrors) {
  2305. cache.set(cacheKey, error, ttl);
  2306. }
  2307. }
  2308. }
  2309. return value;
  2310. };
  2311. }
  2312. function createWrapKey(function_, arguments_, keyPrefix) {
  2313. if (!keyPrefix) {
  2314. return `${function_.name}::${hash(arguments_)}`;
  2315. }
  2316. return `${keyPrefix}::${function_.name}::${hash(arguments_)}`;
  2317. }
  2318. var ListNode = class {
  2319. // eslint-disable-next-line @typescript-eslint/parameter-properties
  2320. value;
  2321. prev = void 0;
  2322. next = void 0;
  2323. constructor(value) {
  2324. this.value = value;
  2325. }
  2326. };
  2327. var DoublyLinkedList = class {
  2328. head = void 0;
  2329. tail = void 0;
  2330. nodesMap = /* @__PURE__ */ new Map();
  2331. // Add a new node to the front (most recently used)
  2332. addToFront(value) {
  2333. const newNode = new ListNode(value);
  2334. if (this.head) {
  2335. newNode.next = this.head;
  2336. this.head.prev = newNode;
  2337. this.head = newNode;
  2338. } else {
  2339. this.head = this.tail = newNode;
  2340. }
  2341. this.nodesMap.set(value, newNode);
  2342. }
  2343. // Move an existing node to the front (most recently used)
  2344. moveToFront(value) {
  2345. const node = this.nodesMap.get(value);
  2346. if (!node || this.head === node) {
  2347. return;
  2348. }
  2349. if (node.prev) {
  2350. node.prev.next = node.next;
  2351. }
  2352. if (node.next) {
  2353. node.next.prev = node.prev;
  2354. }
  2355. if (node === this.tail) {
  2356. this.tail = node.prev;
  2357. }
  2358. node.prev = void 0;
  2359. node.next = this.head;
  2360. if (this.head) {
  2361. this.head.prev = node;
  2362. }
  2363. this.head = node;
  2364. this.tail || (this.tail = node);
  2365. }
  2366. // Get the oldest node (tail)
  2367. getOldest() {
  2368. return this.tail ? this.tail.value : void 0;
  2369. }
  2370. // Remove the oldest node (tail)
  2371. removeOldest() {
  2372. if (!this.tail) {
  2373. return void 0;
  2374. }
  2375. const oldValue = this.tail.value;
  2376. if (this.tail.prev) {
  2377. this.tail = this.tail.prev;
  2378. this.tail.next = void 0;
  2379. } else {
  2380. this.head = this.tail = void 0;
  2381. }
  2382. this.nodesMap.delete(oldValue);
  2383. return oldValue;
  2384. }
  2385. get size() {
  2386. return this.nodesMap.size;
  2387. }
  2388. };
  2389. var CacheableMemory = class extends Hookified {
  2390. _lru = new DoublyLinkedList();
  2391. _hashCache = /* @__PURE__ */ new Map();
  2392. _hash0 = /* @__PURE__ */ new Map();
  2393. _hash1 = /* @__PURE__ */ new Map();
  2394. _hash2 = /* @__PURE__ */ new Map();
  2395. _hash3 = /* @__PURE__ */ new Map();
  2396. _hash4 = /* @__PURE__ */ new Map();
  2397. _hash5 = /* @__PURE__ */ new Map();
  2398. _hash6 = /* @__PURE__ */ new Map();
  2399. _hash7 = /* @__PURE__ */ new Map();
  2400. _hash8 = /* @__PURE__ */ new Map();
  2401. _hash9 = /* @__PURE__ */ new Map();
  2402. _ttl;
  2403. // Turned off by default
  2404. _useClone = true;
  2405. // Turned on by default
  2406. _lruSize = 0;
  2407. // Turned off by default
  2408. _checkInterval = 0;
  2409. // Turned off by default
  2410. _interval = 0;
  2411. // Turned off by default
  2412. /**
  2413. * @constructor
  2414. * @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
  2415. */
  2416. constructor(options) {
  2417. super();
  2418. if (options == null ? void 0 : options.ttl) {
  2419. this.setTtl(options.ttl);
  2420. }
  2421. if ((options == null ? void 0 : options.useClone) !== void 0) {
  2422. this._useClone = options.useClone;
  2423. }
  2424. if (options == null ? void 0 : options.lruSize) {
  2425. this._lruSize = options.lruSize;
  2426. }
  2427. if (options == null ? void 0 : options.checkInterval) {
  2428. this._checkInterval = options.checkInterval;
  2429. }
  2430. this.startIntervalCheck();
  2431. }
  2432. /**
  2433. * Gets the time-to-live
  2434. * @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
  2435. */
  2436. get ttl() {
  2437. return this._ttl;
  2438. }
  2439. /**
  2440. * Sets the time-to-live
  2441. * @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
  2442. */
  2443. set ttl(value) {
  2444. this.setTtl(value);
  2445. }
  2446. /**
  2447. * Gets whether to use clone
  2448. * @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
  2449. */
  2450. get useClone() {
  2451. return this._useClone;
  2452. }
  2453. /**
  2454. * Sets whether to use clone
  2455. * @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
  2456. */
  2457. set useClone(value) {
  2458. this._useClone = value;
  2459. }
  2460. /**
  2461. * Gets the size of the LRU cache
  2462. * @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0.
  2463. */
  2464. get lruSize() {
  2465. return this._lruSize;
  2466. }
  2467. /**
  2468. * Sets the size of the LRU cache
  2469. * @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0.
  2470. */
  2471. set lruSize(value) {
  2472. this._lruSize = value;
  2473. this.lruResize();
  2474. }
  2475. /**
  2476. * Gets the check interval
  2477. * @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
  2478. */
  2479. get checkInterval() {
  2480. return this._checkInterval;
  2481. }
  2482. /**
  2483. * Sets the check interval
  2484. * @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
  2485. */
  2486. set checkInterval(value) {
  2487. this._checkInterval = value;
  2488. }
  2489. /**
  2490. * Gets the size of the cache
  2491. * @returns {number} - The size of the cache
  2492. */
  2493. get size() {
  2494. return this._hash0.size + this._hash1.size + this._hash2.size + this._hash3.size + this._hash4.size + this._hash5.size + this._hash6.size + this._hash7.size + this._hash8.size + this._hash9.size;
  2495. }
  2496. /**
  2497. * Gets the keys
  2498. * @returns {IterableIterator<string>} - The keys
  2499. */
  2500. get keys() {
  2501. return this.concatStores().keys();
  2502. }
  2503. /**
  2504. * Gets the items
  2505. * @returns {IterableIterator<CacheableStoreItem>} - The items
  2506. */
  2507. get items() {
  2508. return this.concatStores().values();
  2509. }
  2510. /**
  2511. * Gets the value of the key
  2512. * @param {string} key - The key to get the value
  2513. * @returns {T | undefined} - The value of the key
  2514. */
  2515. get(key) {
  2516. const store = this.getStore(key);
  2517. const item = store.get(key);
  2518. if (!item) {
  2519. return void 0;
  2520. }
  2521. if (item.expires && item.expires && Date.now() > item.expires) {
  2522. store.delete(key);
  2523. return void 0;
  2524. }
  2525. this.lruMoveToFront(key);
  2526. if (!this._useClone) {
  2527. return item.value;
  2528. }
  2529. return this.clone(item.value);
  2530. }
  2531. /**
  2532. * Gets the values of the keys
  2533. * @param {string[]} keys - The keys to get the values
  2534. * @returns {T[]} - The values of the keys
  2535. */
  2536. getMany(keys2) {
  2537. const result = new Array();
  2538. for (const key of keys2) {
  2539. result.push(this.get(key));
  2540. }
  2541. return result;
  2542. }
  2543. /**
  2544. * Gets the raw value of the key
  2545. * @param {string} key - The key to get the value
  2546. * @returns {CacheableStoreItem | undefined} - The raw value of the key
  2547. */
  2548. getRaw(key) {
  2549. const store = this.getStore(key);
  2550. const item = store.get(key);
  2551. if (!item) {
  2552. return void 0;
  2553. }
  2554. if (item.expires && item.expires && Date.now() > item.expires) {
  2555. store.delete(key);
  2556. return void 0;
  2557. }
  2558. this.lruMoveToFront(key);
  2559. return item;
  2560. }
  2561. /**
  2562. * Gets the raw values of the keys
  2563. * @param {string[]} keys - The keys to get the values
  2564. * @returns {CacheableStoreItem[]} - The raw values of the keys
  2565. */
  2566. getManyRaw(keys2) {
  2567. const result = new Array();
  2568. for (const key of keys2) {
  2569. result.push(this.getRaw(key));
  2570. }
  2571. return result;
  2572. }
  2573. /**
  2574. * Sets the value of the key
  2575. * @param {string} key - The key to set the value
  2576. * @param {any} value - The value to set
  2577. * @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
  2578. * If you want to set expire directly you can do that by setting the expire property in the SetOptions.
  2579. * If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
  2580. * @returns {void}
  2581. */
  2582. set(key, value, ttl) {
  2583. const store = this.getStore(key);
  2584. let expires;
  2585. if (ttl !== void 0 || this._ttl !== void 0) {
  2586. if (typeof ttl === "object") {
  2587. if (ttl.expire) {
  2588. expires = typeof ttl.expire === "number" ? ttl.expire : ttl.expire.getTime();
  2589. }
  2590. if (ttl.ttl) {
  2591. const finalTtl = shorthandToTime(ttl.ttl);
  2592. if (finalTtl !== void 0) {
  2593. expires = finalTtl;
  2594. }
  2595. }
  2596. } else {
  2597. const finalTtl = shorthandToTime(ttl ?? this._ttl);
  2598. if (finalTtl !== void 0) {
  2599. expires = finalTtl;
  2600. }
  2601. }
  2602. }
  2603. if (this._lruSize > 0) {
  2604. if (store.has(key)) {
  2605. this.lruMoveToFront(key);
  2606. } else {
  2607. this.lruAddToFront(key);
  2608. if (this._lru.size > this._lruSize) {
  2609. const oldestKey = this._lru.getOldest();
  2610. if (oldestKey) {
  2611. this._lru.removeOldest();
  2612. this.delete(oldestKey);
  2613. }
  2614. }
  2615. }
  2616. }
  2617. const item = { key, value, expires };
  2618. store.set(
  2619. key,
  2620. item
  2621. );
  2622. }
  2623. /**
  2624. * Sets the values of the keys
  2625. * @param {CacheableItem[]} items - The items to set
  2626. * @returns {void}
  2627. */
  2628. setMany(items) {
  2629. for (const item of items) {
  2630. this.set(item.key, item.value, item.ttl);
  2631. }
  2632. }
  2633. /**
  2634. * Checks if the key exists
  2635. * @param {string} key - The key to check
  2636. * @returns {boolean} - If true, the key exists. If false, the key does not exist.
  2637. */
  2638. has(key) {
  2639. const item = this.get(key);
  2640. return Boolean(item);
  2641. }
  2642. /**
  2643. * @function hasMany
  2644. * @param {string[]} keys - The keys to check
  2645. * @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
  2646. */
  2647. hasMany(keys2) {
  2648. const result = new Array();
  2649. for (const key of keys2) {
  2650. const item = this.get(key);
  2651. result.push(Boolean(item));
  2652. }
  2653. return result;
  2654. }
  2655. /**
  2656. * Take will get the key and delete the entry from cache
  2657. * @param {string} key - The key to take
  2658. * @returns {T | undefined} - The value of the key
  2659. */
  2660. take(key) {
  2661. const item = this.get(key);
  2662. if (!item) {
  2663. return void 0;
  2664. }
  2665. this.delete(key);
  2666. return item;
  2667. }
  2668. /**
  2669. * TakeMany will get the keys and delete the entries from cache
  2670. * @param {string[]} keys - The keys to take
  2671. * @returns {T[]} - The values of the keys
  2672. */
  2673. takeMany(keys2) {
  2674. const result = new Array();
  2675. for (const key of keys2) {
  2676. result.push(this.take(key));
  2677. }
  2678. return result;
  2679. }
  2680. /**
  2681. * Delete the key
  2682. * @param {string} key - The key to delete
  2683. * @returns {void}
  2684. */
  2685. delete(key) {
  2686. const store = this.getStore(key);
  2687. store.delete(key);
  2688. }
  2689. /**
  2690. * Delete the keys
  2691. * @param {string[]} keys - The keys to delete
  2692. * @returns {void}
  2693. */
  2694. deleteMany(keys2) {
  2695. for (const key of keys2) {
  2696. this.delete(key);
  2697. }
  2698. }
  2699. /**
  2700. * Clear the cache
  2701. * @returns {void}
  2702. */
  2703. clear() {
  2704. this._hash0.clear();
  2705. this._hash1.clear();
  2706. this._hash2.clear();
  2707. this._hash3.clear();
  2708. this._hash4.clear();
  2709. this._hash5.clear();
  2710. this._hash6.clear();
  2711. this._hash7.clear();
  2712. this._hash8.clear();
  2713. this._hash9.clear();
  2714. this._hashCache.clear();
  2715. this._lru = new DoublyLinkedList();
  2716. }
  2717. /**
  2718. * Get the store based on the key (internal use)
  2719. * @param {string} key - The key to get the store
  2720. * @returns {CacheableHashStore} - The store
  2721. */
  2722. getStore(key) {
  2723. const hash2 = this.hashKey(key);
  2724. return this.getStoreFromHash(hash2);
  2725. }
  2726. /**
  2727. * Get the store based on the hash (internal use)
  2728. * @param {number} hash
  2729. * @returns {Map<string, CacheableStoreItem>}
  2730. */
  2731. getStoreFromHash(hash2) {
  2732. switch (hash2) {
  2733. case 1: {
  2734. return this._hash1;
  2735. }
  2736. case 2: {
  2737. return this._hash2;
  2738. }
  2739. case 3: {
  2740. return this._hash3;
  2741. }
  2742. case 4: {
  2743. return this._hash4;
  2744. }
  2745. case 5: {
  2746. return this._hash5;
  2747. }
  2748. case 6: {
  2749. return this._hash6;
  2750. }
  2751. case 7: {
  2752. return this._hash7;
  2753. }
  2754. case 8: {
  2755. return this._hash8;
  2756. }
  2757. case 9: {
  2758. return this._hash9;
  2759. }
  2760. default: {
  2761. return this._hash0;
  2762. }
  2763. }
  2764. }
  2765. /**
  2766. * Hash the key (internal use)
  2767. * @param key
  2768. * @returns {number} from 0 to 9
  2769. */
  2770. hashKey(key) {
  2771. const cacheHashNumber = this._hashCache.get(key);
  2772. if (cacheHashNumber) {
  2773. return cacheHashNumber;
  2774. }
  2775. let hash2 = 0;
  2776. const primeMultiplier = 31;
  2777. for (let i = 0; i < key.length; i++) {
  2778. hash2 = hash2 * primeMultiplier + key.charCodeAt(i);
  2779. }
  2780. const result = Math.abs(hash2) % 10;
  2781. this._hashCache.set(key, result);
  2782. return result;
  2783. }
  2784. /**
  2785. * Clone the value. This is for internal use
  2786. * @param {any} value - The value to clone
  2787. * @returns {any} - The cloned value
  2788. */
  2789. clone(value) {
  2790. if (this.isPrimitive(value)) {
  2791. return value;
  2792. }
  2793. return structuredClone(value);
  2794. }
  2795. /**
  2796. * Add to the front of the LRU cache. This is for internal use
  2797. * @param {string} key - The key to add to the front
  2798. * @returns {void}
  2799. */
  2800. lruAddToFront(key) {
  2801. if (this._lruSize === 0) {
  2802. return;
  2803. }
  2804. this._lru.addToFront(key);
  2805. }
  2806. /**
  2807. * Move to the front of the LRU cache. This is for internal use
  2808. * @param {string} key - The key to move to the front
  2809. * @returns {void}
  2810. */
  2811. lruMoveToFront(key) {
  2812. if (this._lruSize === 0) {
  2813. return;
  2814. }
  2815. this._lru.moveToFront(key);
  2816. }
  2817. /**
  2818. * Resize the LRU cache. This is for internal use
  2819. * @returns {void}
  2820. */
  2821. lruResize() {
  2822. if (this._lruSize === 0) {
  2823. return;
  2824. }
  2825. while (this._lru.size > this._lruSize) {
  2826. const oldestKey = this._lru.getOldest();
  2827. if (oldestKey) {
  2828. this._lru.removeOldest();
  2829. this.delete(oldestKey);
  2830. }
  2831. }
  2832. }
  2833. /**
  2834. * Check for expiration. This is for internal use
  2835. * @returns {void}
  2836. */
  2837. checkExpiration() {
  2838. const stores = this.concatStores();
  2839. for (const item of stores.values()) {
  2840. if (item.expires && Date.now() > item.expires) {
  2841. this.delete(item.key);
  2842. }
  2843. }
  2844. }
  2845. /**
  2846. * Start the interval check. This is for internal use
  2847. * @returns {void}
  2848. */
  2849. startIntervalCheck() {
  2850. if (this._checkInterval > 0) {
  2851. if (this._interval) {
  2852. clearInterval(this._interval);
  2853. }
  2854. this._interval = setInterval(() => {
  2855. this.checkExpiration();
  2856. }, this._checkInterval).unref();
  2857. }
  2858. }
  2859. /**
  2860. * Stop the interval check. This is for internal use
  2861. * @returns {void}
  2862. */
  2863. stopIntervalCheck() {
  2864. if (this._interval) {
  2865. clearInterval(this._interval);
  2866. }
  2867. this._interval = 0;
  2868. this._checkInterval = 0;
  2869. }
  2870. /**
  2871. * Hash the object. This is for internal use
  2872. * @param {any} object - The object to hash
  2873. * @param {string} [algorithm='sha256'] - The algorithm to hash
  2874. * @returns {string} - The hashed string
  2875. */
  2876. hash(object2, algorithm = "sha256") {
  2877. return hash(object2, algorithm);
  2878. }
  2879. /**
  2880. * Wrap the function for caching
  2881. * @param {Function} function_ - The function to wrap
  2882. * @param {Object} [options] - The options to wrap
  2883. * @returns {Function} - The wrapped function
  2884. */
  2885. wrap(function_, options) {
  2886. const wrapOptions = {
  2887. ttl: (options == null ? void 0 : options.ttl) ?? this._ttl,
  2888. keyPrefix: options == null ? void 0 : options.keyPrefix,
  2889. cache: this
  2890. };
  2891. return wrapSync(function_, wrapOptions);
  2892. }
  2893. isPrimitive(value) {
  2894. const result = false;
  2895. if (value === null || value === void 0) {
  2896. return true;
  2897. }
  2898. if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
  2899. return true;
  2900. }
  2901. return result;
  2902. }
  2903. concatStores() {
  2904. return new Map([...this._hash0, ...this._hash1, ...this._hash2, ...this._hash3, ...this._hash4, ...this._hash5, ...this._hash6, ...this._hash7, ...this._hash8, ...this._hash9]);
  2905. }
  2906. setTtl(ttl) {
  2907. if (typeof ttl === "string" || ttl === void 0) {
  2908. this._ttl = ttl;
  2909. } else if (ttl > 0) {
  2910. this._ttl = ttl;
  2911. } else {
  2912. this._ttl = void 0;
  2913. }
  2914. }
  2915. };
  2916. // node_modules/flatted/esm/index.js
  2917. var { parse: $parse, stringify: $stringify } = JSON;
  2918. var { keys } = Object;
  2919. var Primitive = String;
  2920. var primitive = "string";
  2921. var ignore = {};
  2922. var object = "object";
  2923. var noop = (_2, value) => value;
  2924. var primitives = (value) => value instanceof Primitive ? Primitive(value) : value;
  2925. var Primitives = (_2, value) => typeof value === primitive ? new Primitive(value) : value;
  2926. var revive = (input, parsed, output, $) => {
  2927. const lazy = [];
  2928. for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) {
  2929. const k = ke[y];
  2930. const value = output[k];
  2931. if (value instanceof Primitive) {
  2932. const tmp = input[value];
  2933. if (typeof tmp === object && !parsed.has(tmp)) {
  2934. parsed.add(tmp);
  2935. output[k] = ignore;
  2936. lazy.push({ k, a: [input, parsed, tmp, $] });
  2937. } else
  2938. output[k] = $.call(output, k, tmp);
  2939. } else if (output[k] !== ignore)
  2940. output[k] = $.call(output, k, value);
  2941. }
  2942. for (let { length } = lazy, i = 0; i < length; i++) {
  2943. const { k, a } = lazy[i];
  2944. output[k] = $.call(output, k, revive.apply(null, a));
  2945. }
  2946. return output;
  2947. };
  2948. var set = (known, input, value) => {
  2949. const index = Primitive(input.push(value) - 1);
  2950. known.set(value, index);
  2951. return index;
  2952. };
  2953. var parse = (text, reviver) => {
  2954. const input = $parse(text, Primitives).map(primitives);
  2955. const value = input[0];
  2956. const $ = reviver || noop;
  2957. const tmp = typeof value === object && value ? revive(input, /* @__PURE__ */ new Set(), value, $) : value;
  2958. return $.call({ "": tmp }, "", tmp);
  2959. };
  2960. var stringify2 = (value, replacer, space) => {
  2961. const $ = replacer && typeof replacer === object ? (k, v) => k === "" || -1 < replacer.indexOf(k) ? v : void 0 : replacer || noop;
  2962. const known = /* @__PURE__ */ new Map();
  2963. const input = [];
  2964. const output = [];
  2965. let i = +set(known, input, $.call({ "": value }, "", value));
  2966. let firstRun = !i;
  2967. while (i < input.length) {
  2968. firstRun = true;
  2969. output[i] = $stringify(input[i++], replace, space);
  2970. }
  2971. return "[" + output.join(",") + "]";
  2972. function replace(key, value2) {
  2973. if (firstRun) {
  2974. firstRun = !firstRun;
  2975. return value2;
  2976. }
  2977. const after = $.call(this, key, value2);
  2978. switch (typeof after) {
  2979. case object:
  2980. if (after === null) return after;
  2981. case primitive:
  2982. return known.get(after) || set(known, input, after);
  2983. }
  2984. return after;
  2985. }
  2986. };
  2987. // node_modules/file-entry-cache/node_modules/flat-cache/dist/index.js
  2988. var FlatCache = class extends Hookified {
  2989. _cache = new CacheableMemory();
  2990. _cacheDir = ".cache";
  2991. _cacheId = "cache1";
  2992. _persistInterval = 0;
  2993. _persistTimer;
  2994. _changesSinceLastSave = false;
  2995. _parse = parse;
  2996. _stringify = stringify2;
  2997. constructor(options) {
  2998. super();
  2999. if (options) {
  3000. this._cache = new CacheableMemory({
  3001. ttl: options.ttl,
  3002. useClone: options.useClone,
  3003. lruSize: options.lruSize,
  3004. checkInterval: options.expirationInterval
  3005. });
  3006. }
  3007. if (options == null ? void 0 : options.cacheDir) {
  3008. this._cacheDir = options.cacheDir;
  3009. }
  3010. if (options == null ? void 0 : options.cacheId) {
  3011. this._cacheId = options.cacheId;
  3012. }
  3013. if (options == null ? void 0 : options.persistInterval) {
  3014. this._persistInterval = options.persistInterval;
  3015. this.startAutoPersist();
  3016. }
  3017. if (options == null ? void 0 : options.deserialize) {
  3018. this._parse = options.deserialize;
  3019. }
  3020. if (options == null ? void 0 : options.serialize) {
  3021. this._stringify = options.serialize;
  3022. }
  3023. }
  3024. /**
  3025. * The cache object
  3026. * @property cache
  3027. * @type {CacheableMemory}
  3028. */
  3029. get cache() {
  3030. return this._cache;
  3031. }
  3032. /**
  3033. * The cache directory
  3034. * @property cacheDir
  3035. * @type {String}
  3036. * @default '.cache'
  3037. */
  3038. get cacheDir() {
  3039. return this._cacheDir;
  3040. }
  3041. /**
  3042. * Set the cache directory
  3043. * @property cacheDir
  3044. * @type {String}
  3045. * @default '.cache'
  3046. */
  3047. set cacheDir(value) {
  3048. this._cacheDir = value;
  3049. }
  3050. /**
  3051. * The cache id
  3052. * @property cacheId
  3053. * @type {String}
  3054. * @default 'cache1'
  3055. */
  3056. get cacheId() {
  3057. return this._cacheId;
  3058. }
  3059. /**
  3060. * Set the cache id
  3061. * @property cacheId
  3062. * @type {String}
  3063. * @default 'cache1'
  3064. */
  3065. set cacheId(value) {
  3066. this._cacheId = value;
  3067. }
  3068. /**
  3069. * The flag to indicate if there are changes since the last save
  3070. * @property changesSinceLastSave
  3071. * @type {Boolean}
  3072. * @default false
  3073. */
  3074. get changesSinceLastSave() {
  3075. return this._changesSinceLastSave;
  3076. }
  3077. /**
  3078. * The interval to persist the cache to disk. 0 means no timed persistence
  3079. * @property persistInterval
  3080. * @type {Number}
  3081. * @default 0
  3082. */
  3083. get persistInterval() {
  3084. return this._persistInterval;
  3085. }
  3086. /**
  3087. * Set the interval to persist the cache to disk. 0 means no timed persistence
  3088. * @property persistInterval
  3089. * @type {Number}
  3090. * @default 0
  3091. */
  3092. set persistInterval(value) {
  3093. this._persistInterval = value;
  3094. }
  3095. /**
  3096. * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
  3097. * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
  3098. * then the cache module directory `.cacheDir` will be used instead
  3099. *
  3100. * @method load
  3101. * @param cacheId {String} the id of the cache, would also be used as the name of the file cache
  3102. * @param cacheDir {String} directory for the cache entry
  3103. */
  3104. // eslint-disable-next-line unicorn/prevent-abbreviations
  3105. load(cacheId, cacheDir) {
  3106. try {
  3107. const filePath = path9.resolve(`${cacheDir ?? this._cacheDir}/${cacheId ?? this._cacheId}`);
  3108. this.loadFile(filePath);
  3109. this.emit(
  3110. "load"
  3111. /* LOAD */
  3112. );
  3113. } catch (error) {
  3114. this.emit("error", error);
  3115. }
  3116. }
  3117. /**
  3118. * Load the cache from the provided file
  3119. * @method loadFile
  3120. * @param {String} pathToFile the path to the file containing the info for the cache
  3121. */
  3122. loadFile(pathToFile) {
  3123. if (fs5.existsSync(pathToFile)) {
  3124. const data = fs5.readFileSync(pathToFile, "utf8");
  3125. const items = this._parse(data);
  3126. for (const key of Object.keys(items)) {
  3127. this._cache.set(items[key].key, items[key].value, { expire: items[key].expires });
  3128. }
  3129. this._changesSinceLastSave = true;
  3130. }
  3131. }
  3132. /**
  3133. * Returns the entire persisted object
  3134. * @method all
  3135. * @returns {*}
  3136. */
  3137. all() {
  3138. const result = {};
  3139. const items = Array.from(this._cache.items);
  3140. for (const item of items) {
  3141. result[item.key] = item.value;
  3142. }
  3143. return result;
  3144. }
  3145. /**
  3146. * Returns an array with all the items in the cache { key, value, ttl }
  3147. * @method items
  3148. * @returns {Array}
  3149. */
  3150. get items() {
  3151. return Array.from(this._cache.items);
  3152. }
  3153. /**
  3154. * Returns the path to the file where the cache is persisted
  3155. * @method cacheFilePath
  3156. * @returns {String}
  3157. */
  3158. get cacheFilePath() {
  3159. return path9.resolve(`${this._cacheDir}/${this._cacheId}`);
  3160. }
  3161. /**
  3162. * Returns the path to the cache directory
  3163. * @method cacheDirPath
  3164. * @returns {String}
  3165. */
  3166. get cacheDirPath() {
  3167. return path9.resolve(this._cacheDir);
  3168. }
  3169. /**
  3170. * Returns an array with all the keys in the cache
  3171. * @method keys
  3172. * @returns {Array}
  3173. */
  3174. keys() {
  3175. return Array.from(this._cache.keys);
  3176. }
  3177. /**
  3178. * (Legacy) set key method. This method will be deprecated in the future
  3179. * @method setKey
  3180. * @param key {string} the key to set
  3181. * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
  3182. */
  3183. setKey(key, value, ttl) {
  3184. this.set(key, value, ttl);
  3185. }
  3186. /**
  3187. * Sets a key to a given value
  3188. * @method set
  3189. * @param key {string} the key to set
  3190. * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
  3191. * @param [ttl] {number} the time to live in milliseconds
  3192. */
  3193. set(key, value, ttl) {
  3194. this._cache.set(key, value, ttl);
  3195. this._changesSinceLastSave = true;
  3196. }
  3197. /**
  3198. * (Legacy) Remove a given key from the cache. This method will be deprecated in the future
  3199. * @method removeKey
  3200. * @param key {String} the key to remove from the object
  3201. */
  3202. removeKey(key) {
  3203. this.delete(key);
  3204. }
  3205. /**
  3206. * Remove a given key from the cache
  3207. * @method delete
  3208. * @param key {String} the key to remove from the object
  3209. */
  3210. delete(key) {
  3211. this._cache.delete(key);
  3212. this._changesSinceLastSave = true;
  3213. this.emit("delete", key);
  3214. }
  3215. /**
  3216. * (Legacy) Return the value of the provided key. This method will be deprecated in the future
  3217. * @method getKey<T>
  3218. * @param key {String} the name of the key to retrieve
  3219. * @returns {*} at T the value from the key
  3220. */
  3221. getKey(key) {
  3222. return this.get(key);
  3223. }
  3224. /**
  3225. * Return the value of the provided key
  3226. * @method get<T>
  3227. * @param key {String} the name of the key to retrieve
  3228. * @returns {*} at T the value from the key
  3229. */
  3230. get(key) {
  3231. return this._cache.get(key);
  3232. }
  3233. /**
  3234. * Clear the cache and save the state to disk
  3235. * @method clear
  3236. */
  3237. clear() {
  3238. try {
  3239. this._cache.clear();
  3240. this._changesSinceLastSave = true;
  3241. this.save();
  3242. this.emit(
  3243. "clear"
  3244. /* CLEAR */
  3245. );
  3246. } catch (error) {
  3247. this.emit("error", error);
  3248. }
  3249. }
  3250. /**
  3251. * Save the state of the cache identified by the docId to disk
  3252. * as a JSON structure
  3253. * @method save
  3254. */
  3255. save(force = false) {
  3256. try {
  3257. if (this._changesSinceLastSave || force) {
  3258. const filePath = this.cacheFilePath;
  3259. const items = Array.from(this._cache.items);
  3260. const data = this._stringify(items);
  3261. if (!fs5.existsSync(this._cacheDir)) {
  3262. fs5.mkdirSync(this._cacheDir, { recursive: true });
  3263. }
  3264. fs5.writeFileSync(filePath, data);
  3265. this._changesSinceLastSave = false;
  3266. this.emit(
  3267. "save"
  3268. /* SAVE */
  3269. );
  3270. }
  3271. } catch (error) {
  3272. this.emit("error", error);
  3273. }
  3274. }
  3275. /**
  3276. * Remove the file where the cache is persisted
  3277. * @method removeCacheFile
  3278. * @return {Boolean} true or false if the file was successfully deleted
  3279. */
  3280. removeCacheFile() {
  3281. try {
  3282. if (fs5.existsSync(this.cacheFilePath)) {
  3283. fs5.rmSync(this.cacheFilePath);
  3284. return true;
  3285. }
  3286. } catch (error) {
  3287. this.emit("error", error);
  3288. }
  3289. return false;
  3290. }
  3291. /**
  3292. * Destroy the cache. This will remove the directory, file, and memory cache
  3293. * @method destroy
  3294. * @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
  3295. * @return {undefined}
  3296. */
  3297. destroy(includeCacheDirectory = false) {
  3298. try {
  3299. this._cache.clear();
  3300. this.stopAutoPersist();
  3301. if (includeCacheDirectory) {
  3302. fs5.rmSync(this.cacheDirPath, { recursive: true, force: true });
  3303. } else {
  3304. fs5.rmSync(this.cacheFilePath, { recursive: true, force: true });
  3305. }
  3306. this._changesSinceLastSave = false;
  3307. this.emit(
  3308. "destroy"
  3309. /* DESTROY */
  3310. );
  3311. } catch (error) {
  3312. this.emit("error", error);
  3313. }
  3314. }
  3315. /**
  3316. * Start the auto persist interval
  3317. * @method startAutoPersist
  3318. */
  3319. startAutoPersist() {
  3320. if (this._persistInterval > 0) {
  3321. if (this._persistTimer) {
  3322. clearInterval(this._persistTimer);
  3323. this._persistTimer = void 0;
  3324. }
  3325. this._persistTimer = setInterval(() => {
  3326. this.save();
  3327. }, this._persistInterval);
  3328. }
  3329. }
  3330. /**
  3331. * Stop the auto persist interval
  3332. * @method stopAutoPersist
  3333. */
  3334. stopAutoPersist() {
  3335. if (this._persistTimer) {
  3336. clearInterval(this._persistTimer);
  3337. this._persistTimer = void 0;
  3338. }
  3339. }
  3340. };
  3341. function createFromFile(filePath, options) {
  3342. const cache = new FlatCache(options);
  3343. cache.loadFile(filePath);
  3344. return cache;
  3345. }
  3346. // node_modules/file-entry-cache/dist/index.js
  3347. function createFromFile2(filePath, useCheckSum, currentWorkingDirectory) {
  3348. const fname = path10.basename(filePath);
  3349. const directory = path10.dirname(filePath);
  3350. return create(fname, directory, useCheckSum, currentWorkingDirectory);
  3351. }
  3352. function create(cacheId, cacheDirectory, useCheckSum, currentWorkingDirectory) {
  3353. const options = {
  3354. currentWorkingDirectory,
  3355. useCheckSum,
  3356. cache: {
  3357. cacheId,
  3358. cacheDir: cacheDirectory
  3359. }
  3360. };
  3361. const fileEntryCache = new FileEntryCache(options);
  3362. if (cacheDirectory) {
  3363. const cachePath = `${cacheDirectory}/${cacheId}`;
  3364. if (fs6.existsSync(cachePath)) {
  3365. fileEntryCache.cache = createFromFile(cachePath, options.cache);
  3366. }
  3367. }
  3368. return fileEntryCache;
  3369. }
  3370. var FileEntryDefault = class {
  3371. static create = create;
  3372. static createFromFile = createFromFile2;
  3373. };
  3374. var FileEntryCache = class {
  3375. _cache = new FlatCache({ useClone: false });
  3376. _useCheckSum = false;
  3377. _currentWorkingDirectory;
  3378. _hashAlgorithm = "md5";
  3379. constructor(options) {
  3380. if (options == null ? void 0 : options.cache) {
  3381. this._cache = new FlatCache(options.cache);
  3382. }
  3383. if (options == null ? void 0 : options.useCheckSum) {
  3384. this._useCheckSum = options.useCheckSum;
  3385. }
  3386. if (options == null ? void 0 : options.currentWorkingDirectory) {
  3387. this._currentWorkingDirectory = options.currentWorkingDirectory;
  3388. }
  3389. if (options == null ? void 0 : options.hashAlgorithm) {
  3390. this._hashAlgorithm = options.hashAlgorithm;
  3391. }
  3392. }
  3393. get cache() {
  3394. return this._cache;
  3395. }
  3396. set cache(cache) {
  3397. this._cache = cache;
  3398. }
  3399. get useCheckSum() {
  3400. return this._useCheckSum;
  3401. }
  3402. set useCheckSum(value) {
  3403. this._useCheckSum = value;
  3404. }
  3405. get hashAlgorithm() {
  3406. return this._hashAlgorithm;
  3407. }
  3408. set hashAlgorithm(value) {
  3409. this._hashAlgorithm = value;
  3410. }
  3411. get currentWorkingDirectory() {
  3412. return this._currentWorkingDirectory;
  3413. }
  3414. set currentWorkingDirectory(value) {
  3415. this._currentWorkingDirectory = value;
  3416. }
  3417. /**
  3418. * Given a buffer, calculate md5 hash of its content.
  3419. * @method getHash
  3420. * @param {Buffer} buffer buffer to calculate hash on
  3421. * @return {String} content hash digest
  3422. */
  3423. // eslint-disable-next-line @typescript-eslint/ban-types
  3424. getHash(buffer) {
  3425. return crypto2.createHash(this._hashAlgorithm).update(buffer).digest("hex");
  3426. }
  3427. /**
  3428. * Create the key for the file path used for caching.
  3429. * @method createFileKey
  3430. * @param {String} filePath
  3431. * @return {String}
  3432. */
  3433. createFileKey(filePath, options) {
  3434. let result = filePath;
  3435. const currentWorkingDirectory = (options == null ? void 0 : options.currentWorkingDirectory) ?? this._currentWorkingDirectory;
  3436. if (currentWorkingDirectory && filePath.startsWith(currentWorkingDirectory)) {
  3437. const splitPath = filePath.split(currentWorkingDirectory).pop();
  3438. if (splitPath) {
  3439. result = splitPath;
  3440. if (result.startsWith("/")) {
  3441. result = result.slice(1);
  3442. }
  3443. }
  3444. }
  3445. return result;
  3446. }
  3447. /**
  3448. * Check if the file path is a relative path
  3449. * @method isRelativePath
  3450. * @param filePath - The file path to check
  3451. * @returns {boolean} if the file path is a relative path, false otherwise
  3452. */
  3453. isRelativePath(filePath) {
  3454. return !path10.isAbsolute(filePath);
  3455. }
  3456. /**
  3457. * Delete the cache file from the disk
  3458. * @method deleteCacheFile
  3459. * @return {boolean} true if the file was deleted, false otherwise
  3460. */
  3461. deleteCacheFile() {
  3462. return this._cache.removeCacheFile();
  3463. }
  3464. /**
  3465. * Remove the cache from the file and clear the memory cache
  3466. * @method destroy
  3467. */
  3468. destroy() {
  3469. this._cache.destroy();
  3470. }
  3471. /**
  3472. * Remove and Entry From the Cache
  3473. * @method removeEntry
  3474. * @param filePath - The file path to remove from the cache
  3475. */
  3476. removeEntry(filePath, options) {
  3477. if (this.isRelativePath(filePath)) {
  3478. filePath = this.getAbsolutePath(filePath, { currentWorkingDirectory: options == null ? void 0 : options.currentWorkingDirectory });
  3479. this._cache.removeKey(this.createFileKey(filePath));
  3480. }
  3481. const key = this.createFileKey(filePath, { currentWorkingDirectory: options == null ? void 0 : options.currentWorkingDirectory });
  3482. this._cache.removeKey(key);
  3483. }
  3484. /**
  3485. * Reconcile the cache
  3486. * @method reconcile
  3487. */
  3488. reconcile() {
  3489. const items = this._cache.items;
  3490. for (const item of items) {
  3491. const fileDescriptor = this.getFileDescriptor(item.key);
  3492. if (fileDescriptor.notFound) {
  3493. this._cache.removeKey(item.key);
  3494. }
  3495. }
  3496. this._cache.save();
  3497. }
  3498. /**
  3499. * Check if the file has changed
  3500. * @method hasFileChanged
  3501. * @param filePath - The file path to check
  3502. * @returns {boolean} if the file has changed, false otherwise
  3503. */
  3504. hasFileChanged(filePath) {
  3505. let result = false;
  3506. const fileDescriptor = this.getFileDescriptor(filePath);
  3507. if ((!fileDescriptor.err || !fileDescriptor.notFound) && fileDescriptor.changed) {
  3508. result = true;
  3509. }
  3510. return result;
  3511. }
  3512. /**
  3513. * Get the file descriptor for the file path
  3514. * @method getFileDescriptor
  3515. * @param filePath - The file path to get the file descriptor for
  3516. * @param options - The options for getting the file descriptor
  3517. * @returns The file descriptor
  3518. */
  3519. getFileDescriptor(filePath, options) {
  3520. var _a, _b, _c;
  3521. let fstat;
  3522. const result = {
  3523. key: this.createFileKey(filePath),
  3524. changed: false,
  3525. meta: {}
  3526. };
  3527. result.meta = this._cache.getKey(result.key) ?? {};
  3528. filePath = this.getAbsolutePath(filePath, { currentWorkingDirectory: options == null ? void 0 : options.currentWorkingDirectory });
  3529. const useCheckSumValue = (options == null ? void 0 : options.useCheckSum) ?? this._useCheckSum;
  3530. try {
  3531. fstat = fs6.statSync(filePath);
  3532. result.meta = {
  3533. size: fstat.size
  3534. };
  3535. result.meta.mtime = fstat.mtime.getTime();
  3536. if (useCheckSumValue) {
  3537. const buffer = fs6.readFileSync(filePath);
  3538. result.meta.hash = this.getHash(buffer);
  3539. }
  3540. } catch (error) {
  3541. this.removeEntry(filePath);
  3542. let notFound = false;
  3543. if (error.message.includes("ENOENT")) {
  3544. notFound = true;
  3545. }
  3546. return {
  3547. key: result.key,
  3548. err: error,
  3549. notFound,
  3550. meta: {}
  3551. };
  3552. }
  3553. const metaCache = this._cache.getKey(result.key);
  3554. if (!metaCache) {
  3555. result.changed = true;
  3556. this._cache.setKey(result.key, result.meta);
  3557. return result;
  3558. }
  3559. if (result.meta.data === void 0) {
  3560. result.meta.data = metaCache.data;
  3561. }
  3562. if ((metaCache == null ? void 0 : metaCache.mtime) !== ((_a = result.meta) == null ? void 0 : _a.mtime) || (metaCache == null ? void 0 : metaCache.size) !== ((_b = result.meta) == null ? void 0 : _b.size)) {
  3563. result.changed = true;
  3564. }
  3565. if (useCheckSumValue && (metaCache == null ? void 0 : metaCache.hash) !== ((_c = result.meta) == null ? void 0 : _c.hash)) {
  3566. result.changed = true;
  3567. }
  3568. this._cache.setKey(result.key, result.meta);
  3569. return result;
  3570. }
  3571. /**
  3572. * Get the file descriptors for the files
  3573. * @method normalizeEntries
  3574. * @param files?: string[] - The files to get the file descriptors for
  3575. * @returns The file descriptors
  3576. */
  3577. normalizeEntries(files) {
  3578. const result = new Array();
  3579. if (files) {
  3580. for (const file of files) {
  3581. const fileDescriptor = this.getFileDescriptor(file);
  3582. result.push(fileDescriptor);
  3583. }
  3584. return result;
  3585. }
  3586. const keys2 = this.cache.keys();
  3587. for (const key of keys2) {
  3588. const fileDescriptor = this.getFileDescriptor(key);
  3589. if (!fileDescriptor.notFound && !fileDescriptor.err) {
  3590. result.push(fileDescriptor);
  3591. }
  3592. }
  3593. return result;
  3594. }
  3595. /**
  3596. * Analyze the files
  3597. * @method analyzeFiles
  3598. * @param files - The files to analyze
  3599. * @returns {AnalyzedFiles} The analysis of the files
  3600. */
  3601. analyzeFiles(files) {
  3602. const result = {
  3603. changedFiles: [],
  3604. notFoundFiles: [],
  3605. notChangedFiles: []
  3606. };
  3607. const fileDescriptors = this.normalizeEntries(files);
  3608. for (const fileDescriptor of fileDescriptors) {
  3609. if (fileDescriptor.notFound) {
  3610. result.notFoundFiles.push(fileDescriptor.key);
  3611. } else if (fileDescriptor.changed) {
  3612. result.changedFiles.push(fileDescriptor.key);
  3613. } else {
  3614. result.notChangedFiles.push(fileDescriptor.key);
  3615. }
  3616. }
  3617. return result;
  3618. }
  3619. /**
  3620. * Get the updated files
  3621. * @method getUpdatedFiles
  3622. * @param files - The files to get the updated files for
  3623. * @returns {string[]} The updated files
  3624. */
  3625. getUpdatedFiles(files) {
  3626. const result = new Array();
  3627. const fileDescriptors = this.normalizeEntries(files);
  3628. for (const fileDescriptor of fileDescriptors) {
  3629. if (fileDescriptor.changed) {
  3630. result.push(fileDescriptor.key);
  3631. }
  3632. }
  3633. return result;
  3634. }
  3635. /**
  3636. * Get the not found files
  3637. * @method getFileDescriptorsByPath
  3638. * @param filePath - the files that you want to get from a path
  3639. * @returns {FileDescriptor[]} The not found files
  3640. */
  3641. getFileDescriptorsByPath(filePath) {
  3642. const result = new Array();
  3643. const keys2 = this._cache.keys();
  3644. for (const key of keys2) {
  3645. const absolutePath = this.getAbsolutePath(filePath);
  3646. if (absolutePath.startsWith(filePath)) {
  3647. const fileDescriptor = this.getFileDescriptor(key);
  3648. result.push(fileDescriptor);
  3649. }
  3650. }
  3651. return result;
  3652. }
  3653. /**
  3654. * Get the Absolute Path. If it is already absolute it will return the path as is.
  3655. * @method getAbsolutePath
  3656. * @param filePath - The file path to get the absolute path for
  3657. * @param options - The options for getting the absolute path. The current working directory is used if not provided.
  3658. * @returns {string}
  3659. */
  3660. getAbsolutePath(filePath, options) {
  3661. if (this.isRelativePath(filePath)) {
  3662. const currentWorkingDirectory = (options == null ? void 0 : options.currentWorkingDirectory) ?? this._currentWorkingDirectory ?? process.cwd();
  3663. filePath = path10.resolve(currentWorkingDirectory, filePath);
  3664. }
  3665. return filePath;
  3666. }
  3667. /**
  3668. * Rename the absolute path keys. This is used when a directory is changed or renamed.
  3669. * @method renameAbsolutePathKeys
  3670. * @param oldPath - The old path to rename
  3671. * @param newPath - The new path to rename to
  3672. */
  3673. renameAbsolutePathKeys(oldPath, newPath) {
  3674. const keys2 = this._cache.keys();
  3675. for (const key of keys2) {
  3676. if (key.startsWith(oldPath)) {
  3677. const newKey = key.replace(oldPath, newPath);
  3678. const meta = this._cache.getKey(key);
  3679. this._cache.removeKey(key);
  3680. this._cache.setKey(newKey, meta);
  3681. }
  3682. }
  3683. }
  3684. };
  3685. // src/cli/format-results-cache.js
  3686. import { version as prettierVersion } from "../index.mjs";
  3687. var optionsHashCache = /* @__PURE__ */ new WeakMap();
  3688. var nodeVersion = process.version;
  3689. function getHashOfOptions(options) {
  3690. if (optionsHashCache.has(options)) {
  3691. return optionsHashCache.get(options);
  3692. }
  3693. const hash2 = createHash(
  3694. `${prettierVersion}_${nodeVersion}_${(0, import_fast_json_stable_stringify2.default)(options)}`
  3695. );
  3696. optionsHashCache.set(options, hash2);
  3697. return hash2;
  3698. }
  3699. function getMetadataFromFileDescriptor(fileDescriptor) {
  3700. return fileDescriptor.meta;
  3701. }
  3702. var _fileEntryCache;
  3703. var FormatResultsCache = class {
  3704. /**
  3705. * @param {string} cacheFileLocation The path of cache file location. (default: `node_modules/.cache/prettier/.prettier-cache`)
  3706. * @param {string} cacheStrategy
  3707. */
  3708. constructor(cacheFileLocation, cacheStrategy) {
  3709. __privateAdd(this, _fileEntryCache);
  3710. const useChecksum = cacheStrategy === "content";
  3711. try {
  3712. __privateSet(this, _fileEntryCache, FileEntryDefault.createFromFile(
  3713. /* filePath */
  3714. cacheFileLocation,
  3715. useChecksum
  3716. ));
  3717. } catch {
  3718. if (fs7.existsSync(cacheFileLocation)) {
  3719. fs7.unlinkSync(cacheFileLocation);
  3720. __privateSet(this, _fileEntryCache, FileEntryDefault.createFromFile(
  3721. /* filePath */
  3722. cacheFileLocation,
  3723. useChecksum
  3724. ));
  3725. }
  3726. }
  3727. }
  3728. /**
  3729. * @param {string} filePath
  3730. * @param {any} options
  3731. */
  3732. existsAvailableFormatResultsCache(filePath, options) {
  3733. var _a;
  3734. const fileDescriptor = __privateGet(this, _fileEntryCache).getFileDescriptor(filePath);
  3735. if (fileDescriptor.notFound || fileDescriptor.changed) {
  3736. return false;
  3737. }
  3738. const hashOfOptions = (_a = getMetadataFromFileDescriptor(fileDescriptor).data) == null ? void 0 : _a.hashOfOptions;
  3739. return hashOfOptions && hashOfOptions === getHashOfOptions(options);
  3740. }
  3741. /**
  3742. * @param {string} filePath
  3743. * @param {any} options
  3744. */
  3745. setFormatResultsCache(filePath, options) {
  3746. const fileDescriptor = __privateGet(this, _fileEntryCache).getFileDescriptor(filePath);
  3747. if (!fileDescriptor.notFound) {
  3748. const meta = getMetadataFromFileDescriptor(fileDescriptor);
  3749. meta.data = { ...meta.data, hashOfOptions: getHashOfOptions(options) };
  3750. }
  3751. }
  3752. /**
  3753. * @param {string} filePath
  3754. */
  3755. removeFormatResultsCache(filePath) {
  3756. __privateGet(this, _fileEntryCache).removeEntry(filePath);
  3757. }
  3758. reconcile() {
  3759. __privateGet(this, _fileEntryCache).reconcile();
  3760. }
  3761. };
  3762. _fileEntryCache = new WeakMap();
  3763. var format_results_cache_default = FormatResultsCache;
  3764. // src/cli/is-tty.js
  3765. function isTTY() {
  3766. return process.stdout.isTTY && !mockable.isCI();
  3767. }
  3768. // src/cli/options/get-options-for-file.js
  3769. var import_dashify2 = __toESM(require_dashify(), 1);
  3770. import { resolveConfig } from "../index.mjs";
  3771. function getOptions(argv, detailedOptions) {
  3772. return Object.fromEntries(
  3773. detailedOptions.filter(({ forwardToApi }) => forwardToApi).map(({ forwardToApi, name }) => [forwardToApi, argv[name]])
  3774. );
  3775. }
  3776. function cliifyOptions(object2, apiDetailedOptionMap) {
  3777. return Object.fromEntries(
  3778. Object.entries(object2 || {}).map(([key, value]) => {
  3779. const apiOption = apiDetailedOptionMap[key];
  3780. const cliKey = apiOption ? apiOption.name : key;
  3781. return [(0, import_dashify2.default)(cliKey), value];
  3782. })
  3783. );
  3784. }
  3785. function createApiDetailedOptionMap(detailedOptions) {
  3786. return Object.fromEntries(
  3787. detailedOptions.filter(
  3788. (option) => option.forwardToApi && option.forwardToApi !== option.name
  3789. ).map((option) => [option.forwardToApi, option])
  3790. );
  3791. }
  3792. function parseArgsToOptions(context, overrideDefaults) {
  3793. const minimistOptions = createMinimistOptions(context.detailedOptions);
  3794. const apiDetailedOptionMap = createApiDetailedOptionMap(
  3795. context.detailedOptions
  3796. );
  3797. return getOptions(
  3798. normalize_cli_options_default(
  3799. minimistParse(context.rawArguments, {
  3800. string: minimistOptions.string,
  3801. boolean: minimistOptions.boolean,
  3802. default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
  3803. }),
  3804. context.detailedOptions,
  3805. { logger: false }
  3806. ),
  3807. context.detailedOptions
  3808. );
  3809. }
  3810. async function getOptionsOrDie(context, filePath) {
  3811. try {
  3812. if (context.argv.config === false) {
  3813. context.logger.debug(
  3814. "'--no-config' option found, skip loading config file."
  3815. );
  3816. return null;
  3817. }
  3818. context.logger.debug(
  3819. context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`
  3820. );
  3821. const options = await resolveConfig(filePath, {
  3822. editorconfig: context.argv.editorconfig,
  3823. config: context.argv.config
  3824. });
  3825. context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
  3826. return options;
  3827. } catch (error) {
  3828. context.logger.error(
  3829. `Invalid configuration${filePath ? ` for file "${filePath}"` : ""}:
  3830. ` + error.message
  3831. );
  3832. process.exit(2);
  3833. }
  3834. }
  3835. function applyConfigPrecedence(context, options) {
  3836. try {
  3837. switch (context.argv.configPrecedence) {
  3838. case "cli-override":
  3839. return parseArgsToOptions(context, options);
  3840. case "file-override":
  3841. return { ...parseArgsToOptions(context), ...options };
  3842. case "prefer-file":
  3843. return options || parseArgsToOptions(context);
  3844. }
  3845. } catch (error) {
  3846. context.logger.error(error.toString());
  3847. process.exit(2);
  3848. }
  3849. }
  3850. async function getOptionsForFile(context, filepath) {
  3851. const options = await getOptionsOrDie(context, filepath);
  3852. const hasPlugins = options == null ? void 0 : options.plugins;
  3853. if (hasPlugins) {
  3854. await context.pushContextPlugins(options.plugins);
  3855. }
  3856. const appliedOptions = {
  3857. filepath,
  3858. ...applyConfigPrecedence(
  3859. context,
  3860. options && normalizeOptions(options, context.supportOptions, {
  3861. logger: context.logger
  3862. })
  3863. )
  3864. };
  3865. context.logger.debug(
  3866. `applied config-precedence (${context.argv.configPrecedence}): ${JSON.stringify(appliedOptions)}`
  3867. );
  3868. if (hasPlugins) {
  3869. context.popContextPlugins();
  3870. }
  3871. return appliedOptions;
  3872. }
  3873. var get_options_for_file_default = getOptionsForFile;
  3874. // src/cli/format.js
  3875. var { getStdin, writeFormattedFile } = mockable;
  3876. function diff(a, b) {
  3877. return createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
  3878. }
  3879. var DebugError = class extends Error {
  3880. name = "DebugError";
  3881. };
  3882. function handleError(context, filename, error, printedFilename, ignoreUnknown) {
  3883. ignoreUnknown || (ignoreUnknown = context.argv.ignoreUnknown);
  3884. const errorIsUndefinedParseError = error instanceof errors.UndefinedParserError;
  3885. if (printedFilename) {
  3886. if ((context.argv.write || ignoreUnknown) && errorIsUndefinedParseError) {
  3887. printedFilename.clear();
  3888. } else {
  3889. process.stdout.write("\n");
  3890. }
  3891. }
  3892. if (errorIsUndefinedParseError) {
  3893. if (ignoreUnknown) {
  3894. return;
  3895. }
  3896. if (!context.argv.check && !context.argv.listDifferent) {
  3897. process.exitCode = 2;
  3898. }
  3899. context.logger.error(error.message);
  3900. return;
  3901. }
  3902. const isParseError = Boolean(error == null ? void 0 : error.loc);
  3903. const isValidationError = /^Invalid \S+ value\./u.test(error == null ? void 0 : error.message);
  3904. if (isParseError) {
  3905. context.logger.error(`${filename}: ${String(error)}`);
  3906. } else if (isValidationError || error instanceof errors.ConfigError) {
  3907. context.logger.error(error.message);
  3908. process.exit(1);
  3909. } else if (error instanceof DebugError) {
  3910. context.logger.error(`${filename}: ${error.message}`);
  3911. } else {
  3912. context.logger.error(filename + ": " + (error.stack || error));
  3913. }
  3914. process.exitCode = 2;
  3915. }
  3916. function writeOutput(context, result, options) {
  3917. process.stdout.write(
  3918. context.argv.debugCheck ? result.filepath : result.formatted
  3919. );
  3920. if (options && options.cursorOffset >= 0) {
  3921. process.stderr.write(result.cursorOffset + "\n");
  3922. }
  3923. }
  3924. async function listDifferent(context, input, options, filename) {
  3925. if (!context.argv.check && !context.argv.listDifferent) {
  3926. return;
  3927. }
  3928. try {
  3929. if (!await prettier.check(input, options) && !context.argv.write) {
  3930. context.logger.log(filename);
  3931. process.exitCode = 1;
  3932. }
  3933. } catch (error) {
  3934. context.logger.error(error.message);
  3935. }
  3936. return true;
  3937. }
  3938. async function format3(context, input, opt) {
  3939. if (context.argv.debugPrintDoc) {
  3940. const doc = await prettier.__debug.printToDoc(input, opt);
  3941. return { formatted: await prettier.__debug.formatDoc(doc) + "\n" };
  3942. }
  3943. if (context.argv.debugPrintComments) {
  3944. return {
  3945. formatted: await prettier.format(
  3946. JSON.stringify(
  3947. (await prettier.formatWithCursor(input, opt)).comments || []
  3948. ),
  3949. { parser: "json" }
  3950. )
  3951. };
  3952. }
  3953. if (context.argv.debugPrintAst) {
  3954. const { ast } = await prettier.__debug.parse(input, opt);
  3955. return {
  3956. formatted: JSON.stringify(ast)
  3957. };
  3958. }
  3959. if (context.argv.debugCheck) {
  3960. const pp = await prettier.format(input, opt);
  3961. const pppp = await prettier.format(pp, opt);
  3962. if (pp !== pppp) {
  3963. throw new DebugError(
  3964. "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp)
  3965. );
  3966. } else {
  3967. const stringify5 = (obj) => JSON.stringify(obj, null, 2);
  3968. const ast = stringify5(
  3969. (await prettier.__debug.parse(input, opt, { massage: true })).ast
  3970. );
  3971. const past = stringify5(
  3972. (await prettier.__debug.parse(pp, opt, { massage: true })).ast
  3973. );
  3974. if (ast !== past) {
  3975. const MAX_AST_SIZE = 2097152;
  3976. const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
  3977. throw new DebugError(
  3978. "ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp)
  3979. );
  3980. }
  3981. }
  3982. return { formatted: pp, filepath: opt.filepath || "(stdin)\n" };
  3983. }
  3984. const { performanceTestFlag } = context;
  3985. if (performanceTestFlag == null ? void 0 : performanceTestFlag.debugBenchmark) {
  3986. let benchmark;
  3987. try {
  3988. ({ default: benchmark } = await import("benchmark"));
  3989. } catch {
  3990. context.logger.debug(
  3991. "'--debug-benchmark' requires the 'benchmark' package to be installed."
  3992. );
  3993. process.exit(2);
  3994. }
  3995. context.logger.debug(
  3996. "'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module."
  3997. );
  3998. const suite = new benchmark.Suite();
  3999. suite.add("format", {
  4000. defer: true,
  4001. async fn(deferred) {
  4002. await prettier.formatWithCursor(input, opt);
  4003. deferred.resolve();
  4004. }
  4005. });
  4006. const result = await new Promise((resolve) => {
  4007. suite.on("complete", (event) => {
  4008. resolve({
  4009. benchmark: String(event.target),
  4010. hz: event.target.hz,
  4011. ms: event.target.times.cycle * 1e3
  4012. });
  4013. }).run({ async: false });
  4014. });
  4015. context.logger.debug(
  4016. "'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(result, null, 2)
  4017. );
  4018. } else if (performanceTestFlag == null ? void 0 : performanceTestFlag.debugRepeat) {
  4019. const repeat = performanceTestFlag.debugRepeat;
  4020. context.logger.debug(
  4021. `'${performanceTestFlag.name}' found, running formatWithCursor ${repeat} times.`
  4022. );
  4023. let totalMs = 0;
  4024. for (let i = 0; i < repeat; ++i) {
  4025. const startMs = Date.now();
  4026. await prettier.formatWithCursor(input, opt);
  4027. totalMs += Date.now() - startMs;
  4028. }
  4029. const averageMs = totalMs / repeat;
  4030. const results = {
  4031. repeat,
  4032. hz: 1e3 / averageMs,
  4033. ms: averageMs
  4034. };
  4035. context.logger.debug(
  4036. `'${performanceTestFlag.name}' measurements for formatWithCursor: ${JSON.stringify(
  4037. results,
  4038. null,
  4039. 2
  4040. )}`
  4041. );
  4042. }
  4043. return prettier.formatWithCursor(input, opt);
  4044. }
  4045. async function createIsIgnoredFromContextOrDie(context) {
  4046. try {
  4047. return await createIsIgnoredFunction(
  4048. context.argv.ignorePath,
  4049. context.argv.withNodeModules
  4050. );
  4051. } catch (e) {
  4052. context.logger.error(e.message);
  4053. process.exit(2);
  4054. }
  4055. }
  4056. async function formatStdin(context) {
  4057. const { filepath } = context.argv;
  4058. try {
  4059. const input = await getStdin();
  4060. let isFileIgnored = false;
  4061. if (filepath) {
  4062. const isIgnored = await createIsIgnoredFromContextOrDie(context);
  4063. isFileIgnored = isIgnored(filepath);
  4064. }
  4065. if (isFileIgnored) {
  4066. writeOutput(context, { formatted: input });
  4067. return;
  4068. }
  4069. const options = await get_options_for_file_default(
  4070. context,
  4071. filepath ? path11.resolve(filepath) : void 0
  4072. );
  4073. if (await listDifferent(context, input, options, "(stdin)")) {
  4074. return;
  4075. }
  4076. const formatted = await format3(context, input, options);
  4077. const { performanceTestFlag } = context;
  4078. if (performanceTestFlag) {
  4079. context.logger.log(
  4080. `'${performanceTestFlag.name}' option found, skipped print code to screen.`
  4081. );
  4082. return;
  4083. }
  4084. writeOutput(context, formatted, options);
  4085. } catch (error) {
  4086. handleError(context, filepath || "stdin", error);
  4087. }
  4088. }
  4089. async function formatFiles(context) {
  4090. const isIgnored = await createIsIgnoredFromContextOrDie(context);
  4091. const cwd2 = process.cwd();
  4092. let numberOfUnformattedFilesFound = 0;
  4093. const { performanceTestFlag } = context;
  4094. if (context.argv.check && !performanceTestFlag) {
  4095. context.logger.log("Checking formatting...");
  4096. }
  4097. let formatResultsCache;
  4098. const cacheFilePath = await find_cache_file_default(context.argv.cacheLocation);
  4099. if (context.argv.cache) {
  4100. formatResultsCache = new format_results_cache_default(
  4101. cacheFilePath,
  4102. context.argv.cacheStrategy || "content"
  4103. );
  4104. } else if (!context.argv.cacheLocation) {
  4105. const stat = await statSafe(cacheFilePath);
  4106. if (stat) {
  4107. await fs8.unlink(cacheFilePath);
  4108. }
  4109. }
  4110. for await (const { error, filename, ignoreUnknown } of expandPatterns(
  4111. context
  4112. )) {
  4113. if (error) {
  4114. context.logger.error(error);
  4115. process.exitCode = 2;
  4116. continue;
  4117. }
  4118. const isFileIgnored = isIgnored(filename);
  4119. if (isFileIgnored && (context.argv.debugCheck || context.argv.write || context.argv.check || context.argv.listDifferent)) {
  4120. continue;
  4121. }
  4122. const options = {
  4123. ...await get_options_for_file_default(context, filename),
  4124. filepath: filename
  4125. };
  4126. const fileNameToDisplay = normalizeToPosix(path11.relative(cwd2, filename));
  4127. let printedFilename;
  4128. if (isTTY()) {
  4129. printedFilename = context.logger.log(fileNameToDisplay, {
  4130. newline: false,
  4131. clearable: true
  4132. });
  4133. }
  4134. let input;
  4135. try {
  4136. input = await fs8.readFile(filename, "utf8");
  4137. } catch (error2) {
  4138. context.logger.log("");
  4139. context.logger.error(
  4140. `Unable to read file "${fileNameToDisplay}":
  4141. ${error2.message}`
  4142. );
  4143. process.exitCode = 2;
  4144. continue;
  4145. }
  4146. if (isFileIgnored) {
  4147. printedFilename == null ? void 0 : printedFilename.clear();
  4148. writeOutput(context, { formatted: input }, options);
  4149. continue;
  4150. }
  4151. const start = Date.now();
  4152. const isCacheExists = formatResultsCache == null ? void 0 : formatResultsCache.existsAvailableFormatResultsCache(
  4153. filename,
  4154. options
  4155. );
  4156. let result;
  4157. let output;
  4158. try {
  4159. if (isCacheExists) {
  4160. result = { formatted: input };
  4161. } else {
  4162. result = await format3(context, input, options);
  4163. }
  4164. output = result.formatted;
  4165. } catch (error2) {
  4166. handleError(
  4167. context,
  4168. fileNameToDisplay,
  4169. error2,
  4170. printedFilename,
  4171. ignoreUnknown
  4172. );
  4173. continue;
  4174. }
  4175. const isDifferent = output !== input;
  4176. let shouldSetCache = !isDifferent;
  4177. printedFilename == null ? void 0 : printedFilename.clear();
  4178. if (performanceTestFlag) {
  4179. context.logger.log(
  4180. `'${performanceTestFlag.name}' option found, skipped print code or write files.`
  4181. );
  4182. return;
  4183. }
  4184. if (context.argv.write) {
  4185. if (isDifferent) {
  4186. if (!context.argv.check && !context.argv.listDifferent) {
  4187. context.logger.log(`${fileNameToDisplay} ${Date.now() - start}ms`);
  4188. }
  4189. try {
  4190. await writeFormattedFile(filename, output);
  4191. shouldSetCache = true;
  4192. } catch (error2) {
  4193. context.logger.error(
  4194. `Unable to write file "${fileNameToDisplay}":
  4195. ${error2.message}`
  4196. );
  4197. process.exitCode = 2;
  4198. }
  4199. } else if (!context.argv.check && !context.argv.listDifferent) {
  4200. const message = `${source_default.grey(fileNameToDisplay)} ${Date.now() - start}ms (unchanged)`;
  4201. if (isCacheExists) {
  4202. context.logger.log(`${message} (cached)`);
  4203. } else {
  4204. context.logger.log(message);
  4205. }
  4206. }
  4207. } else if (context.argv.debugCheck) {
  4208. if (result.filepath) {
  4209. context.logger.log(fileNameToDisplay);
  4210. } else {
  4211. process.exitCode = 2;
  4212. }
  4213. } else if (!context.argv.check && !context.argv.listDifferent) {
  4214. writeOutput(context, result, options);
  4215. }
  4216. if (shouldSetCache) {
  4217. formatResultsCache == null ? void 0 : formatResultsCache.setFormatResultsCache(filename, options);
  4218. } else {
  4219. formatResultsCache == null ? void 0 : formatResultsCache.removeFormatResultsCache(filename);
  4220. }
  4221. if (isDifferent) {
  4222. if (context.argv.check) {
  4223. context.logger.warn(fileNameToDisplay);
  4224. } else if (context.argv.listDifferent) {
  4225. context.logger.log(fileNameToDisplay);
  4226. }
  4227. numberOfUnformattedFilesFound += 1;
  4228. }
  4229. }
  4230. formatResultsCache == null ? void 0 : formatResultsCache.reconcile();
  4231. if (context.argv.check) {
  4232. if (numberOfUnformattedFilesFound === 0) {
  4233. context.logger.log("All matched files use Prettier code style!");
  4234. } else {
  4235. const files = numberOfUnformattedFilesFound === 1 ? "the above file" : `${numberOfUnformattedFilesFound} files`;
  4236. context.logger.warn(
  4237. context.argv.write ? `Code style issues fixed in ${files}.` : `Code style issues found in ${files}. Run Prettier with --write to fix.`
  4238. );
  4239. }
  4240. }
  4241. if ((context.argv.check || context.argv.listDifferent) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
  4242. process.exitCode = 1;
  4243. }
  4244. }
  4245. // src/cli/logger.js
  4246. import readline from "readline";
  4247. // node_modules/strip-ansi/node_modules/ansi-regex/index.js
  4248. function ansiRegex({ onlyFirst = false } = {}) {
  4249. const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
  4250. const pattern = [
  4251. `[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?${ST})`,
  4252. "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
  4253. ].join("|");
  4254. return new RegExp(pattern, onlyFirst ? void 0 : "g");
  4255. }
  4256. // node_modules/strip-ansi/index.js
  4257. var regex = ansiRegex();
  4258. function stripAnsi(string) {
  4259. if (typeof string !== "string") {
  4260. throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
  4261. }
  4262. return string.replace(regex, "");
  4263. }
  4264. // node_modules/wcwidth.js/combining.js
  4265. var combining_default = [
  4266. [768, 879],
  4267. [1155, 1158],
  4268. [1160, 1161],
  4269. [1425, 1469],
  4270. [1471, 1471],
  4271. [1473, 1474],
  4272. [1476, 1477],
  4273. [1479, 1479],
  4274. [1536, 1539],
  4275. [1552, 1557],
  4276. [1611, 1630],
  4277. [1648, 1648],
  4278. [1750, 1764],
  4279. [1767, 1768],
  4280. [1770, 1773],
  4281. [1807, 1807],
  4282. [1809, 1809],
  4283. [1840, 1866],
  4284. [1958, 1968],
  4285. [2027, 2035],
  4286. [2305, 2306],
  4287. [2364, 2364],
  4288. [2369, 2376],
  4289. [2381, 2381],
  4290. [2385, 2388],
  4291. [2402, 2403],
  4292. [2433, 2433],
  4293. [2492, 2492],
  4294. [2497, 2500],
  4295. [2509, 2509],
  4296. [2530, 2531],
  4297. [2561, 2562],
  4298. [2620, 2620],
  4299. [2625, 2626],
  4300. [2631, 2632],
  4301. [2635, 2637],
  4302. [2672, 2673],
  4303. [2689, 2690],
  4304. [2748, 2748],
  4305. [2753, 2757],
  4306. [2759, 2760],
  4307. [2765, 2765],
  4308. [2786, 2787],
  4309. [2817, 2817],
  4310. [2876, 2876],
  4311. [2879, 2879],
  4312. [2881, 2883],
  4313. [2893, 2893],
  4314. [2902, 2902],
  4315. [2946, 2946],
  4316. [3008, 3008],
  4317. [3021, 3021],
  4318. [3134, 3136],
  4319. [3142, 3144],
  4320. [3146, 3149],
  4321. [3157, 3158],
  4322. [3260, 3260],
  4323. [3263, 3263],
  4324. [3270, 3270],
  4325. [3276, 3277],
  4326. [3298, 3299],
  4327. [3393, 3395],
  4328. [3405, 3405],
  4329. [3530, 3530],
  4330. [3538, 3540],
  4331. [3542, 3542],
  4332. [3633, 3633],
  4333. [3636, 3642],
  4334. [3655, 3662],
  4335. [3761, 3761],
  4336. [3764, 3769],
  4337. [3771, 3772],
  4338. [3784, 3789],
  4339. [3864, 3865],
  4340. [3893, 3893],
  4341. [3895, 3895],
  4342. [3897, 3897],
  4343. [3953, 3966],
  4344. [3968, 3972],
  4345. [3974, 3975],
  4346. [3984, 3991],
  4347. [3993, 4028],
  4348. [4038, 4038],
  4349. [4141, 4144],
  4350. [4146, 4146],
  4351. [4150, 4151],
  4352. [4153, 4153],
  4353. [4184, 4185],
  4354. [4448, 4607],
  4355. [4959, 4959],
  4356. [5906, 5908],
  4357. [5938, 5940],
  4358. [5970, 5971],
  4359. [6002, 6003],
  4360. [6068, 6069],
  4361. [6071, 6077],
  4362. [6086, 6086],
  4363. [6089, 6099],
  4364. [6109, 6109],
  4365. [6155, 6157],
  4366. [6313, 6313],
  4367. [6432, 6434],
  4368. [6439, 6440],
  4369. [6450, 6450],
  4370. [6457, 6459],
  4371. [6679, 6680],
  4372. [6912, 6915],
  4373. [6964, 6964],
  4374. [6966, 6970],
  4375. [6972, 6972],
  4376. [6978, 6978],
  4377. [7019, 7027],
  4378. [7616, 7626],
  4379. [7678, 7679],
  4380. [8203, 8207],
  4381. [8234, 8238],
  4382. [8288, 8291],
  4383. [8298, 8303],
  4384. [8400, 8431],
  4385. [12330, 12335],
  4386. [12441, 12442],
  4387. [43014, 43014],
  4388. [43019, 43019],
  4389. [43045, 43046],
  4390. [64286, 64286],
  4391. [65024, 65039],
  4392. [65056, 65059],
  4393. [65279, 65279],
  4394. [65529, 65531],
  4395. [68097, 68099],
  4396. [68101, 68102],
  4397. [68108, 68111],
  4398. [68152, 68154],
  4399. [68159, 68159],
  4400. [119143, 119145],
  4401. [119155, 119170],
  4402. [119173, 119179],
  4403. [119210, 119213],
  4404. [119362, 119364],
  4405. [917505, 917505],
  4406. [917536, 917631],
  4407. [917760, 917999]
  4408. ];
  4409. // node_modules/wcwidth.js/index.js
  4410. var DEFAULTS = {
  4411. nul: 0,
  4412. control: 0
  4413. };
  4414. function bisearch(ucs) {
  4415. let min = 0;
  4416. let max = combining_default.length - 1;
  4417. let mid;
  4418. if (ucs < combining_default[0][0] || ucs > combining_default[max][1]) return false;
  4419. while (max >= min) {
  4420. mid = Math.floor((min + max) / 2);
  4421. if (ucs > combining_default[mid][1]) min = mid + 1;
  4422. else if (ucs < combining_default[mid][0]) max = mid - 1;
  4423. else return true;
  4424. }
  4425. return false;
  4426. }
  4427. function wcwidth(ucs, opts) {
  4428. if (ucs === 0) return opts.nul;
  4429. if (ucs < 32 || ucs >= 127 && ucs < 160) return opts.control;
  4430. if (bisearch(ucs)) return 0;
  4431. return 1 + (ucs >= 4352 && (ucs <= 4447 || // Hangul Jamo init. consonants
  4432. ucs == 9001 || ucs == 9002 || ucs >= 11904 && ucs <= 42191 && ucs != 12351 || // CJK ... Yi
  4433. ucs >= 44032 && ucs <= 55203 || // Hangul Syllables
  4434. ucs >= 63744 && ucs <= 64255 || // CJK Compatibility Ideographs
  4435. ucs >= 65040 && ucs <= 65049 || // Vertical forms
  4436. ucs >= 65072 && ucs <= 65135 || // CJK Compatibility Forms
  4437. ucs >= 65280 && ucs <= 65376 || // Fullwidth Forms
  4438. ucs >= 65504 && ucs <= 65510 || ucs >= 131072 && ucs <= 196605 || ucs >= 196608 && ucs <= 262141));
  4439. }
  4440. function wcswidth(str, opts) {
  4441. let h;
  4442. let l;
  4443. let s = 0;
  4444. let n;
  4445. if (typeof str !== "string") return wcwidth(str, opts);
  4446. for (let i = 0; i < str.length; i++) {
  4447. h = str.charCodeAt(i);
  4448. if (h >= 55296 && h <= 56319) {
  4449. l = str.charCodeAt(++i);
  4450. if (l >= 56320 && l <= 57343) {
  4451. h = (h - 55296) * 1024 + (l - 56320) + 65536;
  4452. } else {
  4453. i--;
  4454. }
  4455. }
  4456. n = wcwidth(h, opts);
  4457. if (n < 0) return -1;
  4458. s += n;
  4459. }
  4460. return s;
  4461. }
  4462. var _ = (str) => wcswidth(str, DEFAULTS);
  4463. _.config = (opts = {}) => {
  4464. opts = {
  4465. ...DEFAULTS,
  4466. ...opts
  4467. };
  4468. return (str) => wcswidth(str, opts);
  4469. };
  4470. var wcwidth_default = _;
  4471. // src/cli/logger.js
  4472. var countLines = (stream, text) => {
  4473. const columns = stream.columns || 80;
  4474. let lineCount = 0;
  4475. for (const line of stripAnsi(text).split("\n")) {
  4476. lineCount += Math.max(1, Math.ceil(wcwidth_default(line) / columns));
  4477. }
  4478. return lineCount;
  4479. };
  4480. var clear = (stream, text) => () => {
  4481. const lineCount = countLines(stream, text);
  4482. for (let line = 0; line < lineCount; line++) {
  4483. if (line > 0) {
  4484. readline.moveCursor(stream, 0, -1);
  4485. }
  4486. readline.clearLine(stream, 0);
  4487. readline.cursorTo(stream, 0);
  4488. }
  4489. };
  4490. var emptyLogResult = { clear() {
  4491. } };
  4492. function createLogger(logLevel = "log") {
  4493. return {
  4494. logLevel,
  4495. warn: createLogFunc("warn", "yellow"),
  4496. error: createLogFunc("error", "red"),
  4497. debug: createLogFunc("debug", "blue"),
  4498. log: createLogFunc("log")
  4499. };
  4500. function createLogFunc(loggerName, color) {
  4501. if (!shouldLog(loggerName)) {
  4502. return () => emptyLogResult;
  4503. }
  4504. const stream = process[loggerName === "log" ? "stdout" : "stderr"];
  4505. const chalkInstance = loggerName === "log" ? source_default : chalkStderr;
  4506. const prefix = color ? `[${chalkInstance[color](loggerName)}] ` : "";
  4507. return (message, options) => {
  4508. options = {
  4509. newline: true,
  4510. clearable: false,
  4511. ...options
  4512. };
  4513. message = string_replace_all_default(
  4514. /* isOptionalObject */
  4515. false,
  4516. message,
  4517. /^/gmu,
  4518. prefix
  4519. ) + (options.newline ? "\n" : "");
  4520. stream.write(message);
  4521. if (options.clearable) {
  4522. return {
  4523. clear: clear(stream, message)
  4524. };
  4525. }
  4526. };
  4527. }
  4528. function shouldLog(loggerName) {
  4529. switch (logLevel) {
  4530. case "silent":
  4531. return false;
  4532. case "debug":
  4533. if (loggerName === "debug") {
  4534. return true;
  4535. }
  4536. // fall through
  4537. case "log":
  4538. if (loggerName === "log") {
  4539. return true;
  4540. }
  4541. // fall through
  4542. case "warn":
  4543. if (loggerName === "warn") {
  4544. return true;
  4545. }
  4546. // fall through
  4547. case "error":
  4548. return loggerName === "error";
  4549. }
  4550. }
  4551. }
  4552. var logger_default = createLogger;
  4553. // src/cli/print-support-info.js
  4554. var import_fast_json_stable_stringify3 = __toESM(require_fast_json_stable_stringify(), 1);
  4555. import { format as format4, getSupportInfo as getSupportInfo2 } from "../index.mjs";
  4556. var sortByName = (array2) => array2.sort((a, b) => a.name.localeCompare(b.name));
  4557. async function printSupportInfo() {
  4558. const { languages, options } = await getSupportInfo2();
  4559. const supportInfo = {
  4560. languages: sortByName(languages),
  4561. options: sortByName(options).map(
  4562. (option) => omit(option, ["cliName", "cliCategory", "cliDescription"])
  4563. )
  4564. };
  4565. printToScreen(await format4((0, import_fast_json_stable_stringify3.default)(supportInfo), { parser: "json" }));
  4566. }
  4567. var print_support_info_default = printSupportInfo;
  4568. // src/cli/constants.evaluate.js
  4569. var categoryOrder = [
  4570. "Output",
  4571. "Format",
  4572. "Config",
  4573. "Editor",
  4574. "Other"
  4575. ];
  4576. var usageSummary = "Usage: prettier [options] [file/dir/glob ...]\n\nBy default, output is written to stdout.\nStdin is read if it is piped to Prettier and no files are given.";
  4577. // src/cli/usage.js
  4578. var OPTION_USAGE_THRESHOLD = 25;
  4579. var CHOICE_USAGE_MARGIN = 3;
  4580. var CHOICE_USAGE_INDENTATION = 2;
  4581. function indent(str, spaces) {
  4582. return string_replace_all_default(
  4583. /* isOptionalObject */
  4584. false,
  4585. str,
  4586. /^/gmu,
  4587. " ".repeat(spaces)
  4588. );
  4589. }
  4590. function createDefaultValueDisplay(value) {
  4591. return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
  4592. }
  4593. function getOptionDefaultValue(context, optionName) {
  4594. var _a;
  4595. const option = context.detailedOptions.find(
  4596. ({ name }) => name === optionName
  4597. );
  4598. if ((option == null ? void 0 : option.default) !== void 0) {
  4599. return option.default;
  4600. }
  4601. const optionCamelName = camelCase(optionName);
  4602. return formatOptionsHiddenDefaults[optionCamelName] ?? ((_a = context.supportOptions.find(
  4603. (option2) => !option2.deprecated && option2.name === optionCamelName
  4604. )) == null ? void 0 : _a.default);
  4605. }
  4606. function createOptionUsageHeader(option) {
  4607. const name = `--${option.name}`;
  4608. const alias = option.alias ? `-${option.alias},` : null;
  4609. const type = createOptionUsageType(option);
  4610. return [alias, name, type].filter(Boolean).join(" ");
  4611. }
  4612. function createOptionUsageRow(header, content, threshold) {
  4613. const separator = header.length >= threshold ? `
  4614. ${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
  4615. const description = string_replace_all_default(
  4616. /* isOptionalObject */
  4617. false,
  4618. content,
  4619. "\n",
  4620. `
  4621. ${" ".repeat(threshold)}`
  4622. );
  4623. return `${header}${separator}${description}`;
  4624. }
  4625. function createOptionUsageType(option) {
  4626. switch (option.type) {
  4627. case "boolean":
  4628. return null;
  4629. case "choice":
  4630. return `<${option.choices.filter((choice) => !choice.deprecated).map((choice) => choice.value).join("|")}>`;
  4631. default:
  4632. return `<${option.type}>`;
  4633. }
  4634. }
  4635. function createChoiceUsages(choices, margin, indentation) {
  4636. const activeChoices = choices.filter((choice) => !choice.deprecated);
  4637. const threshold = Math.max(0, ...activeChoices.map((choice) => choice.value.length)) + margin;
  4638. return activeChoices.map(
  4639. (choice) => indent(
  4640. createOptionUsageRow(choice.value, choice.description, threshold),
  4641. indentation
  4642. )
  4643. );
  4644. }
  4645. function createOptionUsage(context, option, threshold) {
  4646. const header = createOptionUsageHeader(option);
  4647. const optionDefaultValue = getOptionDefaultValue(context, option.name);
  4648. return createOptionUsageRow(
  4649. header,
  4650. `${option.description}${optionDefaultValue === void 0 ? "" : `
  4651. Defaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`,
  4652. threshold
  4653. );
  4654. }
  4655. function getOptionsWithOpposites(options) {
  4656. const optionsWithOpposites = options.map((option) => [
  4657. option.description ? option : null,
  4658. option.oppositeDescription ? {
  4659. ...option,
  4660. name: `no-${option.name}`,
  4661. type: "boolean",
  4662. description: option.oppositeDescription
  4663. } : null
  4664. ]);
  4665. return optionsWithOpposites.flat().filter(Boolean);
  4666. }
  4667. function createUsage(context) {
  4668. const sortedOptions = context.detailedOptions.sort(
  4669. (optionA, optionB) => optionA.name.localeCompare(optionB.name)
  4670. );
  4671. const options = getOptionsWithOpposites(sortedOptions).filter(
  4672. // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
  4673. (option) => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-"))
  4674. );
  4675. const groupedOptions = groupBy(options, (option) => option.category);
  4676. const firstCategories = categoryOrder.slice(0, -1);
  4677. const lastCategories = categoryOrder.slice(-1);
  4678. const restCategories = Object.keys(groupedOptions).filter(
  4679. (category) => !categoryOrder.includes(category)
  4680. );
  4681. const allCategories = [
  4682. ...firstCategories,
  4683. ...restCategories,
  4684. ...lastCategories
  4685. ];
  4686. const optionsUsage = allCategories.map((category) => {
  4687. const categoryOptions = groupedOptions[category].map(
  4688. (option) => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)
  4689. ).join("\n");
  4690. return `${category} options:
  4691. ${indent(categoryOptions, 2)}`;
  4692. });
  4693. return [usageSummary, ...optionsUsage, ""].join("\n\n");
  4694. }
  4695. function createPluginDefaults(pluginDefaults) {
  4696. if (!pluginDefaults || Object.keys(pluginDefaults).length === 0) {
  4697. return "";
  4698. }
  4699. const defaults = Object.entries(pluginDefaults).sort(
  4700. ([pluginNameA], [pluginNameB]) => pluginNameA.localeCompare(pluginNameB)
  4701. ).map(
  4702. ([plugin, value]) => `* ${plugin}: ${createDefaultValueDisplay(value)}`
  4703. ).join("\n");
  4704. return `
  4705. Plugin defaults:
  4706. ${defaults}`;
  4707. }
  4708. function createDetailedUsage(context, flag) {
  4709. const option = getOptionsWithOpposites(context.detailedOptions).find(
  4710. (option2) => option2.name === flag || option2.alias === flag
  4711. );
  4712. const header = createOptionUsageHeader(option);
  4713. const description = `
  4714. ${indent(option.description, 2)}`;
  4715. const choices = option.type !== "choice" ? "" : `
  4716. Valid options:
  4717. ${createChoiceUsages(
  4718. option.choices,
  4719. CHOICE_USAGE_MARGIN,
  4720. CHOICE_USAGE_INDENTATION
  4721. ).join("\n")}`;
  4722. const optionDefaultValue = getOptionDefaultValue(context, option.name);
  4723. const defaults = optionDefaultValue !== void 0 ? `
  4724. Default: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
  4725. const pluginDefaults = createPluginDefaults(option.pluginDefaults);
  4726. return `${header}${description}${choices}${defaults}${pluginDefaults}`;
  4727. }
  4728. // src/cli/index.js
  4729. async function run(rawArguments = process.argv.slice(2)) {
  4730. let logger = logger_default();
  4731. try {
  4732. const { logLevel } = parseArgvWithoutPlugins(
  4733. rawArguments,
  4734. logger,
  4735. "log-level"
  4736. );
  4737. if (logLevel !== logger.logLevel) {
  4738. logger = logger_default(logLevel);
  4739. }
  4740. const context = new context_default({ rawArguments, logger });
  4741. await context.init();
  4742. if (logger.logLevel !== "debug" && context.performanceTestFlag) {
  4743. context.logger = logger_default("debug");
  4744. }
  4745. await main(context);
  4746. } catch (error) {
  4747. logger.error(error.message);
  4748. process.exitCode = 1;
  4749. }
  4750. }
  4751. async function main(context) {
  4752. context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
  4753. if (context.argv.check && context.argv.listDifferent) {
  4754. throw new Error("Cannot use --check and --list-different together.");
  4755. }
  4756. if (context.argv.write && context.argv.debugCheck) {
  4757. throw new Error("Cannot use --write and --debug-check together.");
  4758. }
  4759. if (context.argv.findConfigPath && context.filePatterns.length > 0) {
  4760. throw new Error("Cannot use --find-config-path with multiple files");
  4761. }
  4762. if (context.argv.fileInfo && context.filePatterns.length > 0) {
  4763. throw new Error("Cannot use --file-info with multiple files");
  4764. }
  4765. if (!context.argv.cache && context.argv.cacheStrategy) {
  4766. throw new Error("`--cache-strategy` cannot be used without `--cache`.");
  4767. }
  4768. if (context.argv.version) {
  4769. printToScreen(prettier2.version);
  4770. return;
  4771. }
  4772. if (context.argv.help !== void 0) {
  4773. printToScreen(
  4774. typeof context.argv.help === "string" && context.argv.help !== "" ? createDetailedUsage(context, context.argv.help) : createUsage(context)
  4775. );
  4776. return;
  4777. }
  4778. if (context.argv.supportInfo) {
  4779. return print_support_info_default();
  4780. }
  4781. if (context.argv.findConfigPath) {
  4782. await find_config_path_default(context);
  4783. return;
  4784. }
  4785. if (context.argv.fileInfo) {
  4786. await file_info_default(context);
  4787. return;
  4788. }
  4789. const hasFilePatterns = context.filePatterns.length > 0;
  4790. const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.argv.filepath);
  4791. if (useStdin) {
  4792. if (context.argv.cache) {
  4793. throw new Error("`--cache` cannot be used when formatting stdin.");
  4794. }
  4795. await formatStdin(context);
  4796. return;
  4797. }
  4798. if (hasFilePatterns) {
  4799. await formatFiles(context);
  4800. return;
  4801. }
  4802. process.exitCode = 1;
  4803. printToScreen(createUsage(context));
  4804. }
  4805. export {
  4806. run
  4807. };