FileSystemInfo.js 117 KB

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