FileSystemInfo.js 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555
  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=, (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=, (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=, (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=, 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=, 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=, 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=, 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=, 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=, 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=, 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=, Snapshot=): 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 !== "missing") {
  2152. managedFiles.add(join(this.fs, path, "package.json"));
  2153. }
  2154. managedItemInfo.set(path, cache);
  2155. } else {
  2156. jobs++;
  2157. this.managedItemQueue.add(path, (err, entry) => {
  2158. if (err) {
  2159. if (this.logger) {
  2160. this.logger.debug(
  2161. `Error snapshotting managed item ${path}: ${err.stack}`
  2162. );
  2163. }
  2164. jobError();
  2165. } else if (entry) {
  2166. if (entry !== "missing") {
  2167. managedFiles.add(join(this.fs, path, "package.json"));
  2168. }
  2169. managedItemInfo.set(path, entry);
  2170. jobDone();
  2171. } else {
  2172. // Fallback to normal snapshotting
  2173. const process = (set, fn) => {
  2174. if (set.size === 0) return;
  2175. const captured = new Set();
  2176. for (const file of set) {
  2177. if (file.startsWith(path)) captured.add(file);
  2178. }
  2179. if (captured.size > 0) fn(captured);
  2180. };
  2181. process(managedFiles, processCapturedFiles);
  2182. process(managedContexts, processCapturedDirectories);
  2183. process(managedMissing, processCapturedMissing);
  2184. jobDone();
  2185. }
  2186. });
  2187. }
  2188. }
  2189. jobDone();
  2190. }
  2191. /**
  2192. * @param {Snapshot} snapshot1 a snapshot
  2193. * @param {Snapshot} snapshot2 a snapshot
  2194. * @returns {Snapshot} merged snapshot
  2195. */
  2196. mergeSnapshots(snapshot1, snapshot2) {
  2197. const snapshot = new Snapshot();
  2198. if (snapshot1.hasStartTime() && snapshot2.hasStartTime())
  2199. snapshot.setStartTime(Math.min(snapshot1.startTime, snapshot2.startTime));
  2200. else if (snapshot2.hasStartTime()) snapshot.startTime = snapshot2.startTime;
  2201. else if (snapshot1.hasStartTime()) snapshot.startTime = snapshot1.startTime;
  2202. if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) {
  2203. snapshot.setFileTimestamps(
  2204. mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps)
  2205. );
  2206. }
  2207. if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) {
  2208. snapshot.setFileHashes(
  2209. mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes)
  2210. );
  2211. }
  2212. if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) {
  2213. snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs));
  2214. }
  2215. if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) {
  2216. snapshot.setContextTimestamps(
  2217. mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps)
  2218. );
  2219. }
  2220. if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) {
  2221. snapshot.setContextHashes(
  2222. mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes)
  2223. );
  2224. }
  2225. if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) {
  2226. snapshot.setContextTshs(
  2227. mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs)
  2228. );
  2229. }
  2230. if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) {
  2231. snapshot.setMissingExistence(
  2232. mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence)
  2233. );
  2234. }
  2235. if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) {
  2236. snapshot.setManagedItemInfo(
  2237. mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo)
  2238. );
  2239. }
  2240. if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) {
  2241. snapshot.setManagedFiles(
  2242. mergeSets(snapshot1.managedFiles, snapshot2.managedFiles)
  2243. );
  2244. }
  2245. if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) {
  2246. snapshot.setManagedContexts(
  2247. mergeSets(snapshot1.managedContexts, snapshot2.managedContexts)
  2248. );
  2249. }
  2250. if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) {
  2251. snapshot.setManagedMissing(
  2252. mergeSets(snapshot1.managedMissing, snapshot2.managedMissing)
  2253. );
  2254. }
  2255. if (snapshot1.hasChildren() || snapshot2.hasChildren()) {
  2256. snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children));
  2257. }
  2258. if (
  2259. this._snapshotCache.get(snapshot1) === true &&
  2260. this._snapshotCache.get(snapshot2) === true
  2261. ) {
  2262. this._snapshotCache.set(snapshot, true);
  2263. }
  2264. return snapshot;
  2265. }
  2266. /**
  2267. * @param {Snapshot} snapshot the snapshot made
  2268. * @param {function(WebpackError=, boolean=): void} callback callback function
  2269. * @returns {void}
  2270. */
  2271. checkSnapshotValid(snapshot, callback) {
  2272. const cachedResult = this._snapshotCache.get(snapshot);
  2273. if (cachedResult !== undefined) {
  2274. this._statTestedSnapshotsCached++;
  2275. if (typeof cachedResult === "boolean") {
  2276. callback(null, cachedResult);
  2277. } else {
  2278. cachedResult.push(callback);
  2279. }
  2280. return;
  2281. }
  2282. this._statTestedSnapshotsNotCached++;
  2283. this._checkSnapshotValidNoCache(snapshot, callback);
  2284. }
  2285. /**
  2286. * @param {Snapshot} snapshot the snapshot made
  2287. * @param {function(WebpackError=, boolean=): void} callback callback function
  2288. * @returns {void}
  2289. */
  2290. _checkSnapshotValidNoCache(snapshot, callback) {
  2291. /** @type {number | undefined} */
  2292. let startTime = undefined;
  2293. if (snapshot.hasStartTime()) {
  2294. startTime = snapshot.startTime;
  2295. }
  2296. let jobs = 1;
  2297. const jobDone = () => {
  2298. if (--jobs === 0) {
  2299. this._snapshotCache.set(snapshot, true);
  2300. callback(null, true);
  2301. }
  2302. };
  2303. const invalid = () => {
  2304. if (jobs > 0) {
  2305. // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
  2306. jobs = -100000000;
  2307. this._snapshotCache.set(snapshot, false);
  2308. callback(null, false);
  2309. }
  2310. };
  2311. const invalidWithError = (path, err) => {
  2312. if (this._remainingLogs > 0) {
  2313. this._log(path, `error occurred: %s`, err);
  2314. }
  2315. invalid();
  2316. };
  2317. /**
  2318. * @param {string} path file path
  2319. * @param {string} current current hash
  2320. * @param {string} snap snapshot hash
  2321. * @returns {boolean} true, if ok
  2322. */
  2323. const checkHash = (path, current, snap) => {
  2324. if (current !== snap) {
  2325. // If hash differ it's invalid
  2326. if (this._remainingLogs > 0) {
  2327. this._log(path, `hashes differ (%s != %s)`, current, snap);
  2328. }
  2329. return false;
  2330. }
  2331. return true;
  2332. };
  2333. /**
  2334. * @param {string} path file path
  2335. * @param {boolean} current current entry
  2336. * @param {boolean} snap entry from snapshot
  2337. * @returns {boolean} true, if ok
  2338. */
  2339. const checkExistence = (path, current, snap) => {
  2340. if (!current !== !snap) {
  2341. // If existence of item differs
  2342. // it's invalid
  2343. if (this._remainingLogs > 0) {
  2344. this._log(
  2345. path,
  2346. current ? "it didn't exist before" : "it does no longer exist"
  2347. );
  2348. }
  2349. return false;
  2350. }
  2351. return true;
  2352. };
  2353. /**
  2354. * @param {string} path file path
  2355. * @param {FileSystemInfoEntry} current current entry
  2356. * @param {FileSystemInfoEntry} snap entry from snapshot
  2357. * @param {boolean} log log reason
  2358. * @returns {boolean} true, if ok
  2359. */
  2360. const checkFile = (path, current, snap, log = true) => {
  2361. if (current === snap) return true;
  2362. if (!checkExistence(path, Boolean(current), Boolean(snap))) return false;
  2363. if (current) {
  2364. // For existing items only
  2365. if (typeof startTime === "number" && current.safeTime > startTime) {
  2366. // If a change happened after starting reading the item
  2367. // this may no longer be valid
  2368. if (log && this._remainingLogs > 0) {
  2369. this._log(
  2370. path,
  2371. `it may have changed (%d) after the start time of the snapshot (%d)`,
  2372. current.safeTime,
  2373. startTime
  2374. );
  2375. }
  2376. return false;
  2377. }
  2378. if (
  2379. snap.timestamp !== undefined &&
  2380. current.timestamp !== snap.timestamp
  2381. ) {
  2382. // If we have a timestamp (it was a file or symlink) and it differs from current timestamp
  2383. // it's invalid
  2384. if (log && this._remainingLogs > 0) {
  2385. this._log(
  2386. path,
  2387. `timestamps differ (%d != %d)`,
  2388. current.timestamp,
  2389. snap.timestamp
  2390. );
  2391. }
  2392. return false;
  2393. }
  2394. }
  2395. return true;
  2396. };
  2397. /**
  2398. * @param {string} path file path
  2399. * @param {ResolvedContextFileSystemInfoEntry} current current entry
  2400. * @param {ResolvedContextFileSystemInfoEntry} snap entry from snapshot
  2401. * @param {boolean} log log reason
  2402. * @returns {boolean} true, if ok
  2403. */
  2404. const checkContext = (path, current, snap, log = true) => {
  2405. if (current === snap) return true;
  2406. if (!checkExistence(path, Boolean(current), Boolean(snap))) return false;
  2407. if (current) {
  2408. // For existing items only
  2409. if (typeof startTime === "number" && current.safeTime > startTime) {
  2410. // If a change happened after starting reading the item
  2411. // this may no longer be valid
  2412. if (log && this._remainingLogs > 0) {
  2413. this._log(
  2414. path,
  2415. `it may have changed (%d) after the start time of the snapshot (%d)`,
  2416. current.safeTime,
  2417. startTime
  2418. );
  2419. }
  2420. return false;
  2421. }
  2422. if (
  2423. snap.timestampHash !== undefined &&
  2424. current.timestampHash !== snap.timestampHash
  2425. ) {
  2426. // If we have a timestampHash (it was a directory) and it differs from current timestampHash
  2427. // it's invalid
  2428. if (log && this._remainingLogs > 0) {
  2429. this._log(
  2430. path,
  2431. `timestamps hashes differ (%s != %s)`,
  2432. current.timestampHash,
  2433. snap.timestampHash
  2434. );
  2435. }
  2436. return false;
  2437. }
  2438. }
  2439. return true;
  2440. };
  2441. if (snapshot.hasChildren()) {
  2442. const childCallback = (err, result) => {
  2443. if (err || !result) return invalid();
  2444. else jobDone();
  2445. };
  2446. for (const child of snapshot.children) {
  2447. const cache = this._snapshotCache.get(child);
  2448. if (cache !== undefined) {
  2449. this._statTestedChildrenCached++;
  2450. /* istanbul ignore else */
  2451. if (typeof cache === "boolean") {
  2452. if (cache === false) {
  2453. invalid();
  2454. return;
  2455. }
  2456. } else {
  2457. jobs++;
  2458. cache.push(childCallback);
  2459. }
  2460. } else {
  2461. this._statTestedChildrenNotCached++;
  2462. jobs++;
  2463. this._checkSnapshotValidNoCache(child, childCallback);
  2464. }
  2465. }
  2466. }
  2467. if (snapshot.hasFileTimestamps()) {
  2468. const { fileTimestamps } = snapshot;
  2469. this._statTestedEntries += fileTimestamps.size;
  2470. for (const [path, ts] of fileTimestamps) {
  2471. const cache = this._fileTimestamps.get(path);
  2472. if (cache !== undefined) {
  2473. if (cache !== "ignore" && !checkFile(path, cache, ts)) {
  2474. invalid();
  2475. return;
  2476. }
  2477. } else {
  2478. jobs++;
  2479. this.fileTimestampQueue.add(path, (err, entry) => {
  2480. if (err) return invalidWithError(path, err);
  2481. if (!checkFile(path, entry, ts)) {
  2482. invalid();
  2483. } else {
  2484. jobDone();
  2485. }
  2486. });
  2487. }
  2488. }
  2489. }
  2490. const processFileHashSnapshot = (path, hash) => {
  2491. const cache = this._fileHashes.get(path);
  2492. if (cache !== undefined) {
  2493. if (cache !== "ignore" && !checkHash(path, cache, hash)) {
  2494. invalid();
  2495. return;
  2496. }
  2497. } else {
  2498. jobs++;
  2499. this.fileHashQueue.add(path, (err, entry) => {
  2500. if (err) return invalidWithError(path, err);
  2501. if (!checkHash(path, entry, hash)) {
  2502. invalid();
  2503. } else {
  2504. jobDone();
  2505. }
  2506. });
  2507. }
  2508. };
  2509. if (snapshot.hasFileHashes()) {
  2510. const { fileHashes } = snapshot;
  2511. this._statTestedEntries += fileHashes.size;
  2512. for (const [path, hash] of fileHashes) {
  2513. processFileHashSnapshot(path, hash);
  2514. }
  2515. }
  2516. if (snapshot.hasFileTshs()) {
  2517. const { fileTshs } = snapshot;
  2518. this._statTestedEntries += fileTshs.size;
  2519. for (const [path, tsh] of fileTshs) {
  2520. if (typeof tsh === "string") {
  2521. processFileHashSnapshot(path, tsh);
  2522. } else {
  2523. const cache = this._fileTimestamps.get(path);
  2524. if (cache !== undefined) {
  2525. if (cache === "ignore" || !checkFile(path, cache, tsh, false)) {
  2526. processFileHashSnapshot(path, tsh && tsh.hash);
  2527. }
  2528. } else {
  2529. jobs++;
  2530. this.fileTimestampQueue.add(path, (err, entry) => {
  2531. if (err) return invalidWithError(path, err);
  2532. if (!checkFile(path, entry, tsh, false)) {
  2533. processFileHashSnapshot(path, tsh && tsh.hash);
  2534. }
  2535. jobDone();
  2536. });
  2537. }
  2538. }
  2539. }
  2540. }
  2541. if (snapshot.hasContextTimestamps()) {
  2542. const { contextTimestamps } = snapshot;
  2543. this._statTestedEntries += contextTimestamps.size;
  2544. for (const [path, ts] of contextTimestamps) {
  2545. const cache = this._contextTimestamps.get(path);
  2546. if (cache === "ignore") continue;
  2547. let resolved;
  2548. if (
  2549. cache !== undefined &&
  2550. (resolved = getResolvedTimestamp(cache)) !== undefined
  2551. ) {
  2552. if (!checkContext(path, resolved, ts)) {
  2553. invalid();
  2554. return;
  2555. }
  2556. } else {
  2557. jobs++;
  2558. /**
  2559. * @param {Error=} err error
  2560. * @param {ResolvedContextFileSystemInfoEntry=} entry entry
  2561. * @returns {void}
  2562. */
  2563. const callback = (err, entry) => {
  2564. if (err) return invalidWithError(path, err);
  2565. if (!checkContext(path, entry, ts)) {
  2566. invalid();
  2567. } else {
  2568. jobDone();
  2569. }
  2570. };
  2571. if (cache !== undefined) {
  2572. this._resolveContextTimestamp(cache, callback);
  2573. } else {
  2574. this.getContextTimestamp(path, callback);
  2575. }
  2576. }
  2577. }
  2578. }
  2579. const processContextHashSnapshot = (path, hash) => {
  2580. const cache = this._contextHashes.get(path);
  2581. let resolved;
  2582. if (
  2583. cache !== undefined &&
  2584. (resolved = getResolvedHash(cache)) !== undefined
  2585. ) {
  2586. if (!checkHash(path, resolved, hash)) {
  2587. invalid();
  2588. return;
  2589. }
  2590. } else {
  2591. jobs++;
  2592. const callback = (err, entry) => {
  2593. if (err) return invalidWithError(path, err);
  2594. if (!checkHash(path, entry, hash)) {
  2595. invalid();
  2596. } else {
  2597. jobDone();
  2598. }
  2599. };
  2600. if (cache !== undefined) {
  2601. this._resolveContextHash(cache, callback);
  2602. } else {
  2603. this.getContextHash(path, callback);
  2604. }
  2605. }
  2606. };
  2607. if (snapshot.hasContextHashes()) {
  2608. const { contextHashes } = snapshot;
  2609. this._statTestedEntries += contextHashes.size;
  2610. for (const [path, hash] of contextHashes) {
  2611. processContextHashSnapshot(path, hash);
  2612. }
  2613. }
  2614. if (snapshot.hasContextTshs()) {
  2615. const { contextTshs } = snapshot;
  2616. this._statTestedEntries += contextTshs.size;
  2617. for (const [path, tsh] of contextTshs) {
  2618. if (typeof tsh === "string") {
  2619. processContextHashSnapshot(path, tsh);
  2620. } else {
  2621. const cache = this._contextTimestamps.get(path);
  2622. if (cache === "ignore") continue;
  2623. let resolved;
  2624. if (
  2625. cache !== undefined &&
  2626. (resolved = getResolvedTimestamp(cache)) !== undefined
  2627. ) {
  2628. if (!checkContext(path, resolved, tsh, false)) {
  2629. processContextHashSnapshot(path, tsh && tsh.hash);
  2630. }
  2631. } else {
  2632. jobs++;
  2633. /**
  2634. * @param {Error=} err error
  2635. * @param {ResolvedContextFileSystemInfoEntry=} entry entry
  2636. * @returns {void}
  2637. */
  2638. const callback = (err, entry) => {
  2639. if (err) return invalidWithError(path, err);
  2640. if (!checkContext(path, entry, tsh, false)) {
  2641. processContextHashSnapshot(path, tsh && tsh.hash);
  2642. }
  2643. jobDone();
  2644. };
  2645. if (cache !== undefined) {
  2646. this._resolveContextTimestamp(cache, callback);
  2647. } else {
  2648. this.getContextTimestamp(path, callback);
  2649. }
  2650. }
  2651. }
  2652. }
  2653. }
  2654. if (snapshot.hasMissingExistence()) {
  2655. const { missingExistence } = snapshot;
  2656. this._statTestedEntries += missingExistence.size;
  2657. for (const [path, existence] of missingExistence) {
  2658. const cache = this._fileTimestamps.get(path);
  2659. if (cache !== undefined) {
  2660. if (
  2661. cache !== "ignore" &&
  2662. !checkExistence(path, Boolean(cache), Boolean(existence))
  2663. ) {
  2664. invalid();
  2665. return;
  2666. }
  2667. } else {
  2668. jobs++;
  2669. this.fileTimestampQueue.add(path, (err, entry) => {
  2670. if (err) return invalidWithError(path, err);
  2671. if (!checkExistence(path, Boolean(entry), Boolean(existence))) {
  2672. invalid();
  2673. } else {
  2674. jobDone();
  2675. }
  2676. });
  2677. }
  2678. }
  2679. }
  2680. if (snapshot.hasManagedItemInfo()) {
  2681. const { managedItemInfo } = snapshot;
  2682. this._statTestedEntries += managedItemInfo.size;
  2683. for (const [path, info] of managedItemInfo) {
  2684. const cache = this._managedItems.get(path);
  2685. if (cache !== undefined) {
  2686. if (!checkHash(path, cache, info)) {
  2687. invalid();
  2688. return;
  2689. }
  2690. } else {
  2691. jobs++;
  2692. this.managedItemQueue.add(path, (err, entry) => {
  2693. if (err) return invalidWithError(path, err);
  2694. if (!checkHash(path, entry, info)) {
  2695. invalid();
  2696. } else {
  2697. jobDone();
  2698. }
  2699. });
  2700. }
  2701. }
  2702. }
  2703. jobDone();
  2704. // if there was an async action
  2705. // try to join multiple concurrent request for this snapshot
  2706. if (jobs > 0) {
  2707. const callbacks = [callback];
  2708. callback = (err, result) => {
  2709. for (const callback of callbacks) callback(err, result);
  2710. };
  2711. this._snapshotCache.set(snapshot, callbacks);
  2712. }
  2713. }
  2714. _readFileTimestamp(path, callback) {
  2715. this.fs.stat(path, (err, stat) => {
  2716. if (err) {
  2717. if (err.code === "ENOENT") {
  2718. this._fileTimestamps.set(path, null);
  2719. this._cachedDeprecatedFileTimestamps = undefined;
  2720. return callback(null, null);
  2721. }
  2722. return callback(err);
  2723. }
  2724. let ts;
  2725. if (stat.isDirectory()) {
  2726. ts = {
  2727. safeTime: 0,
  2728. timestamp: undefined
  2729. };
  2730. } else {
  2731. const mtime = +stat.mtime;
  2732. if (mtime) applyMtime(mtime);
  2733. ts = {
  2734. safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
  2735. timestamp: mtime
  2736. };
  2737. }
  2738. this._fileTimestamps.set(path, ts);
  2739. this._cachedDeprecatedFileTimestamps = undefined;
  2740. callback(null, ts);
  2741. });
  2742. }
  2743. _readFileHash(path, callback) {
  2744. this.fs.readFile(path, (err, content) => {
  2745. if (err) {
  2746. if (err.code === "EISDIR") {
  2747. this._fileHashes.set(path, "directory");
  2748. return callback(null, "directory");
  2749. }
  2750. if (err.code === "ENOENT") {
  2751. this._fileHashes.set(path, null);
  2752. return callback(null, null);
  2753. }
  2754. if (err.code === "ERR_FS_FILE_TOO_LARGE") {
  2755. this.logger.warn(`Ignoring ${path} for hashing as it's very large`);
  2756. this._fileHashes.set(path, "too large");
  2757. return callback(null, "too large");
  2758. }
  2759. return callback(err);
  2760. }
  2761. const hash = createHash(this._hashFunction);
  2762. hash.update(content);
  2763. const digest = /** @type {string} */ (hash.digest("hex"));
  2764. this._fileHashes.set(path, digest);
  2765. callback(null, digest);
  2766. });
  2767. }
  2768. _getFileTimestampAndHash(path, callback) {
  2769. const continueWithHash = hash => {
  2770. const cache = this._fileTimestamps.get(path);
  2771. if (cache !== undefined) {
  2772. if (cache !== "ignore") {
  2773. const result = {
  2774. ...cache,
  2775. hash
  2776. };
  2777. this._fileTshs.set(path, result);
  2778. return callback(null, result);
  2779. } else {
  2780. this._fileTshs.set(path, hash);
  2781. return callback(null, hash);
  2782. }
  2783. } else {
  2784. this.fileTimestampQueue.add(path, (err, entry) => {
  2785. if (err) {
  2786. return callback(err);
  2787. }
  2788. const result = {
  2789. ...entry,
  2790. hash
  2791. };
  2792. this._fileTshs.set(path, result);
  2793. return callback(null, result);
  2794. });
  2795. }
  2796. };
  2797. const cache = this._fileHashes.get(path);
  2798. if (cache !== undefined) {
  2799. continueWithHash(cache);
  2800. } else {
  2801. this.fileHashQueue.add(path, (err, entry) => {
  2802. if (err) {
  2803. return callback(err);
  2804. }
  2805. continueWithHash(entry);
  2806. });
  2807. }
  2808. }
  2809. /**
  2810. * @template T
  2811. * @template ItemType
  2812. * @param {Object} options options
  2813. * @param {string} options.path path
  2814. * @param {function(string): ItemType} options.fromImmutablePath called when context item is an immutable path
  2815. * @param {function(string): ItemType} options.fromManagedItem called when context item is a managed path
  2816. * @param {function(string, string, function(Error=, ItemType=): void): void} options.fromSymlink called when context item is a symlink
  2817. * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromFile called when context item is a file
  2818. * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromDirectory called when context item is a directory
  2819. * @param {function(string[], ItemType[]): T} options.reduce called from all context items
  2820. * @param {function(Error=, (T)=): void} callback callback
  2821. */
  2822. _readContext(
  2823. {
  2824. path,
  2825. fromImmutablePath,
  2826. fromManagedItem,
  2827. fromSymlink,
  2828. fromFile,
  2829. fromDirectory,
  2830. reduce
  2831. },
  2832. callback
  2833. ) {
  2834. this.fs.readdir(path, (err, _files) => {
  2835. if (err) {
  2836. if (err.code === "ENOENT") {
  2837. return callback(null, null);
  2838. }
  2839. return callback(err);
  2840. }
  2841. const files = /** @type {string[]} */ (_files)
  2842. .map(file => file.normalize("NFC"))
  2843. .filter(file => !/^\./.test(file))
  2844. .sort();
  2845. asyncLib.map(
  2846. files,
  2847. (file, callback) => {
  2848. const child = join(this.fs, path, file);
  2849. for (const immutablePath of this.immutablePathsRegExps) {
  2850. if (immutablePath.test(path)) {
  2851. // ignore any immutable path for timestamping
  2852. return callback(null, fromImmutablePath(path));
  2853. }
  2854. }
  2855. for (const immutablePath of this.immutablePathsWithSlash) {
  2856. if (path.startsWith(immutablePath)) {
  2857. // ignore any immutable path for timestamping
  2858. return callback(null, fromImmutablePath(path));
  2859. }
  2860. }
  2861. for (const managedPath of this.managedPathsRegExps) {
  2862. const match = managedPath.exec(path);
  2863. if (match) {
  2864. const managedItem = getManagedItem(match[1], path);
  2865. if (managedItem) {
  2866. // construct timestampHash from managed info
  2867. return this.managedItemQueue.add(managedItem, (err, info) => {
  2868. if (err) return callback(err);
  2869. return callback(null, fromManagedItem(info));
  2870. });
  2871. }
  2872. }
  2873. }
  2874. for (const managedPath of this.managedPathsWithSlash) {
  2875. if (path.startsWith(managedPath)) {
  2876. const managedItem = getManagedItem(managedPath, child);
  2877. if (managedItem) {
  2878. // construct timestampHash from managed info
  2879. return this.managedItemQueue.add(managedItem, (err, info) => {
  2880. if (err) return callback(err);
  2881. return callback(null, fromManagedItem(info));
  2882. });
  2883. }
  2884. }
  2885. }
  2886. lstatReadlinkAbsolute(this.fs, child, (err, stat) => {
  2887. if (err) return callback(err);
  2888. if (typeof stat === "string") {
  2889. return fromSymlink(child, stat, callback);
  2890. }
  2891. if (stat.isFile()) {
  2892. return fromFile(child, stat, callback);
  2893. }
  2894. if (stat.isDirectory()) {
  2895. return fromDirectory(child, stat, callback);
  2896. }
  2897. callback(null, null);
  2898. });
  2899. },
  2900. (err, results) => {
  2901. if (err) return callback(err);
  2902. const result = reduce(files, results);
  2903. callback(null, result);
  2904. }
  2905. );
  2906. });
  2907. }
  2908. _readContextTimestamp(path, callback) {
  2909. this._readContext(
  2910. {
  2911. path,
  2912. fromImmutablePath: () => null,
  2913. fromManagedItem: info => ({
  2914. safeTime: 0,
  2915. timestampHash: info
  2916. }),
  2917. fromSymlink: (file, target, callback) => {
  2918. callback(null, {
  2919. timestampHash: target,
  2920. symlinks: new Set([target])
  2921. });
  2922. },
  2923. fromFile: (file, stat, callback) => {
  2924. // Prefer the cached value over our new stat to report consistent results
  2925. const cache = this._fileTimestamps.get(file);
  2926. if (cache !== undefined)
  2927. return callback(null, cache === "ignore" ? null : cache);
  2928. const mtime = +stat.mtime;
  2929. if (mtime) applyMtime(mtime);
  2930. const ts = {
  2931. safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
  2932. timestamp: mtime
  2933. };
  2934. this._fileTimestamps.set(file, ts);
  2935. this._cachedDeprecatedFileTimestamps = undefined;
  2936. callback(null, ts);
  2937. },
  2938. fromDirectory: (directory, stat, callback) => {
  2939. this.contextTimestampQueue.increaseParallelism();
  2940. this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => {
  2941. this.contextTimestampQueue.decreaseParallelism();
  2942. callback(err, tsEntry);
  2943. });
  2944. },
  2945. reduce: (files, tsEntries) => {
  2946. let symlinks = undefined;
  2947. const hash = createHash(this._hashFunction);
  2948. for (const file of files) hash.update(file);
  2949. let safeTime = 0;
  2950. for (const entry of tsEntries) {
  2951. if (!entry) {
  2952. hash.update("n");
  2953. continue;
  2954. }
  2955. if (entry.timestamp) {
  2956. hash.update("f");
  2957. hash.update(`${entry.timestamp}`);
  2958. } else if (entry.timestampHash) {
  2959. hash.update("d");
  2960. hash.update(`${entry.timestampHash}`);
  2961. }
  2962. if (entry.symlinks !== undefined) {
  2963. if (symlinks === undefined) symlinks = new Set();
  2964. addAll(entry.symlinks, symlinks);
  2965. }
  2966. if (entry.safeTime) {
  2967. safeTime = Math.max(safeTime, entry.safeTime);
  2968. }
  2969. }
  2970. const digest = /** @type {string} */ (hash.digest("hex"));
  2971. const result = {
  2972. safeTime,
  2973. timestampHash: digest
  2974. };
  2975. if (symlinks) result.symlinks = symlinks;
  2976. return result;
  2977. }
  2978. },
  2979. (err, result) => {
  2980. if (err) return callback(err);
  2981. this._contextTimestamps.set(path, result);
  2982. this._cachedDeprecatedContextTimestamps = undefined;
  2983. callback(null, result);
  2984. }
  2985. );
  2986. }
  2987. /**
  2988. * @param {ContextFileSystemInfoEntry} entry entry
  2989. * @param {function(Error=, ResolvedContextFileSystemInfoEntry=): void} callback callback
  2990. * @returns {void}
  2991. */
  2992. _resolveContextTimestamp(entry, callback) {
  2993. const hashes = [];
  2994. let safeTime = 0;
  2995. processAsyncTree(
  2996. entry.symlinks,
  2997. 10,
  2998. (target, push, callback) => {
  2999. this._getUnresolvedContextTimestamp(target, (err, entry) => {
  3000. if (err) return callback(err);
  3001. if (entry && entry !== "ignore") {
  3002. hashes.push(entry.timestampHash);
  3003. if (entry.safeTime) {
  3004. safeTime = Math.max(safeTime, entry.safeTime);
  3005. }
  3006. if (entry.symlinks !== undefined) {
  3007. for (const target of entry.symlinks) push(target);
  3008. }
  3009. }
  3010. callback();
  3011. });
  3012. },
  3013. err => {
  3014. if (err) return callback(err);
  3015. const hash = createHash(this._hashFunction);
  3016. hash.update(entry.timestampHash);
  3017. if (entry.safeTime) {
  3018. safeTime = Math.max(safeTime, entry.safeTime);
  3019. }
  3020. hashes.sort();
  3021. for (const h of hashes) {
  3022. hash.update(h);
  3023. }
  3024. callback(
  3025. null,
  3026. (entry.resolved = {
  3027. safeTime,
  3028. timestampHash: /** @type {string} */ (hash.digest("hex"))
  3029. })
  3030. );
  3031. }
  3032. );
  3033. }
  3034. _readContextHash(path, callback) {
  3035. this._readContext(
  3036. {
  3037. path,
  3038. fromImmutablePath: () => "",
  3039. fromManagedItem: info => info || "",
  3040. fromSymlink: (file, target, callback) => {
  3041. callback(null, {
  3042. hash: target,
  3043. symlinks: new Set([target])
  3044. });
  3045. },
  3046. fromFile: (file, stat, callback) =>
  3047. this.getFileHash(file, (err, hash) => {
  3048. callback(err, hash || "");
  3049. }),
  3050. fromDirectory: (directory, stat, callback) => {
  3051. this.contextHashQueue.increaseParallelism();
  3052. this._getUnresolvedContextHash(directory, (err, hash) => {
  3053. this.contextHashQueue.decreaseParallelism();
  3054. callback(err, hash || "");
  3055. });
  3056. },
  3057. /**
  3058. * @param {string[]} files files
  3059. * @param {(string | ContextHash)[]} fileHashes hashes
  3060. * @returns {ContextHash} reduced hash
  3061. */
  3062. reduce: (files, fileHashes) => {
  3063. let symlinks = undefined;
  3064. const hash = createHash(this._hashFunction);
  3065. for (const file of files) hash.update(file);
  3066. for (const entry of fileHashes) {
  3067. if (typeof entry === "string") {
  3068. hash.update(entry);
  3069. } else {
  3070. hash.update(entry.hash);
  3071. if (entry.symlinks) {
  3072. if (symlinks === undefined) symlinks = new Set();
  3073. addAll(entry.symlinks, symlinks);
  3074. }
  3075. }
  3076. }
  3077. const result = {
  3078. hash: /** @type {string} */ (hash.digest("hex"))
  3079. };
  3080. if (symlinks) result.symlinks = symlinks;
  3081. return result;
  3082. }
  3083. },
  3084. (err, result) => {
  3085. if (err) return callback(err);
  3086. this._contextHashes.set(path, result);
  3087. return callback(null, result);
  3088. }
  3089. );
  3090. }
  3091. /**
  3092. * @param {ContextHash} entry context hash
  3093. * @param {function(Error=, string=): void} callback callback
  3094. * @returns {void}
  3095. */
  3096. _resolveContextHash(entry, callback) {
  3097. const hashes = [];
  3098. processAsyncTree(
  3099. entry.symlinks,
  3100. 10,
  3101. (target, push, callback) => {
  3102. this._getUnresolvedContextHash(target, (err, hash) => {
  3103. if (err) return callback(err);
  3104. if (hash) {
  3105. hashes.push(hash.hash);
  3106. if (hash.symlinks !== undefined) {
  3107. for (const target of hash.symlinks) push(target);
  3108. }
  3109. }
  3110. callback();
  3111. });
  3112. },
  3113. err => {
  3114. if (err) return callback(err);
  3115. const hash = createHash(this._hashFunction);
  3116. hash.update(entry.hash);
  3117. hashes.sort();
  3118. for (const h of hashes) {
  3119. hash.update(h);
  3120. }
  3121. callback(
  3122. null,
  3123. (entry.resolved = /** @type {string} */ (hash.digest("hex")))
  3124. );
  3125. }
  3126. );
  3127. }
  3128. _readContextTimestampAndHash(path, callback) {
  3129. const finalize = (timestamp, hash) => {
  3130. const result =
  3131. timestamp === "ignore"
  3132. ? hash
  3133. : {
  3134. ...timestamp,
  3135. ...hash
  3136. };
  3137. this._contextTshs.set(path, result);
  3138. callback(null, result);
  3139. };
  3140. const cachedHash = this._contextHashes.get(path);
  3141. const cachedTimestamp = this._contextTimestamps.get(path);
  3142. if (cachedHash !== undefined) {
  3143. if (cachedTimestamp !== undefined) {
  3144. finalize(cachedTimestamp, cachedHash);
  3145. } else {
  3146. this.contextTimestampQueue.add(path, (err, entry) => {
  3147. if (err) return callback(err);
  3148. finalize(entry, cachedHash);
  3149. });
  3150. }
  3151. } else {
  3152. if (cachedTimestamp !== undefined) {
  3153. this.contextHashQueue.add(path, (err, entry) => {
  3154. if (err) return callback(err);
  3155. finalize(cachedTimestamp, entry);
  3156. });
  3157. } else {
  3158. this._readContext(
  3159. {
  3160. path,
  3161. fromImmutablePath: () => null,
  3162. fromManagedItem: info => ({
  3163. safeTime: 0,
  3164. timestampHash: info,
  3165. hash: info || ""
  3166. }),
  3167. fromSymlink: (fle, target, callback) => {
  3168. callback(null, {
  3169. timestampHash: target,
  3170. hash: target,
  3171. symlinks: new Set([target])
  3172. });
  3173. },
  3174. fromFile: (file, stat, callback) => {
  3175. this._getFileTimestampAndHash(file, callback);
  3176. },
  3177. fromDirectory: (directory, stat, callback) => {
  3178. this.contextTshQueue.increaseParallelism();
  3179. this.contextTshQueue.add(directory, (err, result) => {
  3180. this.contextTshQueue.decreaseParallelism();
  3181. callback(err, result);
  3182. });
  3183. },
  3184. /**
  3185. * @param {string[]} files files
  3186. * @param {(Partial<TimestampAndHash> & Partial<ContextTimestampAndHash> | string | null)[]} results results
  3187. * @returns {ContextTimestampAndHash} tsh
  3188. */
  3189. reduce: (files, results) => {
  3190. let symlinks = undefined;
  3191. const tsHash = createHash(this._hashFunction);
  3192. const hash = createHash(this._hashFunction);
  3193. for (const file of files) {
  3194. tsHash.update(file);
  3195. hash.update(file);
  3196. }
  3197. let safeTime = 0;
  3198. for (const entry of results) {
  3199. if (!entry) {
  3200. tsHash.update("n");
  3201. continue;
  3202. }
  3203. if (typeof entry === "string") {
  3204. tsHash.update("n");
  3205. hash.update(entry);
  3206. continue;
  3207. }
  3208. if (entry.timestamp) {
  3209. tsHash.update("f");
  3210. tsHash.update(`${entry.timestamp}`);
  3211. } else if (entry.timestampHash) {
  3212. tsHash.update("d");
  3213. tsHash.update(`${entry.timestampHash}`);
  3214. }
  3215. if (entry.symlinks !== undefined) {
  3216. if (symlinks === undefined) symlinks = new Set();
  3217. addAll(entry.symlinks, symlinks);
  3218. }
  3219. if (entry.safeTime) {
  3220. safeTime = Math.max(safeTime, entry.safeTime);
  3221. }
  3222. hash.update(entry.hash);
  3223. }
  3224. const result = {
  3225. safeTime,
  3226. timestampHash: /** @type {string} */ (tsHash.digest("hex")),
  3227. hash: /** @type {string} */ (hash.digest("hex"))
  3228. };
  3229. if (symlinks) result.symlinks = symlinks;
  3230. return result;
  3231. }
  3232. },
  3233. (err, result) => {
  3234. if (err) return callback(err);
  3235. this._contextTshs.set(path, result);
  3236. return callback(null, result);
  3237. }
  3238. );
  3239. }
  3240. }
  3241. }
  3242. /**
  3243. * @param {ContextTimestampAndHash} entry entry
  3244. * @param {function(Error=, ResolvedContextTimestampAndHash=): void} callback callback
  3245. * @returns {void}
  3246. */
  3247. _resolveContextTsh(entry, callback) {
  3248. const hashes = [];
  3249. const tsHashes = [];
  3250. let safeTime = 0;
  3251. processAsyncTree(
  3252. entry.symlinks,
  3253. 10,
  3254. (target, push, callback) => {
  3255. this._getUnresolvedContextTsh(target, (err, entry) => {
  3256. if (err) return callback(err);
  3257. if (entry) {
  3258. hashes.push(entry.hash);
  3259. if (entry.timestampHash) tsHashes.push(entry.timestampHash);
  3260. if (entry.safeTime) {
  3261. safeTime = Math.max(safeTime, entry.safeTime);
  3262. }
  3263. if (entry.symlinks !== undefined) {
  3264. for (const target of entry.symlinks) push(target);
  3265. }
  3266. }
  3267. callback();
  3268. });
  3269. },
  3270. err => {
  3271. if (err) return callback(err);
  3272. const hash = createHash(this._hashFunction);
  3273. const tsHash = createHash(this._hashFunction);
  3274. hash.update(entry.hash);
  3275. if (entry.timestampHash) tsHash.update(entry.timestampHash);
  3276. if (entry.safeTime) {
  3277. safeTime = Math.max(safeTime, entry.safeTime);
  3278. }
  3279. hashes.sort();
  3280. for (const h of hashes) {
  3281. hash.update(h);
  3282. }
  3283. tsHashes.sort();
  3284. for (const h of tsHashes) {
  3285. tsHash.update(h);
  3286. }
  3287. callback(
  3288. null,
  3289. (entry.resolved = {
  3290. safeTime,
  3291. timestampHash: /** @type {string} */ (tsHash.digest("hex")),
  3292. hash: /** @type {string} */ (hash.digest("hex"))
  3293. })
  3294. );
  3295. }
  3296. );
  3297. }
  3298. _getManagedItemDirectoryInfo(path, callback) {
  3299. this.fs.readdir(path, (err, elements) => {
  3300. if (err) {
  3301. if (err.code === "ENOENT" || err.code === "ENOTDIR") {
  3302. return callback(null, EMPTY_SET);
  3303. }
  3304. return callback(err);
  3305. }
  3306. const set = new Set(
  3307. /** @type {string[]} */ (elements).map(element =>
  3308. join(this.fs, path, element)
  3309. )
  3310. );
  3311. callback(null, set);
  3312. });
  3313. }
  3314. _getManagedItemInfo(path, callback) {
  3315. const dir = dirname(this.fs, path);
  3316. this.managedItemDirectoryQueue.add(dir, (err, elements) => {
  3317. if (err) {
  3318. return callback(err);
  3319. }
  3320. if (!elements.has(path)) {
  3321. // file or directory doesn't exist
  3322. this._managedItems.set(path, "missing");
  3323. return callback(null, "missing");
  3324. }
  3325. // something exists
  3326. // it may be a file or directory
  3327. if (
  3328. path.endsWith("node_modules") &&
  3329. (path.endsWith("/node_modules") || path.endsWith("\\node_modules"))
  3330. ) {
  3331. // we are only interested in existence of this special directory
  3332. this._managedItems.set(path, "exists");
  3333. return callback(null, "exists");
  3334. }
  3335. // we assume it's a directory, as files shouldn't occur in managed paths
  3336. const packageJsonPath = join(this.fs, path, "package.json");
  3337. this.fs.readFile(packageJsonPath, (err, content) => {
  3338. if (err) {
  3339. if (err.code === "ENOENT" || err.code === "ENOTDIR") {
  3340. // no package.json or path is not a directory
  3341. this.fs.readdir(path, (err, elements) => {
  3342. if (
  3343. !err &&
  3344. elements.length === 1 &&
  3345. elements[0] === "node_modules"
  3346. ) {
  3347. // This is only a grouping folder e. g. used by yarn
  3348. // we are only interested in existence of this special directory
  3349. this._managedItems.set(path, "nested");
  3350. return callback(null, "nested");
  3351. }
  3352. this.logger.warn(
  3353. `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)`
  3354. );
  3355. return callback();
  3356. });
  3357. return;
  3358. }
  3359. return callback(err);
  3360. }
  3361. let data;
  3362. try {
  3363. data = JSON.parse(content.toString("utf-8"));
  3364. } catch (e) {
  3365. return callback(e);
  3366. }
  3367. if (!data.name) {
  3368. this.logger.warn(
  3369. `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)`
  3370. );
  3371. return callback();
  3372. }
  3373. const info = `${data.name || ""}@${data.version || ""}`;
  3374. this._managedItems.set(path, info);
  3375. callback(null, info);
  3376. });
  3377. });
  3378. }
  3379. getDeprecatedFileTimestamps() {
  3380. if (this._cachedDeprecatedFileTimestamps !== undefined)
  3381. return this._cachedDeprecatedFileTimestamps;
  3382. const map = new Map();
  3383. for (const [path, info] of this._fileTimestamps) {
  3384. if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
  3385. }
  3386. return (this._cachedDeprecatedFileTimestamps = map);
  3387. }
  3388. getDeprecatedContextTimestamps() {
  3389. if (this._cachedDeprecatedContextTimestamps !== undefined)
  3390. return this._cachedDeprecatedContextTimestamps;
  3391. const map = new Map();
  3392. for (const [path, info] of this._contextTimestamps) {
  3393. if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
  3394. }
  3395. return (this._cachedDeprecatedContextTimestamps = map);
  3396. }
  3397. }
  3398. module.exports = FileSystemInfo;
  3399. module.exports.Snapshot = Snapshot;