FileSystemInfo.js 102 KB

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