HttpUriPlugin.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const EventEmitter = require("events");
  7. const { basename, extname } = require("path");
  8. const {
  9. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  10. createBrotliDecompress,
  11. createGunzip,
  12. createInflate
  13. } = require("zlib");
  14. const NormalModule = require("../NormalModule");
  15. const createSchemaValidation = require("../util/create-schema-validation");
  16. const createHash = require("../util/createHash");
  17. const { dirname, join, mkdirp } = require("../util/fs");
  18. const memoize = require("../util/memoize");
  19. /** @typedef {import("http").IncomingMessage} IncomingMessage */
  20. /** @typedef {import("http").OutgoingHttpHeaders} OutgoingHttpHeaders */
  21. /** @typedef {import("http").RequestOptions} RequestOptions */
  22. /** @typedef {import("net").Socket} Socket */
  23. /** @typedef {import("stream").Readable} Readable */
  24. /** @typedef {import("../../declarations/plugins/schemes/HttpUriPlugin").HttpUriPluginOptions} HttpUriPluginOptions */
  25. /** @typedef {import("../Compiler")} Compiler */
  26. /** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */
  27. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  28. /** @typedef {import("../NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */
  29. /** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */
  30. const getHttp = memoize(() => require("http"));
  31. const getHttps = memoize(() => require("https"));
  32. const MAX_REDIRECTS = 5;
  33. /**
  34. * @param {typeof import("http") | typeof import("https")} request request
  35. * @param {string | URL | undefined} proxy proxy
  36. * @returns {(url: URL, requestOptions: RequestOptions, callback: (incomingMessage: IncomingMessage) => void) => EventEmitter} fn
  37. */
  38. const proxyFetch = (request, proxy) => (url, options, callback) => {
  39. const eventEmitter = new EventEmitter();
  40. /**
  41. * @param {Socket=} socket socket
  42. * @returns {void}
  43. */
  44. const doRequest = (socket) => {
  45. request
  46. .get(url, { ...options, ...(socket && { socket }) }, callback)
  47. .on("error", eventEmitter.emit.bind(eventEmitter, "error"));
  48. };
  49. if (proxy) {
  50. const { hostname: host, port } = new URL(proxy);
  51. getHttp()
  52. .request({
  53. host, // IP address of proxy server
  54. port, // port of proxy server
  55. method: "CONNECT",
  56. path: url.host
  57. })
  58. .on("connect", (res, socket) => {
  59. if (res.statusCode === 200) {
  60. // connected to proxy server
  61. doRequest(socket);
  62. }
  63. })
  64. .on("error", (err) => {
  65. eventEmitter.emit(
  66. "error",
  67. new Error(
  68. `Failed to connect to proxy server "${proxy}": ${err.message}`
  69. )
  70. );
  71. })
  72. .end();
  73. } else {
  74. doRequest();
  75. }
  76. return eventEmitter;
  77. };
  78. /** @typedef {() => void} InProgressWriteItem */
  79. /** @type {InProgressWriteItem[] | undefined} */
  80. let inProgressWrite;
  81. const validate = createSchemaValidation(
  82. require("../../schemas/plugins/schemes/HttpUriPlugin.check"),
  83. () => require("../../schemas/plugins/schemes/HttpUriPlugin.json"),
  84. {
  85. name: "Http Uri Plugin",
  86. baseDataPath: "options"
  87. }
  88. );
  89. /**
  90. * @param {string} str path
  91. * @returns {string} safe path
  92. */
  93. const toSafePath = (str) =>
  94. str
  95. .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "")
  96. .replace(/[^a-zA-Z0-9._-]+/g, "_");
  97. /**
  98. * @param {Buffer} content content
  99. * @returns {string} integrity
  100. */
  101. const computeIntegrity = (content) => {
  102. const hash = createHash("sha512");
  103. hash.update(content);
  104. const integrity = `sha512-${hash.digest("base64")}`;
  105. return integrity;
  106. };
  107. /**
  108. * @param {Buffer} content content
  109. * @param {string} integrity integrity
  110. * @returns {boolean} true, if integrity matches
  111. */
  112. const verifyIntegrity = (content, integrity) => {
  113. if (integrity === "ignore") return true;
  114. return computeIntegrity(content) === integrity;
  115. };
  116. /**
  117. * @param {string} str input
  118. * @returns {Record<string, string>} parsed
  119. */
  120. const parseKeyValuePairs = (str) => {
  121. /** @type {Record<string, string>} */
  122. const result = {};
  123. for (const item of str.split(",")) {
  124. const i = item.indexOf("=");
  125. if (i >= 0) {
  126. const key = item.slice(0, i).trim();
  127. const value = item.slice(i + 1).trim();
  128. result[key] = value;
  129. } else {
  130. const key = item.trim();
  131. if (!key) continue;
  132. result[key] = key;
  133. }
  134. }
  135. return result;
  136. };
  137. /**
  138. * @param {string | undefined} cacheControl Cache-Control header
  139. * @param {number} requestTime timestamp of request
  140. * @returns {{ storeCache: boolean, storeLock: boolean, validUntil: number }} Logic for storing in cache and lockfile cache
  141. */
  142. const parseCacheControl = (cacheControl, requestTime) => {
  143. // When false resource is not stored in cache
  144. let storeCache = true;
  145. // When false resource is not stored in lockfile cache
  146. let storeLock = true;
  147. // Resource is only revalidated, after that timestamp and when upgrade is chosen
  148. let validUntil = 0;
  149. if (cacheControl) {
  150. const parsed = parseKeyValuePairs(cacheControl);
  151. if (parsed["no-cache"]) storeCache = storeLock = false;
  152. if (parsed["max-age"] && !Number.isNaN(Number(parsed["max-age"]))) {
  153. validUntil = requestTime + Number(parsed["max-age"]) * 1000;
  154. }
  155. if (parsed["must-revalidate"]) validUntil = 0;
  156. }
  157. return {
  158. storeLock,
  159. storeCache,
  160. validUntil
  161. };
  162. };
  163. /**
  164. * @typedef {object} LockfileEntry
  165. * @property {string} resolved
  166. * @property {string} integrity
  167. * @property {string} contentType
  168. */
  169. /**
  170. * @param {LockfileEntry} a first lockfile entry
  171. * @param {LockfileEntry} b second lockfile entry
  172. * @returns {boolean} true when equal, otherwise false
  173. */
  174. const areLockfileEntriesEqual = (a, b) =>
  175. a.resolved === b.resolved &&
  176. a.integrity === b.integrity &&
  177. a.contentType === b.contentType;
  178. /**
  179. * @param {LockfileEntry} entry lockfile entry
  180. * @returns {`resolved: ${string}, integrity: ${string}, contentType: ${string}`} stringified entry
  181. */
  182. const entryToString = (entry) =>
  183. `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`;
  184. /**
  185. * Sanitize URL for inclusion in error messages
  186. * @param {string} href URL string to sanitize
  187. * @returns {string} sanitized URL text for logs/errors
  188. */
  189. const sanitizeUrlForError = (href) => {
  190. try {
  191. const u = new URL(href);
  192. return `${u.protocol}//${u.host}`;
  193. } catch (_err) {
  194. return String(href)
  195. .slice(0, 200)
  196. .replace(/[\r\n]/g, "");
  197. }
  198. };
  199. class Lockfile {
  200. constructor() {
  201. this.version = 1;
  202. /** @type {Map<string, LockfileEntry | "ignore" | "no-cache">} */
  203. this.entries = new Map();
  204. }
  205. /**
  206. * @param {string} content content of the lockfile
  207. * @returns {Lockfile} lockfile
  208. */
  209. static parse(content) {
  210. // TODO handle merge conflicts
  211. const data = JSON.parse(content);
  212. if (data.version !== 1) {
  213. throw new Error(`Unsupported lockfile version ${data.version}`);
  214. }
  215. const lockfile = new Lockfile();
  216. for (const key of Object.keys(data)) {
  217. if (key === "version") continue;
  218. const entry = data[key];
  219. lockfile.entries.set(
  220. key,
  221. typeof entry === "string"
  222. ? entry
  223. : {
  224. resolved: key,
  225. ...entry
  226. }
  227. );
  228. }
  229. return lockfile;
  230. }
  231. /**
  232. * @returns {string} stringified lockfile
  233. */
  234. toString() {
  235. let str = "{\n";
  236. const entries = [...this.entries].sort(([a], [b]) => (a < b ? -1 : 1));
  237. for (const [key, entry] of entries) {
  238. if (typeof entry === "string") {
  239. str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`;
  240. } else {
  241. str += ` ${JSON.stringify(key)}: { `;
  242. if (entry.resolved !== key) {
  243. str += `"resolved": ${JSON.stringify(entry.resolved)}, `;
  244. }
  245. str += `"integrity": ${JSON.stringify(
  246. entry.integrity
  247. )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`;
  248. }
  249. }
  250. str += ` "version": ${this.version}\n}\n`;
  251. return str;
  252. }
  253. }
  254. /**
  255. * @template R
  256. * @typedef {(err: Error | null, result?: R) => void} FnWithoutKeyCallback
  257. */
  258. /**
  259. * @template R
  260. * @typedef {(callback: FnWithoutKeyCallback<R>) => void} FnWithoutKey
  261. */
  262. /**
  263. * @template R
  264. * @param {FnWithoutKey<R>} fn function
  265. * @returns {FnWithoutKey<R>} cached function
  266. */
  267. const cachedWithoutKey = (fn) => {
  268. let inFlight = false;
  269. /** @type {Error | undefined} */
  270. let cachedError;
  271. /** @type {R | undefined} */
  272. let cachedResult;
  273. /** @type {FnWithoutKeyCallback<R>[] | undefined} */
  274. let cachedCallbacks;
  275. return (callback) => {
  276. if (inFlight) {
  277. if (cachedResult !== undefined) return callback(null, cachedResult);
  278. if (cachedError !== undefined) return callback(cachedError);
  279. if (cachedCallbacks === undefined) cachedCallbacks = [callback];
  280. else cachedCallbacks.push(callback);
  281. return;
  282. }
  283. inFlight = true;
  284. fn((err, result) => {
  285. if (err) cachedError = err;
  286. else cachedResult = result;
  287. const callbacks = cachedCallbacks;
  288. cachedCallbacks = undefined;
  289. callback(err, result);
  290. if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
  291. });
  292. };
  293. };
  294. /**
  295. * @template R
  296. * @typedef {(err: Error | null, result?: R) => void} FnWithKeyCallback
  297. */
  298. /**
  299. * @template T
  300. * @template R
  301. * @typedef {(item: T, callback: FnWithKeyCallback<R>) => void} FnWithKey
  302. */
  303. /**
  304. * @template T
  305. * @template R
  306. * @param {FnWithKey<T, R>} fn function
  307. * @param {FnWithKey<T, R>=} forceFn function for the second try
  308. * @returns {FnWithKey<T, R> & { force: FnWithKey<T, R> }} cached function
  309. */
  310. const cachedWithKey = (fn, forceFn = fn) => {
  311. /**
  312. * @template R
  313. * @typedef {{ result?: R, error?: Error, callbacks?: FnWithKeyCallback<R>[], force?: true }} CacheEntry
  314. */
  315. /** @type {Map<T, CacheEntry<R>>} */
  316. const cache = new Map();
  317. /**
  318. * @param {T} arg arg
  319. * @param {FnWithKeyCallback<R>} callback callback
  320. * @returns {void}
  321. */
  322. const resultFn = (arg, callback) => {
  323. const cacheEntry = cache.get(arg);
  324. if (cacheEntry !== undefined) {
  325. if (cacheEntry.result !== undefined) {
  326. return callback(null, cacheEntry.result);
  327. }
  328. if (cacheEntry.error !== undefined) return callback(cacheEntry.error);
  329. if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback];
  330. else cacheEntry.callbacks.push(callback);
  331. return;
  332. }
  333. /** @type {CacheEntry<R>} */
  334. const newCacheEntry = {
  335. result: undefined,
  336. error: undefined,
  337. callbacks: undefined
  338. };
  339. cache.set(arg, newCacheEntry);
  340. fn(arg, (err, result) => {
  341. if (err) newCacheEntry.error = err;
  342. else newCacheEntry.result = result;
  343. const callbacks = newCacheEntry.callbacks;
  344. newCacheEntry.callbacks = undefined;
  345. callback(err, result);
  346. if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
  347. });
  348. };
  349. /**
  350. * @param {T} arg arg
  351. * @param {FnWithKeyCallback<R>} callback callback
  352. * @returns {void}
  353. */
  354. resultFn.force = (arg, callback) => {
  355. const cacheEntry = cache.get(arg);
  356. if (cacheEntry !== undefined && cacheEntry.force) {
  357. if (cacheEntry.result !== undefined) {
  358. return callback(null, cacheEntry.result);
  359. }
  360. if (cacheEntry.error !== undefined) return callback(cacheEntry.error);
  361. if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback];
  362. else cacheEntry.callbacks.push(callback);
  363. return;
  364. }
  365. /** @type {CacheEntry<R>} */
  366. const newCacheEntry = {
  367. result: undefined,
  368. error: undefined,
  369. callbacks: undefined,
  370. force: true
  371. };
  372. cache.set(arg, newCacheEntry);
  373. forceFn(arg, (err, result) => {
  374. if (err) newCacheEntry.error = err;
  375. else newCacheEntry.result = result;
  376. const callbacks = newCacheEntry.callbacks;
  377. newCacheEntry.callbacks = undefined;
  378. callback(err, result);
  379. if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
  380. });
  381. };
  382. return resultFn;
  383. };
  384. /**
  385. * @typedef {object} LockfileCache
  386. * @property {Lockfile} lockfile lockfile
  387. * @property {Snapshot} snapshot snapshot
  388. */
  389. /**
  390. * @typedef {object} ResolveContentResult
  391. * @property {LockfileEntry} entry lockfile entry
  392. * @property {Buffer} content content
  393. * @property {boolean} storeLock need store lockfile
  394. */
  395. /** @typedef {{ storeCache: boolean, storeLock: boolean, validUntil: number, etag: string | undefined, fresh: boolean }} FetchResultMeta */
  396. /** @typedef {FetchResultMeta & { location: string }} RedirectFetchResult */
  397. /** @typedef {FetchResultMeta & { entry: LockfileEntry, content: Buffer }} ContentFetchResult */
  398. /** @typedef {RedirectFetchResult | ContentFetchResult} FetchResult */
  399. const PLUGIN_NAME = "HttpUriPlugin";
  400. class HttpUriPlugin {
  401. /**
  402. * @param {HttpUriPluginOptions} options options
  403. */
  404. constructor(options) {
  405. validate(options);
  406. this._lockfileLocation = options.lockfileLocation;
  407. this._cacheLocation = options.cacheLocation;
  408. this._upgrade = options.upgrade;
  409. this._frozen = options.frozen;
  410. this._allowedUris = options.allowedUris;
  411. this._proxy = options.proxy;
  412. }
  413. /**
  414. * Apply the plugin
  415. * @param {Compiler} compiler the compiler instance
  416. * @returns {void}
  417. */
  418. apply(compiler) {
  419. const proxy =
  420. this._proxy || process.env.http_proxy || process.env.HTTP_PROXY;
  421. const schemes = [
  422. {
  423. scheme: "http",
  424. fetch: proxyFetch(getHttp(), proxy)
  425. },
  426. {
  427. scheme: "https",
  428. fetch: proxyFetch(getHttps(), proxy)
  429. }
  430. ];
  431. /** @type {LockfileCache} */
  432. let lockfileCache;
  433. compiler.hooks.compilation.tap(
  434. PLUGIN_NAME,
  435. (compilation, { normalModuleFactory }) => {
  436. const intermediateFs =
  437. /** @type {IntermediateFileSystem} */
  438. (compiler.intermediateFileSystem);
  439. const fs = compilation.inputFileSystem;
  440. const cache = compilation.getCache(`webpack.${PLUGIN_NAME}`);
  441. const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`);
  442. /** @type {string} */
  443. const lockfileLocation =
  444. this._lockfileLocation ||
  445. join(
  446. intermediateFs,
  447. compiler.context,
  448. compiler.name
  449. ? `${toSafePath(compiler.name)}.webpack.lock`
  450. : "webpack.lock"
  451. );
  452. /** @type {string | false} */
  453. const cacheLocation =
  454. this._cacheLocation !== undefined
  455. ? this._cacheLocation
  456. : `${lockfileLocation}.data`;
  457. const upgrade = this._upgrade || false;
  458. const frozen = this._frozen || false;
  459. const hashFunction = "sha512";
  460. const hashDigest = "hex";
  461. const hashDigestLength = 20;
  462. const allowedUris = this._allowedUris;
  463. let warnedAboutEol = false;
  464. /** @type {Map<string, string>} */
  465. const cacheKeyCache = new Map();
  466. /**
  467. * @param {string} url the url
  468. * @returns {string} the key
  469. */
  470. const getCacheKey = (url) => {
  471. const cachedResult = cacheKeyCache.get(url);
  472. if (cachedResult !== undefined) return cachedResult;
  473. const result = _getCacheKey(url);
  474. cacheKeyCache.set(url, result);
  475. return result;
  476. };
  477. /**
  478. * @param {string} url the url
  479. * @returns {string} the key
  480. */
  481. const _getCacheKey = (url) => {
  482. const parsedUrl = new URL(url);
  483. const folder = toSafePath(parsedUrl.origin);
  484. const name = toSafePath(parsedUrl.pathname);
  485. const query = toSafePath(parsedUrl.search);
  486. let ext = extname(name);
  487. if (ext.length > 20) ext = "";
  488. const basename = ext ? name.slice(0, -ext.length) : name;
  489. const hash = createHash(hashFunction);
  490. hash.update(url);
  491. const digest = hash.digest(hashDigest).slice(0, hashDigestLength);
  492. return `${folder.slice(-50)}/${`${basename}${
  493. query ? `_${query}` : ""
  494. }`.slice(0, 150)}_${digest}${ext}`;
  495. };
  496. const getLockfile = cachedWithoutKey(
  497. /**
  498. * @param {(err: Error | null, lockfile?: Lockfile) => void} callback callback
  499. * @returns {void}
  500. */
  501. (callback) => {
  502. const readLockfile = () => {
  503. intermediateFs.readFile(lockfileLocation, (err, buffer) => {
  504. if (err && err.code !== "ENOENT") {
  505. compilation.missingDependencies.add(lockfileLocation);
  506. return callback(err);
  507. }
  508. compilation.fileDependencies.add(lockfileLocation);
  509. compilation.fileSystemInfo.createSnapshot(
  510. compiler.fsStartTime,
  511. buffer ? [lockfileLocation] : [],
  512. [],
  513. buffer ? [] : [lockfileLocation],
  514. { timestamp: true },
  515. (err, s) => {
  516. if (err) return callback(err);
  517. const lockfile = buffer
  518. ? Lockfile.parse(buffer.toString("utf8"))
  519. : new Lockfile();
  520. lockfileCache = {
  521. lockfile,
  522. snapshot: /** @type {Snapshot} */ (s)
  523. };
  524. callback(null, lockfile);
  525. }
  526. );
  527. });
  528. };
  529. if (lockfileCache) {
  530. compilation.fileSystemInfo.checkSnapshotValid(
  531. lockfileCache.snapshot,
  532. (err, valid) => {
  533. if (err) return callback(err);
  534. if (!valid) return readLockfile();
  535. callback(null, lockfileCache.lockfile);
  536. }
  537. );
  538. } else {
  539. readLockfile();
  540. }
  541. }
  542. );
  543. /** @typedef {Map<string, LockfileEntry | "ignore" | "no-cache">} LockfileUpdates */
  544. /** @type {LockfileUpdates | undefined} */
  545. let lockfileUpdates;
  546. /**
  547. * @param {Lockfile} lockfile lockfile instance
  548. * @param {string} url url to store
  549. * @param {LockfileEntry | "ignore" | "no-cache"} entry lockfile entry
  550. */
  551. const storeLockEntry = (lockfile, url, entry) => {
  552. const oldEntry = lockfile.entries.get(url);
  553. if (lockfileUpdates === undefined) lockfileUpdates = new Map();
  554. lockfileUpdates.set(url, entry);
  555. lockfile.entries.set(url, entry);
  556. if (!oldEntry) {
  557. logger.log(`${url} added to lockfile`);
  558. } else if (typeof oldEntry === "string") {
  559. if (typeof entry === "string") {
  560. logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`);
  561. } else {
  562. logger.log(
  563. `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}`
  564. );
  565. }
  566. } else if (typeof entry === "string") {
  567. logger.log(
  568. `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}`
  569. );
  570. } else if (oldEntry.resolved !== entry.resolved) {
  571. logger.log(
  572. `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}`
  573. );
  574. } else if (oldEntry.integrity !== entry.integrity) {
  575. logger.log(`${url} updated in lockfile: content changed`);
  576. } else if (oldEntry.contentType !== entry.contentType) {
  577. logger.log(
  578. `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}`
  579. );
  580. } else {
  581. logger.log(`${url} updated in lockfile`);
  582. }
  583. };
  584. /**
  585. * @param {Lockfile} lockfile lockfile
  586. * @param {string} url url
  587. * @param {ResolveContentResult} result result
  588. * @param {(err: Error | null, result?: ResolveContentResult) => void} callback callback
  589. * @returns {void}
  590. */
  591. const storeResult = (lockfile, url, result, callback) => {
  592. if (result.storeLock) {
  593. storeLockEntry(lockfile, url, result.entry);
  594. if (!cacheLocation || !result.content) {
  595. return callback(null, result);
  596. }
  597. const key = getCacheKey(result.entry.resolved);
  598. const filePath = join(intermediateFs, cacheLocation, key);
  599. mkdirp(intermediateFs, dirname(intermediateFs, filePath), (err) => {
  600. if (err) return callback(err);
  601. intermediateFs.writeFile(filePath, result.content, (err) => {
  602. if (err) return callback(err);
  603. callback(null, result);
  604. });
  605. });
  606. } else {
  607. storeLockEntry(lockfile, url, "no-cache");
  608. callback(null, result);
  609. }
  610. };
  611. for (const { scheme, fetch } of schemes) {
  612. /**
  613. * @param {string} location Location header value (relative or absolute)
  614. * @param {string} base current absolute URL
  615. * @returns {string} absolute, validated redirect target
  616. */
  617. const validateRedirectLocation = (location, base) => {
  618. let nextUrl;
  619. try {
  620. nextUrl = new URL(location, base);
  621. } catch (err) {
  622. throw new Error(
  623. `Invalid redirect URL: ${sanitizeUrlForError(location)}`,
  624. { cause: err }
  625. );
  626. }
  627. if (nextUrl.protocol !== "http:" && nextUrl.protocol !== "https:") {
  628. throw new Error(
  629. `Redirected URL uses disallowed protocol: ${sanitizeUrlForError(nextUrl.href)}`
  630. );
  631. }
  632. if (!isAllowed(nextUrl.href)) {
  633. throw new Error(
  634. `${nextUrl.href} doesn't match the allowedUris policy after redirect. These URIs are allowed:\n${allowedUris
  635. .map((uri) => ` - ${uri}`)
  636. .join("\n")}`
  637. );
  638. }
  639. return nextUrl.href;
  640. };
  641. /**
  642. * @param {string} url URL
  643. * @param {string | null} integrity integrity
  644. * @param {(err: Error | null, resolveContentResult?: ResolveContentResult) => void} callback callback
  645. * @param {number=} redirectCount number of followed redirects
  646. */
  647. const resolveContent = (
  648. url,
  649. integrity,
  650. callback,
  651. redirectCount = 0
  652. ) => {
  653. /**
  654. * @param {Error | null} err error
  655. * @param {FetchResult=} _result fetch result
  656. * @returns {void}
  657. */
  658. const handleResult = (err, _result) => {
  659. if (err) return callback(err);
  660. const result = /** @type {FetchResult} */ (_result);
  661. if ("location" in result) {
  662. // Validate redirect target before following
  663. let absolute;
  664. try {
  665. absolute = validateRedirectLocation(result.location, url);
  666. } catch (err_) {
  667. return callback(/** @type {Error} */ (err_));
  668. }
  669. if (redirectCount >= MAX_REDIRECTS) {
  670. return callback(new Error("Too many redirects"));
  671. }
  672. return resolveContent(
  673. absolute,
  674. integrity,
  675. (err, innerResult) => {
  676. if (err) return callback(err);
  677. const { entry, content, storeLock } =
  678. /** @type {ResolveContentResult} */ (innerResult);
  679. callback(null, {
  680. entry,
  681. content,
  682. storeLock: storeLock && result.storeLock
  683. });
  684. },
  685. redirectCount + 1
  686. );
  687. }
  688. if (
  689. !result.fresh &&
  690. integrity &&
  691. result.entry.integrity !== integrity &&
  692. !verifyIntegrity(result.content, integrity)
  693. ) {
  694. return fetchContent.force(url, handleResult);
  695. }
  696. return callback(null, {
  697. entry: result.entry,
  698. content: result.content,
  699. storeLock: result.storeLock
  700. });
  701. };
  702. fetchContent(url, handleResult);
  703. };
  704. /**
  705. * @param {string} url URL
  706. * @param {FetchResult | RedirectFetchResult | undefined} cachedResult result from cache
  707. * @param {(err: Error | null, fetchResult?: FetchResult) => void} callback callback
  708. * @returns {void}
  709. */
  710. const fetchContentRaw = (url, cachedResult, callback) => {
  711. const requestTime = Date.now();
  712. /** @type {OutgoingHttpHeaders} */
  713. const headers = {
  714. "accept-encoding": "gzip, deflate, br",
  715. "user-agent": "webpack"
  716. };
  717. if (cachedResult && cachedResult.etag) {
  718. headers["if-none-match"] = cachedResult.etag;
  719. }
  720. fetch(new URL(url), { headers }, (res) => {
  721. const etag = res.headers.etag;
  722. const location = res.headers.location;
  723. const cacheControl = res.headers["cache-control"];
  724. const { storeLock, storeCache, validUntil } = parseCacheControl(
  725. cacheControl,
  726. requestTime
  727. );
  728. /**
  729. * @param {Partial<Pick<FetchResultMeta, "fresh">> & (Pick<RedirectFetchResult, "location"> | Pick<ContentFetchResult, "content" | "entry">)} partialResult result
  730. * @returns {void}
  731. */
  732. const finishWith = (partialResult) => {
  733. if ("location" in partialResult) {
  734. logger.debug(
  735. `GET ${url} [${res.statusCode}] -> ${partialResult.location}`
  736. );
  737. } else {
  738. logger.debug(
  739. `GET ${url} [${res.statusCode}] ${Math.ceil(
  740. partialResult.content.length / 1024
  741. )} kB${!storeLock ? " no-cache" : ""}`
  742. );
  743. }
  744. const result = {
  745. ...partialResult,
  746. fresh: true,
  747. storeLock,
  748. storeCache,
  749. validUntil,
  750. etag
  751. };
  752. if (!storeCache) {
  753. logger.log(
  754. `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}`
  755. );
  756. return callback(null, result);
  757. }
  758. cache.store(
  759. url,
  760. null,
  761. {
  762. ...result,
  763. fresh: false
  764. },
  765. (err) => {
  766. if (err) {
  767. logger.warn(
  768. `${url} can't be stored in cache: ${err.message}`
  769. );
  770. logger.debug(err.stack);
  771. }
  772. callback(null, result);
  773. }
  774. );
  775. };
  776. if (res.statusCode === 304) {
  777. const result = /** @type {FetchResult} */ (cachedResult);
  778. if (
  779. result.validUntil < validUntil ||
  780. result.storeLock !== storeLock ||
  781. result.storeCache !== storeCache ||
  782. result.etag !== etag
  783. ) {
  784. return finishWith(result);
  785. }
  786. logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`);
  787. return callback(null, { ...result, fresh: true });
  788. }
  789. if (
  790. location &&
  791. res.statusCode &&
  792. res.statusCode >= 301 &&
  793. res.statusCode <= 308
  794. ) {
  795. let absolute;
  796. try {
  797. absolute = validateRedirectLocation(location, url);
  798. } catch (err) {
  799. logger.log(
  800. `GET ${url} [${res.statusCode}] -> ${String(location)} (rejected: ${/** @type {Error} */ (err).message})`
  801. );
  802. return callback(/** @type {Error} */ (err));
  803. }
  804. const result = { location: absolute };
  805. if (
  806. !cachedResult ||
  807. !("location" in cachedResult) ||
  808. cachedResult.location !== result.location ||
  809. cachedResult.validUntil < validUntil ||
  810. cachedResult.storeLock !== storeLock ||
  811. cachedResult.storeCache !== storeCache ||
  812. cachedResult.etag !== etag
  813. ) {
  814. return finishWith(result);
  815. }
  816. logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`);
  817. return callback(null, {
  818. ...result,
  819. fresh: true,
  820. storeLock,
  821. storeCache,
  822. validUntil,
  823. etag
  824. });
  825. }
  826. const contentType = res.headers["content-type"] || "";
  827. /** @type {Buffer[]} */
  828. const bufferArr = [];
  829. const contentEncoding = res.headers["content-encoding"];
  830. /** @type {Readable} */
  831. let stream = res;
  832. if (contentEncoding === "gzip") {
  833. stream = stream.pipe(createGunzip());
  834. } else if (contentEncoding === "br") {
  835. stream = stream.pipe(createBrotliDecompress());
  836. } else if (contentEncoding === "deflate") {
  837. stream = stream.pipe(createInflate());
  838. }
  839. stream.on("data", (chunk) => {
  840. bufferArr.push(chunk);
  841. });
  842. stream.on("end", () => {
  843. if (!res.complete) {
  844. logger.log(`GET ${url} [${res.statusCode}] (terminated)`);
  845. return callback(new Error(`${url} request was terminated`));
  846. }
  847. const content = Buffer.concat(bufferArr);
  848. if (res.statusCode !== 200) {
  849. logger.log(`GET ${url} [${res.statusCode}]`);
  850. return callback(
  851. new Error(
  852. `${url} request status code = ${
  853. res.statusCode
  854. }\n${content.toString("utf8")}`
  855. )
  856. );
  857. }
  858. const integrity = computeIntegrity(content);
  859. const entry = { resolved: url, integrity, contentType };
  860. finishWith({
  861. entry,
  862. content
  863. });
  864. });
  865. }).on("error", (err) => {
  866. logger.log(`GET ${url} (error)`);
  867. err.message += `\nwhile fetching ${url}`;
  868. callback(err);
  869. });
  870. };
  871. const fetchContent = cachedWithKey(
  872. /**
  873. * @param {string} url URL
  874. * @param {(err: Error | null, result?: FetchResult) => void} callback callback
  875. * @returns {void}
  876. */
  877. (url, callback) => {
  878. cache.get(url, null, (err, cachedResult) => {
  879. if (err) return callback(err);
  880. if (cachedResult) {
  881. const isValid = cachedResult.validUntil >= Date.now();
  882. if (isValid) return callback(null, cachedResult);
  883. }
  884. fetchContentRaw(url, cachedResult, callback);
  885. });
  886. },
  887. (url, callback) => fetchContentRaw(url, undefined, callback)
  888. );
  889. /**
  890. * @param {string} uri uri
  891. * @returns {boolean} true when allowed, otherwise false
  892. */
  893. const isAllowed = (uri) => {
  894. let parsedUri;
  895. try {
  896. // Parse the URI to prevent userinfo bypass attacks
  897. // (e.g., http://allowed@malicious/path where @malicious is the actual host)
  898. parsedUri = new URL(uri);
  899. } catch (_err) {
  900. return false;
  901. }
  902. for (const allowed of allowedUris) {
  903. if (typeof allowed === "string") {
  904. let parsedAllowed;
  905. try {
  906. parsedAllowed = new URL(allowed);
  907. } catch (_err) {
  908. continue;
  909. }
  910. if (parsedUri.href.startsWith(parsedAllowed.href)) {
  911. return true;
  912. }
  913. } else if (typeof allowed === "function") {
  914. if (allowed(parsedUri.href)) return true;
  915. } else if (allowed.test(parsedUri.href)) {
  916. return true;
  917. }
  918. }
  919. return false;
  920. };
  921. /** @typedef {{ entry: LockfileEntry, content: Buffer }} Info */
  922. const getInfo = cachedWithKey(
  923. /**
  924. * @param {string} url the url
  925. * @param {(err: Error | null, info?: Info) => void} callback callback
  926. * @returns {void}
  927. */
  928. // eslint-disable-next-line no-loop-func
  929. (url, callback) => {
  930. if (!isAllowed(url)) {
  931. return callback(
  932. new Error(
  933. `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris
  934. .map((uri) => ` - ${uri}`)
  935. .join("\n")}`
  936. )
  937. );
  938. }
  939. getLockfile((err, _lockfile) => {
  940. if (err) return callback(err);
  941. const lockfile = /** @type {Lockfile} */ (_lockfile);
  942. const entryOrString = lockfile.entries.get(url);
  943. if (!entryOrString) {
  944. if (frozen) {
  945. return callback(
  946. new Error(
  947. `${url} has no lockfile entry and lockfile is frozen`
  948. )
  949. );
  950. }
  951. resolveContent(url, null, (err, result) => {
  952. if (err) return callback(err);
  953. storeResult(
  954. /** @type {Lockfile} */
  955. (lockfile),
  956. url,
  957. /** @type {ResolveContentResult} */
  958. (result),
  959. callback
  960. );
  961. });
  962. return;
  963. }
  964. if (typeof entryOrString === "string") {
  965. const entryTag = entryOrString;
  966. resolveContent(url, null, (err, _result) => {
  967. if (err) return callback(err);
  968. const result =
  969. /** @type {ResolveContentResult} */
  970. (_result);
  971. if (!result.storeLock || entryTag === "ignore") {
  972. return callback(null, result);
  973. }
  974. if (frozen) {
  975. return callback(
  976. new Error(
  977. `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen`
  978. )
  979. );
  980. }
  981. if (!upgrade) {
  982. return callback(
  983. new Error(
  984. `${url} used to have ${entryTag} lockfile entry and has content now.
  985. This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled.
  986. Remove this line from the lockfile to force upgrading.`
  987. )
  988. );
  989. }
  990. storeResult(lockfile, url, result, callback);
  991. });
  992. return;
  993. }
  994. let entry = entryOrString;
  995. /**
  996. * @param {Buffer=} lockedContent locked content
  997. */
  998. const doFetch = (lockedContent) => {
  999. resolveContent(url, entry.integrity, (err, _result) => {
  1000. if (err) {
  1001. if (lockedContent) {
  1002. logger.warn(
  1003. `Upgrade request to ${url} failed: ${err.message}`
  1004. );
  1005. logger.debug(err.stack);
  1006. return callback(null, {
  1007. entry,
  1008. content: lockedContent
  1009. });
  1010. }
  1011. return callback(err);
  1012. }
  1013. const result =
  1014. /** @type {ResolveContentResult} */
  1015. (_result);
  1016. if (!result.storeLock) {
  1017. // When the lockfile entry should be no-cache
  1018. // we need to update the lockfile
  1019. if (frozen) {
  1020. return callback(
  1021. new Error(
  1022. `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString(
  1023. entry
  1024. )}`
  1025. )
  1026. );
  1027. }
  1028. storeResult(lockfile, url, result, callback);
  1029. return;
  1030. }
  1031. if (!areLockfileEntriesEqual(result.entry, entry)) {
  1032. // When the lockfile entry is outdated
  1033. // we need to update the lockfile
  1034. if (frozen) {
  1035. return callback(
  1036. new Error(
  1037. `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString(
  1038. entry
  1039. )}\nExpected: ${entryToString(result.entry)}`
  1040. )
  1041. );
  1042. }
  1043. storeResult(lockfile, url, result, callback);
  1044. return;
  1045. }
  1046. if (!lockedContent && cacheLocation) {
  1047. // When the lockfile cache content is missing
  1048. // we need to update the lockfile
  1049. if (frozen) {
  1050. return callback(
  1051. new Error(
  1052. `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString(
  1053. entry
  1054. )}`
  1055. )
  1056. );
  1057. }
  1058. storeResult(lockfile, url, result, callback);
  1059. return;
  1060. }
  1061. return callback(null, result);
  1062. });
  1063. };
  1064. if (cacheLocation) {
  1065. // When there is a lockfile cache
  1066. // we read the content from there
  1067. const key = getCacheKey(entry.resolved);
  1068. const filePath = join(intermediateFs, cacheLocation, key);
  1069. fs.readFile(filePath, (err, result) => {
  1070. if (err) {
  1071. if (err.code === "ENOENT") return doFetch();
  1072. return callback(err);
  1073. }
  1074. const content = /** @type {Buffer} */ (result);
  1075. /**
  1076. * @param {Buffer | undefined} _result result
  1077. * @returns {void}
  1078. */
  1079. const continueWithCachedContent = (_result) => {
  1080. if (!upgrade) {
  1081. // When not in upgrade mode, we accept the result from the lockfile cache
  1082. return callback(null, { entry, content });
  1083. }
  1084. return doFetch(content);
  1085. };
  1086. if (!verifyIntegrity(content, entry.integrity)) {
  1087. /** @type {Buffer | undefined} */
  1088. let contentWithChangedEol;
  1089. let isEolChanged = false;
  1090. try {
  1091. contentWithChangedEol = Buffer.from(
  1092. content.toString("utf8").replace(/\r\n/g, "\n")
  1093. );
  1094. isEolChanged = verifyIntegrity(
  1095. contentWithChangedEol,
  1096. entry.integrity
  1097. );
  1098. } catch (_err) {
  1099. // ignore
  1100. }
  1101. if (isEolChanged) {
  1102. if (!warnedAboutEol) {
  1103. const explainer = `Incorrect end of line sequence was detected in the lockfile cache.
  1104. The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache.
  1105. When using git make sure to configure .gitattributes correctly for the lockfile cache:
  1106. **/*webpack.lock.data/** -text
  1107. This will avoid that the end of line sequence is changed by git on Windows.`;
  1108. if (frozen) {
  1109. logger.error(explainer);
  1110. } else {
  1111. logger.warn(explainer);
  1112. logger.info(
  1113. "Lockfile cache will be automatically fixed now, but when lockfile is frozen this would result in an error."
  1114. );
  1115. }
  1116. warnedAboutEol = true;
  1117. }
  1118. if (!frozen) {
  1119. // "fix" the end of line sequence of the lockfile content
  1120. logger.log(
  1121. `${filePath} fixed end of line sequence (\\r\\n instead of \\n).`
  1122. );
  1123. intermediateFs.writeFile(
  1124. filePath,
  1125. /** @type {Buffer} */
  1126. (contentWithChangedEol),
  1127. (err) => {
  1128. if (err) return callback(err);
  1129. continueWithCachedContent(
  1130. /** @type {Buffer} */
  1131. (contentWithChangedEol)
  1132. );
  1133. }
  1134. );
  1135. return;
  1136. }
  1137. }
  1138. if (frozen) {
  1139. return callback(
  1140. new Error(
  1141. `${
  1142. entry.resolved
  1143. } integrity mismatch, expected content with integrity ${
  1144. entry.integrity
  1145. } but got ${computeIntegrity(content)}.
  1146. Lockfile corrupted (${
  1147. isEolChanged
  1148. ? "end of line sequence was unexpectedly changed"
  1149. : "incorrectly merged? changed by other tools?"
  1150. }).
  1151. Run build with un-frozen lockfile to automatically fix lockfile.`
  1152. )
  1153. );
  1154. }
  1155. // "fix" the lockfile entry to the correct integrity
  1156. // the content has priority over the integrity value
  1157. entry = {
  1158. ...entry,
  1159. integrity: computeIntegrity(content)
  1160. };
  1161. storeLockEntry(lockfile, url, entry);
  1162. }
  1163. continueWithCachedContent(result);
  1164. });
  1165. } else {
  1166. doFetch();
  1167. }
  1168. });
  1169. }
  1170. );
  1171. /**
  1172. * @param {URL} url url
  1173. * @param {ResourceDataWithData} resourceData resource data
  1174. * @param {(err: Error | null, result: true | void) => void} callback callback
  1175. */
  1176. const respondWithUrlModule = (url, resourceData, callback) => {
  1177. getInfo(url.href, (err, _result) => {
  1178. if (err) return callback(err);
  1179. const result = /** @type {Info} */ (_result);
  1180. resourceData.resource = url.href;
  1181. resourceData.path = url.origin + url.pathname;
  1182. resourceData.query = url.search;
  1183. resourceData.fragment = url.hash;
  1184. resourceData.context = new URL(
  1185. ".",
  1186. result.entry.resolved
  1187. ).href.slice(0, -1);
  1188. resourceData.data.mimetype = result.entry.contentType;
  1189. callback(null, true);
  1190. });
  1191. };
  1192. normalModuleFactory.hooks.resolveForScheme
  1193. .for(scheme)
  1194. .tapAsync(PLUGIN_NAME, (resourceData, resolveData, callback) => {
  1195. respondWithUrlModule(
  1196. new URL(resourceData.resource),
  1197. resourceData,
  1198. callback
  1199. );
  1200. });
  1201. normalModuleFactory.hooks.resolveInScheme
  1202. .for(scheme)
  1203. .tapAsync(PLUGIN_NAME, (resourceData, data, callback) => {
  1204. // Only handle relative urls (./xxx, ../xxx, /xxx, //xxx)
  1205. if (
  1206. data.dependencyType !== "url" &&
  1207. !/^\.{0,2}\//.test(resourceData.resource)
  1208. ) {
  1209. return callback();
  1210. }
  1211. respondWithUrlModule(
  1212. new URL(resourceData.resource, `${data.context}/`),
  1213. resourceData,
  1214. callback
  1215. );
  1216. });
  1217. const hooks = NormalModule.getCompilationHooks(compilation);
  1218. hooks.readResourceForScheme
  1219. .for(scheme)
  1220. .tapAsync(PLUGIN_NAME, (resource, module, callback) =>
  1221. getInfo(resource, (err, _result) => {
  1222. if (err) return callback(err);
  1223. const result = /** @type {Info} */ (_result);
  1224. if (module) {
  1225. /** @type {BuildInfo} */
  1226. (module.buildInfo).resourceIntegrity = result.entry.integrity;
  1227. }
  1228. callback(null, result.content);
  1229. })
  1230. );
  1231. hooks.needBuild.tapAsync(PLUGIN_NAME, (module, context, callback) => {
  1232. if (module.resource && module.resource.startsWith(`${scheme}://`)) {
  1233. getInfo(module.resource, (err, _result) => {
  1234. if (err) return callback(err);
  1235. const result = /** @type {Info} */ (_result);
  1236. if (
  1237. result.entry.integrity !==
  1238. /** @type {BuildInfo} */
  1239. (module.buildInfo).resourceIntegrity
  1240. ) {
  1241. return callback(null, true);
  1242. }
  1243. callback();
  1244. });
  1245. } else {
  1246. return callback();
  1247. }
  1248. });
  1249. }
  1250. compilation.hooks.finishModules.tapAsync(
  1251. PLUGIN_NAME,
  1252. (modules, callback) => {
  1253. if (!lockfileUpdates) return callback();
  1254. const ext = extname(lockfileLocation);
  1255. const tempFile = join(
  1256. intermediateFs,
  1257. dirname(intermediateFs, lockfileLocation),
  1258. `.${basename(lockfileLocation, ext)}.${
  1259. (Math.random() * 10000) | 0
  1260. }${ext}`
  1261. );
  1262. const writeDone = () => {
  1263. const nextOperation =
  1264. /** @type {InProgressWriteItem[]} */
  1265. (inProgressWrite).shift();
  1266. if (nextOperation) {
  1267. nextOperation();
  1268. } else {
  1269. inProgressWrite = undefined;
  1270. }
  1271. };
  1272. const runWrite = () => {
  1273. intermediateFs.readFile(lockfileLocation, (err, buffer) => {
  1274. if (err && err.code !== "ENOENT") {
  1275. writeDone();
  1276. return callback(err);
  1277. }
  1278. const lockfile = buffer
  1279. ? Lockfile.parse(buffer.toString("utf8"))
  1280. : new Lockfile();
  1281. for (const [key, value] of /** @type {LockfileUpdates} */ (
  1282. lockfileUpdates
  1283. )) {
  1284. lockfile.entries.set(key, value);
  1285. }
  1286. intermediateFs.writeFile(
  1287. tempFile,
  1288. lockfile.toString(),
  1289. (err) => {
  1290. if (err) {
  1291. writeDone();
  1292. return (
  1293. /** @type {NonNullable<IntermediateFileSystem["unlink"]>} */
  1294. (intermediateFs.unlink)(tempFile, () => callback(err))
  1295. );
  1296. }
  1297. intermediateFs.rename(tempFile, lockfileLocation, (err) => {
  1298. if (err) {
  1299. writeDone();
  1300. return (
  1301. /** @type {NonNullable<IntermediateFileSystem["unlink"]>} */
  1302. (intermediateFs.unlink)(tempFile, () => callback(err))
  1303. );
  1304. }
  1305. writeDone();
  1306. callback();
  1307. });
  1308. }
  1309. );
  1310. });
  1311. };
  1312. if (inProgressWrite) {
  1313. inProgressWrite.push(runWrite);
  1314. } else {
  1315. inProgressWrite = [];
  1316. runWrite();
  1317. }
  1318. }
  1319. );
  1320. }
  1321. );
  1322. }
  1323. }
  1324. module.exports = HttpUriPlugin;