Skip to content

Commit

Permalink
Add support for network proxy (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
ota-meshi authored Jul 4, 2022
1 parent cbd34e2 commit 0d7b1c8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
48 changes: 47 additions & 1 deletion lib/utils/package-json/worker.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,57 @@
import type packageJson from "package-json"
import type { Options } from "package-json"
import { runAsWorker } from "synckit"
// @ts-expect-error -- no types
import tunnel from "tunnel-agent"
type PackageJson = typeof packageJson

const dynamicImport = new Function("m", "return import(m)")
runAsWorker(async (packageName: string, options: Options) => {
const m = await dynamicImport("package-json")
const packageJson: PackageJson = m?.default || m
return packageJson(packageName, options)
return packageJson(packageName, withAutoProxy(options))
})

/**
* If users are using a proxy for their npm preferences, set the option to use that proxy.
*/
function withAutoProxy(options: Options): Options {
const PROXY_ENV = [
"https_proxy",
"HTTPS_PROXY",
"http_proxy",
"HTTP_PROXY",
"npm_config_https_proxy",
"npm_config_http_proxy",
]

const proxyStr: string | undefined =
// eslint-disable-next-line no-process-env -- ignore
PROXY_ENV.map((k) => process.env[k]).find((v) => v)
if (proxyStr) {
const proxyUrl = new URL(proxyStr)
const tunnelOption = {
proxy: {
host: proxyUrl.hostname,
port: Number(proxyUrl.port),
proxyAuth:
proxyUrl.username || proxyUrl.password
? `${proxyUrl.username}:${proxyUrl.password}`
: undefined,
},
}
const httpAgent =
tunnel[`httpOverHttp${proxyUrl.protocol === "https:" ? "s" : ""}`](
tunnelOption,
)
const httpsAgent =
tunnel[`httpsOverHttp${proxyUrl.protocol === "https:" ? "s" : ""}`](
tunnelOption,
)
return {
agent: { http: httpAgent, https: httpsAgent },
...options,
}
}
return options
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"npm-package-arg": "^9.0.0",
"package-json": "^8.1.0",
"semver": "^7.3.5",
"synckit": "^0.7.1"
"synckit": "^0.7.1",
"tunnel-agent": "^0.6.0"
}
}

0 comments on commit 0d7b1c8

Please sign in to comment.