FileSystemInfo.js 122 KB

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