HttpUriPlugin.js 39 KB

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