FileSystemInfo.js 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const nodeModule = require("module");
  7. const { isAbsolute } = require("path");
  8. const { create: createResolver } = require("enhanced-resolve");
  9. const asyncLib = require("neo-async");
  10. const { DEFAULTS } = require("./config/defaults");
  11. const AsyncQueue = require("./util/AsyncQueue");
  12. const StackedCacheMap = require("./util/StackedCacheMap");
  13. const createHash = require("./util/createHash");
  14. const { dirname, join, lstatReadlinkAbsolute, relative } = require("./util/fs");
  15. const makeSerializable = require("./util/makeSerializable");
  16. const memoize = require("./util/memoize");
  17. const processAsyncTree = require("./util/processAsyncTree");
  18. /** @typedef {import("enhanced-resolve").Resolver} Resolver */
  19. /** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
  20. /** @typedef {import("enhanced-resolve").ResolveFunctionAsync} ResolveFunctionAsync */
  21. /** @typedef {import("./WebpackError")} WebpackError */
  22. /** @typedef {import("./logging/Logger").Logger} Logger */
  23. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  24. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  25. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  26. /** @typedef {import("./util/fs").IStats} IStats */
  27. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  28. /** @typedef {import("./util/fs").PathLike} PathLike */
  29. /** @typedef {import("./util/fs").StringCallback} StringCallback */
  30. /**
  31. * @template T
  32. * @typedef {import("./util/AsyncQueue").Callback<T>} ProcessorCallback
  33. */
  34. /**
  35. * @template T, R
  36. * @typedef {import("./util/AsyncQueue").Processor<T, R>} Processor
  37. */
  38. const supportsEsm = Number(process.versions.modules) >= 83;
  39. /** @type {Set<string>} */
  40. const builtinModules = new Set(nodeModule.builtinModules);
  41. let FS_ACCURACY = 2000;
  42. const EMPTY_SET = new Set();
  43. const RBDT_RESOLVE_CJS = 0;
  44. const RBDT_RESOLVE_ESM = 1;
  45. const RBDT_RESOLVE_DIRECTORY = 2;
  46. const RBDT_RESOLVE_CJS_FILE = 3;
  47. const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4;
  48. const RBDT_RESOLVE_ESM_FILE = 5;
  49. const RBDT_DIRECTORY = 6;
  50. const RBDT_FILE = 7;
  51. const RBDT_DIRECTORY_DEPENDENCIES = 8;
  52. const RBDT_FILE_DEPENDENCIES = 9;
  53. /** @typedef {RBDT_RESOLVE_CJS | RBDT_RESOLVE_ESM | RBDT_RESOLVE_DIRECTORY | RBDT_RESOLVE_CJS_FILE | RBDT_RESOLVE_CJS_FILE_AS_CHILD | RBDT_RESOLVE_ESM_FILE | RBDT_DIRECTORY | RBDT_FILE | RBDT_DIRECTORY_DEPENDENCIES | RBDT_FILE_DEPENDENCIES} JobType */
  54. const INVALID = Symbol("invalid");
  55. /**
  56. * @typedef {object} FileSystemInfoEntry
  57. * @property {number} safeTime
  58. * @property {number=} timestamp
  59. */
  60. /**
  61. * @typedef {object} ResolvedContextFileSystemInfoEntry
  62. * @property {number} safeTime
  63. * @property {string=} timestampHash
  64. */
  65. /** @typedef {Set<string>} Symlinks */
  66. /**
  67. * @typedef {object} ContextFileSystemInfoEntry
  68. * @property {number} safeTime
  69. * @property {string=} timestampHash
  70. * @property {ResolvedContextFileSystemInfoEntry=} resolved
  71. * @property {Symlinks=} symlinks
  72. */
  73. /**
  74. * @typedef {object} TimestampAndHash
  75. * @property {number} safeTime
  76. * @property {number=} timestamp
  77. * @property {string} hash
  78. */
  79. /**
  80. * @typedef {object} ResolvedContextTimestampAndHash
  81. * @property {number} safeTime
  82. * @property {string=} timestampHash
  83. * @property {string} hash
  84. */
  85. /**
  86. * @typedef {object} ContextTimestampAndHash
  87. * @property {number} safeTime
  88. * @property {string=} timestampHash
  89. * @property {string} hash
  90. * @property {ResolvedContextTimestampAndHash=} resolved
  91. * @property {Symlinks=} symlinks
  92. */
  93. /**
  94. * @typedef {object} ContextHash
  95. * @property {string} hash
  96. * @property {string=} resolved
  97. * @property {Symlinks=} symlinks
  98. */
  99. /** @typedef {Set<string>} SnapshotContent */
  100. /**
  101. * @typedef {object} SnapshotOptimizationEntry
  102. * @property {Snapshot} snapshot
  103. * @property {number} shared
  104. * @property {SnapshotContent | undefined} snapshotContent
  105. * @property {Set<SnapshotOptimizationEntry> | undefined} children
  106. */
  107. /** @typedef {Map<string, string | false | undefined>} ResolveResults */
  108. /** @typedef {Set<string>} Files */
  109. /** @typedef {Set<string>} Directories */
  110. /** @typedef {Set<string>} Missing */
  111. /**
  112. * @typedef {object} ResolveDependencies
  113. * @property {Files} files list of files
  114. * @property {Directories} directories list of directories
  115. * @property {Missing} missing list of missing entries
  116. */
  117. /**
  118. * @typedef {object} ResolveBuildDependenciesResult
  119. * @property {Files} files list of files
  120. * @property {Directories} directories list of directories
  121. * @property {Missing} missing list of missing entries
  122. * @property {ResolveResults} resolveResults stored resolve results
  123. * @property {ResolveDependencies} resolveDependencies dependencies of the resolving
  124. */
  125. /**
  126. * @typedef {object} SnapshotOptions
  127. * @property {boolean=} hash should use hash to snapshot
  128. * @property {boolean=} timestamp should use timestamp to snapshot
  129. */
  130. const DONE_ITERATOR_RESULT = new Set().keys().next();
  131. // cspell:word tshs
  132. // Tsh = Timestamp + Hash
  133. // Tshs = Timestamp + Hash combinations
  134. class SnapshotIterator {
  135. /**
  136. * @param {() => IteratorResult<string>} next next
  137. */
  138. constructor(next) {
  139. this.next = next;
  140. }
  141. }
  142. /** @typedef {Map<string, TODO> | Set<string> | undefined} SnapshotMap */
  143. /** @typedef {(snapshot: Snapshot) => SnapshotMap[]} GetMapsFunction */
  144. class SnapshotIterable {
  145. /**
  146. * @param {Snapshot} snapshot snapshot
  147. * @param {GetMapsFunction} getMaps get maps function
  148. */
  149. constructor(snapshot, getMaps) {
  150. this.snapshot = snapshot;
  151. this.getMaps = getMaps;
  152. }
  153. [Symbol.iterator]() {
  154. let state = 0;
  155. /** @type {IterableIterator<string>} */
  156. let it;
  157. /** @type {GetMapsFunction} */
  158. let getMaps;
  159. /** @type {SnapshotMap[]} */
  160. let maps;
  161. /** @type {Snapshot} */
  162. let snapshot;
  163. /** @type {Snapshot[] | undefined} */
  164. let queue;
  165. return new SnapshotIterator(() => {
  166. for (;;) {
  167. switch (state) {
  168. case 0:
  169. snapshot = this.snapshot;
  170. getMaps = this.getMaps;
  171. maps = getMaps(snapshot);
  172. state = 1;
  173. /* falls through */
  174. case 1:
  175. if (maps.length > 0) {
  176. const map = maps.pop();
  177. if (map !== undefined) {
  178. it = map.keys();
  179. state = 2;
  180. } else {
  181. break;
  182. }
  183. } else {
  184. state = 3;
  185. break;
  186. }
  187. /* falls through */
  188. case 2: {
  189. const result = it.next();
  190. if (!result.done) return result;
  191. state = 1;
  192. break;
  193. }
  194. case 3: {
  195. const children = snapshot.children;
  196. if (children !== undefined) {
  197. if (children.size === 1) {
  198. // shortcut for a single child
  199. // avoids allocation of queue
  200. for (const child of children) snapshot = child;
  201. maps = getMaps(snapshot);
  202. state = 1;
  203. break;
  204. }
  205. if (queue === undefined) queue = [];
  206. for (const child of children) {
  207. queue.push(child);
  208. }
  209. }
  210. if (queue !== undefined && queue.length > 0) {
  211. snapshot = /** @type {Snapshot} */ (queue.pop());
  212. maps = getMaps(snapshot);
  213. state = 1;
  214. break;
  215. } else {
  216. state = 4;
  217. }
  218. }
  219. /* falls through */
  220. case 4:
  221. return DONE_ITERATOR_RESULT;
  222. }
  223. }
  224. });
  225. }
  226. }
  227. /** @typedef {Map<string, FileSystemInfoEntry | null>} FileTimestamps */
  228. /** @typedef {Map<string, string | null>} FileHashes */
  229. /** @typedef {Map<string, TimestampAndHash | string | null>} FileTshs */
  230. /** @typedef {Map<string, ResolvedContextFileSystemInfoEntry | null>} ContextTimestamps */
  231. /** @typedef {Map<string, string | null>} ContextHashes */
  232. /** @typedef {Map<string, ResolvedContextTimestampAndHash | null>} ContextTshs */
  233. /** @typedef {Map<string, boolean>} MissingExistence */
  234. /** @typedef {Map<string, string>} ManagedItemInfo */
  235. /** @typedef {Set<string>} ManagedFiles */
  236. /** @typedef {Set<string>} ManagedContexts */
  237. /** @typedef {Set<string>} ManagedMissing */
  238. /** @typedef {Set<Snapshot>} Children */
  239. class Snapshot {
  240. constructor() {
  241. this._flags = 0;
  242. /** @type {Iterable<string> | undefined} */
  243. this._cachedFileIterable = undefined;
  244. /** @type {Iterable<string> | undefined} */
  245. this._cachedContextIterable = undefined;
  246. /** @type {Iterable<string> | undefined} */
  247. this._cachedMissingIterable = undefined;
  248. /** @type {number | undefined} */
  249. this.startTime = undefined;
  250. /** @type {FileTimestamps | undefined} */
  251. this.fileTimestamps = undefined;
  252. /** @type {FileHashes | undefined} */
  253. this.fileHashes = undefined;
  254. /** @type {FileTshs | undefined} */
  255. this.fileTshs = undefined;
  256. /** @type {ContextTimestamps | undefined} */
  257. this.contextTimestamps = undefined;
  258. /** @type {ContextHashes | undefined} */
  259. this.contextHashes = undefined;
  260. /** @type {ContextTshs | undefined} */
  261. this.contextTshs = undefined;
  262. /** @type {MissingExistence | undefined} */
  263. this.missingExistence = undefined;
  264. /** @type {ManagedItemInfo | undefined} */
  265. this.managedItemInfo = undefined;
  266. /** @type {ManagedFiles | undefined} */
  267. this.managedFiles = undefined;
  268. /** @type {ManagedContexts | undefined} */
  269. this.managedContexts = undefined;
  270. /** @type {ManagedMissing | undefined} */
  271. this.managedMissing = undefined;
  272. /** @type {Children | undefined} */
  273. this.children = undefined;
  274. }
  275. hasStartTime() {
  276. return (this._flags & 1) !== 0;
  277. }
  278. /**
  279. * @param {number} value start value
  280. */
  281. setStartTime(value) {
  282. this._flags |= 1;
  283. this.startTime = value;
  284. }
  285. /**
  286. * @param {number | undefined} value value
  287. * @param {Snapshot} snapshot snapshot
  288. */
  289. setMergedStartTime(value, snapshot) {
  290. if (value) {
  291. if (snapshot.hasStartTime()) {
  292. this.setStartTime(
  293. Math.min(
  294. value,
  295. /** @type {NonNullable<Snapshot["startTime"]>} */
  296. (snapshot.startTime)
  297. )
  298. );
  299. } else {
  300. this.setStartTime(value);
  301. }
  302. } else if (snapshot.hasStartTime()) {
  303. this.setStartTime(
  304. /** @type {NonNullable<Snapshot["startTime"]>} */
  305. (snapshot.startTime)
  306. );
  307. }
  308. }
  309. hasFileTimestamps() {
  310. return (this._flags & 2) !== 0;
  311. }
  312. /**
  313. * @param {FileTimestamps} value file timestamps
  314. */
  315. setFileTimestamps(value) {
  316. this._flags |= 2;
  317. this.fileTimestamps = value;
  318. }
  319. hasFileHashes() {
  320. return (this._flags & 4) !== 0;
  321. }
  322. /**
  323. * @param {FileHashes} value file hashes
  324. */
  325. setFileHashes(value) {
  326. this._flags |= 4;
  327. this.fileHashes = value;
  328. }
  329. hasFileTshs() {
  330. return (this._flags & 8) !== 0;
  331. }
  332. /**
  333. * @param {FileTshs} value file tshs
  334. */
  335. setFileTshs(value) {
  336. this._flags |= 8;
  337. this.fileTshs = value;
  338. }
  339. hasContextTimestamps() {
  340. return (this._flags & 0x10) !== 0;
  341. }
  342. /**
  343. * @param {ContextTimestamps} value context timestamps
  344. */
  345. setContextTimestamps(value) {
  346. this._flags |= 0x10;
  347. this.contextTimestamps = value;
  348. }
  349. hasContextHashes() {
  350. return (this._flags & 0x20) !== 0;
  351. }
  352. /**
  353. * @param {ContextHashes} value context hashes
  354. */
  355. setContextHashes(value) {
  356. this._flags |= 0x20;
  357. this.contextHashes = value;
  358. }
  359. hasContextTshs() {
  360. return (this._flags & 0x40) !== 0;
  361. }
  362. /**
  363. * @param {ContextTshs} value context tshs
  364. */
  365. setContextTshs(value) {
  366. this._flags |= 0x40;
  367. this.contextTshs = value;
  368. }
  369. hasMissingExistence() {
  370. return (this._flags & 0x80) !== 0;
  371. }
  372. /**
  373. * @param {MissingExistence} value context tshs
  374. */
  375. setMissingExistence(value) {
  376. this._flags |= 0x80;
  377. this.missingExistence = value;
  378. }
  379. hasManagedItemInfo() {
  380. return (this._flags & 0x100) !== 0;
  381. }
  382. /**
  383. * @param {ManagedItemInfo} value managed item info
  384. */
  385. setManagedItemInfo(value) {
  386. this._flags |= 0x100;
  387. this.managedItemInfo = value;
  388. }
  389. hasManagedFiles() {
  390. return (this._flags & 0x200) !== 0;
  391. }
  392. /**
  393. * @param {ManagedFiles} value managed files
  394. */
  395. setManagedFiles(value) {
  396. this._flags |= 0x200;
  397. this.managedFiles = value;
  398. }
  399. hasManagedContexts() {
  400. return (this._flags & 0x400) !== 0;
  401. }
  402. /**
  403. * @param {ManagedContexts} value managed contexts
  404. */
  405. setManagedContexts(value) {
  406. this._flags |= 0x400;
  407. this.managedContexts = value;
  408. }
  409. hasManagedMissing() {
  410. return (this._flags & 0x800) !== 0;
  411. }
  412. /**
  413. * @param {ManagedMissing} value managed missing
  414. */
  415. setManagedMissing(value) {
  416. this._flags |= 0x800;
  417. this.managedMissing = value;
  418. }
  419. hasChildren() {
  420. return (this._flags & 0x1000) !== 0;
  421. }
  422. /**
  423. * @param {Children} value children
  424. */
  425. setChildren(value) {
  426. this._flags |= 0x1000;
  427. this.children = value;
  428. }
  429. /**
  430. * @param {Snapshot} child children
  431. */
  432. addChild(child) {
  433. if (!this.hasChildren()) {
  434. this.setChildren(new Set());
  435. }
  436. /** @type {Children} */
  437. (this.children).add(child);
  438. }
  439. /**
  440. * @param {ObjectSerializerContext} context context
  441. */
  442. serialize({ write }) {
  443. write(this._flags);
  444. if (this.hasStartTime()) write(this.startTime);
  445. if (this.hasFileTimestamps()) write(this.fileTimestamps);
  446. if (this.hasFileHashes()) write(this.fileHashes);
  447. if (this.hasFileTshs()) write(this.fileTshs);
  448. if (this.hasContextTimestamps()) write(this.contextTimestamps);
  449. if (this.hasContextHashes()) write(this.contextHashes);
  450. if (this.hasContextTshs()) write(this.contextTshs);
  451. if (this.hasMissingExistence()) write(this.missingExistence);
  452. if (this.hasManagedItemInfo()) write(this.managedItemInfo);
  453. if (this.hasManagedFiles()) write(this.managedFiles);
  454. if (this.hasManagedContexts()) write(this.managedContexts);
  455. if (this.hasManagedMissing()) write(this.managedMissing);
  456. if (this.hasChildren()) write(this.children);
  457. }
  458. /**
  459. * @param {ObjectDeserializerContext} context context
  460. */
  461. deserialize({ read }) {
  462. this._flags = read();
  463. if (this.hasStartTime()) this.startTime = read();
  464. if (this.hasFileTimestamps()) this.fileTimestamps = read();
  465. if (this.hasFileHashes()) this.fileHashes = read();
  466. if (this.hasFileTshs()) this.fileTshs = read();
  467. if (this.hasContextTimestamps()) this.contextTimestamps = read();
  468. if (this.hasContextHashes()) this.contextHashes = read();
  469. if (this.hasContextTshs()) this.contextTshs = read();
  470. if (this.hasMissingExistence()) this.missingExistence = read();
  471. if (this.hasManagedItemInfo()) this.managedItemInfo = read();
  472. if (this.hasManagedFiles()) this.managedFiles = read();
  473. if (this.hasManagedContexts()) this.managedContexts = read();
  474. if (this.hasManagedMissing()) this.managedMissing = read();
  475. if (this.hasChildren()) this.children = read();
  476. }
  477. /**
  478. * @param {GetMapsFunction} getMaps first
  479. * @returns {Iterable<string>} iterable
  480. */
  481. _createIterable(getMaps) {
  482. return new SnapshotIterable(this, getMaps);
  483. }
  484. /**
  485. * @returns {Iterable<string>} iterable
  486. */
  487. getFileIterable() {
  488. if (this._cachedFileIterable === undefined) {
  489. this._cachedFileIterable = this._createIterable((s) => [
  490. s.fileTimestamps,
  491. s.fileHashes,
  492. s.fileTshs,
  493. s.managedFiles
  494. ]);
  495. }
  496. return this._cachedFileIterable;
  497. }
  498. /**
  499. * @returns {Iterable<string>} iterable
  500. */
  501. getContextIterable() {
  502. if (this._cachedContextIterable === undefined) {
  503. this._cachedContextIterable = this._createIterable((s) => [
  504. s.contextTimestamps,
  505. s.contextHashes,
  506. s.contextTshs,
  507. s.managedContexts
  508. ]);
  509. }
  510. return this._cachedContextIterable;
  511. }
  512. /**
  513. * @returns {Iterable<string>} iterable
  514. */
  515. getMissingIterable() {
  516. if (this._cachedMissingIterable === undefined) {
  517. this._cachedMissingIterable = this._createIterable((s) => [
  518. s.missingExistence,
  519. s.managedMissing
  520. ]);
  521. }
  522. return this._cachedMissingIterable;
  523. }
  524. }
  525. makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot");
  526. const MIN_COMMON_SNAPSHOT_SIZE = 3;
  527. /**
  528. * @template U, T
  529. * @typedef {U extends true ? Set<string> : Map<string, T>} SnapshotOptimizationValue
  530. */
  531. /**
  532. * @template T
  533. * @template {boolean} [U=false]
  534. */
  535. class SnapshotOptimization {
  536. /**
  537. * @param {(snapshot: Snapshot) => boolean} has has value
  538. * @param {(snapshot: Snapshot) => SnapshotOptimizationValue<U, T> | undefined} get get value
  539. * @param {(snapshot: Snapshot, value: SnapshotOptimizationValue<U, T>) => void} set set value
  540. * @param {boolean=} useStartTime use the start time of snapshots
  541. * @param {U=} isSet value is an Set instead of a Map
  542. */
  543. constructor(
  544. has,
  545. get,
  546. set,
  547. useStartTime = true,
  548. isSet = /** @type {U} */ (false)
  549. ) {
  550. this._has = has;
  551. this._get = get;
  552. this._set = set;
  553. this._useStartTime = useStartTime;
  554. /** @type {U} */
  555. this._isSet = isSet;
  556. /** @type {Map<string, SnapshotOptimizationEntry>} */
  557. this._map = new Map();
  558. this._statItemsShared = 0;
  559. this._statItemsUnshared = 0;
  560. this._statSharedSnapshots = 0;
  561. this._statReusedSharedSnapshots = 0;
  562. }
  563. getStatisticMessage() {
  564. const total = this._statItemsShared + this._statItemsUnshared;
  565. if (total === 0) return;
  566. return `${
  567. this._statItemsShared && Math.round((this._statItemsShared * 100) / total)
  568. }% (${this._statItemsShared}/${total}) entries shared via ${
  569. this._statSharedSnapshots
  570. } shared snapshots (${
  571. this._statReusedSharedSnapshots + this._statSharedSnapshots
  572. } times referenced)`;
  573. }
  574. clear() {
  575. this._map.clear();
  576. this._statItemsShared = 0;
  577. this._statItemsUnshared = 0;
  578. this._statSharedSnapshots = 0;
  579. this._statReusedSharedSnapshots = 0;
  580. }
  581. /**
  582. * @param {Snapshot} newSnapshot snapshot
  583. * @param {Set<string>} capturedFiles files to snapshot/share
  584. * @returns {void}
  585. */
  586. optimize(newSnapshot, capturedFiles) {
  587. /**
  588. * @param {SnapshotOptimizationEntry} entry optimization entry
  589. * @returns {void}
  590. */
  591. const increaseSharedAndStoreOptimizationEntry = (entry) => {
  592. if (entry.children !== undefined) {
  593. for (const child of entry.children) {
  594. increaseSharedAndStoreOptimizationEntry(child);
  595. }
  596. }
  597. entry.shared++;
  598. storeOptimizationEntry(entry);
  599. };
  600. /**
  601. * @param {SnapshotOptimizationEntry} entry optimization entry
  602. * @returns {void}
  603. */
  604. const storeOptimizationEntry = (entry) => {
  605. for (const path of /** @type {SnapshotContent} */ (
  606. entry.snapshotContent
  607. )) {
  608. const old =
  609. /** @type {SnapshotOptimizationEntry} */
  610. (this._map.get(path));
  611. if (old.shared < entry.shared) {
  612. this._map.set(path, entry);
  613. }
  614. capturedFiles.delete(path);
  615. }
  616. };
  617. /** @type {SnapshotOptimizationEntry | undefined} */
  618. let newOptimizationEntry;
  619. const capturedFilesSize = capturedFiles.size;
  620. /** @type {Set<SnapshotOptimizationEntry> | undefined} */
  621. const optimizationEntries = new Set();
  622. for (const path of capturedFiles) {
  623. const optimizationEntry = this._map.get(path);
  624. if (optimizationEntry === undefined) {
  625. if (newOptimizationEntry === undefined) {
  626. newOptimizationEntry = {
  627. snapshot: newSnapshot,
  628. shared: 0,
  629. snapshotContent: undefined,
  630. children: undefined
  631. };
  632. }
  633. this._map.set(path, newOptimizationEntry);
  634. } else {
  635. optimizationEntries.add(optimizationEntry);
  636. }
  637. }
  638. optimizationEntriesLabel: for (const optimizationEntry of optimizationEntries) {
  639. const snapshot = optimizationEntry.snapshot;
  640. if (optimizationEntry.shared > 0) {
  641. // It's a shared snapshot
  642. // We can't change it, so we can only use it when all files match
  643. // and startTime is compatible
  644. if (
  645. this._useStartTime &&
  646. newSnapshot.startTime &&
  647. (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime)
  648. ) {
  649. continue;
  650. }
  651. const nonSharedFiles = new Set();
  652. const snapshotContent =
  653. /** @type {NonNullable<SnapshotOptimizationEntry["snapshotContent"]>} */
  654. (optimizationEntry.snapshotContent);
  655. const snapshotEntries =
  656. /** @type {SnapshotOptimizationValue<U, T>} */
  657. (this._get(snapshot));
  658. for (const path of snapshotContent) {
  659. if (!capturedFiles.has(path)) {
  660. if (!snapshotEntries.has(path)) {
  661. // File is not shared and can't be removed from the snapshot
  662. // because it's in a child of the snapshot
  663. continue optimizationEntriesLabel;
  664. }
  665. nonSharedFiles.add(path);
  666. }
  667. }
  668. if (nonSharedFiles.size === 0) {
  669. // The complete snapshot is shared
  670. // add it as child
  671. newSnapshot.addChild(snapshot);
  672. increaseSharedAndStoreOptimizationEntry(optimizationEntry);
  673. this._statReusedSharedSnapshots++;
  674. } else {
  675. // Only a part of the snapshot is shared
  676. const sharedCount = snapshotContent.size - nonSharedFiles.size;
  677. if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) {
  678. // Common part it too small
  679. continue;
  680. }
  681. // Extract common timestamps from both snapshots
  682. let commonMap;
  683. if (this._isSet) {
  684. commonMap = new Set();
  685. for (const path of /** @type {Set<string>} */ (snapshotEntries)) {
  686. if (nonSharedFiles.has(path)) continue;
  687. commonMap.add(path);
  688. snapshotEntries.delete(path);
  689. }
  690. } else {
  691. commonMap = new Map();
  692. const map = /** @type {Map<string, T>} */ (snapshotEntries);
  693. for (const [path, value] of map) {
  694. if (nonSharedFiles.has(path)) continue;
  695. commonMap.set(path, value);
  696. snapshotEntries.delete(path);
  697. }
  698. }
  699. // Create and attach snapshot
  700. const commonSnapshot = new Snapshot();
  701. if (this._useStartTime) {
  702. commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot);
  703. }
  704. this._set(
  705. commonSnapshot,
  706. /** @type {SnapshotOptimizationValue<U, T>} */ (commonMap)
  707. );
  708. newSnapshot.addChild(commonSnapshot);
  709. snapshot.addChild(commonSnapshot);
  710. // Create optimization entry
  711. const newEntry = {
  712. snapshot: commonSnapshot,
  713. shared: optimizationEntry.shared + 1,
  714. snapshotContent: new Set(commonMap.keys()),
  715. children: undefined
  716. };
  717. if (optimizationEntry.children === undefined) {
  718. optimizationEntry.children = new Set();
  719. }
  720. optimizationEntry.children.add(newEntry);
  721. storeOptimizationEntry(newEntry);
  722. this._statSharedSnapshots++;
  723. }
  724. } else {
  725. // It's a unshared snapshot
  726. // We can extract a common shared snapshot
  727. // with all common files
  728. const snapshotEntries = this._get(snapshot);
  729. if (snapshotEntries === undefined) {
  730. // Incomplete snapshot, that can't be used
  731. continue;
  732. }
  733. let commonMap;
  734. if (this._isSet) {
  735. commonMap = new Set();
  736. const set = /** @type {Set<string>} */ (snapshotEntries);
  737. if (capturedFiles.size < set.size) {
  738. for (const path of capturedFiles) {
  739. if (set.has(path)) commonMap.add(path);
  740. }
  741. } else {
  742. for (const path of set) {
  743. if (capturedFiles.has(path)) commonMap.add(path);
  744. }
  745. }
  746. } else {
  747. commonMap = new Map();
  748. const map = /** @type {Map<string, T>} */ (snapshotEntries);
  749. for (const path of capturedFiles) {
  750. const ts = map.get(path);
  751. if (ts === undefined) continue;
  752. commonMap.set(path, ts);
  753. }
  754. }
  755. if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) {
  756. // Common part it too small
  757. continue;
  758. }
  759. // Create and attach snapshot
  760. const commonSnapshot = new Snapshot();
  761. if (this._useStartTime) {
  762. commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot);
  763. }
  764. this._set(
  765. commonSnapshot,
  766. /** @type {SnapshotOptimizationValue<U, T>} */
  767. (commonMap)
  768. );
  769. newSnapshot.addChild(commonSnapshot);
  770. snapshot.addChild(commonSnapshot);
  771. // Remove files from snapshot
  772. for (const path of commonMap.keys()) snapshotEntries.delete(path);
  773. const sharedCount = commonMap.size;
  774. this._statItemsUnshared -= sharedCount;
  775. this._statItemsShared += sharedCount;
  776. // Create optimization entry
  777. storeOptimizationEntry({
  778. snapshot: commonSnapshot,
  779. shared: 2,
  780. snapshotContent: new Set(commonMap.keys()),
  781. children: undefined
  782. });
  783. this._statSharedSnapshots++;
  784. }
  785. }
  786. const unshared = capturedFiles.size;
  787. this._statItemsUnshared += unshared;
  788. this._statItemsShared += capturedFilesSize - unshared;
  789. }
  790. }
  791. /**
  792. * @param {string} str input
  793. * @returns {string} result
  794. */
  795. const parseString = (str) => {
  796. if (str[0] === "'" || str[0] === "`") {
  797. str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`;
  798. }
  799. return JSON.parse(str);
  800. };
  801. /* istanbul ignore next */
  802. /**
  803. * @param {number} mtime mtime
  804. */
  805. const applyMtime = (mtime) => {
  806. if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1;
  807. else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10;
  808. else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100;
  809. else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000;
  810. };
  811. /**
  812. * @template T
  813. * @template K
  814. * @param {Map<T, K> | undefined} a source map
  815. * @param {Map<T, K> | undefined} b joining map
  816. * @returns {Map<T, K>} joined map
  817. */
  818. const mergeMaps = (a, b) => {
  819. if (!b || b.size === 0) return /** @type {Map<T, K>} */ (a);
  820. if (!a || a.size === 0) return /** @type {Map<T, K>} */ (b);
  821. /** @type {Map<T, K>} */
  822. const map = new Map(a);
  823. for (const [key, value] of b) {
  824. map.set(key, value);
  825. }
  826. return map;
  827. };
  828. /**
  829. * @template T
  830. * @param {Set<T> | undefined} a source map
  831. * @param {Set<T> | undefined} b joining map
  832. * @returns {Set<T>} joined map
  833. */
  834. const mergeSets = (a, b) => {
  835. if (!b || b.size === 0) return /** @type {Set<T>} */ (a);
  836. if (!a || a.size === 0) return /** @type {Set<T>} */ (b);
  837. /** @type {Set<T>} */
  838. const map = new Set(a);
  839. for (const item of b) {
  840. map.add(item);
  841. }
  842. return map;
  843. };
  844. /**
  845. * Finding file or directory to manage
  846. * @param {string} managedPath path that is managing by {@link FileSystemInfo}
  847. * @param {string} path path to file or directory
  848. * @returns {string|null} managed item
  849. * @example
  850. * getManagedItem(
  851. * '/Users/user/my-project/node_modules/',
  852. * '/Users/user/my-project/node_modules/package/index.js'
  853. * ) === '/Users/user/my-project/node_modules/package'
  854. * getManagedItem(
  855. * '/Users/user/my-project/node_modules/',
  856. * '/Users/user/my-project/node_modules/package1/node_modules/package2'
  857. * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2'
  858. * getManagedItem(
  859. * '/Users/user/my-project/node_modules/',
  860. * '/Users/user/my-project/node_modules/.bin/script.js'
  861. * ) === null // hidden files are disallowed as managed items
  862. * getManagedItem(
  863. * '/Users/user/my-project/node_modules/',
  864. * '/Users/user/my-project/node_modules/package'
  865. * ) === '/Users/user/my-project/node_modules/package'
  866. */
  867. const getManagedItem = (managedPath, path) => {
  868. let i = managedPath.length;
  869. let slashes = 1;
  870. let startingPosition = true;
  871. loop: while (i < path.length) {
  872. switch (path.charCodeAt(i)) {
  873. case 47: // slash
  874. case 92: // backslash
  875. if (--slashes === 0) break loop;
  876. startingPosition = true;
  877. break;
  878. case 46: // .
  879. // hidden files are disallowed as managed items
  880. // it's probably .yarn-integrity or .cache
  881. if (startingPosition) return null;
  882. break;
  883. case 64: // @
  884. if (!startingPosition) return null;
  885. slashes++;
  886. break;
  887. default:
  888. startingPosition = false;
  889. break;
  890. }
  891. i++;
  892. }
  893. if (i === path.length) slashes--;
  894. // return null when path is incomplete
  895. if (slashes !== 0) return null;
  896. // if (path.slice(i + 1, i + 13) === "node_modules")
  897. if (
  898. path.length >= i + 13 &&
  899. path.charCodeAt(i + 1) === 110 &&
  900. path.charCodeAt(i + 2) === 111 &&
  901. path.charCodeAt(i + 3) === 100 &&
  902. path.charCodeAt(i + 4) === 101 &&
  903. path.charCodeAt(i + 5) === 95 &&
  904. path.charCodeAt(i + 6) === 109 &&
  905. path.charCodeAt(i + 7) === 111 &&
  906. path.charCodeAt(i + 8) === 100 &&
  907. path.charCodeAt(i + 9) === 117 &&
  908. path.charCodeAt(i + 10) === 108 &&
  909. path.charCodeAt(i + 11) === 101 &&
  910. path.charCodeAt(i + 12) === 115
  911. ) {
  912. // if this is the end of the path
  913. if (path.length === i + 13) {
  914. // return the node_modules directory
  915. // it's special
  916. return path;
  917. }
  918. const c = path.charCodeAt(i + 13);
  919. // if next symbol is slash or backslash
  920. if (c === 47 || c === 92) {
  921. // Managed subpath
  922. return getManagedItem(path.slice(0, i + 14), path);
  923. }
  924. }
  925. return path.slice(0, i);
  926. };
  927. /**
  928. * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T
  929. * @param {T | null} entry entry
  930. * @returns {T["resolved"] | null | undefined} the resolved entry
  931. */
  932. const getResolvedTimestamp = (entry) => {
  933. if (entry === null) return null;
  934. if (entry.resolved !== undefined) return entry.resolved;
  935. return entry.symlinks === undefined ? entry : undefined;
  936. };
  937. /**
  938. * @param {ContextHash | null} entry entry
  939. * @returns {string | null | undefined} the resolved entry
  940. */
  941. const getResolvedHash = (entry) => {
  942. if (entry === null) return null;
  943. if (entry.resolved !== undefined) return entry.resolved;
  944. return entry.symlinks === undefined ? entry.hash : undefined;
  945. };
  946. /**
  947. * @template T
  948. * @param {Set<T>} source source
  949. * @param {Set<T>} target target
  950. */
  951. const addAll = (source, target) => {
  952. for (const key of source) target.add(key);
  953. };
  954. const getEsModuleLexer = memoize(() => require("es-module-lexer"));
  955. /** @typedef {Set<string>} LoggedPaths */
  956. /** @typedef {FileSystemInfoEntry | "ignore" | null} FileTimestamp */
  957. /** @typedef {ContextFileSystemInfoEntry | "ignore" | null} ContextTimestamp */
  958. /** @typedef {ResolvedContextFileSystemInfoEntry | "ignore" | null} ResolvedContextTimestamp */
  959. /** @typedef {(err?: WebpackError | null, result?: boolean) => void} CheckSnapshotValidCallback */
  960. /**
  961. * Used to access information about the filesystem in a cached way
  962. */
  963. class FileSystemInfo {
  964. /**
  965. * @param {InputFileSystem} fs file system
  966. * @param {object} options options
  967. * @param {Iterable<string | RegExp>=} options.unmanagedPaths paths that are not managed by a package manager and the contents are subject to change
  968. * @param {Iterable<string | RegExp>=} options.managedPaths paths that are only managed by a package manager
  969. * @param {Iterable<string | RegExp>=} options.immutablePaths paths that are immutable
  970. * @param {Logger=} options.logger logger used to log invalid snapshots
  971. * @param {HashFunction=} options.hashFunction the hash function to use
  972. */
  973. constructor(
  974. fs,
  975. {
  976. unmanagedPaths = [],
  977. managedPaths = [],
  978. immutablePaths = [],
  979. logger,
  980. hashFunction = DEFAULTS.HASH_FUNCTION
  981. } = {}
  982. ) {
  983. this.fs = fs;
  984. this.logger = logger;
  985. this._remainingLogs = logger ? 40 : 0;
  986. /** @type {LoggedPaths | undefined} */
  987. this._loggedPaths = logger ? new Set() : undefined;
  988. this._hashFunction = hashFunction;
  989. /** @type {WeakMap<Snapshot, boolean | CheckSnapshotValidCallback[]>} */
  990. this._snapshotCache = new WeakMap();
  991. this._fileTimestampsOptimization = new SnapshotOptimization(
  992. (s) => s.hasFileTimestamps(),
  993. (s) => s.fileTimestamps,
  994. (s, v) => s.setFileTimestamps(v)
  995. );
  996. this._fileHashesOptimization = new SnapshotOptimization(
  997. (s) => s.hasFileHashes(),
  998. (s) => s.fileHashes,
  999. (s, v) => s.setFileHashes(v),
  1000. false
  1001. );
  1002. this._fileTshsOptimization = new SnapshotOptimization(
  1003. (s) => s.hasFileTshs(),
  1004. (s) => s.fileTshs,
  1005. (s, v) => s.setFileTshs(v)
  1006. );
  1007. this._contextTimestampsOptimization = new SnapshotOptimization(
  1008. (s) => s.hasContextTimestamps(),
  1009. (s) => s.contextTimestamps,
  1010. (s, v) => s.setContextTimestamps(v)
  1011. );
  1012. this._contextHashesOptimization = new SnapshotOptimization(
  1013. (s) => s.hasContextHashes(),
  1014. (s) => s.contextHashes,
  1015. (s, v) => s.setContextHashes(v),
  1016. false
  1017. );
  1018. this._contextTshsOptimization = new SnapshotOptimization(
  1019. (s) => s.hasContextTshs(),
  1020. (s) => s.contextTshs,
  1021. (s, v) => s.setContextTshs(v)
  1022. );
  1023. this._missingExistenceOptimization = new SnapshotOptimization(
  1024. (s) => s.hasMissingExistence(),
  1025. (s) => s.missingExistence,
  1026. (s, v) => s.setMissingExistence(v),
  1027. false
  1028. );
  1029. this._managedItemInfoOptimization = new SnapshotOptimization(
  1030. (s) => s.hasManagedItemInfo(),
  1031. (s) => s.managedItemInfo,
  1032. (s, v) => s.setManagedItemInfo(v),
  1033. false
  1034. );
  1035. this._managedFilesOptimization = new SnapshotOptimization(
  1036. (s) => s.hasManagedFiles(),
  1037. (s) => s.managedFiles,
  1038. (s, v) => s.setManagedFiles(v),
  1039. false,
  1040. true
  1041. );
  1042. this._managedContextsOptimization = new SnapshotOptimization(
  1043. (s) => s.hasManagedContexts(),
  1044. (s) => s.managedContexts,
  1045. (s, v) => s.setManagedContexts(v),
  1046. false,
  1047. true
  1048. );
  1049. this._managedMissingOptimization = new SnapshotOptimization(
  1050. (s) => s.hasManagedMissing(),
  1051. (s) => s.managedMissing,
  1052. (s, v) => s.setManagedMissing(v),
  1053. false,
  1054. true
  1055. );
  1056. /** @type {StackedCacheMap<string, FileTimestamp>} */
  1057. this._fileTimestamps = new StackedCacheMap();
  1058. /** @type {Map<string, string | null>} */
  1059. this._fileHashes = new Map();
  1060. /** @type {Map<string, TimestampAndHash | string>} */
  1061. this._fileTshs = new Map();
  1062. /** @type {StackedCacheMap<string, ContextTimestamp>} */
  1063. this._contextTimestamps = new StackedCacheMap();
  1064. /** @type {Map<string, ContextHash>} */
  1065. this._contextHashes = new Map();
  1066. /** @type {Map<string, ContextTimestampAndHash>} */
  1067. this._contextTshs = new Map();
  1068. /** @type {Map<string, string>} */
  1069. this._managedItems = new Map();
  1070. /** @type {AsyncQueue<string, string, FileSystemInfoEntry>} */
  1071. this.fileTimestampQueue = new AsyncQueue({
  1072. name: "file timestamp",
  1073. parallelism: 30,
  1074. processor: this._readFileTimestamp.bind(this)
  1075. });
  1076. /** @type {AsyncQueue<string, string, string>} */
  1077. this.fileHashQueue = new AsyncQueue({
  1078. name: "file hash",
  1079. parallelism: 10,
  1080. processor: this._readFileHash.bind(this)
  1081. });
  1082. /** @type {AsyncQueue<string, string, ContextFileSystemInfoEntry>} */
  1083. this.contextTimestampQueue = new AsyncQueue({
  1084. name: "context timestamp",
  1085. parallelism: 2,
  1086. processor: this._readContextTimestamp.bind(this)
  1087. });
  1088. /** @type {AsyncQueue<string, string, ContextHash>} */
  1089. this.contextHashQueue = new AsyncQueue({
  1090. name: "context hash",
  1091. parallelism: 2,
  1092. processor: this._readContextHash.bind(this)
  1093. });
  1094. /** @type {AsyncQueue<string, string, ContextTimestampAndHash>} */
  1095. this.contextTshQueue = new AsyncQueue({
  1096. name: "context hash and timestamp",
  1097. parallelism: 2,
  1098. processor: this._readContextTimestampAndHash.bind(this)
  1099. });
  1100. /** @type {AsyncQueue<string, string, string>} */
  1101. this.managedItemQueue = new AsyncQueue({
  1102. name: "managed item info",
  1103. parallelism: 10,
  1104. processor: this._getManagedItemInfo.bind(this)
  1105. });
  1106. /** @type {AsyncQueue<string, string, Set<string>>} */
  1107. this.managedItemDirectoryQueue = new AsyncQueue({
  1108. name: "managed item directory info",
  1109. parallelism: 10,
  1110. processor: this._getManagedItemDirectoryInfo.bind(this)
  1111. });
  1112. const _unmanagedPaths = [...unmanagedPaths];
  1113. this.unmanagedPathsWithSlash =
  1114. /** @type {string[]} */
  1115. (_unmanagedPaths.filter((p) => typeof p === "string")).map((p) =>
  1116. join(fs, p, "_").slice(0, -1)
  1117. );
  1118. this.unmanagedPathsRegExps =
  1119. /** @type {RegExp[]} */
  1120. (_unmanagedPaths.filter((p) => typeof p !== "string"));
  1121. this.managedPaths = [...managedPaths];
  1122. this.managedPathsWithSlash =
  1123. /** @type {string[]} */
  1124. (this.managedPaths.filter((p) => typeof p === "string")).map((p) =>
  1125. join(fs, p, "_").slice(0, -1)
  1126. );
  1127. this.managedPathsRegExps =
  1128. /** @type {RegExp[]} */
  1129. (this.managedPaths.filter((p) => typeof p !== "string"));
  1130. this.immutablePaths = [...immutablePaths];
  1131. this.immutablePathsWithSlash =
  1132. /** @type {string[]} */
  1133. (this.immutablePaths.filter((p) => typeof p === "string")).map((p) =>
  1134. join(fs, p, "_").slice(0, -1)
  1135. );
  1136. this.immutablePathsRegExps =
  1137. /** @type {RegExp[]} */
  1138. (this.immutablePaths.filter((p) => typeof p !== "string"));
  1139. this._cachedDeprecatedFileTimestamps = undefined;
  1140. this._cachedDeprecatedContextTimestamps = undefined;
  1141. this._warnAboutExperimentalEsmTracking = false;
  1142. this._statCreatedSnapshots = 0;
  1143. this._statTestedSnapshotsCached = 0;
  1144. this._statTestedSnapshotsNotCached = 0;
  1145. this._statTestedChildrenCached = 0;
  1146. this._statTestedChildrenNotCached = 0;
  1147. this._statTestedEntries = 0;
  1148. }
  1149. logStatistics() {
  1150. const logger = /** @type {Logger} */ (this.logger);
  1151. /**
  1152. * @param {string} header header
  1153. * @param {string | undefined} message message
  1154. */
  1155. const logWhenMessage = (header, message) => {
  1156. if (message) {
  1157. logger.log(`${header}: ${message}`);
  1158. }
  1159. };
  1160. logger.log(`${this._statCreatedSnapshots} new snapshots created`);
  1161. logger.log(
  1162. `${
  1163. this._statTestedSnapshotsNotCached &&
  1164. Math.round(
  1165. (this._statTestedSnapshotsNotCached * 100) /
  1166. (this._statTestedSnapshotsCached +
  1167. this._statTestedSnapshotsNotCached)
  1168. )
  1169. }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${
  1170. this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached
  1171. })`
  1172. );
  1173. logger.log(
  1174. `${
  1175. this._statTestedChildrenNotCached &&
  1176. Math.round(
  1177. (this._statTestedChildrenNotCached * 100) /
  1178. (this._statTestedChildrenCached + this._statTestedChildrenNotCached)
  1179. )
  1180. }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${
  1181. this._statTestedChildrenCached + this._statTestedChildrenNotCached
  1182. })`
  1183. );
  1184. logger.log(`${this._statTestedEntries} entries tested`);
  1185. logger.log(
  1186. `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations`
  1187. );
  1188. logWhenMessage(
  1189. "File timestamp snapshot optimization",
  1190. this._fileTimestampsOptimization.getStatisticMessage()
  1191. );
  1192. logWhenMessage(
  1193. "File hash snapshot optimization",
  1194. this._fileHashesOptimization.getStatisticMessage()
  1195. );
  1196. logWhenMessage(
  1197. "File timestamp hash combination snapshot optimization",
  1198. this._fileTshsOptimization.getStatisticMessage()
  1199. );
  1200. logger.log(
  1201. `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations`
  1202. );
  1203. logWhenMessage(
  1204. "Directory timestamp snapshot optimization",
  1205. this._contextTimestampsOptimization.getStatisticMessage()
  1206. );
  1207. logWhenMessage(
  1208. "Directory hash snapshot optimization",
  1209. this._contextHashesOptimization.getStatisticMessage()
  1210. );
  1211. logWhenMessage(
  1212. "Directory timestamp hash combination snapshot optimization",
  1213. this._contextTshsOptimization.getStatisticMessage()
  1214. );
  1215. logWhenMessage(
  1216. "Missing items snapshot optimization",
  1217. this._missingExistenceOptimization.getStatisticMessage()
  1218. );
  1219. logger.log(`Managed items info in cache: ${this._managedItems.size} items`);
  1220. logWhenMessage(
  1221. "Managed items snapshot optimization",
  1222. this._managedItemInfoOptimization.getStatisticMessage()
  1223. );
  1224. logWhenMessage(
  1225. "Managed files snapshot optimization",
  1226. this._managedFilesOptimization.getStatisticMessage()
  1227. );
  1228. logWhenMessage(
  1229. "Managed contexts snapshot optimization",
  1230. this._managedContextsOptimization.getStatisticMessage()
  1231. );
  1232. logWhenMessage(
  1233. "Managed missing snapshot optimization",
  1234. this._managedMissingOptimization.getStatisticMessage()
  1235. );
  1236. }
  1237. /**
  1238. * @private
  1239. * @param {string} path path
  1240. * @param {string} reason reason
  1241. * @param {EXPECTED_ANY[]} args arguments
  1242. */
  1243. _log(path, reason, ...args) {
  1244. const key = path + reason;
  1245. const loggedPaths = /** @type {LoggedPaths} */ (this._loggedPaths);
  1246. if (loggedPaths.has(key)) return;
  1247. loggedPaths.add(key);
  1248. /** @type {Logger} */
  1249. (this.logger).debug(`${path} invalidated because ${reason}`, ...args);
  1250. if (--this._remainingLogs === 0) {
  1251. /** @type {Logger} */
  1252. (this.logger).debug(
  1253. "Logging limit has been reached and no further logging will be emitted by FileSystemInfo"
  1254. );
  1255. }
  1256. }
  1257. clear() {
  1258. this._remainingLogs = this.logger ? 40 : 0;
  1259. if (this._loggedPaths !== undefined) this._loggedPaths.clear();
  1260. this._snapshotCache = new WeakMap();
  1261. this._fileTimestampsOptimization.clear();
  1262. this._fileHashesOptimization.clear();
  1263. this._fileTshsOptimization.clear();
  1264. this._contextTimestampsOptimization.clear();
  1265. this._contextHashesOptimization.clear();
  1266. this._contextTshsOptimization.clear();
  1267. this._missingExistenceOptimization.clear();
  1268. this._managedItemInfoOptimization.clear();
  1269. this._managedFilesOptimization.clear();
  1270. this._managedContextsOptimization.clear();
  1271. this._managedMissingOptimization.clear();
  1272. this._fileTimestamps.clear();
  1273. this._fileHashes.clear();
  1274. this._fileTshs.clear();
  1275. this._contextTimestamps.clear();
  1276. this._contextHashes.clear();
  1277. this._contextTshs.clear();
  1278. this._managedItems.clear();
  1279. this._managedItems.clear();
  1280. this._cachedDeprecatedFileTimestamps = undefined;
  1281. this._cachedDeprecatedContextTimestamps = undefined;
  1282. this._statCreatedSnapshots = 0;
  1283. this._statTestedSnapshotsCached = 0;
  1284. this._statTestedSnapshotsNotCached = 0;
  1285. this._statTestedChildrenCached = 0;
  1286. this._statTestedChildrenNotCached = 0;
  1287. this._statTestedEntries = 0;
  1288. }
  1289. /**
  1290. * @param {ReadonlyMap<string, FileTimestamp>} map timestamps
  1291. * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it
  1292. * @returns {void}
  1293. */
  1294. addFileTimestamps(map, immutable) {
  1295. this._fileTimestamps.addAll(map, immutable);
  1296. this._cachedDeprecatedFileTimestamps = undefined;
  1297. }
  1298. /**
  1299. * @param {ReadonlyMap<string, ContextTimestamp>} map timestamps
  1300. * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it
  1301. * @returns {void}
  1302. */
  1303. addContextTimestamps(map, immutable) {
  1304. this._contextTimestamps.addAll(map, immutable);
  1305. this._cachedDeprecatedContextTimestamps = undefined;
  1306. }
  1307. /**
  1308. * @param {string} path file path
  1309. * @param {(err?: WebpackError | null, fileTimestamp?: FileTimestamp) => void} callback callback function
  1310. * @returns {void}
  1311. */
  1312. getFileTimestamp(path, callback) {
  1313. const cache = this._fileTimestamps.get(path);
  1314. if (cache !== undefined) return callback(null, cache);
  1315. this.fileTimestampQueue.add(path, callback);
  1316. }
  1317. /**
  1318. * @param {string} path context path
  1319. * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback function
  1320. * @returns {void}
  1321. */
  1322. getContextTimestamp(path, callback) {
  1323. const cache = this._contextTimestamps.get(path);
  1324. if (cache !== undefined) {
  1325. if (cache === "ignore") return callback(null, "ignore");
  1326. const resolved = getResolvedTimestamp(cache);
  1327. if (resolved !== undefined) return callback(null, resolved);
  1328. return this._resolveContextTimestamp(
  1329. /** @type {ResolvedContextFileSystemInfoEntry} */
  1330. (cache),
  1331. callback
  1332. );
  1333. }
  1334. this.contextTimestampQueue.add(path, (err, _entry) => {
  1335. if (err) return callback(err);
  1336. const entry = /** @type {ContextFileSystemInfoEntry} */ (_entry);
  1337. const resolved = getResolvedTimestamp(entry);
  1338. if (resolved !== undefined) return callback(null, resolved);
  1339. this._resolveContextTimestamp(entry, callback);
  1340. });
  1341. }
  1342. /**
  1343. * @private
  1344. * @param {string} path context path
  1345. * @param {(err?: WebpackError | null, contextTimestamp?: ContextTimestamp) => void} callback callback function
  1346. * @returns {void}
  1347. */
  1348. _getUnresolvedContextTimestamp(path, callback) {
  1349. const cache = this._contextTimestamps.get(path);
  1350. if (cache !== undefined) return callback(null, cache);
  1351. this.contextTimestampQueue.add(path, callback);
  1352. }
  1353. /**
  1354. * @param {string} path file path
  1355. * @param {(err?: WebpackError | null, hash?: string | null) => void} callback callback function
  1356. * @returns {void}
  1357. */
  1358. getFileHash(path, callback) {
  1359. const cache = this._fileHashes.get(path);
  1360. if (cache !== undefined) return callback(null, cache);
  1361. this.fileHashQueue.add(path, callback);
  1362. }
  1363. /**
  1364. * @param {string} path context path
  1365. * @param {(err?: WebpackError | null, contextHash?: string) => void} callback callback function
  1366. * @returns {void}
  1367. */
  1368. getContextHash(path, callback) {
  1369. const cache = this._contextHashes.get(path);
  1370. if (cache !== undefined) {
  1371. const resolved = getResolvedHash(cache);
  1372. if (resolved !== undefined) {
  1373. return callback(null, /** @type {string} */ (resolved));
  1374. }
  1375. return this._resolveContextHash(cache, callback);
  1376. }
  1377. this.contextHashQueue.add(path, (err, _entry) => {
  1378. if (err) return callback(err);
  1379. const entry = /** @type {ContextHash} */ (_entry);
  1380. const resolved = getResolvedHash(entry);
  1381. if (resolved !== undefined) {
  1382. return callback(null, /** @type {string} */ (resolved));
  1383. }
  1384. this._resolveContextHash(entry, callback);
  1385. });
  1386. }
  1387. /**
  1388. * @private
  1389. * @param {string} path context path
  1390. * @param {(err?: WebpackError | null, contextHash?: ContextHash | null) => void} callback callback function
  1391. * @returns {void}
  1392. */
  1393. _getUnresolvedContextHash(path, callback) {
  1394. const cache = this._contextHashes.get(path);
  1395. if (cache !== undefined) return callback(null, cache);
  1396. this.contextHashQueue.add(path, callback);
  1397. }
  1398. /**
  1399. * @param {string} path context path
  1400. * @param {(err?: WebpackError | null, resolvedContextTimestampAndHash?: ResolvedContextTimestampAndHash | null) => void} callback callback function
  1401. * @returns {void}
  1402. */
  1403. getContextTsh(path, callback) {
  1404. const cache = this._contextTshs.get(path);
  1405. if (cache !== undefined) {
  1406. const resolved = getResolvedTimestamp(cache);
  1407. if (resolved !== undefined) return callback(null, resolved);
  1408. return this._resolveContextTsh(cache, callback);
  1409. }
  1410. this.contextTshQueue.add(path, (err, _entry) => {
  1411. if (err) return callback(err);
  1412. const entry = /** @type {ContextTimestampAndHash} */ (_entry);
  1413. const resolved = getResolvedTimestamp(entry);
  1414. if (resolved !== undefined) return callback(null, resolved);
  1415. this._resolveContextTsh(entry, callback);
  1416. });
  1417. }
  1418. /**
  1419. * @private
  1420. * @param {string} path context path
  1421. * @param {(err?: WebpackError | null, contextTimestampAndHash?: ContextTimestampAndHash | null) => void} callback callback function
  1422. * @returns {void}
  1423. */
  1424. _getUnresolvedContextTsh(path, callback) {
  1425. const cache = this._contextTshs.get(path);
  1426. if (cache !== undefined) return callback(null, cache);
  1427. this.contextTshQueue.add(path, callback);
  1428. }
  1429. _createBuildDependenciesResolvers() {
  1430. const resolveContext = createResolver({
  1431. resolveToContext: true,
  1432. exportsFields: [],
  1433. fileSystem: this.fs
  1434. });
  1435. const resolveCjs = createResolver({
  1436. extensions: [".js", ".json", ".node"],
  1437. conditionNames: ["require", "node"],
  1438. exportsFields: ["exports"],
  1439. fileSystem: this.fs
  1440. });
  1441. const resolveCjsAsChild = createResolver({
  1442. extensions: [".js", ".json", ".node"],
  1443. conditionNames: ["require", "node"],
  1444. exportsFields: [],
  1445. fileSystem: this.fs
  1446. });
  1447. const resolveEsm = createResolver({
  1448. extensions: [".js", ".json", ".node"],
  1449. fullySpecified: true,
  1450. conditionNames: ["import", "node"],
  1451. exportsFields: ["exports"],
  1452. fileSystem: this.fs
  1453. });
  1454. return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild };
  1455. }
  1456. /**
  1457. * @param {string} context context directory
  1458. * @param {Iterable<string>} deps dependencies
  1459. * @param {(err?: Error | null, resolveBuildDependenciesResult?: ResolveBuildDependenciesResult) => void} callback callback function
  1460. * @returns {void}
  1461. */
  1462. resolveBuildDependencies(context, deps, callback) {
  1463. const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } =
  1464. this._createBuildDependenciesResolvers();
  1465. /** @type {Files} */
  1466. const files = new Set();
  1467. /** @type {Symlinks} */
  1468. const fileSymlinks = new Set();
  1469. /** @type {Directories} */
  1470. const directories = new Set();
  1471. /** @type {Symlinks} */
  1472. const directorySymlinks = new Set();
  1473. /** @type {Missing} */
  1474. const missing = new Set();
  1475. /** @type {ResolveDependencies["files"]} */
  1476. const resolveFiles = new Set();
  1477. /** @type {ResolveDependencies["directories"]} */
  1478. const resolveDirectories = new Set();
  1479. /** @type {ResolveDependencies["missing"]} */
  1480. const resolveMissing = new Set();
  1481. /** @type {ResolveResults} */
  1482. const resolveResults = new Map();
  1483. /** @type {Set<string>} */
  1484. const invalidResolveResults = new Set();
  1485. const resolverContext = {
  1486. fileDependencies: resolveFiles,
  1487. contextDependencies: resolveDirectories,
  1488. missingDependencies: resolveMissing
  1489. };
  1490. /**
  1491. * @param {undefined | boolean | string} expected expected result
  1492. * @returns {string} expected result
  1493. */
  1494. const expectedToString = (expected) =>
  1495. expected ? ` (expected ${expected})` : "";
  1496. /** @typedef {{ type: JobType, context: string | undefined, path: string, issuer: Job | undefined, expected: undefined | boolean | string }} Job */
  1497. /**
  1498. * @param {Job} job job
  1499. * @returns {`resolve commonjs file ${string}${string}`|`resolve esm file ${string}${string}`|`resolve esm ${string}${string}`|`resolve directory ${string}`|`file ${string}`|`unknown ${string} ${string}`|`resolve commonjs ${string}${string}`|`directory ${string}`|`file dependencies ${string}`|`directory dependencies ${string}`} result
  1500. */
  1501. const jobToString = (job) => {
  1502. switch (job.type) {
  1503. case RBDT_RESOLVE_CJS:
  1504. return `resolve commonjs ${job.path}${expectedToString(
  1505. job.expected
  1506. )}`;
  1507. case RBDT_RESOLVE_ESM:
  1508. return `resolve esm ${job.path}${expectedToString(job.expected)}`;
  1509. case RBDT_RESOLVE_DIRECTORY:
  1510. return `resolve directory ${job.path}`;
  1511. case RBDT_RESOLVE_CJS_FILE:
  1512. return `resolve commonjs file ${job.path}${expectedToString(
  1513. job.expected
  1514. )}`;
  1515. case RBDT_RESOLVE_ESM_FILE:
  1516. return `resolve esm file ${job.path}${expectedToString(
  1517. job.expected
  1518. )}`;
  1519. case RBDT_DIRECTORY:
  1520. return `directory ${job.path}`;
  1521. case RBDT_FILE:
  1522. return `file ${job.path}`;
  1523. case RBDT_DIRECTORY_DEPENDENCIES:
  1524. return `directory dependencies ${job.path}`;
  1525. case RBDT_FILE_DEPENDENCIES:
  1526. return `file dependencies ${job.path}`;
  1527. }
  1528. return `unknown ${job.type} ${job.path}`;
  1529. };
  1530. /**
  1531. * @param {Job} job job
  1532. * @returns {string} string value
  1533. */
  1534. const pathToString = (job) => {
  1535. let result = ` at ${jobToString(job)}`;
  1536. /** @type {Job | undefined} */
  1537. (job) = job.issuer;
  1538. while (job !== undefined) {
  1539. result += `\n at ${jobToString(job)}`;
  1540. job = /** @type {Job} */ (job.issuer);
  1541. }
  1542. return result;
  1543. };
  1544. const logger = /** @type {Logger} */ (this.logger);
  1545. processAsyncTree(
  1546. Array.from(
  1547. deps,
  1548. (dep) =>
  1549. /** @type {Job} */ ({
  1550. type: RBDT_RESOLVE_CJS,
  1551. context,
  1552. path: dep,
  1553. expected: undefined,
  1554. issuer: undefined
  1555. })
  1556. ),
  1557. 20,
  1558. (job, push, callback) => {
  1559. const { type, context, path, expected } = job;
  1560. /**
  1561. * @param {string} path path
  1562. * @returns {void}
  1563. */
  1564. const resolveDirectory = (path) => {
  1565. const key = `d\n${context}\n${path}`;
  1566. if (resolveResults.has(key)) {
  1567. return callback();
  1568. }
  1569. resolveResults.set(key, undefined);
  1570. resolveContext(
  1571. /** @type {string} */ (context),
  1572. path,
  1573. resolverContext,
  1574. (err, _, result) => {
  1575. if (err) {
  1576. if (expected === false) {
  1577. resolveResults.set(key, false);
  1578. return callback();
  1579. }
  1580. invalidResolveResults.add(key);
  1581. err.message += `\nwhile resolving '${path}' in ${context} to a directory`;
  1582. return callback(err);
  1583. }
  1584. const resultPath = /** @type {ResolveRequest} */ (result).path;
  1585. resolveResults.set(key, resultPath);
  1586. push({
  1587. type: RBDT_DIRECTORY,
  1588. context: undefined,
  1589. path: /** @type {string} */ (resultPath),
  1590. expected: undefined,
  1591. issuer: job
  1592. });
  1593. callback();
  1594. }
  1595. );
  1596. };
  1597. /**
  1598. * @param {string} path path
  1599. * @param {("f" | "c" | "e")=} symbol symbol
  1600. * @param {(ResolveFunctionAsync)=} resolve resolve fn
  1601. * @returns {void}
  1602. */
  1603. const resolveFile = (path, symbol, resolve) => {
  1604. const key = `${symbol}\n${context}\n${path}`;
  1605. if (resolveResults.has(key)) {
  1606. return callback();
  1607. }
  1608. resolveResults.set(key, undefined);
  1609. /** @type {ResolveFunctionAsync} */
  1610. (resolve)(
  1611. /** @type {string} */ (context),
  1612. path,
  1613. resolverContext,
  1614. (err, _, result) => {
  1615. if (typeof expected === "string") {
  1616. if (!err && result && result.path === expected) {
  1617. resolveResults.set(key, result.path);
  1618. } else {
  1619. invalidResolveResults.add(key);
  1620. logger.warn(
  1621. `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${
  1622. err || (result && result.path)
  1623. }' instead. Resolving dependencies are ignored for this path.\n${pathToString(
  1624. job
  1625. )}`
  1626. );
  1627. }
  1628. } else {
  1629. if (err) {
  1630. if (expected === false) {
  1631. resolveResults.set(key, false);
  1632. return callback();
  1633. }
  1634. invalidResolveResults.add(key);
  1635. err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString(
  1636. job
  1637. )}`;
  1638. return callback(err);
  1639. }
  1640. const resultPath = /** @type {ResolveRequest} */ (result).path;
  1641. resolveResults.set(key, resultPath);
  1642. push({
  1643. type: RBDT_FILE,
  1644. context: undefined,
  1645. path: /** @type {string} */ (resultPath),
  1646. expected: undefined,
  1647. issuer: job
  1648. });
  1649. }
  1650. callback();
  1651. }
  1652. );
  1653. };
  1654. switch (type) {
  1655. case RBDT_RESOLVE_CJS: {
  1656. const isDirectory = /[\\/]$/.test(path);
  1657. if (isDirectory) {
  1658. resolveDirectory(path.slice(0, -1));
  1659. } else {
  1660. resolveFile(path, "f", resolveCjs);
  1661. }
  1662. break;
  1663. }
  1664. case RBDT_RESOLVE_ESM: {
  1665. const isDirectory = /[\\/]$/.test(path);
  1666. if (isDirectory) {
  1667. resolveDirectory(path.slice(0, -1));
  1668. } else {
  1669. resolveFile(path);
  1670. }
  1671. break;
  1672. }
  1673. case RBDT_RESOLVE_DIRECTORY: {
  1674. resolveDirectory(path);
  1675. break;
  1676. }
  1677. case RBDT_RESOLVE_CJS_FILE: {
  1678. resolveFile(path, "f", resolveCjs);
  1679. break;
  1680. }
  1681. case RBDT_RESOLVE_CJS_FILE_AS_CHILD: {
  1682. resolveFile(path, "c", resolveCjsAsChild);
  1683. break;
  1684. }
  1685. case RBDT_RESOLVE_ESM_FILE: {
  1686. resolveFile(path, "e", resolveEsm);
  1687. break;
  1688. }
  1689. case RBDT_FILE: {
  1690. if (files.has(path)) {
  1691. callback();
  1692. break;
  1693. }
  1694. files.add(path);
  1695. /** @type {NonNullable<InputFileSystem["realpath"]>} */
  1696. (this.fs.realpath)(path, (err, _realPath) => {
  1697. if (err) return callback(err);
  1698. const realPath = /** @type {string} */ (_realPath);
  1699. if (realPath !== path) {
  1700. fileSymlinks.add(path);
  1701. resolveFiles.add(path);
  1702. if (files.has(realPath)) return callback();
  1703. files.add(realPath);
  1704. }
  1705. push({
  1706. type: RBDT_FILE_DEPENDENCIES,
  1707. context: undefined,
  1708. path: realPath,
  1709. expected: undefined,
  1710. issuer: job
  1711. });
  1712. callback();
  1713. });
  1714. break;
  1715. }
  1716. case RBDT_DIRECTORY: {
  1717. if (directories.has(path)) {
  1718. callback();
  1719. break;
  1720. }
  1721. directories.add(path);
  1722. /** @type {NonNullable<InputFileSystem["realpath"]>} */
  1723. (this.fs.realpath)(path, (err, _realPath) => {
  1724. if (err) return callback(err);
  1725. const realPath = /** @type {string} */ (_realPath);
  1726. if (realPath !== path) {
  1727. directorySymlinks.add(path);
  1728. resolveFiles.add(path);
  1729. if (directories.has(realPath)) return callback();
  1730. directories.add(realPath);
  1731. }
  1732. push({
  1733. type: RBDT_DIRECTORY_DEPENDENCIES,
  1734. context: undefined,
  1735. path: realPath,
  1736. expected: undefined,
  1737. issuer: job
  1738. });
  1739. callback();
  1740. });
  1741. break;
  1742. }
  1743. case RBDT_FILE_DEPENDENCIES: {
  1744. // Check for known files without dependencies
  1745. if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) {
  1746. process.nextTick(callback);
  1747. break;
  1748. }
  1749. // Check commonjs cache for the module
  1750. /** @type {NodeModule | undefined} */
  1751. const module = require.cache[path];
  1752. if (module && Array.isArray(module.children)) {
  1753. children: for (const child of module.children) {
  1754. const childPath = child.filename;
  1755. if (childPath) {
  1756. push({
  1757. type: RBDT_FILE,
  1758. context: undefined,
  1759. path: childPath,
  1760. expected: undefined,
  1761. issuer: job
  1762. });
  1763. const context = dirname(this.fs, path);
  1764. for (const modulePath of module.paths) {
  1765. if (childPath.startsWith(modulePath)) {
  1766. const subPath = childPath.slice(modulePath.length + 1);
  1767. const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec(
  1768. subPath
  1769. );
  1770. if (packageMatch) {
  1771. push({
  1772. type: RBDT_FILE,
  1773. context: undefined,
  1774. path: `${
  1775. modulePath +
  1776. childPath[modulePath.length] +
  1777. packageMatch[0] +
  1778. childPath[modulePath.length]
  1779. }package.json`,
  1780. expected: false,
  1781. issuer: job
  1782. });
  1783. }
  1784. let request = subPath.replace(/\\/g, "/");
  1785. if (request.endsWith(".js")) {
  1786. request = request.slice(0, -3);
  1787. }
  1788. push({
  1789. type: RBDT_RESOLVE_CJS_FILE_AS_CHILD,
  1790. context,
  1791. path: request,
  1792. expected: child.filename,
  1793. issuer: job
  1794. });
  1795. continue children;
  1796. }
  1797. }
  1798. let request = relative(this.fs, context, childPath);
  1799. if (request.endsWith(".js")) request = request.slice(0, -3);
  1800. request = request.replace(/\\/g, "/");
  1801. if (!request.startsWith("../") && !isAbsolute(request)) {
  1802. request = `./${request}`;
  1803. }
  1804. push({
  1805. type: RBDT_RESOLVE_CJS_FILE,
  1806. context,
  1807. path: request,
  1808. expected: child.filename,
  1809. issuer: job
  1810. });
  1811. }
  1812. }
  1813. } else if (supportsEsm && /\.m?js$/.test(path)) {
  1814. if (!this._warnAboutExperimentalEsmTracking) {
  1815. logger.log(
  1816. "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" +
  1817. "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" +
  1818. "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking."
  1819. );
  1820. this._warnAboutExperimentalEsmTracking = true;
  1821. }
  1822. const lexer = getEsModuleLexer();
  1823. lexer.init.then(() => {
  1824. this.fs.readFile(path, (err, content) => {
  1825. if (err) return callback(err);
  1826. try {
  1827. const context = dirname(this.fs, path);
  1828. const source = /** @type {Buffer} */ (content).toString();
  1829. const [imports] = lexer.parse(source);
  1830. for (const imp of imports) {
  1831. try {
  1832. let dependency;
  1833. if (imp.d === -1) {
  1834. // import ... from "..."
  1835. dependency = parseString(
  1836. source.slice(imp.s - 1, imp.e + 1)
  1837. );
  1838. } else if (imp.d > -1) {
  1839. // import()
  1840. const expr = source.slice(imp.s, imp.e).trim();
  1841. dependency = parseString(expr);
  1842. } else {
  1843. // e.g. import.meta
  1844. continue;
  1845. }
  1846. // we should not track Node.js build dependencies
  1847. if (dependency.startsWith("node:")) continue;
  1848. if (builtinModules.has(dependency)) continue;
  1849. push({
  1850. type: RBDT_RESOLVE_ESM_FILE,
  1851. context,
  1852. path: dependency,
  1853. expected: imp.d > -1 ? false : undefined,
  1854. issuer: job
  1855. });
  1856. } catch (err1) {
  1857. logger.warn(
  1858. `Parsing of ${path} for build dependencies failed at 'import(${source.slice(
  1859. imp.s,
  1860. imp.e
  1861. )})'.\n` +
  1862. "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation."
  1863. );
  1864. logger.debug(pathToString(job));
  1865. logger.debug(/** @type {Error} */ (err1).stack);
  1866. }
  1867. }
  1868. } catch (err2) {
  1869. logger.warn(
  1870. `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..`
  1871. );
  1872. logger.debug(pathToString(job));
  1873. logger.debug(/** @type {Error} */ (err2).stack);
  1874. }
  1875. process.nextTick(callback);
  1876. });
  1877. }, callback);
  1878. break;
  1879. } else {
  1880. logger.log(
  1881. `Assuming ${path} has no dependencies as we were unable to assign it to any module system.`
  1882. );
  1883. logger.debug(pathToString(job));
  1884. }
  1885. process.nextTick(callback);
  1886. break;
  1887. }
  1888. case RBDT_DIRECTORY_DEPENDENCIES: {
  1889. const match =
  1890. /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path);
  1891. const packagePath = match ? match[1] : path;
  1892. const packageJson = join(this.fs, packagePath, "package.json");
  1893. this.fs.readFile(packageJson, (err, content) => {
  1894. if (err) {
  1895. if (err.code === "ENOENT") {
  1896. resolveMissing.add(packageJson);
  1897. const parent = dirname(this.fs, packagePath);
  1898. if (parent !== packagePath) {
  1899. push({
  1900. type: RBDT_DIRECTORY_DEPENDENCIES,
  1901. context: undefined,
  1902. path: parent,
  1903. expected: undefined,
  1904. issuer: job
  1905. });
  1906. }
  1907. callback();
  1908. return;
  1909. }
  1910. return callback(err);
  1911. }
  1912. resolveFiles.add(packageJson);
  1913. let packageData;
  1914. try {
  1915. packageData = JSON.parse(
  1916. /** @type {Buffer} */
  1917. (content).toString("utf8")
  1918. );
  1919. } catch (parseErr) {
  1920. return callback(/** @type {Error} */ (parseErr));
  1921. }
  1922. const depsObject = packageData.dependencies;
  1923. const optionalDepsObject = packageData.optionalDependencies;
  1924. const allDeps = new Set();
  1925. const optionalDeps = new Set();
  1926. if (typeof depsObject === "object" && depsObject) {
  1927. for (const dep of Object.keys(depsObject)) {
  1928. allDeps.add(dep);
  1929. }
  1930. }
  1931. if (
  1932. typeof optionalDepsObject === "object" &&
  1933. optionalDepsObject
  1934. ) {
  1935. for (const dep of Object.keys(optionalDepsObject)) {
  1936. allDeps.add(dep);
  1937. optionalDeps.add(dep);
  1938. }
  1939. }
  1940. for (const dep of allDeps) {
  1941. push({
  1942. type: RBDT_RESOLVE_DIRECTORY,
  1943. context: packagePath,
  1944. path: dep,
  1945. expected: !optionalDeps.has(dep),
  1946. issuer: job
  1947. });
  1948. }
  1949. callback();
  1950. });
  1951. break;
  1952. }
  1953. }
  1954. },
  1955. (err) => {
  1956. if (err) return callback(err);
  1957. for (const l of fileSymlinks) files.delete(l);
  1958. for (const l of directorySymlinks) directories.delete(l);
  1959. for (const k of invalidResolveResults) resolveResults.delete(k);
  1960. callback(null, {
  1961. files,
  1962. directories,
  1963. missing,
  1964. resolveResults,
  1965. resolveDependencies: {
  1966. files: resolveFiles,
  1967. directories: resolveDirectories,
  1968. missing: resolveMissing
  1969. }
  1970. });
  1971. }
  1972. );
  1973. }
  1974. /**
  1975. * @param {ResolveResults} resolveResults results from resolving
  1976. * @param {(err?: Error | null, result?: boolean) => void} callback callback with true when resolveResults resolve the same way
  1977. * @returns {void}
  1978. */
  1979. checkResolveResultsValid(resolveResults, callback) {
  1980. const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } =
  1981. this._createBuildDependenciesResolvers();
  1982. asyncLib.eachLimit(
  1983. resolveResults,
  1984. 20,
  1985. ([key, expectedResult], callback) => {
  1986. const [type, context, path] = key.split("\n");
  1987. switch (type) {
  1988. case "d":
  1989. resolveContext(context, path, {}, (err, _, result) => {
  1990. if (expectedResult === false) {
  1991. return callback(err ? undefined : INVALID);
  1992. }
  1993. if (err) return callback(err);
  1994. const resultPath = /** @type {ResolveRequest} */ (result).path;
  1995. if (resultPath !== expectedResult) return callback(INVALID);
  1996. callback();
  1997. });
  1998. break;
  1999. case "f":
  2000. resolveCjs(context, path, {}, (err, _, result) => {
  2001. if (expectedResult === false) {
  2002. return callback(err ? undefined : INVALID);
  2003. }
  2004. if (err) return callback(err);
  2005. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2006. if (resultPath !== expectedResult) return callback(INVALID);
  2007. callback();
  2008. });
  2009. break;
  2010. case "c":
  2011. resolveCjsAsChild(context, path, {}, (err, _, result) => {
  2012. if (expectedResult === false) {
  2013. return callback(err ? undefined : INVALID);
  2014. }
  2015. if (err) return callback(err);
  2016. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2017. if (resultPath !== expectedResult) return callback(INVALID);
  2018. callback();
  2019. });
  2020. break;
  2021. case "e":
  2022. resolveEsm(context, path, {}, (err, _, result) => {
  2023. if (expectedResult === false) {
  2024. return callback(err ? undefined : INVALID);
  2025. }
  2026. if (err) return callback(err);
  2027. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2028. if (resultPath !== expectedResult) return callback(INVALID);
  2029. callback();
  2030. });
  2031. break;
  2032. default:
  2033. callback(new Error("Unexpected type in resolve result key"));
  2034. break;
  2035. }
  2036. },
  2037. /**
  2038. * @param {Error | typeof INVALID=} err error or invalid flag
  2039. * @returns {void}
  2040. */
  2041. (err) => {
  2042. if (err === INVALID) {
  2043. return callback(null, false);
  2044. }
  2045. if (err) {
  2046. return callback(err);
  2047. }
  2048. return callback(null, true);
  2049. }
  2050. );
  2051. }
  2052. /**
  2053. * @param {number | null | undefined} startTime when processing the files has started
  2054. * @param {Iterable<string> | null | undefined} files all files
  2055. * @param {Iterable<string> | null | undefined} directories all directories
  2056. * @param {Iterable<string> | null | undefined} missing all missing files or directories
  2057. * @param {SnapshotOptions | null | undefined} options options object (for future extensions)
  2058. * @param {(err: WebpackError | null, snapshot: Snapshot | null) => void} callback callback function
  2059. * @returns {void}
  2060. */
  2061. createSnapshot(startTime, files, directories, missing, options, callback) {
  2062. /** @type {FileTimestamps} */
  2063. const fileTimestamps = new Map();
  2064. /** @type {FileHashes} */
  2065. const fileHashes = new Map();
  2066. /** @type {FileTshs} */
  2067. const fileTshs = new Map();
  2068. /** @type {ContextTimestamps} */
  2069. const contextTimestamps = new Map();
  2070. /** @type {ContextHashes} */
  2071. const contextHashes = new Map();
  2072. /** @type {ContextTshs} */
  2073. const contextTshs = new Map();
  2074. /** @type {MissingExistence} */
  2075. const missingExistence = new Map();
  2076. /** @type {ManagedItemInfo} */
  2077. const managedItemInfo = new Map();
  2078. /** @type {ManagedFiles} */
  2079. const managedFiles = new Set();
  2080. /** @type {ManagedContexts} */
  2081. const managedContexts = new Set();
  2082. /** @type {ManagedMissing} */
  2083. const managedMissing = new Set();
  2084. /** @type {Children} */
  2085. const children = new Set();
  2086. const snapshot = new Snapshot();
  2087. if (startTime) snapshot.setStartTime(startTime);
  2088. /** @type {Set<string>} */
  2089. const managedItems = new Set();
  2090. /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */
  2091. const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1;
  2092. let jobs = 1;
  2093. const jobDone = () => {
  2094. if (--jobs === 0) {
  2095. if (fileTimestamps.size !== 0) {
  2096. snapshot.setFileTimestamps(fileTimestamps);
  2097. }
  2098. if (fileHashes.size !== 0) {
  2099. snapshot.setFileHashes(fileHashes);
  2100. }
  2101. if (fileTshs.size !== 0) {
  2102. snapshot.setFileTshs(fileTshs);
  2103. }
  2104. if (contextTimestamps.size !== 0) {
  2105. snapshot.setContextTimestamps(contextTimestamps);
  2106. }
  2107. if (contextHashes.size !== 0) {
  2108. snapshot.setContextHashes(contextHashes);
  2109. }
  2110. if (contextTshs.size !== 0) {
  2111. snapshot.setContextTshs(contextTshs);
  2112. }
  2113. if (missingExistence.size !== 0) {
  2114. snapshot.setMissingExistence(missingExistence);
  2115. }
  2116. if (managedItemInfo.size !== 0) {
  2117. snapshot.setManagedItemInfo(managedItemInfo);
  2118. }
  2119. this._managedFilesOptimization.optimize(snapshot, managedFiles);
  2120. if (managedFiles.size !== 0) {
  2121. snapshot.setManagedFiles(managedFiles);
  2122. }
  2123. this._managedContextsOptimization.optimize(snapshot, managedContexts);
  2124. if (managedContexts.size !== 0) {
  2125. snapshot.setManagedContexts(managedContexts);
  2126. }
  2127. this._managedMissingOptimization.optimize(snapshot, managedMissing);
  2128. if (managedMissing.size !== 0) {
  2129. snapshot.setManagedMissing(managedMissing);
  2130. }
  2131. if (children.size !== 0) {
  2132. snapshot.setChildren(children);
  2133. }
  2134. this._snapshotCache.set(snapshot, true);
  2135. this._statCreatedSnapshots++;
  2136. callback(null, snapshot);
  2137. }
  2138. };
  2139. const jobError = () => {
  2140. if (jobs > 0) {
  2141. // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
  2142. jobs = -100000000;
  2143. callback(null, null);
  2144. }
  2145. };
  2146. /**
  2147. * @param {string} path path
  2148. * @param {ManagedFiles} managedSet managed set
  2149. * @returns {boolean} true when managed
  2150. */
  2151. const checkManaged = (path, managedSet) => {
  2152. for (const unmanagedPath of this.unmanagedPathsRegExps) {
  2153. if (unmanagedPath.test(path)) return false;
  2154. }
  2155. for (const unmanagedPath of this.unmanagedPathsWithSlash) {
  2156. if (path.startsWith(unmanagedPath)) return false;
  2157. }
  2158. for (const immutablePath of this.immutablePathsRegExps) {
  2159. if (immutablePath.test(path)) {
  2160. managedSet.add(path);
  2161. return true;
  2162. }
  2163. }
  2164. for (const immutablePath of this.immutablePathsWithSlash) {
  2165. if (path.startsWith(immutablePath)) {
  2166. managedSet.add(path);
  2167. return true;
  2168. }
  2169. }
  2170. for (const managedPath of this.managedPathsRegExps) {
  2171. const match = managedPath.exec(path);
  2172. if (match) {
  2173. const managedItem = getManagedItem(match[1], path);
  2174. if (managedItem) {
  2175. managedItems.add(managedItem);
  2176. managedSet.add(path);
  2177. return true;
  2178. }
  2179. }
  2180. }
  2181. for (const managedPath of this.managedPathsWithSlash) {
  2182. if (path.startsWith(managedPath)) {
  2183. const managedItem = getManagedItem(managedPath, path);
  2184. if (managedItem) {
  2185. managedItems.add(managedItem);
  2186. managedSet.add(path);
  2187. return true;
  2188. }
  2189. }
  2190. }
  2191. return false;
  2192. };
  2193. /**
  2194. * @param {Iterable<string>} items items
  2195. * @param {Set<string>} managedSet managed set
  2196. * @returns {Set<string>} result
  2197. */
  2198. const captureNonManaged = (items, managedSet) => {
  2199. /** @type {Set<string>} */
  2200. const capturedItems = new Set();
  2201. for (const path of items) {
  2202. if (!checkManaged(path, managedSet)) capturedItems.add(path);
  2203. }
  2204. return capturedItems;
  2205. };
  2206. /**
  2207. * @param {ManagedFiles} capturedFiles captured files
  2208. */
  2209. const processCapturedFiles = (capturedFiles) => {
  2210. switch (mode) {
  2211. case 3:
  2212. this._fileTshsOptimization.optimize(snapshot, capturedFiles);
  2213. for (const path of capturedFiles) {
  2214. const cache = this._fileTshs.get(path);
  2215. if (cache !== undefined) {
  2216. fileTshs.set(path, cache);
  2217. } else {
  2218. jobs++;
  2219. this._getFileTimestampAndHash(path, (err, entry) => {
  2220. if (err) {
  2221. if (this.logger) {
  2222. this.logger.debug(
  2223. `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}`
  2224. );
  2225. }
  2226. jobError();
  2227. } else {
  2228. fileTshs.set(path, /** @type {TimestampAndHash} */ (entry));
  2229. jobDone();
  2230. }
  2231. });
  2232. }
  2233. }
  2234. break;
  2235. case 2:
  2236. this._fileHashesOptimization.optimize(snapshot, capturedFiles);
  2237. for (const path of capturedFiles) {
  2238. const cache = this._fileHashes.get(path);
  2239. if (cache !== undefined) {
  2240. fileHashes.set(path, cache);
  2241. } else {
  2242. jobs++;
  2243. this.fileHashQueue.add(path, (err, entry) => {
  2244. if (err) {
  2245. if (this.logger) {
  2246. this.logger.debug(
  2247. `Error snapshotting file hash of ${path}: ${err.stack}`
  2248. );
  2249. }
  2250. jobError();
  2251. } else {
  2252. fileHashes.set(path, /** @type {string} */ (entry));
  2253. jobDone();
  2254. }
  2255. });
  2256. }
  2257. }
  2258. break;
  2259. case 1:
  2260. this._fileTimestampsOptimization.optimize(snapshot, capturedFiles);
  2261. for (const path of capturedFiles) {
  2262. const cache = this._fileTimestamps.get(path);
  2263. if (cache !== undefined) {
  2264. if (cache !== "ignore") {
  2265. fileTimestamps.set(path, cache);
  2266. }
  2267. } else {
  2268. jobs++;
  2269. this.fileTimestampQueue.add(path, (err, entry) => {
  2270. if (err) {
  2271. if (this.logger) {
  2272. this.logger.debug(
  2273. `Error snapshotting file timestamp of ${path}: ${err.stack}`
  2274. );
  2275. }
  2276. jobError();
  2277. } else {
  2278. fileTimestamps.set(
  2279. path,
  2280. /** @type {FileSystemInfoEntry} */
  2281. (entry)
  2282. );
  2283. jobDone();
  2284. }
  2285. });
  2286. }
  2287. }
  2288. break;
  2289. }
  2290. };
  2291. if (files) {
  2292. processCapturedFiles(captureNonManaged(files, managedFiles));
  2293. }
  2294. /**
  2295. * @param {ManagedContexts} capturedDirectories captured directories
  2296. */
  2297. const processCapturedDirectories = (capturedDirectories) => {
  2298. switch (mode) {
  2299. case 3:
  2300. this._contextTshsOptimization.optimize(snapshot, capturedDirectories);
  2301. for (const path of capturedDirectories) {
  2302. const cache = this._contextTshs.get(path);
  2303. /** @type {ResolvedContextTimestampAndHash | null | undefined} */
  2304. let resolved;
  2305. if (
  2306. cache !== undefined &&
  2307. (resolved = getResolvedTimestamp(cache)) !== undefined
  2308. ) {
  2309. contextTshs.set(path, resolved);
  2310. } else {
  2311. jobs++;
  2312. /**
  2313. * @param {(WebpackError | null)=} err error
  2314. * @param {(ResolvedContextTimestampAndHash | null)=} entry entry
  2315. * @returns {void}
  2316. */
  2317. const callback = (err, entry) => {
  2318. if (err) {
  2319. if (this.logger) {
  2320. this.logger.debug(
  2321. `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}`
  2322. );
  2323. }
  2324. jobError();
  2325. } else {
  2326. contextTshs.set(
  2327. path,
  2328. /** @type {ResolvedContextTimestampAndHash | null} */
  2329. (entry)
  2330. );
  2331. jobDone();
  2332. }
  2333. };
  2334. if (cache !== undefined) {
  2335. this._resolveContextTsh(cache, callback);
  2336. } else {
  2337. this.getContextTsh(path, callback);
  2338. }
  2339. }
  2340. }
  2341. break;
  2342. case 2:
  2343. this._contextHashesOptimization.optimize(
  2344. snapshot,
  2345. capturedDirectories
  2346. );
  2347. for (const path of capturedDirectories) {
  2348. const cache = this._contextHashes.get(path);
  2349. let resolved;
  2350. if (
  2351. cache !== undefined &&
  2352. (resolved = getResolvedHash(cache)) !== undefined
  2353. ) {
  2354. contextHashes.set(path, resolved);
  2355. } else {
  2356. jobs++;
  2357. /**
  2358. * @param {(WebpackError | null)=} err err
  2359. * @param {string=} entry entry
  2360. */
  2361. const callback = (err, entry) => {
  2362. if (err) {
  2363. if (this.logger) {
  2364. this.logger.debug(
  2365. `Error snapshotting context hash of ${path}: ${err.stack}`
  2366. );
  2367. }
  2368. jobError();
  2369. } else {
  2370. contextHashes.set(path, /** @type {string} */ (entry));
  2371. jobDone();
  2372. }
  2373. };
  2374. if (cache !== undefined) {
  2375. this._resolveContextHash(cache, callback);
  2376. } else {
  2377. this.getContextHash(path, callback);
  2378. }
  2379. }
  2380. }
  2381. break;
  2382. case 1:
  2383. this._contextTimestampsOptimization.optimize(
  2384. snapshot,
  2385. capturedDirectories
  2386. );
  2387. for (const path of capturedDirectories) {
  2388. const cache = this._contextTimestamps.get(path);
  2389. if (cache === "ignore") continue;
  2390. let resolved;
  2391. if (
  2392. cache !== undefined &&
  2393. (resolved = getResolvedTimestamp(cache)) !== undefined
  2394. ) {
  2395. contextTimestamps.set(path, resolved);
  2396. } else {
  2397. jobs++;
  2398. /**
  2399. * @param {(Error | null)=} err error
  2400. * @param {FileTimestamp=} entry entry
  2401. * @returns {void}
  2402. */
  2403. const callback = (err, entry) => {
  2404. if (err) {
  2405. if (this.logger) {
  2406. this.logger.debug(
  2407. `Error snapshotting context timestamp of ${path}: ${err.stack}`
  2408. );
  2409. }
  2410. jobError();
  2411. } else {
  2412. contextTimestamps.set(
  2413. path,
  2414. /** @type {FileSystemInfoEntry | null} */
  2415. (entry)
  2416. );
  2417. jobDone();
  2418. }
  2419. };
  2420. if (cache !== undefined) {
  2421. this._resolveContextTimestamp(
  2422. /** @type {ContextFileSystemInfoEntry} */
  2423. (cache),
  2424. callback
  2425. );
  2426. } else {
  2427. this.getContextTimestamp(path, callback);
  2428. }
  2429. }
  2430. }
  2431. break;
  2432. }
  2433. };
  2434. if (directories) {
  2435. processCapturedDirectories(
  2436. captureNonManaged(directories, managedContexts)
  2437. );
  2438. }
  2439. /**
  2440. * @param {ManagedMissing} capturedMissing captured missing
  2441. */
  2442. const processCapturedMissing = (capturedMissing) => {
  2443. this._missingExistenceOptimization.optimize(snapshot, capturedMissing);
  2444. for (const path of capturedMissing) {
  2445. const cache = this._fileTimestamps.get(path);
  2446. if (cache !== undefined) {
  2447. if (cache !== "ignore") {
  2448. missingExistence.set(path, Boolean(cache));
  2449. }
  2450. } else {
  2451. jobs++;
  2452. this.fileTimestampQueue.add(path, (err, entry) => {
  2453. if (err) {
  2454. if (this.logger) {
  2455. this.logger.debug(
  2456. `Error snapshotting missing timestamp of ${path}: ${err.stack}`
  2457. );
  2458. }
  2459. jobError();
  2460. } else {
  2461. missingExistence.set(path, Boolean(entry));
  2462. jobDone();
  2463. }
  2464. });
  2465. }
  2466. }
  2467. };
  2468. if (missing) {
  2469. processCapturedMissing(captureNonManaged(missing, managedMissing));
  2470. }
  2471. this._managedItemInfoOptimization.optimize(snapshot, managedItems);
  2472. for (const path of managedItems) {
  2473. const cache = this._managedItems.get(path);
  2474. if (cache !== undefined) {
  2475. if (!cache.startsWith("*")) {
  2476. managedFiles.add(join(this.fs, path, "package.json"));
  2477. } else if (cache === "*nested") {
  2478. managedMissing.add(join(this.fs, path, "package.json"));
  2479. }
  2480. managedItemInfo.set(path, cache);
  2481. } else {
  2482. jobs++;
  2483. this.managedItemQueue.add(path, (err, entry) => {
  2484. if (err) {
  2485. if (this.logger) {
  2486. this.logger.debug(
  2487. `Error snapshotting managed item ${path}: ${err.stack}`
  2488. );
  2489. }
  2490. jobError();
  2491. } else if (entry) {
  2492. if (!entry.startsWith("*")) {
  2493. managedFiles.add(join(this.fs, path, "package.json"));
  2494. } else if (cache === "*nested") {
  2495. managedMissing.add(join(this.fs, path, "package.json"));
  2496. }
  2497. managedItemInfo.set(path, entry);
  2498. jobDone();
  2499. } else {
  2500. // Fallback to normal snapshotting
  2501. /**
  2502. * @param {Set<string>} set set
  2503. * @param {(set: Set<string>) => void} fn fn
  2504. */
  2505. const process = (set, fn) => {
  2506. if (set.size === 0) return;
  2507. const captured = new Set();
  2508. for (const file of set) {
  2509. if (file.startsWith(path)) captured.add(file);
  2510. }
  2511. if (captured.size > 0) fn(captured);
  2512. };
  2513. process(managedFiles, processCapturedFiles);
  2514. process(managedContexts, processCapturedDirectories);
  2515. process(managedMissing, processCapturedMissing);
  2516. jobDone();
  2517. }
  2518. });
  2519. }
  2520. }
  2521. jobDone();
  2522. }
  2523. /**
  2524. * @param {Snapshot} snapshot1 a snapshot
  2525. * @param {Snapshot} snapshot2 a snapshot
  2526. * @returns {Snapshot} merged snapshot
  2527. */
  2528. mergeSnapshots(snapshot1, snapshot2) {
  2529. const snapshot = new Snapshot();
  2530. if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) {
  2531. snapshot.setStartTime(
  2532. Math.min(
  2533. /** @type {NonNullable<Snapshot["startTime"]>} */
  2534. (snapshot1.startTime),
  2535. /** @type {NonNullable<Snapshot["startTime"]>} */
  2536. (snapshot2.startTime)
  2537. )
  2538. );
  2539. } else if (snapshot2.hasStartTime()) {
  2540. snapshot.startTime = snapshot2.startTime;
  2541. } else if (snapshot1.hasStartTime()) {
  2542. snapshot.startTime = snapshot1.startTime;
  2543. }
  2544. if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) {
  2545. snapshot.setFileTimestamps(
  2546. mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps)
  2547. );
  2548. }
  2549. if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) {
  2550. snapshot.setFileHashes(
  2551. mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes)
  2552. );
  2553. }
  2554. if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) {
  2555. snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs));
  2556. }
  2557. if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) {
  2558. snapshot.setContextTimestamps(
  2559. mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps)
  2560. );
  2561. }
  2562. if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) {
  2563. snapshot.setContextHashes(
  2564. mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes)
  2565. );
  2566. }
  2567. if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) {
  2568. snapshot.setContextTshs(
  2569. mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs)
  2570. );
  2571. }
  2572. if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) {
  2573. snapshot.setMissingExistence(
  2574. mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence)
  2575. );
  2576. }
  2577. if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) {
  2578. snapshot.setManagedItemInfo(
  2579. mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo)
  2580. );
  2581. }
  2582. if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) {
  2583. snapshot.setManagedFiles(
  2584. mergeSets(snapshot1.managedFiles, snapshot2.managedFiles)
  2585. );
  2586. }
  2587. if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) {
  2588. snapshot.setManagedContexts(
  2589. mergeSets(snapshot1.managedContexts, snapshot2.managedContexts)
  2590. );
  2591. }
  2592. if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) {
  2593. snapshot.setManagedMissing(
  2594. mergeSets(snapshot1.managedMissing, snapshot2.managedMissing)
  2595. );
  2596. }
  2597. if (snapshot1.hasChildren() || snapshot2.hasChildren()) {
  2598. snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children));
  2599. }
  2600. if (
  2601. this._snapshotCache.get(snapshot1) === true &&
  2602. this._snapshotCache.get(snapshot2) === true
  2603. ) {
  2604. this._snapshotCache.set(snapshot, true);
  2605. }
  2606. return snapshot;
  2607. }
  2608. /**
  2609. * @param {Snapshot} snapshot the snapshot made
  2610. * @param {CheckSnapshotValidCallback} callback callback function
  2611. * @returns {void}
  2612. */
  2613. checkSnapshotValid(snapshot, callback) {
  2614. const cachedResult = this._snapshotCache.get(snapshot);
  2615. if (cachedResult !== undefined) {
  2616. this._statTestedSnapshotsCached++;
  2617. if (typeof cachedResult === "boolean") {
  2618. callback(null, cachedResult);
  2619. } else {
  2620. cachedResult.push(callback);
  2621. }
  2622. return;
  2623. }
  2624. this._statTestedSnapshotsNotCached++;
  2625. this._checkSnapshotValidNoCache(snapshot, callback);
  2626. }
  2627. /**
  2628. * @private
  2629. * @param {Snapshot} snapshot the snapshot made
  2630. * @param {CheckSnapshotValidCallback} callback callback function
  2631. * @returns {void}
  2632. */
  2633. _checkSnapshotValidNoCache(snapshot, callback) {
  2634. /** @type {number | undefined} */
  2635. let startTime;
  2636. if (snapshot.hasStartTime()) {
  2637. startTime = snapshot.startTime;
  2638. }
  2639. let jobs = 1;
  2640. const jobDone = () => {
  2641. if (--jobs === 0) {
  2642. this._snapshotCache.set(snapshot, true);
  2643. callback(null, true);
  2644. }
  2645. };
  2646. const invalid = () => {
  2647. if (jobs > 0) {
  2648. // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
  2649. jobs = -100000000;
  2650. this._snapshotCache.set(snapshot, false);
  2651. callback(null, false);
  2652. }
  2653. };
  2654. /**
  2655. * @param {string} path path
  2656. * @param {WebpackError} err err
  2657. */
  2658. const invalidWithError = (path, err) => {
  2659. if (this._remainingLogs > 0) {
  2660. this._log(path, "error occurred: %s", err);
  2661. }
  2662. invalid();
  2663. };
  2664. /**
  2665. * @param {string} path file path
  2666. * @param {string | null} current current hash
  2667. * @param {string | null} snap snapshot hash
  2668. * @returns {boolean} true, if ok
  2669. */
  2670. const checkHash = (path, current, snap) => {
  2671. if (current !== snap) {
  2672. // If hash differ it's invalid
  2673. if (this._remainingLogs > 0) {
  2674. this._log(path, "hashes differ (%s != %s)", current, snap);
  2675. }
  2676. return false;
  2677. }
  2678. return true;
  2679. };
  2680. /**
  2681. * @param {string} path file path
  2682. * @param {boolean} current current entry
  2683. * @param {boolean} snap entry from snapshot
  2684. * @returns {boolean} true, if ok
  2685. */
  2686. const checkExistence = (path, current, snap) => {
  2687. if (!current !== !snap) {
  2688. // If existence of item differs
  2689. // it's invalid
  2690. if (this._remainingLogs > 0) {
  2691. this._log(
  2692. path,
  2693. current ? "it didn't exist before" : "it does no longer exist"
  2694. );
  2695. }
  2696. return false;
  2697. }
  2698. return true;
  2699. };
  2700. /**
  2701. * @param {string} path file path
  2702. * @param {FileSystemInfoEntry | null} c current entry
  2703. * @param {FileSystemInfoEntry | null} s entry from snapshot
  2704. * @param {boolean} log log reason
  2705. * @returns {boolean} true, if ok
  2706. */
  2707. const checkFile = (path, c, s, log = true) => {
  2708. if (c === s) return true;
  2709. if (!checkExistence(path, Boolean(c), Boolean(s))) return false;
  2710. if (c) {
  2711. // For existing items only
  2712. if (typeof startTime === "number" && c.safeTime > startTime) {
  2713. // If a change happened after starting reading the item
  2714. // this may no longer be valid
  2715. if (log && this._remainingLogs > 0) {
  2716. this._log(
  2717. path,
  2718. "it may have changed (%d) after the start time of the snapshot (%d)",
  2719. c.safeTime,
  2720. startTime
  2721. );
  2722. }
  2723. return false;
  2724. }
  2725. const snap = /** @type {FileSystemInfoEntry} */ (s);
  2726. if (snap.timestamp !== undefined && c.timestamp !== snap.timestamp) {
  2727. // If we have a timestamp (it was a file or symlink) and it differs from current timestamp
  2728. // it's invalid
  2729. if (log && this._remainingLogs > 0) {
  2730. this._log(
  2731. path,
  2732. "timestamps differ (%d != %d)",
  2733. c.timestamp,
  2734. snap.timestamp
  2735. );
  2736. }
  2737. return false;
  2738. }
  2739. }
  2740. return true;
  2741. };
  2742. /**
  2743. * @param {string} path file path
  2744. * @param {ResolvedContextFileSystemInfoEntry | null} c current entry
  2745. * @param {ResolvedContextFileSystemInfoEntry | null} s entry from snapshot
  2746. * @param {boolean} log log reason
  2747. * @returns {boolean} true, if ok
  2748. */
  2749. const checkContext = (path, c, s, log = true) => {
  2750. if (c === s) return true;
  2751. if (!checkExistence(path, Boolean(c), Boolean(s))) return false;
  2752. if (c) {
  2753. // For existing items only
  2754. if (typeof startTime === "number" && c.safeTime > startTime) {
  2755. // If a change happened after starting reading the item
  2756. // this may no longer be valid
  2757. if (log && this._remainingLogs > 0) {
  2758. this._log(
  2759. path,
  2760. "it may have changed (%d) after the start time of the snapshot (%d)",
  2761. c.safeTime,
  2762. startTime
  2763. );
  2764. }
  2765. return false;
  2766. }
  2767. const snap = /** @type {ResolvedContextFileSystemInfoEntry} */ (s);
  2768. if (
  2769. snap.timestampHash !== undefined &&
  2770. c.timestampHash !== snap.timestampHash
  2771. ) {
  2772. // If we have a timestampHash (it was a directory) and it differs from current timestampHash
  2773. // it's invalid
  2774. if (log && this._remainingLogs > 0) {
  2775. this._log(
  2776. path,
  2777. "timestamps hashes differ (%s != %s)",
  2778. c.timestampHash,
  2779. snap.timestampHash
  2780. );
  2781. }
  2782. return false;
  2783. }
  2784. }
  2785. return true;
  2786. };
  2787. if (snapshot.hasChildren()) {
  2788. /**
  2789. * @param {(WebpackError | null)=} err err
  2790. * @param {boolean=} result result
  2791. * @returns {void}
  2792. */
  2793. const childCallback = (err, result) => {
  2794. if (err || !result) return invalid();
  2795. jobDone();
  2796. };
  2797. for (const child of /** @type {Children} */ (snapshot.children)) {
  2798. const cache = this._snapshotCache.get(child);
  2799. if (cache !== undefined) {
  2800. this._statTestedChildrenCached++;
  2801. /* istanbul ignore else */
  2802. if (typeof cache === "boolean") {
  2803. if (cache === false) {
  2804. invalid();
  2805. return;
  2806. }
  2807. } else {
  2808. jobs++;
  2809. cache.push(childCallback);
  2810. }
  2811. } else {
  2812. this._statTestedChildrenNotCached++;
  2813. jobs++;
  2814. this._checkSnapshotValidNoCache(child, childCallback);
  2815. }
  2816. }
  2817. }
  2818. if (snapshot.hasFileTimestamps()) {
  2819. const fileTimestamps =
  2820. /** @type {FileTimestamps} */
  2821. (snapshot.fileTimestamps);
  2822. this._statTestedEntries += fileTimestamps.size;
  2823. for (const [path, ts] of fileTimestamps) {
  2824. const cache = this._fileTimestamps.get(path);
  2825. if (cache !== undefined) {
  2826. if (cache !== "ignore" && !checkFile(path, cache, ts)) {
  2827. invalid();
  2828. return;
  2829. }
  2830. } else {
  2831. jobs++;
  2832. this.fileTimestampQueue.add(path, (err, entry) => {
  2833. if (err) return invalidWithError(path, err);
  2834. if (
  2835. !checkFile(
  2836. path,
  2837. /** @type {FileSystemInfoEntry | null} */ (entry),
  2838. ts
  2839. )
  2840. ) {
  2841. invalid();
  2842. } else {
  2843. jobDone();
  2844. }
  2845. });
  2846. }
  2847. }
  2848. }
  2849. /**
  2850. * @param {string} path file path
  2851. * @param {string | null} hash hash
  2852. */
  2853. const processFileHashSnapshot = (path, hash) => {
  2854. const cache = this._fileHashes.get(path);
  2855. if (cache !== undefined) {
  2856. if (cache !== "ignore" && !checkHash(path, cache, hash)) {
  2857. invalid();
  2858. }
  2859. } else {
  2860. jobs++;
  2861. this.fileHashQueue.add(path, (err, entry) => {
  2862. if (err) return invalidWithError(path, err);
  2863. if (!checkHash(path, /** @type {string} */ (entry), hash)) {
  2864. invalid();
  2865. } else {
  2866. jobDone();
  2867. }
  2868. });
  2869. }
  2870. };
  2871. if (snapshot.hasFileHashes()) {
  2872. const fileHashes = /** @type {FileHashes} */ (snapshot.fileHashes);
  2873. this._statTestedEntries += fileHashes.size;
  2874. for (const [path, hash] of fileHashes) {
  2875. processFileHashSnapshot(path, hash);
  2876. }
  2877. }
  2878. if (snapshot.hasFileTshs()) {
  2879. const fileTshs = /** @type {FileTshs} */ (snapshot.fileTshs);
  2880. this._statTestedEntries += fileTshs.size;
  2881. for (const [path, tsh] of fileTshs) {
  2882. if (typeof tsh === "string") {
  2883. processFileHashSnapshot(path, tsh);
  2884. } else {
  2885. const cache = this._fileTimestamps.get(path);
  2886. if (cache !== undefined) {
  2887. if (cache === "ignore" || !checkFile(path, cache, tsh, false)) {
  2888. processFileHashSnapshot(path, tsh && tsh.hash);
  2889. }
  2890. } else {
  2891. jobs++;
  2892. this.fileTimestampQueue.add(path, (err, entry) => {
  2893. if (err) return invalidWithError(path, err);
  2894. if (
  2895. !checkFile(
  2896. path,
  2897. /** @type {FileSystemInfoEntry | null} */
  2898. (entry),
  2899. tsh,
  2900. false
  2901. )
  2902. ) {
  2903. processFileHashSnapshot(path, tsh && tsh.hash);
  2904. }
  2905. jobDone();
  2906. });
  2907. }
  2908. }
  2909. }
  2910. }
  2911. if (snapshot.hasContextTimestamps()) {
  2912. const contextTimestamps =
  2913. /** @type {ContextTimestamps} */
  2914. (snapshot.contextTimestamps);
  2915. this._statTestedEntries += contextTimestamps.size;
  2916. for (const [path, ts] of contextTimestamps) {
  2917. const cache = this._contextTimestamps.get(path);
  2918. if (cache === "ignore") continue;
  2919. let resolved;
  2920. if (
  2921. cache !== undefined &&
  2922. (resolved = getResolvedTimestamp(cache)) !== undefined
  2923. ) {
  2924. if (!checkContext(path, resolved, ts)) {
  2925. invalid();
  2926. return;
  2927. }
  2928. } else {
  2929. jobs++;
  2930. /**
  2931. * @param {(WebpackError | null)=} err error
  2932. * @param {ResolvedContextTimestamp=} entry entry
  2933. * @returns {void}
  2934. */
  2935. const callback = (err, entry) => {
  2936. if (err) return invalidWithError(path, err);
  2937. if (
  2938. !checkContext(
  2939. path,
  2940. /** @type {ResolvedContextFileSystemInfoEntry | null} */
  2941. (entry),
  2942. ts
  2943. )
  2944. ) {
  2945. invalid();
  2946. } else {
  2947. jobDone();
  2948. }
  2949. };
  2950. if (cache !== undefined) {
  2951. this._resolveContextTimestamp(
  2952. /** @type {ContextFileSystemInfoEntry} */
  2953. (cache),
  2954. callback
  2955. );
  2956. } else {
  2957. this.getContextTimestamp(path, callback);
  2958. }
  2959. }
  2960. }
  2961. }
  2962. /**
  2963. * @param {string} path path
  2964. * @param {string | null} hash hash
  2965. */
  2966. const processContextHashSnapshot = (path, hash) => {
  2967. const cache = this._contextHashes.get(path);
  2968. let resolved;
  2969. if (
  2970. cache !== undefined &&
  2971. (resolved = getResolvedHash(cache)) !== undefined
  2972. ) {
  2973. if (!checkHash(path, resolved, hash)) {
  2974. invalid();
  2975. }
  2976. } else {
  2977. jobs++;
  2978. /**
  2979. * @param {(WebpackError | null)=} err err
  2980. * @param {string=} entry entry
  2981. * @returns {void}
  2982. */
  2983. const callback = (err, entry) => {
  2984. if (err) return invalidWithError(path, err);
  2985. if (!checkHash(path, /** @type {string} */ (entry), hash)) {
  2986. invalid();
  2987. } else {
  2988. jobDone();
  2989. }
  2990. };
  2991. if (cache !== undefined) {
  2992. this._resolveContextHash(cache, callback);
  2993. } else {
  2994. this.getContextHash(path, callback);
  2995. }
  2996. }
  2997. };
  2998. if (snapshot.hasContextHashes()) {
  2999. const contextHashes =
  3000. /** @type {ContextHashes} */
  3001. (snapshot.contextHashes);
  3002. this._statTestedEntries += contextHashes.size;
  3003. for (const [path, hash] of contextHashes) {
  3004. processContextHashSnapshot(path, hash);
  3005. }
  3006. }
  3007. if (snapshot.hasContextTshs()) {
  3008. const contextTshs = /** @type {ContextTshs} */ (snapshot.contextTshs);
  3009. this._statTestedEntries += contextTshs.size;
  3010. for (const [path, tsh] of contextTshs) {
  3011. if (typeof tsh === "string") {
  3012. processContextHashSnapshot(path, tsh);
  3013. } else {
  3014. const cache = this._contextTimestamps.get(path);
  3015. if (cache === "ignore") continue;
  3016. let resolved;
  3017. if (
  3018. cache !== undefined &&
  3019. (resolved = getResolvedTimestamp(cache)) !== undefined
  3020. ) {
  3021. if (
  3022. !checkContext(
  3023. path,
  3024. /** @type {ResolvedContextFileSystemInfoEntry | null} */
  3025. (resolved),
  3026. tsh,
  3027. false
  3028. )
  3029. ) {
  3030. processContextHashSnapshot(path, tsh && tsh.hash);
  3031. }
  3032. } else {
  3033. jobs++;
  3034. /**
  3035. * @param {(WebpackError | null)=} err error
  3036. * @param {ResolvedContextTimestamp=} entry entry
  3037. * @returns {void}
  3038. */
  3039. const callback = (err, entry) => {
  3040. if (err) return invalidWithError(path, err);
  3041. if (
  3042. !checkContext(
  3043. path,
  3044. // TODO: test with `"ignore"`
  3045. /** @type {ResolvedContextFileSystemInfoEntry | null} */
  3046. (entry),
  3047. tsh,
  3048. false
  3049. )
  3050. ) {
  3051. processContextHashSnapshot(path, tsh && tsh.hash);
  3052. }
  3053. jobDone();
  3054. };
  3055. if (cache !== undefined) {
  3056. this._resolveContextTimestamp(
  3057. /** @type {ContextFileSystemInfoEntry} */
  3058. (cache),
  3059. callback
  3060. );
  3061. } else {
  3062. this.getContextTimestamp(path, callback);
  3063. }
  3064. }
  3065. }
  3066. }
  3067. }
  3068. if (snapshot.hasMissingExistence()) {
  3069. const missingExistence =
  3070. /** @type {MissingExistence} */
  3071. (snapshot.missingExistence);
  3072. this._statTestedEntries += missingExistence.size;
  3073. for (const [path, existence] of missingExistence) {
  3074. const cache = this._fileTimestamps.get(path);
  3075. if (cache !== undefined) {
  3076. if (
  3077. cache !== "ignore" &&
  3078. !checkExistence(path, Boolean(cache), Boolean(existence))
  3079. ) {
  3080. invalid();
  3081. return;
  3082. }
  3083. } else {
  3084. jobs++;
  3085. this.fileTimestampQueue.add(path, (err, entry) => {
  3086. if (err) return invalidWithError(path, err);
  3087. if (!checkExistence(path, Boolean(entry), Boolean(existence))) {
  3088. invalid();
  3089. } else {
  3090. jobDone();
  3091. }
  3092. });
  3093. }
  3094. }
  3095. }
  3096. if (snapshot.hasManagedItemInfo()) {
  3097. const managedItemInfo =
  3098. /** @type {ManagedItemInfo} */
  3099. (snapshot.managedItemInfo);
  3100. this._statTestedEntries += managedItemInfo.size;
  3101. for (const [path, info] of managedItemInfo) {
  3102. const cache = this._managedItems.get(path);
  3103. if (cache !== undefined) {
  3104. if (!checkHash(path, cache, info)) {
  3105. invalid();
  3106. return;
  3107. }
  3108. } else {
  3109. jobs++;
  3110. this.managedItemQueue.add(path, (err, entry) => {
  3111. if (err) return invalidWithError(path, err);
  3112. if (!checkHash(path, /** @type {string} */ (entry), info)) {
  3113. invalid();
  3114. } else {
  3115. jobDone();
  3116. }
  3117. });
  3118. }
  3119. }
  3120. }
  3121. jobDone();
  3122. // if there was an async action
  3123. // try to join multiple concurrent request for this snapshot
  3124. if (jobs > 0) {
  3125. const callbacks = [callback];
  3126. callback = (err, result) => {
  3127. for (const callback of callbacks) callback(err, result);
  3128. };
  3129. this._snapshotCache.set(snapshot, callbacks);
  3130. }
  3131. }
  3132. /**
  3133. * @private
  3134. * @type {Processor<string, FileSystemInfoEntry>}
  3135. */
  3136. _readFileTimestamp(path, callback) {
  3137. this.fs.stat(path, (err, _stat) => {
  3138. if (err) {
  3139. if (err.code === "ENOENT") {
  3140. this._fileTimestamps.set(path, null);
  3141. this._cachedDeprecatedFileTimestamps = undefined;
  3142. return callback(null, null);
  3143. }
  3144. return callback(/** @type {WebpackError} */ (err));
  3145. }
  3146. const stat = /** @type {IStats} */ (_stat);
  3147. let ts;
  3148. if (stat.isDirectory()) {
  3149. ts = {
  3150. safeTime: 0,
  3151. timestamp: undefined
  3152. };
  3153. } else {
  3154. const mtime = Number(stat.mtime);
  3155. if (mtime) applyMtime(mtime);
  3156. ts = {
  3157. safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
  3158. timestamp: mtime
  3159. };
  3160. }
  3161. this._fileTimestamps.set(path, ts);
  3162. this._cachedDeprecatedFileTimestamps = undefined;
  3163. callback(null, ts);
  3164. });
  3165. }
  3166. /**
  3167. * @private
  3168. * @type {Processor<string, string>}
  3169. */
  3170. _readFileHash(path, callback) {
  3171. this.fs.readFile(path, (err, content) => {
  3172. if (err) {
  3173. if (err.code === "EISDIR") {
  3174. this._fileHashes.set(path, "directory");
  3175. return callback(null, "directory");
  3176. }
  3177. if (err.code === "ENOENT") {
  3178. this._fileHashes.set(path, null);
  3179. return callback(null, null);
  3180. }
  3181. if (err.code === "ERR_FS_FILE_TOO_LARGE") {
  3182. /** @type {Logger} */
  3183. (this.logger).warn(`Ignoring ${path} for hashing as it's very large`);
  3184. this._fileHashes.set(path, "too large");
  3185. return callback(null, "too large");
  3186. }
  3187. return callback(/** @type {WebpackError} */ (err));
  3188. }
  3189. const hash = createHash(this._hashFunction);
  3190. hash.update(/** @type {string | Buffer} */ (content));
  3191. const digest = /** @type {string} */ (hash.digest("hex"));
  3192. this._fileHashes.set(path, digest);
  3193. callback(null, digest);
  3194. });
  3195. }
  3196. /**
  3197. * @private
  3198. * @param {string} path path
  3199. * @param {(err: WebpackError | null, timestampAndHash?: TimestampAndHash) => void} callback callback
  3200. */
  3201. _getFileTimestampAndHash(path, callback) {
  3202. /**
  3203. * @param {string} hash hash
  3204. * @returns {void}
  3205. */
  3206. const continueWithHash = (hash) => {
  3207. const cache = this._fileTimestamps.get(path);
  3208. if (cache !== undefined) {
  3209. if (cache !== "ignore") {
  3210. /** @type {TimestampAndHash} */
  3211. const result = {
  3212. .../** @type {FileSystemInfoEntry} */ (cache),
  3213. hash
  3214. };
  3215. this._fileTshs.set(path, result);
  3216. return callback(null, result);
  3217. }
  3218. this._fileTshs.set(path, hash);
  3219. return callback(null, /** @type {TODO} */ (hash));
  3220. }
  3221. this.fileTimestampQueue.add(path, (err, entry) => {
  3222. if (err) {
  3223. return callback(err);
  3224. }
  3225. /** @type {TimestampAndHash} */
  3226. const result = {
  3227. .../** @type {FileSystemInfoEntry} */ (entry),
  3228. hash
  3229. };
  3230. this._fileTshs.set(path, result);
  3231. return callback(null, result);
  3232. });
  3233. };
  3234. const cache = this._fileHashes.get(path);
  3235. if (cache !== undefined) {
  3236. continueWithHash(/** @type {string} */ (cache));
  3237. } else {
  3238. this.fileHashQueue.add(path, (err, entry) => {
  3239. if (err) {
  3240. return callback(err);
  3241. }
  3242. continueWithHash(/** @type {string} */ (entry));
  3243. });
  3244. }
  3245. }
  3246. /**
  3247. * @private
  3248. * @template T
  3249. * @template ItemType
  3250. * @param {object} options options
  3251. * @param {string} options.path path
  3252. * @param {(value: string) => ItemType} options.fromImmutablePath called when context item is an immutable path
  3253. * @param {(value: string) => ItemType} options.fromManagedItem called when context item is a managed path
  3254. * @param {(value: string, result: string, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromSymlink called when context item is a symlink
  3255. * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType | null) => void) => void} options.fromFile called when context item is a file
  3256. * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromDirectory called when context item is a directory
  3257. * @param {(arr: string[], arr1: ItemType[]) => T} options.reduce called from all context items
  3258. * @param {(err?: Error | null, result?: T | null) => void} callback callback
  3259. */
  3260. _readContext(
  3261. {
  3262. path,
  3263. fromImmutablePath,
  3264. fromManagedItem,
  3265. fromSymlink,
  3266. fromFile,
  3267. fromDirectory,
  3268. reduce
  3269. },
  3270. callback
  3271. ) {
  3272. this.fs.readdir(path, (err, _files) => {
  3273. if (err) {
  3274. if (err.code === "ENOENT") {
  3275. return callback(null, null);
  3276. }
  3277. return callback(err);
  3278. }
  3279. const files = /** @type {string[]} */ (_files)
  3280. .map((file) => file.normalize("NFC"))
  3281. .filter((file) => !/^\./.test(file))
  3282. .sort();
  3283. asyncLib.map(
  3284. files,
  3285. (file, callback) => {
  3286. const child = join(this.fs, path, file);
  3287. for (const immutablePath of this.immutablePathsRegExps) {
  3288. if (immutablePath.test(path)) {
  3289. // ignore any immutable path for timestamping
  3290. return callback(null, fromImmutablePath(path));
  3291. }
  3292. }
  3293. for (const immutablePath of this.immutablePathsWithSlash) {
  3294. if (path.startsWith(immutablePath)) {
  3295. // ignore any immutable path for timestamping
  3296. return callback(null, fromImmutablePath(path));
  3297. }
  3298. }
  3299. for (const managedPath of this.managedPathsRegExps) {
  3300. const match = managedPath.exec(path);
  3301. if (match) {
  3302. const managedItem = getManagedItem(match[1], path);
  3303. if (managedItem) {
  3304. // construct timestampHash from managed info
  3305. return this.managedItemQueue.add(managedItem, (err, info) => {
  3306. if (err) return callback(err);
  3307. return callback(
  3308. null,
  3309. fromManagedItem(/** @type {string} */ (info))
  3310. );
  3311. });
  3312. }
  3313. }
  3314. }
  3315. for (const managedPath of this.managedPathsWithSlash) {
  3316. if (path.startsWith(managedPath)) {
  3317. const managedItem = getManagedItem(managedPath, child);
  3318. if (managedItem) {
  3319. // construct timestampHash from managed info
  3320. return this.managedItemQueue.add(managedItem, (err, info) => {
  3321. if (err) return callback(err);
  3322. return callback(
  3323. null,
  3324. fromManagedItem(/** @type {string} */ (info))
  3325. );
  3326. });
  3327. }
  3328. }
  3329. }
  3330. lstatReadlinkAbsolute(this.fs, child, (err, _stat) => {
  3331. if (err) return callback(err);
  3332. const stat = /** @type {IStats | string} */ (_stat);
  3333. if (typeof stat === "string") {
  3334. return fromSymlink(child, stat, callback);
  3335. }
  3336. if (stat.isFile()) {
  3337. return fromFile(child, stat, callback);
  3338. }
  3339. if (stat.isDirectory()) {
  3340. return fromDirectory(child, stat, callback);
  3341. }
  3342. callback(null, null);
  3343. });
  3344. },
  3345. (err, results) => {
  3346. if (err) return callback(err);
  3347. const result = reduce(files, /** @type {ItemType[]} */ (results));
  3348. callback(null, result);
  3349. }
  3350. );
  3351. });
  3352. }
  3353. /**
  3354. * @private
  3355. * @type {Processor<string, ContextFileSystemInfoEntry>}
  3356. */
  3357. _readContextTimestamp(path, callback) {
  3358. this._readContext(
  3359. {
  3360. path,
  3361. fromImmutablePath: () =>
  3362. /** @type {ContextFileSystemInfoEntry | FileSystemInfoEntry | "ignore" | null} */
  3363. (null),
  3364. fromManagedItem: (info) => ({
  3365. safeTime: 0,
  3366. timestampHash: info
  3367. }),
  3368. fromSymlink: (file, target, callback) => {
  3369. callback(
  3370. null,
  3371. /** @type {ContextFileSystemInfoEntry} */
  3372. ({
  3373. timestampHash: target,
  3374. symlinks: new Set([target])
  3375. })
  3376. );
  3377. },
  3378. fromFile: (file, stat, callback) => {
  3379. // Prefer the cached value over our new stat to report consistent results
  3380. const cache = this._fileTimestamps.get(file);
  3381. if (cache !== undefined) {
  3382. return callback(null, cache === "ignore" ? null : cache);
  3383. }
  3384. const mtime = Number(stat.mtime);
  3385. if (mtime) applyMtime(mtime);
  3386. /** @type {FileSystemInfoEntry} */
  3387. const ts = {
  3388. safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
  3389. timestamp: mtime
  3390. };
  3391. this._fileTimestamps.set(file, ts);
  3392. this._cachedDeprecatedFileTimestamps = undefined;
  3393. callback(null, ts);
  3394. },
  3395. fromDirectory: (directory, stat, callback) => {
  3396. this.contextTimestampQueue.increaseParallelism();
  3397. this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => {
  3398. this.contextTimestampQueue.decreaseParallelism();
  3399. callback(err, tsEntry);
  3400. });
  3401. },
  3402. reduce: (files, tsEntries) => {
  3403. let symlinks;
  3404. const hash = createHash(this._hashFunction);
  3405. for (const file of files) hash.update(file);
  3406. let safeTime = 0;
  3407. for (const _e of tsEntries) {
  3408. if (!_e) {
  3409. hash.update("n");
  3410. continue;
  3411. }
  3412. const entry =
  3413. /** @type {FileSystemInfoEntry | ContextFileSystemInfoEntry} */
  3414. (_e);
  3415. if (/** @type {FileSystemInfoEntry} */ (entry).timestamp) {
  3416. hash.update("f");
  3417. hash.update(
  3418. `${/** @type {FileSystemInfoEntry} */ (entry).timestamp}`
  3419. );
  3420. } else if (
  3421. /** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash
  3422. ) {
  3423. hash.update("d");
  3424. hash.update(
  3425. `${/** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash}`
  3426. );
  3427. }
  3428. if (
  3429. /** @type {ContextFileSystemInfoEntry} */
  3430. (entry).symlinks !== undefined
  3431. ) {
  3432. if (symlinks === undefined) symlinks = new Set();
  3433. addAll(
  3434. /** @type {ContextFileSystemInfoEntry} */ (entry).symlinks,
  3435. symlinks
  3436. );
  3437. }
  3438. if (entry.safeTime) {
  3439. safeTime = Math.max(safeTime, entry.safeTime);
  3440. }
  3441. }
  3442. const digest = /** @type {string} */ (hash.digest("hex"));
  3443. /** @type {ContextFileSystemInfoEntry} */
  3444. const result = {
  3445. safeTime,
  3446. timestampHash: digest
  3447. };
  3448. if (symlinks) result.symlinks = symlinks;
  3449. return result;
  3450. }
  3451. },
  3452. (err, result) => {
  3453. if (err) return callback(/** @type {WebpackError} */ (err));
  3454. this._contextTimestamps.set(path, result);
  3455. this._cachedDeprecatedContextTimestamps = undefined;
  3456. callback(null, result);
  3457. }
  3458. );
  3459. }
  3460. /**
  3461. * @private
  3462. * @param {ContextFileSystemInfoEntry} entry entry
  3463. * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback
  3464. * @returns {void}
  3465. */
  3466. _resolveContextTimestamp(entry, callback) {
  3467. /** @type {string[]} */
  3468. const hashes = [];
  3469. let safeTime = 0;
  3470. processAsyncTree(
  3471. /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
  3472. 10,
  3473. (target, push, callback) => {
  3474. this._getUnresolvedContextTimestamp(target, (err, entry) => {
  3475. if (err) return callback(err);
  3476. if (entry && entry !== "ignore") {
  3477. hashes.push(/** @type {string} */ (entry.timestampHash));
  3478. if (entry.safeTime) {
  3479. safeTime = Math.max(safeTime, entry.safeTime);
  3480. }
  3481. if (entry.symlinks !== undefined) {
  3482. for (const target of entry.symlinks) push(target);
  3483. }
  3484. }
  3485. callback();
  3486. });
  3487. },
  3488. (err) => {
  3489. if (err) return callback(/** @type {WebpackError} */ (err));
  3490. const hash = createHash(this._hashFunction);
  3491. hash.update(/** @type {string} */ (entry.timestampHash));
  3492. if (entry.safeTime) {
  3493. safeTime = Math.max(safeTime, entry.safeTime);
  3494. }
  3495. hashes.sort();
  3496. for (const h of hashes) {
  3497. hash.update(h);
  3498. }
  3499. callback(
  3500. null,
  3501. (entry.resolved = {
  3502. safeTime,
  3503. timestampHash: /** @type {string} */ (hash.digest("hex"))
  3504. })
  3505. );
  3506. }
  3507. );
  3508. }
  3509. /**
  3510. * @private
  3511. * @type {Processor<string, ContextHash>}
  3512. */
  3513. _readContextHash(path, callback) {
  3514. this._readContext(
  3515. {
  3516. path,
  3517. fromImmutablePath: () => /** @type {ContextHash | ""} */ (""),
  3518. fromManagedItem: (info) => info || "",
  3519. fromSymlink: (file, target, callback) => {
  3520. callback(
  3521. null,
  3522. /** @type {ContextHash} */
  3523. ({
  3524. hash: target,
  3525. symlinks: new Set([target])
  3526. })
  3527. );
  3528. },
  3529. fromFile: (file, stat, callback) =>
  3530. this.getFileHash(file, (err, hash) => {
  3531. callback(err, hash || "");
  3532. }),
  3533. fromDirectory: (directory, stat, callback) => {
  3534. this.contextHashQueue.increaseParallelism();
  3535. this._getUnresolvedContextHash(directory, (err, hash) => {
  3536. this.contextHashQueue.decreaseParallelism();
  3537. callback(err, hash || "");
  3538. });
  3539. },
  3540. /**
  3541. * @param {string[]} files files
  3542. * @param {(string | ContextHash)[]} fileHashes hashes
  3543. * @returns {ContextHash} reduced hash
  3544. */
  3545. reduce: (files, fileHashes) => {
  3546. let symlinks;
  3547. const hash = createHash(this._hashFunction);
  3548. for (const file of files) hash.update(file);
  3549. for (const entry of fileHashes) {
  3550. if (typeof entry === "string") {
  3551. hash.update(entry);
  3552. } else {
  3553. hash.update(entry.hash);
  3554. if (entry.symlinks) {
  3555. if (symlinks === undefined) symlinks = new Set();
  3556. addAll(entry.symlinks, symlinks);
  3557. }
  3558. }
  3559. }
  3560. /** @type {ContextHash} */
  3561. const result = {
  3562. hash: /** @type {string} */ (hash.digest("hex"))
  3563. };
  3564. if (symlinks) result.symlinks = symlinks;
  3565. return result;
  3566. }
  3567. },
  3568. (err, _result) => {
  3569. if (err) return callback(/** @type {WebpackError} */ (err));
  3570. const result = /** @type {ContextHash} */ (_result);
  3571. this._contextHashes.set(path, result);
  3572. return callback(null, result);
  3573. }
  3574. );
  3575. }
  3576. /**
  3577. * @private
  3578. * @param {ContextHash} entry context hash
  3579. * @param {(err: WebpackError | null, contextHash?: string) => void} callback callback
  3580. * @returns {void}
  3581. */
  3582. _resolveContextHash(entry, callback) {
  3583. /** @type {string[]} */
  3584. const hashes = [];
  3585. processAsyncTree(
  3586. /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
  3587. 10,
  3588. (target, push, callback) => {
  3589. this._getUnresolvedContextHash(target, (err, hash) => {
  3590. if (err) return callback(err);
  3591. if (hash) {
  3592. hashes.push(hash.hash);
  3593. if (hash.symlinks !== undefined) {
  3594. for (const target of hash.symlinks) push(target);
  3595. }
  3596. }
  3597. callback();
  3598. });
  3599. },
  3600. (err) => {
  3601. if (err) return callback(/** @type {WebpackError} */ (err));
  3602. const hash = createHash(this._hashFunction);
  3603. hash.update(entry.hash);
  3604. hashes.sort();
  3605. for (const h of hashes) {
  3606. hash.update(h);
  3607. }
  3608. callback(
  3609. null,
  3610. (entry.resolved = /** @type {string} */ (hash.digest("hex")))
  3611. );
  3612. }
  3613. );
  3614. }
  3615. /**
  3616. * @private
  3617. * @type {Processor<string, ContextTimestampAndHash>}
  3618. */
  3619. _readContextTimestampAndHash(path, callback) {
  3620. /**
  3621. * @param {ContextTimestamp} timestamp timestamp
  3622. * @param {ContextHash} hash hash
  3623. */
  3624. const finalize = (timestamp, hash) => {
  3625. const result =
  3626. /** @type {ContextTimestampAndHash} */
  3627. (timestamp === "ignore" ? hash : { ...timestamp, ...hash });
  3628. this._contextTshs.set(path, result);
  3629. callback(null, result);
  3630. };
  3631. const cachedHash = this._contextHashes.get(path);
  3632. const cachedTimestamp = this._contextTimestamps.get(path);
  3633. if (cachedHash !== undefined) {
  3634. if (cachedTimestamp !== undefined) {
  3635. finalize(cachedTimestamp, cachedHash);
  3636. } else {
  3637. this.contextTimestampQueue.add(path, (err, entry) => {
  3638. if (err) return callback(err);
  3639. finalize(
  3640. /** @type {ContextFileSystemInfoEntry} */
  3641. (entry),
  3642. cachedHash
  3643. );
  3644. });
  3645. }
  3646. } else if (cachedTimestamp !== undefined) {
  3647. this.contextHashQueue.add(path, (err, entry) => {
  3648. if (err) return callback(err);
  3649. finalize(cachedTimestamp, /** @type {ContextHash} */ (entry));
  3650. });
  3651. } else {
  3652. this._readContext(
  3653. {
  3654. path,
  3655. fromImmutablePath: () =>
  3656. /** @type {ContextTimestampAndHash | null} */ (null),
  3657. fromManagedItem: (info) => ({
  3658. safeTime: 0,
  3659. timestampHash: info,
  3660. hash: info || ""
  3661. }),
  3662. fromSymlink: (file, target, callback) => {
  3663. callback(
  3664. null,
  3665. /** @type {TODO} */
  3666. ({
  3667. timestampHash: target,
  3668. hash: target,
  3669. symlinks: new Set([target])
  3670. })
  3671. );
  3672. },
  3673. fromFile: (file, stat, callback) => {
  3674. this._getFileTimestampAndHash(file, callback);
  3675. },
  3676. fromDirectory: (directory, stat, callback) => {
  3677. this.contextTshQueue.increaseParallelism();
  3678. this.contextTshQueue.add(directory, (err, result) => {
  3679. this.contextTshQueue.decreaseParallelism();
  3680. callback(err, result);
  3681. });
  3682. },
  3683. /**
  3684. * @param {string[]} files files
  3685. * @param {(Partial<TimestampAndHash> & Partial<ContextTimestampAndHash> | string | null)[]} results results
  3686. * @returns {ContextTimestampAndHash} tsh
  3687. */
  3688. reduce: (files, results) => {
  3689. let symlinks;
  3690. const tsHash = createHash(this._hashFunction);
  3691. const hash = createHash(this._hashFunction);
  3692. for (const file of files) {
  3693. tsHash.update(file);
  3694. hash.update(file);
  3695. }
  3696. let safeTime = 0;
  3697. for (const entry of results) {
  3698. if (!entry) {
  3699. tsHash.update("n");
  3700. continue;
  3701. }
  3702. if (typeof entry === "string") {
  3703. tsHash.update("n");
  3704. hash.update(entry);
  3705. continue;
  3706. }
  3707. if (entry.timestamp) {
  3708. tsHash.update("f");
  3709. tsHash.update(`${entry.timestamp}`);
  3710. } else if (entry.timestampHash) {
  3711. tsHash.update("d");
  3712. tsHash.update(`${entry.timestampHash}`);
  3713. }
  3714. if (entry.symlinks !== undefined) {
  3715. if (symlinks === undefined) symlinks = new Set();
  3716. addAll(entry.symlinks, symlinks);
  3717. }
  3718. if (entry.safeTime) {
  3719. safeTime = Math.max(safeTime, entry.safeTime);
  3720. }
  3721. hash.update(/** @type {string} */ (entry.hash));
  3722. }
  3723. /** @type {ContextTimestampAndHash} */
  3724. const result = {
  3725. safeTime,
  3726. timestampHash: /** @type {string} */ (tsHash.digest("hex")),
  3727. hash: /** @type {string} */ (hash.digest("hex"))
  3728. };
  3729. if (symlinks) result.symlinks = symlinks;
  3730. return result;
  3731. }
  3732. },
  3733. (err, _result) => {
  3734. if (err) return callback(/** @type {WebpackError} */ (err));
  3735. const result = /** @type {ContextTimestampAndHash} */ (_result);
  3736. this._contextTshs.set(path, result);
  3737. return callback(null, result);
  3738. }
  3739. );
  3740. }
  3741. }
  3742. /**
  3743. * @private
  3744. * @param {ContextTimestampAndHash} entry entry
  3745. * @param {ProcessorCallback<ResolvedContextTimestampAndHash>} callback callback
  3746. * @returns {void}
  3747. */
  3748. _resolveContextTsh(entry, callback) {
  3749. /** @type {string[]} */
  3750. const hashes = [];
  3751. /** @type {string[]} */
  3752. const tsHashes = [];
  3753. let safeTime = 0;
  3754. processAsyncTree(
  3755. /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
  3756. 10,
  3757. (target, push, callback) => {
  3758. this._getUnresolvedContextTsh(target, (err, entry) => {
  3759. if (err) return callback(err);
  3760. if (entry) {
  3761. hashes.push(entry.hash);
  3762. if (entry.timestampHash) tsHashes.push(entry.timestampHash);
  3763. if (entry.safeTime) {
  3764. safeTime = Math.max(safeTime, entry.safeTime);
  3765. }
  3766. if (entry.symlinks !== undefined) {
  3767. for (const target of entry.symlinks) push(target);
  3768. }
  3769. }
  3770. callback();
  3771. });
  3772. },
  3773. (err) => {
  3774. if (err) return callback(/** @type {WebpackError} */ (err));
  3775. const hash = createHash(this._hashFunction);
  3776. const tsHash = createHash(this._hashFunction);
  3777. hash.update(entry.hash);
  3778. if (entry.timestampHash) tsHash.update(entry.timestampHash);
  3779. if (entry.safeTime) {
  3780. safeTime = Math.max(safeTime, entry.safeTime);
  3781. }
  3782. hashes.sort();
  3783. for (const h of hashes) {
  3784. hash.update(h);
  3785. }
  3786. tsHashes.sort();
  3787. for (const h of tsHashes) {
  3788. tsHash.update(h);
  3789. }
  3790. callback(
  3791. null,
  3792. (entry.resolved = {
  3793. safeTime,
  3794. timestampHash: /** @type {string} */ (tsHash.digest("hex")),
  3795. hash: /** @type {string} */ (hash.digest("hex"))
  3796. })
  3797. );
  3798. }
  3799. );
  3800. }
  3801. /**
  3802. * @private
  3803. * @type {Processor<string, Set<string>>}
  3804. */
  3805. _getManagedItemDirectoryInfo(path, callback) {
  3806. this.fs.readdir(path, (err, elements) => {
  3807. if (err) {
  3808. if (err.code === "ENOENT" || err.code === "ENOTDIR") {
  3809. return callback(null, EMPTY_SET);
  3810. }
  3811. return callback(/** @type {WebpackError} */ (err));
  3812. }
  3813. const set = new Set(
  3814. /** @type {string[]} */ (elements).map((element) =>
  3815. join(this.fs, path, element)
  3816. )
  3817. );
  3818. callback(null, set);
  3819. });
  3820. }
  3821. /**
  3822. * @private
  3823. * @type {Processor<string, string>}
  3824. */
  3825. _getManagedItemInfo(path, callback) {
  3826. const dir = dirname(this.fs, path);
  3827. this.managedItemDirectoryQueue.add(dir, (err, elements) => {
  3828. if (err) {
  3829. return callback(err);
  3830. }
  3831. if (!(/** @type {Set<string>} */ (elements).has(path))) {
  3832. // file or directory doesn't exist
  3833. this._managedItems.set(path, "*missing");
  3834. return callback(null, "*missing");
  3835. }
  3836. // something exists
  3837. // it may be a file or directory
  3838. if (
  3839. path.endsWith("node_modules") &&
  3840. (path.endsWith("/node_modules") || path.endsWith("\\node_modules"))
  3841. ) {
  3842. // we are only interested in existence of this special directory
  3843. this._managedItems.set(path, "*node_modules");
  3844. return callback(null, "*node_modules");
  3845. }
  3846. // we assume it's a directory, as files shouldn't occur in managed paths
  3847. const packageJsonPath = join(this.fs, path, "package.json");
  3848. this.fs.readFile(packageJsonPath, (err, content) => {
  3849. if (err) {
  3850. if (err.code === "ENOENT" || err.code === "ENOTDIR") {
  3851. // no package.json or path is not a directory
  3852. this.fs.readdir(path, (err, elements) => {
  3853. if (
  3854. !err &&
  3855. /** @type {string[]} */ (elements).length === 1 &&
  3856. /** @type {string[]} */ (elements)[0] === "node_modules"
  3857. ) {
  3858. // This is only a grouping folder e.g. used by yarn
  3859. // we are only interested in existence of this special directory
  3860. this._managedItems.set(path, "*nested");
  3861. return callback(null, "*nested");
  3862. }
  3863. /** @type {Logger} */
  3864. (this.logger).warn(
  3865. `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)`
  3866. );
  3867. return callback();
  3868. });
  3869. return;
  3870. }
  3871. return callback(/** @type {WebpackError} */ (err));
  3872. }
  3873. let data;
  3874. try {
  3875. data = JSON.parse(/** @type {Buffer} */ (content).toString("utf8"));
  3876. } catch (parseErr) {
  3877. return callback(/** @type {WebpackError} */ (parseErr));
  3878. }
  3879. if (!data.name) {
  3880. /** @type {Logger} */
  3881. (this.logger).warn(
  3882. `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)`
  3883. );
  3884. return callback();
  3885. }
  3886. const info = `${data.name || ""}@${data.version || ""}`;
  3887. this._managedItems.set(path, info);
  3888. callback(null, info);
  3889. });
  3890. });
  3891. }
  3892. getDeprecatedFileTimestamps() {
  3893. if (this._cachedDeprecatedFileTimestamps !== undefined) {
  3894. return this._cachedDeprecatedFileTimestamps;
  3895. }
  3896. /** @type {Map<string, number | null>} */
  3897. const map = new Map();
  3898. for (const [path, info] of this._fileTimestamps) {
  3899. if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
  3900. }
  3901. return (this._cachedDeprecatedFileTimestamps = map);
  3902. }
  3903. getDeprecatedContextTimestamps() {
  3904. if (this._cachedDeprecatedContextTimestamps !== undefined) {
  3905. return this._cachedDeprecatedContextTimestamps;
  3906. }
  3907. /** @type {Map<string, number | null>} */
  3908. const map = new Map();
  3909. for (const [path, info] of this._contextTimestamps) {
  3910. if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
  3911. }
  3912. return (this._cachedDeprecatedContextTimestamps = map);
  3913. }
  3914. }
  3915. module.exports = FileSystemInfo;
  3916. module.exports.Snapshot = Snapshot;