FileSystemInfo.js 117 KB

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