FileSystemInfo.js 105 KB

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