55
66"use strict" ;
77
8+ const EventEmitter = require ( "events" ) ;
89const { extname, basename } = require ( "path" ) ;
910const { URL } = require ( "url" ) ;
1011const { createGunzip, createBrotliDecompress, createInflate } = require ( "zlib" ) ;
@@ -19,6 +20,44 @@ const memoize = require("../util/memoize");
1920
2021const getHttp = memoize ( ( ) => require ( "http" ) ) ;
2122const getHttps = memoize ( ( ) => require ( "https" ) ) ;
23+ const proxyFetch = ( request , proxy ) => ( url , options , callback ) => {
24+ const eventEmitter = new EventEmitter ( ) ;
25+ const doRequest = socket =>
26+ request
27+ . get ( url , { ...options , ...( socket && { socket } ) } , callback )
28+ . on ( "error" , eventEmitter . emit . bind ( eventEmitter , "error" ) ) ;
29+
30+ if ( proxy ) {
31+ const { hostname : host , port } = new URL ( proxy ) ;
32+
33+ getHttp ( )
34+ . request ( {
35+ host, // IP address of proxy server
36+ port, // port of proxy server
37+ method : "CONNECT" ,
38+ path : url . host
39+ } )
40+ . on ( "connect" , ( res , socket ) => {
41+ if ( res . statusCode === 200 ) {
42+ // connected to proxy server
43+ doRequest ( socket ) ;
44+ }
45+ } )
46+ . on ( "error" , err => {
47+ eventEmitter . emit (
48+ "error" ,
49+ new Error (
50+ `Failed to connect to proxy server "${ proxy } ": ${ err . message } `
51+ )
52+ ) ;
53+ } )
54+ . end ( ) ;
55+ } else {
56+ doRequest ( ) ;
57+ }
58+
59+ return eventEmitter ;
60+ } ;
2261
2362/** @type {(() => void)[] | undefined } */
2463let inProgressWrite = undefined ;
@@ -274,6 +313,7 @@ class HttpUriPlugin {
274313 this . _upgrade = options . upgrade ;
275314 this . _frozen = options . frozen ;
276315 this . _allowedUris = options . allowedUris ;
316+ this . _proxy = options . proxy ;
277317 }
278318
279319 /**
@@ -282,15 +322,16 @@ class HttpUriPlugin {
282322 * @returns {void }
283323 */
284324 apply ( compiler ) {
325+ const proxy =
326+ this . _proxy || process . env [ "http_proxy" ] || process . env [ "HTTP_PROXY" ] ;
285327 const schemes = [
286328 {
287329 scheme : "http" ,
288- fetch : ( url , options , callback ) => getHttp ( ) . get ( url , options , callback )
330+ fetch : proxyFetch ( getHttp ( ) , proxy )
289331 } ,
290332 {
291333 scheme : "https" ,
292- fetch : ( url , options , callback ) =>
293- getHttps ( ) . get ( url , options , callback )
334+ fetch : proxyFetch ( getHttps ( ) , proxy )
294335 }
295336 ] ;
296337 let lockfileCache ;
0 commit comments