diff --git a/lib/pac/resolver.js b/lib/pac/resolver.js index 45a221d..19b948c 100644 --- a/lib/pac/resolver.js +++ b/lib/pac/resolver.js @@ -6,33 +6,57 @@ const url = require('url') const request = require('request') const pac = require('pac-resolver') const local = require('./local-address') +const fs = require('fs'); const defaults = { url: undefined, auth: undefined } -module.exports = (options) => { +const FILE_PROTOCOL = 'file://'; + +function retrievePacFile(url) { + return new Promise((resolve, reject) => { + debug('retrieving proxy.pac at %j', url) + + if (!url.startsWith(FILE_PROTOCOL)) { + request( + { + url: url, + proxy: false + }, + (err, res, body) => { + if (err) { + return reject(err); + } else if (Math.floor(res.statusCode / 100) !== 2) { + return reject(new Error(res.statusMessage)) + } + + debug('proxy.pac retrieved') + return resolve(body) + } + ); + } else { + fs.readFile(url.substr(FILE_PROTOCOL.length), (err, contents) => { + if (err) { + return reject(err) + } else { + return resolve(contents) + } + }) + } + }) +} + +module.exports = async (options) => { options = _.defaults(options, defaults) if (typeof options.url === 'undefined') { throw new Error('missing url parameter') } - - return new Promise((resolve, reject) => { - debug('retrieving proxy.pac at %j', options.url) - request({ - url: options.url, - proxy: false - }, (err, res, body) => { - if (err) { - return reject(err) - } else if (Math.floor(res.statusCode / 100) !== 2) { - return reject(new Error(res.statusMessage)) - } - debug('proxy.pac retrieved') + const body = await retrievePacFile(options.url) try { const resolver = pac(body, { @@ -42,8 +66,7 @@ module.exports = (options) => { }) debug('returning resolver for proxy.pac at %j', options.url) - return resolve((uri) => { - return new Promise(async (resolve, reject) => { + return async (uri) => { debug('resolving proxy for %j', uri) try { if (await local.check(url.parse(uri).hostname)) { @@ -57,23 +80,20 @@ module.exports = (options) => { } else { uri = url.parse(uri) } - return resolve({ + return { connection: verb, host: uri.hostname, port: (uri.port ? uri.port : (uri.protocol === 'https:' ? 443 : 80)), auth: (proxy ? options.auth : undefined) - }) + } } catch (err) { debug('error resolving %j: %O', uri, err) - return reject(err) + throw err } - }) - }) - } catch (err) { + } + } catch (err) { debug('error creating resolver for proxy.pac at %j', options.url) - return reject(err) - } - }) - }) + throw err + } }