FileSystemInfo.js 117 KB

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