diff --git a/README.md b/README.md index 8d3e5feb..7e4df7a5 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,26 @@ jobs: # ... ``` +## Authentication method + +The `method` parameter can have these value : +- **token**: (by default) you must provide a token parameter +```yaml +... +with: + url: https://vault.mycompany.com:8200 + token: ${{ secrets.VaultToken }} +``` +- **approle**: you must provide a roleId & secretId parameter +```yaml +... +with: + url: https://vault.mycompany.com:8200 + method: approle + roleId: ${{ secrets.roleId }} + secretId : ${{ secrets.secretId }} +``` + ## Key Syntax The `secrets` parameter is a set of multiple secret requests separated by the `;` character. @@ -84,6 +104,7 @@ steps: uses: RichiCoder1/vault-action with: url: https://vault-enterprise.mycompany.com:8200 + method: token token: ${{ secrets.VaultToken }} namespace: ns1 secrets: | diff --git a/action.js b/action.js index 5b136cff..68104ced 100644 --- a/action.js +++ b/action.js @@ -2,23 +2,58 @@ const core = require('@actions/core'); const command = require('@actions/core/lib/command'); const got = require('got'); +const AUTH_METHODS = ['approle', 'token']; async function exportSecrets() { const vaultUrl = core.getInput('url', { required: true }); - const vaultToken = core.getInput('token', { required: true }); const vaultNamespace = core.getInput('namespace', { required: false }); const secretsInput = core.getInput('secrets', { required: true }); const secrets = parseSecretsInput(secretsInput); + const vaultMethod = core.getInput('method', { required: false }) || 'token'; + if (!AUTH_METHODS.includes(vaultMethod)) { + throw Error(`Sorry, the authentication method ${vaultMethod} is not currently supported.`); + } + + let vaultToken = null; + switch (vaultMethod) { + case 'approle': + const vaultRoleId = core.getInput('roleId', { required: true }); + const vaultSecretId = core.getInput('secretId', { required: true }); + core.debug('Try to retrieve Vault Token from approle'); + var options = { + headers: {}, + json: { role_id: vaultRoleId, secret_id: vaultSecretId }, + responseType: 'json' + }; + + if (vaultNamespace != null) { + options.headers["X-Vault-Namespace"] = vaultNamespace; + } + + const result = await got.post(`${vaultUrl}/v1/auth/approle/login`, options); + if (result && result.body && result.body.auth && result.body.auth.client_token) { + vaultToken = result.body.auth.client_token; + core.debug('✔ Vault Token has retrieved from approle'); + } else { + throw Error(`No token was retrieved with the role_id and secret_id provided.`); + } + break; + default: + vaultToken = core.getInput('token', { required: true }); + break; + } + for (const secret of secrets) { const { secretPath, outputName, secretKey } = secret; const requestOptions = { headers: { 'X-Vault-Token': vaultToken - }}; + }, + }; - if (vaultNamespace != null){ - requestOptions.headers["X-Vault-Namespace"] = vaultNamespace + if (vaultNamespace != null) { + requestOptions.headers["X-Vault-Namespace"] = vaultNamespace; } const result = await got(`${vaultUrl}/v1/secret/data/${secretPath}`, requestOptions); @@ -35,7 +70,7 @@ async function exportSecrets() { /** * Parses a secrets input string into key paths and their resulting environment variable name. - * @param {string} secretsInput + * @param {string} secretsInput */ function parseSecretsInput(secretsInput) { const secrets = secretsInput @@ -86,7 +121,7 @@ function parseSecretsInput(secretsInput) { } /** - * Replaces any forward-slash characters to + * Replaces any forward-slash characters to * @param {string} dataKey */ function normalizeOutputKey(dataKey) { diff --git a/dist/index.js b/dist/index.js index 9ad7e228..74c01d65 100644 --- a/dist/index.js +++ b/dist/index.js @@ -36,6 +36,8 @@ module.exports = /******/ // Load entry module and return exports /******/ return __webpack_require__(104); /******/ }; +/******/ // initialize runtime +/******/ runtime(__webpack_require__); /******/ /******/ // run startup /******/ return startup(); @@ -241,174 +243,6 @@ module.exports.array = (stream, options) => getStream(stream, {...options, array module.exports.MaxBufferError = MaxBufferError; -/***/ }), - -/***/ 18: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const net = __webpack_require__(631); - -class TimeoutError extends Error { - constructor(threshold, event) { - super(`Timeout awaiting '${event}' for ${threshold}ms`); - this.name = 'TimeoutError'; - this.code = 'ETIMEDOUT'; - this.event = event; - } -} - -const reentry = Symbol('reentry'); - -const noop = () => {}; - -module.exports = (request, delays, options) => { - /* istanbul ignore next: this makes sure timed-out isn't called twice */ - if (request[reentry]) { - return; - } - - request[reentry] = true; - - let stopNewTimeouts = false; - - const addTimeout = (delay, callback, ...args) => { - // An error had been thrown before. Going further would result in uncaught errors. - // See https://github.com/sindresorhus/got/issues/631#issuecomment-435675051 - if (stopNewTimeouts) { - return noop; - } - - // Event loop order is timers, poll, immediates. - // The timed event may emit during the current tick poll phase, so - // defer calling the handler until the poll phase completes. - let immediate; - const timeout = setTimeout(() => { - immediate = setImmediate(callback, delay, ...args); - /* istanbul ignore next: added in node v9.7.0 */ - if (immediate.unref) { - immediate.unref(); - } - }, delay); - - /* istanbul ignore next: in order to support electron renderer */ - if (timeout.unref) { - timeout.unref(); - } - - const cancel = () => { - clearTimeout(timeout); - clearImmediate(immediate); - }; - - cancelers.push(cancel); - - return cancel; - }; - - const {host, hostname} = options; - const timeoutHandler = (delay, event) => { - request.emit('error', new TimeoutError(delay, event)); - request.once('error', () => {}); // Ignore the `socket hung up` error made by request.abort() - - request.abort(); - }; - - const cancelers = []; - const cancelTimeouts = () => { - stopNewTimeouts = true; - cancelers.forEach(cancelTimeout => cancelTimeout()); - }; - - request.once('error', cancelTimeouts); - request.once('response', response => { - response.once('end', cancelTimeouts); - }); - - if (delays.request !== undefined) { - addTimeout(delays.request, timeoutHandler, 'request'); - } - - if (delays.socket !== undefined) { - const socketTimeoutHandler = () => { - timeoutHandler(delays.socket, 'socket'); - }; - - request.setTimeout(delays.socket, socketTimeoutHandler); - - // `request.setTimeout(0)` causes a memory leak. - // We can just remove the listener and forget about the timer - it's unreffed. - // See https://github.com/sindresorhus/got/issues/690 - cancelers.push(() => request.removeListener('timeout', socketTimeoutHandler)); - } - - if (delays.lookup !== undefined && !request.socketPath && !net.isIP(hostname || host)) { - request.once('socket', socket => { - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); - socket.once('lookup', cancelTimeout); - } - }); - } - - if (delays.connect !== undefined) { - request.once('socket', socket => { - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); - - if (request.socketPath || net.isIP(hostname || host)) { - socket.once('connect', timeConnect()); - } else { - socket.once('lookup', error => { - if (error === null) { - socket.once('connect', timeConnect()); - } - }); - } - } - }); - } - - if (delays.secureConnect !== undefined && options.protocol === 'https:') { - request.once('socket', socket => { - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - socket.once('connect', () => { - const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); - socket.once('secureConnect', cancelTimeout); - }); - } - }); - } - - if (delays.send !== undefined) { - request.once('socket', socket => { - const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - socket.once('connect', () => { - request.once('upload-complete', timeRequest()); - }); - } else { - request.once('upload-complete', timeRequest()); - } - }); - } - - if (delays.response !== undefined) { - request.once('upload-complete', () => { - const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); - request.once('response', cancelTimeout); - }); - } -}; - -module.exports.TimeoutError = TimeoutError; - - /***/ }), /***/ 49: @@ -681,315 +515,163 @@ module.exports.default = normalizeUrl; /***/ }), -/***/ 57: +/***/ 72: /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(747); -const util = __webpack_require__(669); -const is = __webpack_require__(534); -const isFormData = __webpack_require__(504); - -module.exports = async options => { - const {body} = options; - - if (options.headers['content-length']) { - return Number(options.headers['content-length']); - } - - if (!body && !options.stream) { - return 0; - } - - if (is.string(body)) { - return Buffer.byteLength(body); - } - - if (isFormData(body)) { - return util.promisify(body.getLength.bind(body))(); - } - - if (body instanceof fs.ReadStream) { - const {size} = await util.promisify(fs.stat)(body.path); - return size; - } - - return null; -}; - - -/***/ }), - -/***/ 86: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; +const {PassThrough: PassThroughStream} = __webpack_require__(413); -const {URL, URLSearchParams} = __webpack_require__(835); // TODO: Use the `URL` global when targeting Node.js 10 -const urlLib = __webpack_require__(835); -const is = __webpack_require__(534); -const urlParseLax = __webpack_require__(173); -const lowercaseKeys = __webpack_require__(474); -const urlToOptions = __webpack_require__(811); -const isFormData = __webpack_require__(504); -const merge = __webpack_require__(821); -const knownHookEvents = __webpack_require__(433); +module.exports = options => { + options = {...options}; -const retryAfterStatusCodes = new Set([413, 429, 503]); + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; -// `preNormalize` handles static options (e.g. headers). -// For example, when you create a custom instance and make a request -// with no static changes, they won't be normalized again. -// -// `normalize` operates on dynamic options - they cannot be saved. -// For example, `body` is everytime different per request. -// When it's done normalizing the new options, it performs merge() -// on the prenormalized options and the normalized ones. - -const preNormalize = (options, defaults) => { - if (is.nullOrUndefined(options.headers)) { - options.headers = {}; + if (array) { + objectMode = !(encoding || isBuffer); } else { - options.headers = lowercaseKeys(options.headers); - } - - if (options.baseUrl && !options.baseUrl.toString().endsWith('/')) { - options.baseUrl += '/'; - } - - if (options.stream) { - options.json = false; - } - - if (is.nullOrUndefined(options.hooks)) { - options.hooks = {}; - } else if (!is.object(options.hooks)) { - throw new TypeError(`Parameter \`hooks\` must be an object, not ${is(options.hooks)}`); - } - - for (const event of knownHookEvents) { - if (is.nullOrUndefined(options.hooks[event])) { - if (defaults) { - options.hooks[event] = [...defaults.hooks[event]]; - } else { - options.hooks[event] = []; - } - } - } - - if (is.number(options.timeout)) { - options.gotTimeout = {request: options.timeout}; - } else if (is.object(options.timeout)) { - options.gotTimeout = options.timeout; - } - - delete options.timeout; - - const {retry} = options; - options.retry = { - retries: 0, - methods: [], - statusCodes: [], - errorCodes: [] - }; - - if (is.nonEmptyObject(defaults) && retry !== false) { - options.retry = {...defaults.retry}; - } - - if (retry !== false) { - if (is.number(retry)) { - options.retry.retries = retry; - } else { - options.retry = {...options.retry, ...retry}; - } - } - - if (options.gotTimeout) { - options.retry.maxRetryAfter = Math.min(...[options.gotTimeout.request, options.gotTimeout.connection].filter(n => !is.nullOrUndefined(n))); - } - - if (is.array(options.retry.methods)) { - options.retry.methods = new Set(options.retry.methods.map(method => method.toUpperCase())); - } - - if (is.array(options.retry.statusCodes)) { - options.retry.statusCodes = new Set(options.retry.statusCodes); + encoding = encoding || 'utf8'; } - if (is.array(options.retry.errorCodes)) { - options.retry.errorCodes = new Set(options.retry.errorCodes); + if (isBuffer) { + encoding = null; } - return options; -}; - -const normalize = (url, options, defaults) => { - if (is.plainObject(url)) { - options = {...url, ...options}; - url = options.url || {}; - delete options.url; - } + const stream = new PassThroughStream({objectMode}); - if (defaults) { - options = merge({}, defaults.options, options ? preNormalize(options, defaults.options) : {}); - } else { - options = merge({}, preNormalize(options)); + if (encoding) { + stream.setEncoding(encoding); } - if (!is.string(url) && !is.object(url)) { - throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(url)}`); - } + let length = 0; + const chunks = []; - if (is.string(url)) { - if (options.baseUrl) { - if (url.toString().startsWith('/')) { - url = url.toString().slice(1); - } + stream.on('data', chunk => { + chunks.push(chunk); - url = urlToOptions(new URL(url, options.baseUrl)); + if (objectMode) { + length = chunks.length; } else { - url = url.replace(/^unix:/, 'http://$&'); - url = urlParseLax(url); - } - } else if (is(url) === 'URL') { - url = urlToOptions(url); - } - - // Override both null/undefined with default protocol - options = merge({path: ''}, url, {protocol: url.protocol || 'https:'}, options); - - for (const hook of options.hooks.init) { - const called = hook(options); - - if (is.promise(called)) { - throw new TypeError('The `init` hook must be a synchronous function'); + length += chunk.length; } - } - - const {baseUrl} = options; - Object.defineProperty(options, 'baseUrl', { - set: () => { - throw new Error('Failed to set baseUrl. Options are normalized already.'); - }, - get: () => baseUrl }); - const {query} = options; - if (is.nonEmptyString(query) || is.nonEmptyObject(query) || query instanceof URLSearchParams) { - if (!is.string(query)) { - options.query = (new URLSearchParams(query)).toString(); - } - - options.path = `${options.path.split('?')[0]}?${options.query}`; - delete options.query; - } - - if (options.hostname === 'unix') { - const matches = /(.+?):(.+)/.exec(options.path); - - if (matches) { - const [, socketPath, path] = matches; - options = { - ...options, - socketPath, - path, - host: null - }; - } - } - - const {headers} = options; - for (const [key, value] of Object.entries(headers)) { - if (is.nullOrUndefined(value)) { - delete headers[key]; - } - } - - if (options.json && is.undefined(headers.accept)) { - headers.accept = 'application/json'; - } - - if (options.decompress && is.undefined(headers['accept-encoding'])) { - headers['accept-encoding'] = 'gzip, deflate'; - } - - const {body} = options; - if (is.nullOrUndefined(body)) { - options.method = options.method ? options.method.toUpperCase() : 'GET'; - } else { - const isObject = is.object(body) && !is.buffer(body) && !is.nodeStream(body); - if (!is.nodeStream(body) && !is.string(body) && !is.buffer(body) && !(options.form || options.json)) { - throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); - } - - if (options.json && !(isObject || is.array(body))) { - throw new TypeError('The `body` option must be an Object or Array when the `json` option is used'); - } - - if (options.form && !isObject) { - throw new TypeError('The `body` option must be an Object when the `form` option is used'); - } - - if (isFormData(body)) { - // Special case for https://github.com/form-data/form-data - headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`; - } else if (options.form) { - headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded'; - options.body = (new URLSearchParams(body)).toString(); - } else if (options.json) { - headers['content-type'] = headers['content-type'] || 'application/json'; - options.body = JSON.stringify(body); + stream.getBufferedValue = () => { + if (array) { + return chunks; } - options.method = options.method ? options.method.toUpperCase() : 'POST'; - } - - if (!is.function(options.retry.retries)) { - const {retries} = options.retry; - - options.retry.retries = (iteration, error) => { - if (iteration > retries) { - return 0; - } + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; - if ((!error || !options.retry.errorCodes.has(error.code)) && (!options.retry.methods.has(error.method) || !options.retry.statusCodes.has(error.statusCode))) { - return 0; - } + stream.getBufferedLength = () => length; - if (Reflect.has(error, 'headers') && Reflect.has(error.headers, 'retry-after') && retryAfterStatusCodes.has(error.statusCode)) { - let after = Number(error.headers['retry-after']); - if (is.nan(after)) { - after = Date.parse(error.headers['retry-after']) - Date.now(); - } else { - after *= 1000; - } + return stream; +}; - if (after > options.retry.maxRetryAfter) { - return 0; - } - return after; - } +/***/ }), - if (error.statusCode === 413) { - return 0; - } +/***/ 77: +/***/ (function(module, exports, __webpack_require__) { - const noise = Math.random() * 100; - return ((2 ** (iteration - 1)) * 1000) + noise; - }; - } +"use strict"; - return options; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +Object.defineProperty(exports, "__esModule", { value: true }); +const create_1 = __webpack_require__(323); +const defaults = { + options: { + method: 'GET', + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE' + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524 + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN' + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue + }, + timeout: {}, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)' + }, + hooks: { + init: [], + beforeRequest: [], + beforeRedirect: [], + beforeRetry: [], + beforeError: [], + afterResponse: [] + }, + decompress: true, + throwHttpErrors: true, + followRedirect: true, + isStream: false, + cache: false, + dnsCache: false, + useElectronNet: false, + responseType: 'text', + resolveBodyOnly: false, + maxRedirects: 10, + prefixUrl: '', + methodRewriting: true, + ignoreInvalidCookies: false, + context: {} + }, + handlers: [create_1.defaultHandler], + mutableDefaults: false }; - -const reNormalize = options => normalize(urlLib.format(options), options); - -module.exports = normalize; -module.exports.preNormalize = preNormalize; -module.exports.reNormalize = reNormalize; +const got = create_1.default(defaults); +exports.default = got; +// For CommonJS default export support +module.exports = got; +module.exports.default = got; +// Export types +__export(__webpack_require__(839)); +var as_stream_1 = __webpack_require__(379); +exports.ResponseStream = as_stream_1.ProxyStream; +var errors_1 = __webpack_require__(378); +exports.GotError = errors_1.GotError; +exports.CacheError = errors_1.CacheError; +exports.RequestError = errors_1.RequestError; +exports.ParseError = errors_1.ParseError; +exports.HTTPError = errors_1.HTTPError; +exports.MaxRedirectsError = errors_1.MaxRedirectsError; +exports.UnsupportedProtocolError = errors_1.UnsupportedProtocolError; +exports.TimeoutError = errors_1.TimeoutError; +exports.CancelError = errors_1.CancelError; /***/ }), @@ -1010,23 +692,27 @@ module.exports = require("os"); // We define these manually to ensure they're always copied // even if they would move up the prototype chain // https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProps = [ +const knownProperties = [ + 'aborted', + 'complete', 'destroy', - 'setTimeout', - 'socket', 'headers', - 'trailers', - 'rawHeaders', - 'statusCode', 'httpVersion', 'httpVersionMinor', 'httpVersionMajor', + 'method', + 'rawHeaders', 'rawTrailers', - 'statusMessage' + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url' ]; module.exports = (fromStream, toStream) => { - const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); + const fromProps = new Set(Object.keys(fromStream).concat(knownProperties)); for (const prop of fromProps) { // Don't overwrite existing properties @@ -1081,24 +767,6 @@ class Response extends Readable { module.exports = Response; -/***/ }), - -/***/ 97: -/***/ (function(module) { - -"use strict"; - -module.exports = object => { - const result = {}; - - for (const [key, value] of Object.entries(object)) { - result[key.toLowerCase()] = value; - } - - return result; -}; - - /***/ }), /***/ 104: @@ -1117,83 +785,412 @@ const { exportSecrets } = __webpack_require__(751); /***/ }), -/***/ 128: -/***/ (function(module) { +/***/ 110: +/***/ (function(module, exports, __webpack_require__) { "use strict"; +/* module decorator */ module = __webpack_require__.nmd(module); -module.exports = (url, opts) => { - if (typeof url !== 'string') { - throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof url}\``); - } - - url = url.trim(); - opts = Object.assign({https: false}, opts); - - if (/^\.*\/|^(?!localhost)\w+:/.test(url)) { - return url; - } - - return url.replace(/^(?!(?:\w+:)?\/\/)/, opts.https ? 'https://' : 'http://'); -}; - - -/***/ }), - -/***/ 145: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const pump = __webpack_require__(453); -const bufferStream = __webpack_require__(966); - -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} - -function getStream(inputStream, options) { - if (!inputStream) { - return Promise.reject(new Error('Expected a stream')); - } - - options = Object.assign({maxBuffer: Infinity}, options); - - const {maxBuffer} = options; - - let stream; - return new Promise((resolve, reject) => { - const rejectPromise = error => { - if (error) { // A null check - error.bufferedData = stream.getBufferedValue(); - } - reject(error); - }; - - stream = pump(inputStream, bufferStream(options), error => { - if (error) { - rejectPromise(error); - return; - } - - resolve(); - }); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }).then(() => stream.getBufferedValue()); -} - -module.exports = getStream; -module.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'})); -module.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true})); -module.exports.MaxBufferError = MaxBufferError; +Object.defineProperty(exports, "__esModule", { value: true }); +const url_1 = __webpack_require__(835); +const util_1 = __webpack_require__(669); +const CacheableRequest = __webpack_require__(946); +const http = __webpack_require__(605); +const https = __webpack_require__(211); +const lowercaseKeys = __webpack_require__(474); +const toReadableStream = __webpack_require__(952); +const is_1 = __webpack_require__(534); +const cacheable_lookup_1 = __webpack_require__(753); +const errors_1 = __webpack_require__(378); +const known_hook_events_1 = __webpack_require__(766); +const dynamic_require_1 = __webpack_require__(415); +const get_body_size_1 = __webpack_require__(232); +const is_form_data_1 = __webpack_require__(219); +const merge_1 = __webpack_require__(164); +const options_to_url_1 = __webpack_require__(856); +const supports_brotli_1 = __webpack_require__(620); +const types_1 = __webpack_require__(839); +const nonEnumerableProperties = [ + 'context', + 'body', + 'json', + 'form' +]; +const isAgentByProtocol = (agent) => is_1.default.object(agent); +// TODO: `preNormalizeArguments` should merge `options` & `defaults` +exports.preNormalizeArguments = (options, defaults) => { + var _a, _b, _c, _d, _e, _f; + // `options.headers` + if (is_1.default.undefined(options.headers)) { + options.headers = {}; + } + else { + options.headers = lowercaseKeys(options.headers); + } + for (const [key, value] of Object.entries(options.headers)) { + if (is_1.default.null_(value)) { + throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); + } + } + // `options.prefixUrl` + if (is_1.default.urlInstance(options.prefixUrl) || is_1.default.string(options.prefixUrl)) { + options.prefixUrl = options.prefixUrl.toString(); + if (options.prefixUrl.length !== 0 && !options.prefixUrl.endsWith('/')) { + options.prefixUrl += '/'; + } + } + else { + options.prefixUrl = defaults ? defaults.prefixUrl : ''; + } + // `options.hooks` + if (is_1.default.undefined(options.hooks)) { + options.hooks = {}; + } + if (is_1.default.object(options.hooks)) { + for (const event of known_hook_events_1.default) { + if (Reflect.has(options.hooks, event)) { + if (!is_1.default.array(options.hooks[event])) { + throw new TypeError(`Parameter \`${event}\` must be an Array, not ${is_1.default(options.hooks[event])}`); + } + } + else { + options.hooks[event] = []; + } + } + } + else { + throw new TypeError(`Parameter \`hooks\` must be an Object, not ${is_1.default(options.hooks)}`); + } + if (defaults) { + for (const event of known_hook_events_1.default) { + if (!(Reflect.has(options.hooks, event) && is_1.default.undefined(options.hooks[event]))) { + // @ts-ignore Union type array is not assignable to union array type + options.hooks[event] = [ + ...defaults.hooks[event], + ...options.hooks[event] + ]; + } + } + } + // `options.timeout` + if (is_1.default.number(options.timeout)) { + options.timeout = { request: options.timeout }; + } + else if (!is_1.default.object(options.timeout)) { + options.timeout = {}; + } + // `options.retry` + const { retry } = options; + if (defaults) { + options.retry = { ...defaults.retry }; + } + else { + options.retry = { + calculateDelay: retryObject => retryObject.computedValue, + limit: 0, + methods: [], + statusCodes: [], + errorCodes: [], + maxRetryAfter: undefined + }; + } + if (is_1.default.object(retry)) { + options.retry = { + ...options.retry, + ...retry + }; + } + else if (is_1.default.number(retry)) { + options.retry.limit = retry; + } + if (options.retry.maxRetryAfter === undefined) { + options.retry.maxRetryAfter = Math.min(...[options.timeout.request, options.timeout.connect].filter((n) => !is_1.default.nullOrUndefined(n))); + } + options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; + options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; + options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; + // `options.dnsCache` + if (options.dnsCache && !(options.dnsCache instanceof cacheable_lookup_1.default)) { + options.dnsCache = new cacheable_lookup_1.default({ cacheAdapter: options.dnsCache }); + } + // `options.method` + if (is_1.default.string(options.method)) { + options.method = options.method.toUpperCase(); + } + else { + options.method = (_b = (_a = defaults) === null || _a === void 0 ? void 0 : _a.method, (_b !== null && _b !== void 0 ? _b : 'GET')); + } + // Better memory management, so we don't have to generate a new object every time + if (options.cache) { + options.cacheableRequest = new CacheableRequest( + // @ts-ignore Cannot properly type a function with multiple definitions yet + (requestOptions, handler) => requestOptions[types_1.requestSymbol](requestOptions, handler), options.cache); + } + // `options.cookieJar` + if (is_1.default.object(options.cookieJar)) { + let { setCookie, getCookieString } = options.cookieJar; + // Horrible `tough-cookie` check + if (setCookie.length === 4 && getCookieString.length === 0) { + if (!Reflect.has(setCookie, util_1.promisify.custom)) { + // @ts-ignore TS is dumb. + setCookie = util_1.promisify(setCookie.bind(options.cookieJar)); + getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); + } + } + else if (setCookie.length !== 2) { + throw new TypeError('`options.cookieJar.setCookie` needs to be an async function with 2 arguments'); + } + else if (getCookieString.length !== 1) { + throw new TypeError('`options.cookieJar.getCookieString` needs to be an async function with 1 argument'); + } + options.cookieJar = { setCookie, getCookieString }; + } + // `options.encoding` + if (is_1.default.null_(options.encoding)) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + // `options.maxRedirects` + if (!Reflect.has(options, 'maxRedirects') && !(defaults && Reflect.has(defaults, 'maxRedirects'))) { + options.maxRedirects = 0; + } + // Merge defaults + if (defaults) { + options = merge_1.default({}, defaults, options); + } + // Other values + options.decompress = Boolean(options.decompress); + options.isStream = Boolean(options.isStream); + options.throwHttpErrors = Boolean(options.throwHttpErrors); + options.ignoreInvalidCookies = Boolean(options.ignoreInvalidCookies); + options.cache = (_c = options.cache, (_c !== null && _c !== void 0 ? _c : false)); + options.responseType = (_d = options.responseType, (_d !== null && _d !== void 0 ? _d : 'text')); + options.resolveBodyOnly = Boolean(options.resolveBodyOnly); + options.followRedirect = Boolean(options.followRedirect); + options.dnsCache = (_e = options.dnsCache, (_e !== null && _e !== void 0 ? _e : false)); + options.useElectronNet = Boolean(options.useElectronNet); + options.methodRewriting = Boolean(options.methodRewriting); + options.context = (_f = options.context, (_f !== null && _f !== void 0 ? _f : {})); + return options; +}; +exports.mergeOptions = (...sources) => { + let mergedOptions = exports.preNormalizeArguments({}); + // Non enumerable properties shall not be merged + const properties = {}; + for (const source of sources) { + mergedOptions = exports.preNormalizeArguments(merge_1.default({}, source), mergedOptions); + for (const name of nonEnumerableProperties) { + if (!Reflect.has(source, name)) { + continue; + } + properties[name] = { + writable: true, + configurable: true, + enumerable: false, + value: source[name] + }; + } + } + Object.defineProperties(mergedOptions, properties); + return mergedOptions; +}; +exports.normalizeArguments = (url, options, defaults) => { + var _a, _b, _c, _d; + // Merge options + if (typeof url === 'undefined') { + throw new TypeError('Missing `url` argument'); + } + if (typeof options === 'undefined') { + options = {}; + } + if (is_1.default.urlInstance(url) || is_1.default.string(url)) { + if (Reflect.has(options, 'url')) { + throw new TypeError('The `url` option cannot be used if the input is a valid URL.'); + } + // @ts-ignore URL is not URL + options.url = url; + options = exports.mergeOptions((_b = (_a = defaults) === null || _a === void 0 ? void 0 : _a.options, (_b !== null && _b !== void 0 ? _b : {})), options); + } + else { + if (Reflect.has(url, 'resolve')) { + throw new Error('The legacy `url.Url` is deprecated. Use `URL` instead.'); + } + options = exports.mergeOptions((_d = (_c = defaults) === null || _c === void 0 ? void 0 : _c.options, (_d !== null && _d !== void 0 ? _d : {})), url, options); + } + // Normalize URL + // TODO: drop `optionsToUrl` in Got 12 + if (is_1.default.string(options.url)) { + options.url = options.prefixUrl + options.url; + options.url = options.url.replace(/^unix:/, 'http://$&'); + if (options.searchParams || options.search) { + options.url = options.url.split('?')[0]; + } + // @ts-ignore URL is not URL + options.url = options_to_url_1.default({ + origin: options.url, + ...options + }); + } + else if (!is_1.default.urlInstance(options.url)) { + // @ts-ignore URL is not URL + options.url = options_to_url_1.default({ origin: options.prefixUrl, ...options }); + } + const normalizedOptions = options; + // Make it possible to change `options.prefixUrl` + let prefixUrl = options.prefixUrl; + Object.defineProperty(normalizedOptions, 'prefixUrl', { + set: (value) => { + if (!normalizedOptions.url.href.startsWith(value)) { + throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${normalizedOptions.url.href}`); + } + normalizedOptions.url = new url_1.URL(value + normalizedOptions.url.href.slice(prefixUrl.length)); + prefixUrl = value; + }, + get: () => prefixUrl + }); + // Make it possible to remove default headers + for (const [key, value] of Object.entries(normalizedOptions.headers)) { + if (is_1.default.undefined(value)) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete normalizedOptions.headers[key]; + } + } + for (const hook of normalizedOptions.hooks.init) { + const result = hook(normalizedOptions); + if (is_1.default.promise(result)) { + throw new TypeError('The `init` hook must be a synchronous function'); + } + } + return normalizedOptions; +}; +const withoutBody = new Set(['GET', 'HEAD']); +exports.normalizeRequestArguments = async (options) => { + var _a, _b, _c; + options = exports.mergeOptions(options); + // Serialize body + const { headers } = options; + const noContentType = is_1.default.undefined(headers['content-type']); + { + // TODO: these checks should be moved to `preNormalizeArguments` + const isForm = !is_1.default.undefined(options.form); + const isJSON = !is_1.default.undefined(options.json); + const isBody = !is_1.default.undefined(options.body); + if ((isBody || isForm || isJSON) && withoutBody.has(options.method)) { + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + } + if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) { + throw new TypeError('The `body`, `json` and `form` options are mutually exclusive'); + } + if (isBody && + !is_1.default.nodeStream(options.body) && + !is_1.default.string(options.body) && + !is_1.default.buffer(options.body) && + !(is_1.default.object(options.body) && is_form_data_1.default(options.body))) { + throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); + } + if (isForm && !is_1.default.object(options.form)) { + throw new TypeError('The `form` option must be an Object'); + } + } + if (options.body) { + // Special case for https://github.com/form-data/form-data + if (is_1.default.object(options.body) && is_form_data_1.default(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + } + } + else if (options.form) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + options.body = (new url_1.URLSearchParams(options.form)).toString(); + } + else if (options.json) { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + options.body = JSON.stringify(options.json); + } + const uploadBodySize = await get_body_size_1.default(options); + if (!is_1.default.nodeStream(options.body)) { + options.body = toReadableStream(options.body); + } + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) { + if ((options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') && + !is_1.default.undefined(uploadBodySize)) { + // @ts-ignore We assign if it is undefined, so this IS correct + headers['content-length'] = String(uploadBodySize); + } + } + if (!options.isStream && options.responseType === 'json' && is_1.default.undefined(headers.accept)) { + headers.accept = 'application/json'; + } + if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) { + headers['accept-encoding'] = supports_brotli_1.default ? 'gzip, deflate, br' : 'gzip, deflate'; + } + // Validate URL + if (options.url.protocol !== 'http:' && options.url.protocol !== 'https:') { + throw new errors_1.UnsupportedProtocolError(options); + } + decodeURI(options.url.toString()); + // Normalize request function + if (is_1.default.function_(options.request)) { + options[types_1.requestSymbol] = options.request; + delete options.request; + } + else { + options[types_1.requestSymbol] = options.url.protocol === 'https:' ? https.request : http.request; + } + // UNIX sockets + if (options.url.hostname === 'unix') { + const matches = /(?.+?):(?.+)/.exec(options.url.pathname); + if ((_a = matches) === null || _a === void 0 ? void 0 : _a.groups) { + const { socketPath, path } = matches.groups; + options = { + ...options, + socketPath, + path, + host: '' + }; + } + } + if (isAgentByProtocol(options.agent)) { + options.agent = (_b = options.agent[options.url.protocol.slice(0, -1)], (_b !== null && _b !== void 0 ? _b : options.agent)); + } + if (options.dnsCache) { + options.lookup = options.dnsCache.lookup; + } + /* istanbul ignore next: electron.net is broken */ + // No point in typing process.versions correctly, as + // `process.version.electron` is used only once, right here. + if (options.useElectronNet && process.versions.electron) { + const electron = dynamic_require_1.default(module, 'electron'); // Trick webpack + options.request = util_1.deprecate((_c = electron.net.request, (_c !== null && _c !== void 0 ? _c : electron.remote.net.request)), 'Electron support has been deprecated and will be removed in Got 11.\n' + + 'See https://github.com/sindresorhus/got/issues/899 for further information.', 'GOT_ELECTRON'); + } + // Got's `timeout` is an object, http's `timeout` is a number, so they're not compatible. + delete options.timeout; + // Set cookies + if (options.cookieJar) { + const cookieString = await options.cookieJar.getCookieString(options.url.toString()); + if (is_1.default.nonEmptyString(cookieString)) { + options.headers.cookie = cookieString; + } + else { + delete options.headers.cookie; + } + } + // `http-cache-semantics` checks this + delete options.url; + return options; +}; /***/ }), @@ -1859,22 +1856,45 @@ module.exports = class CachePolicy { /***/ }), -/***/ 173: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 164: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -const url = __webpack_require__(835); -const prependHttp = __webpack_require__(128); - -module.exports = (input, options) => { - if (typeof input !== 'string') { - throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof input}\` instead.`); - } - - const finalUrl = prependHttp(input, Object.assign({https: true}, options)); - return url.parse(finalUrl); -}; +Object.defineProperty(exports, "__esModule", { value: true }); +const url_1 = __webpack_require__(835); +const is_1 = __webpack_require__(534); +function merge(target, ...sources) { + for (const source of sources) { + for (const [key, sourceValue] of Object.entries(source)) { + const targetValue = target[key]; + if (is_1.default.urlInstance(targetValue) && is_1.default.string(sourceValue)) { + // @ts-ignore TS doesn't recognise Target accepts string keys + target[key] = new url_1.URL(sourceValue, targetValue); + } + else if (is_1.default.plainObject(sourceValue)) { + if (is_1.default.plainObject(targetValue)) { + // @ts-ignore TS doesn't recognise Target accepts string keys + target[key] = merge({}, targetValue, sourceValue); + } + else { + // @ts-ignore TS doesn't recognise Target accepts string keys + target[key] = merge({}, sourceValue); + } + } + else if (is_1.default.array(sourceValue)) { + // @ts-ignore TS doesn't recognise Target accepts string keys + target[key] = sourceValue.slice(); + } + else { + // @ts-ignore TS doesn't recognise Target accepts string keys + target[key] = sourceValue; + } + } + } + return target; +} +exports.default = merge; /***/ }), @@ -1942,6 +1962,46 @@ exports.parse = function (s) { } +/***/ }), + +/***/ 210: +/***/ (function(module) { + +"use strict"; + + +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProps = [ + 'destroy', + 'setTimeout', + 'socket', + 'headers', + 'trailers', + 'rawHeaders', + 'statusCode', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'rawTrailers', + 'statusMessage' +]; + +module.exports = (fromStream, toStream) => { + const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); + + for (const prop of fromProps) { + // Don't overwrite existing properties + if (prop in toStream) { + continue; + } + + toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop]; + } +}; + + /***/ }), /***/ 211: @@ -1951,34 +2011,282 @@ module.exports = require("https"); /***/ }), -/***/ 262: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 215: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -const is = __webpack_require__(534); +Object.defineProperty(exports, "__esModule", { value: true }); +const net = __webpack_require__(631); +const unhandle_1 = __webpack_require__(668); +const reentry = Symbol('reentry'); +const noop = () => { }; +class TimeoutError extends Error { + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + this.event = event; + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; + } +} +exports.TimeoutError = TimeoutError; +exports.default = (request, delays, options) => { + if (Reflect.has(request, reentry)) { + return noop; + } + request[reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle_1.default(); + const addTimeout = (delay, callback, event) => { + var _a, _b; + const timeout = setTimeout(callback, delay, delay, event); + (_b = (_a = timeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + if (request.socket) { + // @ts-ignore We do not want the `socket hang up` error + request.socket._hadError = true; + } + request.abort(); + request.emit('error', new TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); + } + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + if (request.listenerCount('error') === 0) { + throw error; + } + }); + request.once('abort', cancelTimeouts); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeouts); + }); + if (typeof delays.request !== 'undefined') { + addTimeout(delays.request, timeoutHandler, 'request'); + } + if (typeof delays.socket !== 'undefined') { + const socketTimeoutHandler = () => { + timeoutHandler(delays.socket, 'socket'); + }; + request.setTimeout(delays.socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); + } + once(request, 'socket', (socket) => { + var _a; + // @ts-ignore Node typings doesn't have this property + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean((socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = (hostname !== null && hostname !== void 0 ? hostname : host), (_a !== null && _a !== void 0 ? _a : ''))) !== 0)); + if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (typeof delays.connect !== 'undefined') { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (typeof delays.send !== 'undefined') { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); + if (typeof delays.response !== 'undefined') { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); + } + return cancelTimeouts; +}; + -module.exports = function deepFreeze(object) { - for (const [key, value] of Object.entries(object)) { - if (is.plainObject(value) || is.array(value)) { - deepFreeze(object[key]); - } - } +/***/ }), - return Object.freeze(object); -}; +/***/ 219: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +exports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); /***/ }), -/***/ 303: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 232: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs_1 = __webpack_require__(747); +const util_1 = __webpack_require__(669); +const is_1 = __webpack_require__(534); +const is_form_data_1 = __webpack_require__(219); +const statAsync = util_1.promisify(fs_1.stat); +exports.default = async (options) => { + const { body, headers } = options; + if (headers && 'content-length' in headers) { + return Number(headers['content-length']); + } + if (!body) { + return 0; + } + if (is_1.default.string(body)) { + return Buffer.byteLength(body); + } + if (is_1.default.buffer(body)) { + return body.length; + } + if (is_form_data_1.default(body)) { + return util_1.promisify(body.getLength.bind(body))(); + } + if (body instanceof fs_1.ReadStream) { + const { size } = await statAsync(body.path); + return size; + } + return undefined; +}; -const EventEmitter = __webpack_require__(614); -const JSONB = __webpack_require__(205); + +/***/ }), + +/***/ 234: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const decompressResponse = __webpack_require__(861); +const mimicResponse = __webpack_require__(89); +const stream = __webpack_require__(413); +const util_1 = __webpack_require__(669); +const progress_1 = __webpack_require__(489); +const pipeline = util_1.promisify(stream.pipeline); +exports.default = async (response, options, emitter) => { + var _a; + const downloadBodySize = Number(response.headers['content-length']) || undefined; + const progressStream = progress_1.createProgressStream('downloadProgress', emitter, downloadBodySize); + mimicResponse(response, progressStream); + const newResponse = (options.decompress && + options.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream); + if (!options.decompress && ['gzip', 'deflate', 'br'].includes((_a = newResponse.headers['content-encoding'], (_a !== null && _a !== void 0 ? _a : '')))) { + options.responseType = 'buffer'; + } + emitter.emit('response', newResponse); + return pipeline(response, progressStream).catch(error => { + if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + throw error; + } + }); +}; + + +/***/ }), + +/***/ 278: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +exports.default = (url) => { + // Cast to URL + url = url; + const options = { + protocol: url.protocol, + hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}` + }; + if (is_1.default.string(url.port) && url.port.length !== 0) { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; + } + return options; +}; + + +/***/ }), + +/***/ 291: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +function deepFreeze(object) { + for (const value of Object.values(object)) { + if (is_1.default.plainObject(value) || is_1.default.array(value)) { + deepFreeze(value); + } + } + return Object.freeze(object); +} +exports.default = deepFreeze; + + +/***/ }), + +/***/ 303: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const EventEmitter = __webpack_require__(614); +const JSONB = __webpack_require__(205); const loadStore = opts => { const adapters = { @@ -2082,19 +2390,111 @@ module.exports = Keyv; /***/ }), -/***/ 308: -/***/ (function(module) { +/***/ 323: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -module.exports = (socket, callback) => { - if (socket.writable && !socket.connecting) { - callback(); - } else { - socket.once('connect', callback); - } +Object.defineProperty(exports, "__esModule", { value: true }); +const as_promise_1 = __webpack_require__(616); +const as_stream_1 = __webpack_require__(379); +const errors = __webpack_require__(378); +const normalize_arguments_1 = __webpack_require__(110); +const deep_freeze_1 = __webpack_require__(291); +const getPromiseOrStream = (options) => options.isStream ? as_stream_1.default(options) : as_promise_1.default(options); +const isGotInstance = (value) => (Reflect.has(value, 'defaults') && Reflect.has(value.defaults, 'options')); +const aliases = [ + 'get', + 'post', + 'put', + 'patch', + 'head', + 'delete' +]; +exports.defaultHandler = (options, next) => next(options); +const create = (defaults) => { + // Proxy properties from next handlers + defaults._rawHandlers = defaults.handlers; + defaults.handlers = defaults.handlers.map(fn => ((options, next) => { + // This will be assigned by assigning result + let root; + const result = fn(options, newOptions => { + root = next(newOptions); + return root; + }); + if (result !== root && !options.isStream) { + Object.setPrototypeOf(result, Object.getPrototypeOf(root)); + Object.defineProperties(result, Object.getOwnPropertyDescriptors(root)); + } + return result; + })); + // @ts-ignore Because the for loop handles it for us, as well as the other Object.defines + const got = (url, options) => { + var _a; + let iteration = 0; + const iterateHandlers = (newOptions) => { + return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); + }; + /* eslint-disable @typescript-eslint/return-await */ + try { + return iterateHandlers(normalize_arguments_1.normalizeArguments(url, options, defaults)); + } + catch (error) { + if ((_a = options) === null || _a === void 0 ? void 0 : _a.isStream) { + throw error; + } + else { + // @ts-ignore It's an Error not a response, but TS thinks it's calling .resolve + return Promise.reject(error); + } + } + /* eslint-enable @typescript-eslint/return-await */ + }; + got.extend = (...instancesOrOptions) => { + const optionsArray = [defaults.options]; + let handlers = [...defaults._rawHandlers]; + let mutableDefaults; + for (const value of instancesOrOptions) { + if (isGotInstance(value)) { + optionsArray.push(value.defaults.options); + handlers.push(...value.defaults._rawHandlers); + mutableDefaults = value.defaults.mutableDefaults; + } + else { + optionsArray.push(value); + if (Reflect.has(value, 'handlers')) { + handlers.push(...value.handlers); + } + mutableDefaults = value.mutableDefaults; + } + } + handlers = handlers.filter(handler => handler !== exports.defaultHandler); + if (handlers.length === 0) { + handlers.push(exports.defaultHandler); + } + return create({ + options: normalize_arguments_1.mergeOptions(...optionsArray), + handlers, + mutableDefaults: Boolean(mutableDefaults) + }); + }; + // @ts-ignore The missing methods because the for-loop handles it for us + got.stream = (url, options) => got(url, { ...options, isStream: true }); + for (const method of aliases) { + // @ts-ignore Cannot properly type a function with multiple definitions yet + got[method] = (url, options) => got(url, { ...options, method }); + got.stream[method] = (url, options) => got.stream(url, { ...options, method }); + } + Object.assign(got, { ...errors, mergeOptions: normalize_arguments_1.mergeOptions }); + Object.defineProperty(got, 'defaults', { + value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), + writable: defaults.mutableDefaults, + configurable: defaults.mutableDefaults, + enumerable: true + }); + return got; }; +exports.default = create; /***/ }), @@ -2106,7 +2506,7 @@ module.exports = (socket, callback) => { const PassThrough = __webpack_require__(413).PassThrough; -const mimicResponse = __webpack_require__(89); +const mimicResponse = __webpack_require__(210); const cloneResponse = response => { if (!(response && response.pipe)) { @@ -2122,197 +2522,6 @@ const cloneResponse = response => { module.exports = cloneResponse; -/***/ }), - -/***/ 338: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const errors = __webpack_require__(774); -const asStream = __webpack_require__(794); -const asPromise = __webpack_require__(916); -const normalizeArguments = __webpack_require__(86); -const merge = __webpack_require__(821); -const deepFreeze = __webpack_require__(262); - -const getPromiseOrStream = options => options.stream ? asStream(options) : asPromise(options); - -const aliases = [ - 'get', - 'post', - 'put', - 'patch', - 'head', - 'delete' -]; - -const create = defaults => { - defaults = merge({}, defaults); - normalizeArguments.preNormalize(defaults.options); - - if (!defaults.handler) { - // This can't be getPromiseOrStream, because when merging - // the chain would stop at this point and no further handlers would be called. - defaults.handler = (options, next) => next(options); - } - - function got(url, options) { - try { - return defaults.handler(normalizeArguments(url, options, defaults), getPromiseOrStream); - } catch (error) { - if (options && options.stream) { - throw error; - } else { - return Promise.reject(error); - } - } - } - - got.create = create; - got.extend = options => { - let mutableDefaults; - if (options && Reflect.has(options, 'mutableDefaults')) { - mutableDefaults = options.mutableDefaults; - delete options.mutableDefaults; - } else { - mutableDefaults = defaults.mutableDefaults; - } - - return create({ - options: merge.options(defaults.options, options), - handler: defaults.handler, - mutableDefaults - }); - }; - - got.mergeInstances = (...args) => create(merge.instances(args)); - - got.stream = (url, options) => got(url, {...options, stream: true}); - - for (const method of aliases) { - got[method] = (url, options) => got(url, {...options, method}); - got.stream[method] = (url, options) => got.stream(url, {...options, method}); - } - - Object.assign(got, {...errors, mergeOptions: merge.options}); - Object.defineProperty(got, 'defaults', { - value: defaults.mutableDefaults ? defaults : deepFreeze(defaults), - writable: defaults.mutableDefaults, - configurable: defaults.mutableDefaults, - enumerable: true - }); - - return got; -}; - -module.exports = create; - - -/***/ }), - -/***/ 365: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const {Transform} = __webpack_require__(413); - -module.exports = { - download(response, emitter, downloadBodySize) { - let downloaded = 0; - - return new Transform({ - transform(chunk, encoding, callback) { - downloaded += chunk.length; - - const percent = downloadBodySize ? downloaded / downloadBodySize : 0; - - // Let `flush()` be responsible for emitting the last event - if (percent < 1) { - emitter.emit('downloadProgress', { - percent, - transferred: downloaded, - total: downloadBodySize - }); - } - - callback(null, chunk); - }, - - flush(callback) { - emitter.emit('downloadProgress', { - percent: 1, - transferred: downloaded, - total: downloadBodySize - }); - - callback(); - } - }); - }, - - upload(request, emitter, uploadBodySize) { - const uploadEventFrequency = 150; - let uploaded = 0; - let progressInterval; - - emitter.emit('uploadProgress', { - percent: 0, - transferred: 0, - total: uploadBodySize - }); - - request.once('error', () => { - clearInterval(progressInterval); - }); - - request.once('response', () => { - clearInterval(progressInterval); - - emitter.emit('uploadProgress', { - percent: 1, - transferred: uploaded, - total: uploadBodySize - }); - }); - - request.once('socket', socket => { - const onSocketConnect = () => { - progressInterval = setInterval(() => { - const lastUploaded = uploaded; - /* istanbul ignore next: see #490 (occurs randomly!) */ - const headersSize = request._header ? Buffer.byteLength(request._header) : 0; - uploaded = socket.bytesWritten - headersSize; - - // Don't emit events with unchanged progress and - // prevent last event from being emitted, because - // it's emitted when `response` is emitted - if (uploaded === lastUploaded || uploaded === uploadBodySize) { - return; - } - - emitter.emit('uploadProgress', { - percent: uploadBodySize ? uploaded / uploadBodySize : 0, - transferred: uploaded, - total: uploadBodySize - }); - }, uploadEventFrequency); - }; - - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - socket.once('connect', onSocketConnect); - } else if (socket.writable) { - // The socket is being reused from pool, - // so the connect event will not be emitted - onSocketConnect(); - } - }); - } -}; - - /***/ }), /***/ 375: @@ -2373,6 +2582,245 @@ module.exports = options => { }; +/***/ }), + +/***/ 378: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +class GotError extends Error { + constructor(message, error, options) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.name = 'GotError'; + if (!is_1.default.undefined(error.code)) { + this.code = error.code; + } + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: options + }); + // Recover the original stacktrace + if (!is_1.default.undefined(error.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); + } + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; + } + } +} +exports.GotError = GotError; +class CacheError extends GotError { + constructor(error, options) { + super(error.message, error, options); + this.name = 'CacheError'; + } +} +exports.CacheError = CacheError; +class RequestError extends GotError { + constructor(error, options) { + super(error.message, error, options); + this.name = 'RequestError'; + } +} +exports.RequestError = RequestError; +class ReadError extends GotError { + constructor(error, options) { + super(error.message, error, options); + this.name = 'ReadError'; + } +} +exports.ReadError = ReadError; +class ParseError extends GotError { + constructor(error, response, options) { + super(`${error.message} in "${options.url.toString()}"`, error, options); + this.name = 'ParseError'; + Object.defineProperty(this, 'response', { + enumerable: false, + value: response + }); + } +} +exports.ParseError = ParseError; +class HTTPError extends GotError { + constructor(response, options) { + super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, options); + this.name = 'HTTPError'; + Object.defineProperty(this, 'response', { + enumerable: false, + value: response + }); + } +} +exports.HTTPError = HTTPError; +class MaxRedirectsError extends GotError { + constructor(response, maxRedirects, options) { + super(`Redirected ${maxRedirects} times. Aborting.`, {}, options); + this.name = 'MaxRedirectsError'; + Object.defineProperty(this, 'response', { + enumerable: false, + value: response + }); + } +} +exports.MaxRedirectsError = MaxRedirectsError; +class UnsupportedProtocolError extends GotError { + constructor(options) { + super(`Unsupported protocol "${options.url.protocol}"`, {}, options); + this.name = 'UnsupportedProtocolError'; + } +} +exports.UnsupportedProtocolError = UnsupportedProtocolError; +class TimeoutError extends GotError { + constructor(error, timings, options) { + super(error.message, error, options); + this.name = 'TimeoutError'; + this.event = error.event; + this.timings = timings; + } +} +exports.TimeoutError = TimeoutError; +var p_cancelable_1 = __webpack_require__(557); +exports.CancelError = p_cancelable_1.CancelError; + + +/***/ }), + +/***/ 379: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const duplexer3 = __webpack_require__(718); +const stream = __webpack_require__(413); +const http_1 = __webpack_require__(605); +const stream_1 = __webpack_require__(413); +const errors_1 = __webpack_require__(378); +const request_as_event_emitter_1 = __webpack_require__(872); +class ProxyStream extends stream_1.Duplex { +} +exports.ProxyStream = ProxyStream; +function asStream(options) { + const input = new stream_1.PassThrough(); + const output = new stream_1.PassThrough(); + const proxy = duplexer3(input, output); + const piped = new Set(); + let isFinished = false; + options.retry.calculateDelay = () => 0; + if (options.body || options.json || options.form) { + proxy.write = () => { + proxy.destroy(); + throw new Error('Got\'s stream is not writable when the `body`, `json` or `form` option is used'); + }; + } + else if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') { + options.body = input; + } + else { + proxy.write = () => { + proxy.destroy(); + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + }; + } + const emitter = request_as_event_emitter_1.default(options); + const emitError = async (error) => { + try { + for (const hook of options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + proxy.emit('error', error); + } + catch (error_) { + proxy.emit('error', error_); + } + }; + // Cancels the request + proxy._destroy = (error, callback) => { + callback(error); + emitter.abort(); + }; + emitter.on('response', (response) => { + const { statusCode, isFromCache } = response; + proxy.isFromCache = isFromCache; + if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) { + emitError(new errors_1.HTTPError(response, options)); + return; + } + { + const read = proxy._read; + proxy._read = (...args) => { + isFinished = true; + proxy._read = read; + return read.apply(proxy, args); + }; + } + if (options.encoding) { + proxy.setEncoding(options.encoding); + } + stream.pipeline(response, output, error => { + if (error && error.message !== 'Premature close') { + emitError(new errors_1.ReadError(error, options)); + } + }); + for (const destination of piped) { + if (destination.headersSent) { + continue; + } + for (const [key, value] of Object.entries(response.headers)) { + // Got gives *decompressed* data. Overriding `content-encoding` header would result in an error. + // It's not possible to decompress already decompressed data, is it? + const isAllowed = options.decompress ? key !== 'content-encoding' : true; + if (isAllowed) { + destination.setHeader(key, value); + } + } + destination.statusCode = response.statusCode; + } + proxy.emit('response', response); + }); + request_as_event_emitter_1.proxyEvents(proxy, emitter); + emitter.on('error', (error) => proxy.emit('error', error)); + const pipe = proxy.pipe.bind(proxy); + const unpipe = proxy.unpipe.bind(proxy); + proxy.pipe = (destination, options) => { + if (isFinished) { + throw new Error('Failed to pipe. The response has been emitted already.'); + } + pipe(destination, options); + if (destination instanceof http_1.ServerResponse) { + piped.add(destination); + } + return destination; + }; + proxy.unpipe = stream => { + piped.delete(stream); + return unpipe(stream); + }; + proxy.on('pipe', source => { + if (source instanceof http_1.IncomingMessage) { + options.headers = { + ...source.headers, + ...options.headers + }; + } + }); + proxy.isFromCache = undefined; + return proxy; +} +exports.default = asStream; + + /***/ }), /***/ 413: @@ -2380,6 +2828,18 @@ module.exports = options => { module.exports = require("stream"); +/***/ }), + +/***/ 415: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* istanbul ignore file: used for webpack */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = (moduleObject, moduleId) => moduleObject.require(moduleId); + + /***/ }), /***/ 431: @@ -2453,24 +2913,6 @@ function escape(s) { } //# sourceMappingURL=command.js.map -/***/ }), - -/***/ 433: -/***/ (function(module) { - -"use strict"; - - -module.exports = [ - 'beforeError', - 'init', - 'beforeRequest', - 'beforeRedirect', - 'beforeRetry', - 'afterResponse' -]; - - /***/ }), /***/ 453: @@ -2562,115 +3004,8 @@ module.exports = pump /***/ }), -/***/ 456: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const deferToConnect = __webpack_require__(308); - -module.exports = request => { - const timings = { - start: Date.now(), - socket: null, - lookup: null, - connect: null, - upload: null, - response: null, - end: null, - error: null, - phases: { - wait: null, - dns: null, - tcp: null, - request: null, - firstByte: null, - download: null, - total: null - } - }; - - const handleError = origin => { - const emit = origin.emit.bind(origin); - origin.emit = (event, ...args) => { - // Catches the `error` event - if (event === 'error') { - timings.error = Date.now(); - timings.phases.total = timings.error - timings.start; - - origin.emit = emit; - } - - // Saves the original behavior - return emit(event, ...args); - }; - }; - - let uploadFinished = false; - const onUpload = () => { - timings.upload = Date.now(); - timings.phases.request = timings.upload - timings.connect; - }; - - handleError(request); - - request.once('socket', socket => { - timings.socket = Date.now(); - timings.phases.wait = timings.socket - timings.start; - - const lookupListener = () => { - timings.lookup = Date.now(); - timings.phases.dns = timings.lookup - timings.socket; - }; - - socket.once('lookup', lookupListener); - - deferToConnect(socket, () => { - timings.connect = Date.now(); - - if (timings.lookup === null) { - socket.removeListener('lookup', lookupListener); - timings.lookup = timings.connect; - timings.phases.dns = timings.lookup - timings.socket; - } - - timings.phases.tcp = timings.connect - timings.lookup; - - if (uploadFinished && !timings.upload) { - onUpload(); - } - }); - }); - - request.once('finish', () => { - uploadFinished = true; - - if (timings.connect) { - onUpload(); - } - }); - - request.once('response', response => { - timings.response = Date.now(); - timings.phases.firstByte = timings.response - timings.upload; - - handleError(response); - - response.once('end', () => { - timings.end = Date.now(); - timings.phases.download = timings.end - timings.response; - timings.phases.total = timings.end - timings.start; - }); - }); - - return timings; -}; - - -/***/ }), - -/***/ 470: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 470: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; @@ -2858,35 +3193,63 @@ exports.group = group; "use strict"; -module.exports = function (obj) { - var ret = {}; - var keys = Object.keys(Object(obj)); +module.exports = object => { + const result = {}; - for (var i = 0; i < keys.length; i++) { - ret[keys[i].toLowerCase()] = obj[keys[i]]; + for (const [key, value] of Object.entries(object)) { + result[key.toLowerCase()] = value; } - return ret; + return result; }; /***/ }), -/***/ 482: -/***/ (function(module) { - -module.exports = {"_from":"got","_id":"got@9.6.0","_inBundle":false,"_integrity":"sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==","_location":"/got","_phantomChildren":{},"_requested":{"type":"tag","registry":true,"raw":"got","name":"got","escapedName":"got","rawSpec":"","saveSpec":null,"fetchSpec":"latest"},"_requiredBy":["#USER","/"],"_resolved":"https://registry.npmjs.org/got/-/got-9.6.0.tgz","_shasum":"edf45e7d67f99545705de1f7bbeeeb121765ed85","_spec":"got","_where":"C:\\src\\richicoder1\\vault-action","ava":{"concurrency":4},"browser":{"decompress-response":false,"electron":false},"bugs":{"url":"https://github.com/sindresorhus/got/issues"},"bundleDependencies":false,"dependencies":{"@sindresorhus/is":"^0.14.0","@szmarczak/http-timer":"^1.1.2","cacheable-request":"^6.0.0","decompress-response":"^3.3.0","duplexer3":"^0.1.4","get-stream":"^4.1.0","lowercase-keys":"^1.0.1","mimic-response":"^1.0.1","p-cancelable":"^1.0.0","to-readable-stream":"^1.0.0","url-parse-lax":"^3.0.0"},"deprecated":false,"description":"Simplified HTTP requests","devDependencies":{"ava":"^1.1.0","coveralls":"^3.0.0","delay":"^4.1.0","form-data":"^2.3.3","get-port":"^4.0.0","np":"^3.1.0","nyc":"^13.1.0","p-event":"^2.1.0","pem":"^1.13.2","proxyquire":"^2.0.1","sinon":"^7.2.2","slow-stream":"0.0.4","tempfile":"^2.0.0","tempy":"^0.2.1","tough-cookie":"^3.0.0","xo":"^0.24.0"},"engines":{"node":">=8.6"},"files":["source"],"homepage":"https://github.com/sindresorhus/got#readme","keywords":["http","https","get","got","url","uri","request","util","utility","simple","curl","wget","fetch","net","network","electron"],"license":"MIT","main":"source","name":"got","repository":{"type":"git","url":"git+https://github.com/sindresorhus/got.git"},"scripts":{"release":"np","test":"xo && nyc ava"},"version":"9.6.0"}; - -/***/ }), - -/***/ 504: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 489: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -const is = __webpack_require__(534); - -module.exports = body => is.nodeStream(body) && is.function(body.getBoundary); +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(413); +const is_1 = __webpack_require__(534); +function createProgressStream(name, emitter, totalBytes) { + let transformedBytes = 0; + if (is_1.default.string(totalBytes)) { + totalBytes = Number(totalBytes); + } + const progressStream = new stream_1.Transform({ + transform(chunk, _encoding, callback) { + transformedBytes += chunk.length; + const percent = totalBytes ? transformedBytes / totalBytes : 0; + // Let `flush()` be responsible for emitting the last event + if (percent < 1) { + emitter.emit(name, { + percent, + transferred: transformedBytes, + total: totalBytes + }); + } + callback(undefined, chunk); + }, + flush(callback) { + emitter.emit(name, { + percent: 1, + transferred: transformedBytes, + total: totalBytes + }); + callback(); + } + }); + emitter.emit(name, { + percent: 0, + transferred: 0, + total: totalBytes + }); + return progressStream; +} +exports.createProgressStream = createProgressStream; /***/ }), @@ -2896,23 +3259,19 @@ module.exports = body => is.nodeStream(body) && is.function(body.getBoundary); "use strict"; -/// -/// -/// +/// /// Object.defineProperty(exports, "__esModule", { value: true }); // TODO: Use the `URL` global when targeting Node.js 10 -// tslint:disable-next-line const URLGlobal = typeof URL === 'undefined' ? __webpack_require__(835).URL : URL; -const toString = Object.prototype.toString; +const { toString } = Object.prototype; const isOfType = (type) => (value) => typeof value === type; -const isBuffer = (input) => !is.nullOrUndefined(input) && !is.nullOrUndefined(input.constructor) && is.function_(input.constructor.isBuffer) && input.constructor.isBuffer(input); const getObjectType = (value) => { const objectName = toString.call(value).slice(8, -1); if (objectName) { return objectName; } - return null; + return undefined; }; const isObjectOfType = (type) => (value) => getObjectType(value) === type; function is(value) { @@ -2931,6 +3290,8 @@ function is(value) { return "string" /* string */; case 'number': return "number" /* number */; + case 'bigint': + return "bigint" /* bigint */; case 'symbol': return "symbol" /* symbol */; default: @@ -2941,10 +3302,10 @@ function is(value) { if (is.observable(value)) { return "Observable" /* Observable */; } - if (Array.isArray(value)) { + if (is.array(value)) { return "Array" /* Array */; } - if (isBuffer(value)) { + if (is.buffer(value)) { return "Buffer" /* Buffer */; } const tagType = getObjectType(value); @@ -2956,172 +3317,180 @@ function is(value) { } return "Object" /* Object */; } -(function (is) { - // tslint:disable-next-line:strict-type-predicates - const isObject = (value) => typeof value === 'object'; - // tslint:disable:variable-name - is.undefined = isOfType('undefined'); - is.string = isOfType('string'); - is.number = isOfType('number'); - is.function_ = isOfType('function'); - // tslint:disable-next-line:strict-type-predicates - is.null_ = (value) => value === null; - is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); - is.boolean = (value) => value === true || value === false; - is.symbol = isOfType('symbol'); - // tslint:enable:variable-name - is.numericString = (value) => is.string(value) && value.length > 0 && !Number.isNaN(Number(value)); - is.array = Array.isArray; - is.buffer = isBuffer; - is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); - is.object = (value) => !is.nullOrUndefined(value) && (is.function_(value) || isObject(value)); - is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]); - is.asyncIterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.asyncIterator]); - is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw); - is.nativePromise = (value) => isObjectOfType("Promise" /* Promise */)(value); - const hasPromiseAPI = (value) => !is.null_(value) && - isObject(value) && - is.function_(value.then) && - is.function_(value.catch); - is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); - is.generatorFunction = isObjectOfType("GeneratorFunction" /* GeneratorFunction */); - is.asyncFunction = isObjectOfType("AsyncFunction" /* AsyncFunction */); - is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); - is.regExp = isObjectOfType("RegExp" /* RegExp */); - is.date = isObjectOfType("Date" /* Date */); - is.error = isObjectOfType("Error" /* Error */); - is.map = (value) => isObjectOfType("Map" /* Map */)(value); - is.set = (value) => isObjectOfType("Set" /* Set */)(value); - is.weakMap = (value) => isObjectOfType("WeakMap" /* WeakMap */)(value); - is.weakSet = (value) => isObjectOfType("WeakSet" /* WeakSet */)(value); - is.int8Array = isObjectOfType("Int8Array" /* Int8Array */); - is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */); - is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */); - is.int16Array = isObjectOfType("Int16Array" /* Int16Array */); - is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */); - is.int32Array = isObjectOfType("Int32Array" /* Int32Array */); - is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */); - is.float32Array = isObjectOfType("Float32Array" /* Float32Array */); - is.float64Array = isObjectOfType("Float64Array" /* Float64Array */); - is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */); - is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */); - is.dataView = isObjectOfType("DataView" /* DataView */); - is.directInstanceOf = (instance, klass) => Object.getPrototypeOf(instance) === klass.prototype; - is.urlInstance = (value) => isObjectOfType("URL" /* URL */)(value); - is.urlString = (value) => { - if (!is.string(value)) { - return false; - } - try { - new URLGlobal(value); // tslint:disable-line no-unused-expression - return true; - } - catch (_a) { - return false; - } - }; - is.truthy = (value) => Boolean(value); - is.falsy = (value) => !value; - is.nan = (value) => Number.isNaN(value); - const primitiveTypes = new Set([ - 'undefined', - 'string', - 'number', - 'boolean', - 'symbol' - ]); - is.primitive = (value) => is.null_(value) || primitiveTypes.has(typeof value); - is.integer = (value) => Number.isInteger(value); - is.safeInteger = (value) => Number.isSafeInteger(value); - is.plainObject = (value) => { - // From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js - let prototype; - return getObjectType(value) === "Object" /* Object */ && - (prototype = Object.getPrototypeOf(value), prototype === null || // tslint:disable-line:ban-comma-operator - prototype === Object.getPrototypeOf({})); - }; - const typedArrayTypes = new Set([ - "Int8Array" /* Int8Array */, - "Uint8Array" /* Uint8Array */, - "Uint8ClampedArray" /* Uint8ClampedArray */, - "Int16Array" /* Int16Array */, - "Uint16Array" /* Uint16Array */, - "Int32Array" /* Int32Array */, - "Uint32Array" /* Uint32Array */, - "Float32Array" /* Float32Array */, - "Float64Array" /* Float64Array */ - ]); - is.typedArray = (value) => { - const objectType = getObjectType(value); - if (objectType === null) { - return false; - } - return typedArrayTypes.has(objectType); - }; - const isValidLength = (value) => is.safeInteger(value) && value > -1; - is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); - is.inRange = (value, range) => { - if (is.number(range)) { - return value >= Math.min(0, range) && value <= Math.max(range, 0); - } - if (is.array(range) && range.length === 2) { - return value >= Math.min(...range) && value <= Math.max(...range); - } - throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); - }; - const NODE_TYPE_ELEMENT = 1; - const DOM_PROPERTIES_TO_CHECK = [ - 'innerHTML', - 'ownerDocument', - 'style', - 'attributes', - 'nodeValue' - ]; - is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) && - !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value); - is.observable = (value) => { - if (!value) { - return false; - } - if (value[Symbol.observable] && value === value[Symbol.observable]()) { - return true; - } - if (value['@@observable'] && value === value['@@observable']()) { - return true; - } +is.undefined = isOfType('undefined'); +is.string = isOfType('string'); +const isNumberType = isOfType('number'); +is.number = (value) => isNumberType(value) && !is.nan(value); +is.bigint = isOfType('bigint'); +// eslint-disable-next-line @typescript-eslint/ban-types +is.function_ = isOfType('function'); +is.null_ = (value) => value === null; +is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); +is.boolean = (value) => value === true || value === false; +is.symbol = isOfType('symbol'); +is.numericString = (value) => is.string(value) && value.length > 0 && !Number.isNaN(Number(value)); +is.array = Array.isArray; +is.buffer = (value) => !is.nullOrUndefined(value) && !is.nullOrUndefined(value.constructor) && is.function_(value.constructor.isBuffer) && value.constructor.isBuffer(value); +is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); +is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); +is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]); +is.asyncIterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.asyncIterator]); +is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw); +is.nativePromise = (value) => isObjectOfType("Promise" /* Promise */)(value); +const hasPromiseAPI = (value) => is.object(value) && + is.function_(value.then) && // eslint-disable-line promise/prefer-await-to-then + is.function_(value.catch); +is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); +is.generatorFunction = isObjectOfType("GeneratorFunction" /* GeneratorFunction */); +// eslint-disable-next-line @typescript-eslint/ban-types +is.asyncFunction = isObjectOfType("AsyncFunction" /* AsyncFunction */); +// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types +is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); +is.regExp = isObjectOfType("RegExp" /* RegExp */); +is.date = isObjectOfType("Date" /* Date */); +is.error = isObjectOfType("Error" /* Error */); +is.map = (value) => isObjectOfType("Map" /* Map */)(value); +is.set = (value) => isObjectOfType("Set" /* Set */)(value); +is.weakMap = (value) => isObjectOfType("WeakMap" /* WeakMap */)(value); +is.weakSet = (value) => isObjectOfType("WeakSet" /* WeakSet */)(value); +is.int8Array = isObjectOfType("Int8Array" /* Int8Array */); +is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */); +is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */); +is.int16Array = isObjectOfType("Int16Array" /* Int16Array */); +is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */); +is.int32Array = isObjectOfType("Int32Array" /* Int32Array */); +is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */); +is.float32Array = isObjectOfType("Float32Array" /* Float32Array */); +is.float64Array = isObjectOfType("Float64Array" /* Float64Array */); +is.bigInt64Array = isObjectOfType("BigInt64Array" /* BigInt64Array */); +is.bigUint64Array = isObjectOfType("BigUint64Array" /* BigUint64Array */); +is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */); +is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */); +is.dataView = isObjectOfType("DataView" /* DataView */); +is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; +is.urlInstance = (value) => isObjectOfType("URL" /* URL */)(value); +is.urlString = (value) => { + if (!is.string(value)) { return false; - }; - is.nodeStream = (value) => !is.nullOrUndefined(value) && isObject(value) && is.function_(value.pipe) && !is.observable(value); - is.infinite = (value) => value === Infinity || value === -Infinity; - const isAbsoluteMod2 = (rem) => (value) => is.integer(value) && Math.abs(value % 2) === rem; - is.even = isAbsoluteMod2(0); - is.odd = isAbsoluteMod2(1); - const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false; - is.emptyArray = (value) => is.array(value) && value.length === 0; - is.nonEmptyArray = (value) => is.array(value) && value.length > 0; - is.emptyString = (value) => is.string(value) && value.length === 0; - is.nonEmptyString = (value) => is.string(value) && value.length > 0; - is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); - is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; - is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; - is.emptySet = (value) => is.set(value) && value.size === 0; - is.nonEmptySet = (value) => is.set(value) && value.size > 0; - is.emptyMap = (value) => is.map(value) && value.size === 0; - is.nonEmptyMap = (value) => is.map(value) && value.size > 0; - const predicateOnArray = (method, predicate, values) => { - if (is.function_(predicate) === false) { - throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); - } - if (values.length === 0) { - throw new TypeError('Invalid number of values'); - } - return method.call(values, predicate); - }; - // tslint:disable variable-name - is.any = (predicate, ...values) => predicateOnArray(Array.prototype.some, predicate, values); - is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); - // tslint:enable variable-name -})(is || (is = {})); + } + try { + new URLGlobal(value); // eslint-disable-line no-new + return true; + } + catch (_a) { + return false; + } +}; +// TODO: Use the `not` operator with a type guard here when it's available. +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +is.truthy = (value) => Boolean(value); +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +is.falsy = (value) => !value; +is.nan = (value) => Number.isNaN(value); +const primitiveTypeOfTypes = new Set([ + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol' +]); +is.primitive = (value) => is.null_(value) || primitiveTypeOfTypes.has(typeof value); +is.integer = (value) => Number.isInteger(value); +is.safeInteger = (value) => Number.isSafeInteger(value); +is.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js + if (getObjectType(value) !== "Object" /* Object */) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; +const typedArrayTypes = new Set([ + "Int8Array" /* Int8Array */, + "Uint8Array" /* Uint8Array */, + "Uint8ClampedArray" /* Uint8ClampedArray */, + "Int16Array" /* Int16Array */, + "Uint16Array" /* Uint16Array */, + "Int32Array" /* Int32Array */, + "Uint32Array" /* Uint32Array */, + "Float32Array" /* Float32Array */, + "Float64Array" /* Float64Array */, + "BigInt64Array" /* BigInt64Array */, + "BigUint64Array" /* BigUint64Array */ +]); +is.typedArray = (value) => { + const objectType = getObjectType(value); + if (objectType === undefined) { + return false; + } + return typedArrayTypes.has(objectType); +}; +const isValidLength = (value) => is.safeInteger(value) && value >= 0; +is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); +is.inRange = (value, range) => { + if (is.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +}; +const NODE_TYPE_ELEMENT = 1; +const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue' +]; +is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) && + !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value); +is.observable = (value) => { + if (!value) { + return false; + } + // eslint-disable-next-line no-use-extend-native/no-use-extend-native + if (value[Symbol.observable] && value === value[Symbol.observable]()) { + return true; + } + if (value['@@observable'] && value === value['@@observable']()) { + return true; + } + return false; +}; +is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); +is.infinite = (value) => value === Infinity || value === -Infinity; +const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; +is.evenInteger = isAbsoluteMod2(0); +is.oddInteger = isAbsoluteMod2(1); +is.emptyArray = (value) => is.array(value) && value.length === 0; +is.nonEmptyArray = (value) => is.array(value) && value.length > 0; +is.emptyString = (value) => is.string(value) && value.length === 0; +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyString = (value) => is.string(value) && value.length > 0; +const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false; +is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); +is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; +is.emptySet = (value) => is.set(value) && value.size === 0; +is.nonEmptySet = (value) => is.set(value) && value.size > 0; +is.emptyMap = (value) => is.map(value) && value.size === 0; +is.nonEmptyMap = (value) => is.map(value) && value.size > 0; +const predicateOnArray = (method, predicate, values) => { + if (is.function_(predicate) === false) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); +}; +is.any = (predicate, ...values) => predicateOnArray(Array.prototype.some, predicate, values); +is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); // Some few keywords are reserved, but we'll populate them for Node.js users // See https://github.com/Microsoft/TypeScript/issues/2536 Object.defineProperties(is, { @@ -3162,10 +3531,11 @@ class CancelError extends Error { class PCancelable { static fn(userFn) { - return (...args) => { + return (...arguments_) => { return new PCancelable((resolve, reject, onCancel) => { - args.push(onCancel); - userFn(...args).then(resolve, reject); + arguments_.push(onCancel); + // eslint-disable-next-line promise/prefer-await-to-then + userFn(...arguments_).then(resolve, reject); }); }; } @@ -3190,14 +3560,18 @@ class PCancelable { }; const onCancel = handler => { + if (!this._isPending) { + throw new Error('The `onCancel` handler was attached after the promise settled.'); + } + this._cancelHandlers.push(handler); }; Object.defineProperties(onCancel, { shouldReject: { get: () => this._rejectOnCancel, - set: bool => { - this._rejectOnCancel = bool; + set: boolean => { + this._rejectOnCancel = boolean; } } }); @@ -3207,6 +3581,7 @@ class PCancelable { } then(onFulfilled, onRejected) { + // eslint-disable-next-line promise/prefer-await-to-then return this._promise.then(onFulfilled, onRejected); } @@ -3247,404 +3622,348 @@ class PCancelable { Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); module.exports = PCancelable; -module.exports.default = PCancelable; - module.exports.CancelError = CancelError; /***/ }), -/***/ 584: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 605: +/***/ (function(module) { -"use strict"; +module.exports = require("http"); -const {URL} = __webpack_require__(835); // TODO: Use the `URL` global when targeting Node.js 10 -const util = __webpack_require__(669); -const EventEmitter = __webpack_require__(614); -const http = __webpack_require__(605); -const https = __webpack_require__(211); -const urlLib = __webpack_require__(835); -const CacheableRequest = __webpack_require__(946); -const toReadableStream = __webpack_require__(952); -const is = __webpack_require__(534); -const timer = __webpack_require__(456); -const timedOut = __webpack_require__(18); -const getBodySize = __webpack_require__(57); -const getResponse = __webpack_require__(633); -const progress = __webpack_require__(365); -const {CacheError, UnsupportedProtocolError, MaxRedirectsError, RequestError, TimeoutError} = __webpack_require__(774); -const urlToOptions = __webpack_require__(811); - -const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]); -const allMethodRedirectCodes = new Set([300, 303, 307, 308]); - -module.exports = (options, input) => { - const emitter = new EventEmitter(); - const redirects = []; - let currentRequest; - let requestUrl; - let redirectString; - let uploadBodySize; - let retryCount = 0; - let shouldAbort = false; - - const setCookie = options.cookieJar ? util.promisify(options.cookieJar.setCookie.bind(options.cookieJar)) : null; - const getCookieString = options.cookieJar ? util.promisify(options.cookieJar.getCookieString.bind(options.cookieJar)) : null; - const agents = is.object(options.agent) ? options.agent : null; - - const emitError = async error => { - try { - for (const hook of options.hooks.beforeError) { - // eslint-disable-next-line no-await-in-loop - error = await hook(error); - } +/***/ }), - emitter.emit('error', error); - } catch (error2) { - emitter.emit('error', error2); - } - }; +/***/ 614: +/***/ (function(module) { - const get = async options => { - const currentUrl = redirectString || requestUrl; +module.exports = require("events"); - if (options.protocol !== 'http:' && options.protocol !== 'https:') { - throw new UnsupportedProtocolError(options); - } +/***/ }), - decodeURI(currentUrl); +/***/ 616: +/***/ (function(__unusedmodule, exports, __webpack_require__) { - let fn; - if (is.function(options.request)) { - fn = {request: options.request}; - } else { - fn = options.protocol === 'https:' ? https : http; - } +"use strict"; - if (agents) { - const protocolName = options.protocol === 'https:' ? 'https' : 'http'; - options.agent = agents[protocolName] || options.agent; - } +Object.defineProperty(exports, "__esModule", { value: true }); +const EventEmitter = __webpack_require__(614); +const getStream = __webpack_require__(705); +const PCancelable = __webpack_require__(557); +const is_1 = __webpack_require__(534); +const errors_1 = __webpack_require__(378); +const normalize_arguments_1 = __webpack_require__(110); +const request_as_event_emitter_1 = __webpack_require__(872); +const parseBody = (body, responseType, encoding) => { + if (responseType === 'json') { + return body.length === 0 ? '' : JSON.parse(body.toString()); + } + if (responseType === 'buffer') { + return Buffer.from(body); + } + if (responseType === 'text') { + return body.toString(encoding); + } + throw new TypeError(`Unknown body type '${responseType}'`); +}; +function asPromise(options) { + const proxy = new EventEmitter(); + let body; + const promise = new PCancelable((resolve, reject, onCancel) => { + const emitter = request_as_event_emitter_1.default(options); + onCancel(emitter.abort); + const emitError = async (error) => { + try { + for (const hook of options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + reject(error); + } + catch (error_) { + reject(error_); + } + }; + emitter.on('response', async (response) => { + var _a; + proxy.emit('response', response); + // Download body + try { + body = await getStream.buffer(response, { encoding: 'binary' }); + } + catch (error) { + emitError(new errors_1.ReadError(error, options)); + return; + } + if ((_a = response.req) === null || _a === void 0 ? void 0 : _a.aborted) { + // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error + return; + } + const isOk = () => { + const { statusCode } = response; + const limitStatusCode = options.followRedirect ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; + }; + // Parse body + try { + response.body = parseBody(body, options.responseType, options.encoding); + } + catch (error) { + if (isOk()) { + const parseError = new errors_1.ParseError(error, response, options); + emitError(parseError); + return; + } + // Fall back to `utf8` + response.body = body.toString(); + } + try { + for (const [index, hook] of options.hooks.afterResponse.entries()) { + // @ts-ignore TS doesn't notice that CancelableRequest is a Promise + // eslint-disable-next-line no-await-in-loop + response = await hook(response, async (updatedOptions) => { + const typedOptions = normalize_arguments_1.normalizeArguments(normalize_arguments_1.mergeOptions(options, { + ...updatedOptions, + retry: { + calculateDelay: () => 0 + }, + throwHttpErrors: false, + resolveBodyOnly: false + })); + // Remove any further hooks for that request, because we'll call them anyway. + // The loop continues. We don't want duplicates (asPromise recursion). + typedOptions.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); + for (const hook of options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedOptions); + } + const promise = asPromise(typedOptions); + onCancel(() => { + promise.catch(() => { }); + promise.cancel(); + }); + return promise; + }); + } + } + catch (error) { + emitError(error); + return; + } + // Check for HTTP error codes + if (!isOk()) { + const error = new errors_1.HTTPError(response, options); + if (emitter.retry(error)) { + return; + } + if (options.throwHttpErrors) { + emitError(error); + return; + } + } + resolve(options.resolveBodyOnly ? response.body : response); + }); + emitter.once('error', reject); + request_as_event_emitter_1.proxyEvents(proxy, emitter); + }); + promise.on = (name, fn) => { + proxy.on(name, fn); + return promise; + }; + const shortcut = (responseType) => { + // eslint-disable-next-line promise/prefer-await-to-then + const newPromise = promise.then(() => parseBody(body, responseType, options.encoding)); + Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); + return newPromise; + }; + promise.json = () => { + if (is_1.default.undefined(body) && is_1.default.undefined(options.headers.accept)) { + options.headers.accept = 'application/json'; + } + return shortcut('json'); + }; + promise.buffer = () => shortcut('buffer'); + promise.text = () => shortcut('text'); + return promise; +} +exports.default = asPromise; - /* istanbul ignore next: electron.net is broken */ - if (options.useElectronNet && process.versions.electron) { - const r = ({x: require})['yx'.slice(1)]; // Trick webpack - const electron = r('electron'); - fn = electron.net || electron.remote.net; - } - if (options.cookieJar) { - const cookieString = await getCookieString(currentUrl, {}); +/***/ }), - if (is.nonEmptyString(cookieString)) { - options.headers.cookie = cookieString; - } - } +/***/ 620: +/***/ (function(__unusedmodule, exports, __webpack_require__) { - let timings; - const handleResponse = async response => { - try { - /* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */ - if (options.useElectronNet) { - response = new Proxy(response, { - get: (target, name) => { - if (name === 'trailers' || name === 'rawTrailers') { - return []; - } +"use strict"; - const value = target[name]; - return is.function(value) ? value.bind(target) : value; - } - }); - } +Object.defineProperty(exports, "__esModule", { value: true }); +const zlib = __webpack_require__(761); +exports.default = typeof zlib.createBrotliDecompress === 'function'; - const {statusCode} = response; - response.url = currentUrl; - response.requestUrl = requestUrl; - response.retryCount = retryCount; - response.timings = timings; - response.redirectUrls = redirects; - response.request = { - gotOptions: options - }; - const rawCookies = response.headers['set-cookie']; - if (options.cookieJar && rawCookies) { - await Promise.all(rawCookies.map(rawCookie => setCookie(rawCookie, response.url))); - } +/***/ }), - if (options.followRedirect && 'location' in response.headers) { - if (allMethodRedirectCodes.has(statusCode) || (getMethodRedirectCodes.has(statusCode) && (options.method === 'GET' || options.method === 'HEAD'))) { - response.resume(); // We're being redirected, we don't care about the response. +/***/ 622: +/***/ (function(module) { - if (statusCode === 303) { - // Server responded with "see other", indicating that the resource exists at another location, - // and the client should request it from that location via GET or HEAD. - options.method = 'GET'; - } +module.exports = require("path"); - if (redirects.length >= 10) { - throw new MaxRedirectsError(statusCode, redirects, options); - } +/***/ }), - // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 - const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); - const redirectURL = new URL(redirectBuffer, currentUrl); - redirectString = redirectURL.toString(); +/***/ 631: +/***/ (function(module) { - redirects.push(redirectString); +module.exports = require("net"); - const redirectOptions = { - ...options, - ...urlToOptions(redirectURL) - }; +/***/ }), - for (const hook of options.hooks.beforeRedirect) { - // eslint-disable-next-line no-await-in-loop - await hook(redirectOptions); - } +/***/ 668: +/***/ (function(__unusedmodule, exports) { - emitter.emit('redirect', response, redirectOptions); +"use strict"; - await get(redirectOptions); - return; - } - } +Object.defineProperty(exports, "__esModule", { value: true }); +// When attaching listeners, it's very easy to forget about them. +// Especially if you do error handling and set timeouts. +// So instead of checking if it's proper to throw an error on every timeout ever, +// use this simple tool which will remove all listeners you have attached. +exports.default = () => { + const handlers = []; + return { + once(origin, event, fn) { + origin.once(event, fn); + handlers.push({ origin, event, fn }); + }, + unhandleAll() { + for (const handler of handlers) { + const { origin, event, fn } = handler; + origin.removeListener(event, fn); + } + handlers.length = 0; + } + }; +}; - getResponse(response, options, emitter); - } catch (error) { - emitError(error); - } - }; - const handleRequest = request => { - if (shouldAbort) { - request.once('error', () => {}); - request.abort(); - return; - } +/***/ }), - currentRequest = request; +/***/ 669: +/***/ (function(module) { - request.once('error', error => { - if (request.aborted) { - return; - } +module.exports = require("util"); - if (error instanceof timedOut.TimeoutError) { - error = new TimeoutError(error, options); - } else { - error = new RequestError(error, options); - } +/***/ }), - if (emitter.retry(error) === false) { - emitError(error); - } - }); +/***/ 678: +/***/ (function(__unusedmodule, exports, __webpack_require__) { - timings = timer(request); +"use strict"; - progress.upload(request, emitter, uploadBodySize); +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +const errors_1 = __webpack_require__(378); +const retryAfterStatusCodes = new Set([413, 429, 503]); +const isErrorWithResponse = (error) => (error instanceof errors_1.HTTPError || error instanceof errors_1.ParseError || error instanceof errors_1.MaxRedirectsError); +const calculateRetryDelay = ({ attemptCount, retryOptions, error }) => { + if (attemptCount > retryOptions.limit) { + return 0; + } + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = Reflect.has(error, 'code') && retryOptions.errorCodes.includes(error.code); + const hasStatusCode = isErrorWithResponse(error) && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (isErrorWithResponse(error)) { + const { response } = error; + if (response && Reflect.has(response.headers, 'retry-after') && retryAfterStatusCodes.has(response.statusCode)) { + let after = Number(response.headers['retry-after']); + if (is_1.default.nan(after)) { + after = Date.parse(response.headers['retry-after']) - Date.now(); + } + else { + after *= 1000; + } + if (after > retryOptions.maxRetryAfter) { + return 0; + } + return after; + } + if (response.statusCode === 413) { + return 0; + } + } + const noise = Math.random() * 100; + return ((2 ** (attemptCount - 1)) * 1000) + noise; +}; +exports.default = calculateRetryDelay; - if (options.gotTimeout) { - timedOut(request, options.gotTimeout, options); - } - emitter.emit('request', request); +/***/ }), - const uploadComplete = () => { - request.emit('upload-complete'); - }; +/***/ 705: +/***/ (function(module, __unusedexports, __webpack_require__) { - try { - if (is.nodeStream(options.body)) { - options.body.once('end', uploadComplete); - options.body.pipe(request); - options.body = undefined; - } else if (options.body) { - request.end(options.body, uploadComplete); - } else if (input && (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH')) { - input.once('end', uploadComplete); - input.pipe(request); - } else { - request.end(uploadComplete); - } - } catch (error) { - emitError(new RequestError(error, options)); - } - }; +"use strict"; - if (options.cache) { - const cacheableRequest = new CacheableRequest(fn.request, options.cache); - const cacheRequest = cacheableRequest(options, handleResponse); +const pump = __webpack_require__(453); +const bufferStream = __webpack_require__(72); - cacheRequest.once('error', error => { - if (error instanceof CacheableRequest.RequestError) { - emitError(new RequestError(error, options)); - } else { - emitError(new CacheError(error, options)); - } - }); +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} - cacheRequest.once('request', handleRequest); - } else { - // Catches errors thrown by calling fn.request(...) - try { - handleRequest(fn.request(options, handleResponse)); - } catch (error) { - emitError(new RequestError(error, options)); - } - } - }; - - emitter.retry = error => { - let backoff; - - try { - backoff = options.retry.retries(++retryCount, error); - } catch (error2) { - emitError(error2); - return; - } - - if (backoff) { - const retry = async options => { - try { - for (const hook of options.hooks.beforeRetry) { - // eslint-disable-next-line no-await-in-loop - await hook(options, error, retryCount); - } - - await get(options); - } catch (error) { - emitError(error); - } - }; - - setTimeout(retry, backoff, {...options, forceRefresh: true}); - return true; - } +async function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } - return false; + options = { + maxBuffer: Infinity, + ...options }; - emitter.abort = () => { - if (currentRequest) { - currentRequest.once('error', () => {}); - currentRequest.abort(); - } else { - shouldAbort = true; - } - }; + const {maxBuffer} = options; - setImmediate(async () => { - try { - // Convert buffer to stream to receive upload progress events (#322) - const {body} = options; - if (is.buffer(body)) { - options.body = toReadableStream(body); - uploadBodySize = body.length; - } else { - uploadBodySize = await getBodySize(options); + let stream; + await new Promise((resolve, reject) => { + const rejectPromise = error => { + if (error) { // A null check + error.bufferedData = stream.getBufferedValue(); } - if (is.undefined(options.headers['content-length']) && is.undefined(options.headers['transfer-encoding'])) { - if ((uploadBodySize > 0 || options.method === 'PUT') && !is.null(uploadBodySize)) { - options.headers['content-length'] = uploadBodySize; - } - } + reject(error); + }; - for (const hook of options.hooks.beforeRequest) { - // eslint-disable-next-line no-await-in-loop - await hook(options); + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; } - requestUrl = options.href || (new URL(options.path, urlLib.format(options))).toString(); - - await get(options); - } catch (error) { - emitError(error); - } - }); - - return emitter; -}; - - -/***/ }), - -/***/ 605: -/***/ (function(module) { - -module.exports = require("http"); - -/***/ }), - -/***/ 614: -/***/ (function(module) { - -module.exports = require("events"); - -/***/ }), - -/***/ 622: -/***/ (function(module) { - -module.exports = require("path"); - -/***/ }), - -/***/ 631: -/***/ (function(module) { - -module.exports = require("net"); - -/***/ }), - -/***/ 633: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const decompressResponse = __webpack_require__(861); -const is = __webpack_require__(534); -const mimicResponse = __webpack_require__(89); -const progress = __webpack_require__(365); - -module.exports = (response, options, emitter) => { - const downloadBodySize = Number(response.headers['content-length']) || null; - - const progressStream = progress.download(response, emitter, downloadBodySize); - - mimicResponse(response, progressStream); - - const newResponse = options.decompress === true && - is.function(decompressResponse) && - options.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream; - - if (!options.decompress && ['gzip', 'deflate'].includes(response.headers['content-encoding'])) { - options.encoding = null; - } - - emitter.emit('response', newResponse); + resolve(); + }); - emitter.emit('downloadProgress', { - percent: 0, - transferred: 0, - total: downloadBodySize + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); }); - response.pipe(progressStream); -}; - - -/***/ }), + return stream.getBufferedValue(); +} -/***/ 669: -/***/ (function(module) { +module.exports = getStream; +// TODO: Remove this for the next major release +module.exports.default = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; -module.exports = require("util"); /***/ }), @@ -3744,25 +4063,60 @@ module.exports = require("fs"); const core = __webpack_require__(470); const command = __webpack_require__(431); -const got = __webpack_require__(798); +const got = __webpack_require__(77); +const AUTH_METHODS = ['approle', 'token']; async function exportSecrets() { const vaultUrl = core.getInput('url', { required: true }); - const vaultToken = core.getInput('token', { required: true }); const vaultNamespace = core.getInput('namespace', { required: false }); const secretsInput = core.getInput('secrets', { required: true }); const secrets = parseSecretsInput(secretsInput); + const vaultMethod = core.getInput('method', { required: false }) || 'token'; + if (!AUTH_METHODS.includes(vaultMethod)) { + throw Error(`Sorry, the authentication method ${vaultMethod} is not currently supported.`); + } + + let vaultToken = null; + switch (vaultMethod) { + case 'approle': + const vaultRoleId = core.getInput('roleId', { required: true }); + const vaultSecretId = core.getInput('secretId', { required: true }); + core.debug('Try to retrieve Vault Token from approle'); + var options = { + headers: {}, + json: { role_id: vaultRoleId, secret_id: vaultSecretId }, + responseType: 'json' + }; + + if (vaultNamespace != null) { + options.headers["X-Vault-Namespace"] = vaultNamespace; + } + + const result = await got.post(`${vaultUrl}/v1/auth/approle/login`, options); + if (result && result.body && result.body.auth && result.body.auth.client_token) { + vaultToken = result.body.auth.client_token; + core.debug('✔ Vault Token has retrieved from approle'); + } else { + throw Error(`No token was retrieved with the role_id and secret_id provided.`); + } + break; + default: + vaultToken = core.getInput('token', { required: true }); + break; + } + for (const secret of secrets) { const { secretPath, outputName, secretKey } = secret; const requestOptions = { headers: { 'X-Vault-Token': vaultToken - }}; + }, + }; - if (vaultNamespace != null){ - requestOptions.headers["X-Vault-Namespace"] = vaultNamespace + if (vaultNamespace != null) { + requestOptions.headers["X-Vault-Namespace"] = vaultNamespace; } const result = await got(`${vaultUrl}/v1/secret/data/${secretPath}`, requestOptions); @@ -3779,7 +4133,7 @@ async function exportSecrets() { /** * Parses a secrets input string into key paths and their resulting environment variable name. - * @param {string} secretsInput + * @param {string} secretsInput */ function parseSecretsInput(secretsInput) { const secrets = secretsInput @@ -3830,7 +4184,7 @@ function parseSecretsInput(secretsInput) { } /** - * Replaces any forward-slash characters to + * Replaces any forward-slash characters to * @param {string} dataKey */ function normalizeOutputKey(dataKey) { @@ -3846,415 +4200,328 @@ module.exports = { /***/ }), -/***/ 761: -/***/ (function(module) { - -module.exports = require("zlib"); - -/***/ }), - -/***/ 774: +/***/ 753: /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -const urlLib = __webpack_require__(835); -const http = __webpack_require__(605); -const PCancelable = __webpack_require__(557); -const is = __webpack_require__(534); - -class GotError extends Error { - constructor(message, error, options) { - super(message); - Error.captureStackTrace(this, this.constructor); - this.name = 'GotError'; - - if (!is.undefined(error.code)) { - this.code = error.code; - } +const {Resolver, V4MAPPED, ADDRCONFIG} = __webpack_require__(881); +const {promisify} = __webpack_require__(669); +const os = __webpack_require__(87); +const Keyv = __webpack_require__(303); - Object.assign(this, { - host: options.host, - hostname: options.hostname, - method: options.method, - path: options.path, - socketPath: options.socketPath, - protocol: options.protocol, - url: options.href, - gotOptions: options - }); +const map4to6 = entries => { + for (const entry of entries) { + entry.address = `::ffff:${entry.address}`; + entry.family = 6; } -} +}; -module.exports.GotError = GotError; +const getIfaceInfo = () => { + let has4 = false; + let has6 = false; -module.exports.CacheError = class extends GotError { - constructor(error, options) { - super(error.message, error, options); - this.name = 'CacheError'; - } -}; + for (const device of Object.values(os.networkInterfaces())) { + for (const iface of device) { + if (iface.internal) { + continue; + } -module.exports.RequestError = class extends GotError { - constructor(error, options) { - super(error.message, error, options); - this.name = 'RequestError'; - } -}; + if (iface.family === 'IPv6') { + has6 = true; + } else { + has4 = true; + } -module.exports.ReadError = class extends GotError { - constructor(error, options) { - super(error.message, error, options); - this.name = 'ReadError'; + if (has4 && has6) { + break; + } + } } -}; -module.exports.ParseError = class extends GotError { - constructor(error, statusCode, options, data) { - super(`${error.message} in "${urlLib.format(options)}": \n${data.slice(0, 77)}...`, error, options); - this.name = 'ParseError'; - this.statusCode = statusCode; - this.statusMessage = http.STATUS_CODES[this.statusCode]; - } + return {has4, has6}; }; -module.exports.HTTPError = class extends GotError { - constructor(response, options) { - const {statusCode} = response; - let {statusMessage} = response; +class CacheableLookup { + constructor(options = {}) { + const {cacheAdapter} = options; + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cached-lookup' + }); - if (statusMessage) { - statusMessage = statusMessage.replace(/\r?\n/g, ' ').trim(); - } else { - statusMessage = http.STATUS_CODES[statusCode]; - } + this.maxTtl = options.maxTtl === 0 ? 0 : (options.maxTtl || Infinity); - super(`Response code ${statusCode} (${statusMessage})`, {}, options); - this.name = 'HTTPError'; - this.statusCode = statusCode; - this.statusMessage = statusMessage; - this.headers = response.headers; - this.body = response.body; - } -}; + this._resolver = options.resolver || new Resolver(); + this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); + this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); -module.exports.MaxRedirectsError = class extends GotError { - constructor(statusCode, redirectUrls, options) { - super('Redirected 10 times. Aborting.', {}, options); - this.name = 'MaxRedirectsError'; - this.statusCode = statusCode; - this.statusMessage = http.STATUS_CODES[this.statusCode]; - this.redirectUrls = redirectUrls; + this.lookup = this.lookup.bind(this); + this.lookupAsync = this.lookupAsync.bind(this); } -}; -module.exports.UnsupportedProtocolError = class extends GotError { - constructor(options) { - super(`Unsupported protocol "${options.protocol}"`, {}, options); - this.name = 'UnsupportedProtocolError'; + set servers(servers) { + this._resolver.setServers(servers); } -}; -module.exports.TimeoutError = class extends GotError { - constructor(error, options) { - super(error.message, {code: 'ETIMEDOUT'}, options); - this.name = 'TimeoutError'; - this.event = error.event; + get servers() { + return this._resolver.getServers(); } -}; - -module.exports.CancelError = PCancelable.CancelError; - - -/***/ }), - -/***/ 794: -/***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; - -const {PassThrough} = __webpack_require__(413); -const duplexer3 = __webpack_require__(718); -const requestAsEventEmitter = __webpack_require__(584); -const {HTTPError, ReadError} = __webpack_require__(774); - -module.exports = options => { - const input = new PassThrough(); - const output = new PassThrough(); - const proxy = duplexer3(input, output); - const piped = new Set(); - let isFinished = false; - - options.retry.retries = () => 0; + lookup(hostname, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } - if (options.body) { - proxy.write = () => { - throw new Error('Got\'s stream is not writable when the `body` option is used'); - }; + this.lookupAsync(hostname, {...options, throwNotFound: true}).then(result => { + if (options.all) { + callback(null, result); + } else { + callback(null, result.address, result.family); + } + }).catch(callback); } - const emitter = requestAsEventEmitter(options, input); - - // Cancels the request - proxy._destroy = emitter.abort; - - emitter.on('response', response => { - const {statusCode} = response; + async lookupAsync(hostname, options = {}) { + let cached; + if (!options.family && options.all) { + const [cached4, cached6] = await Promise.all([this.lookupAsync(hostname, {all: true, family: 4, details: true}), this.lookupAsync(hostname, {all: true, family: 6, details: true})]); + cached = [...cached4, ...cached6]; + } else { + cached = await this.query(hostname, options.family || 4); - response.on('error', error => { - proxy.emit('error', new ReadError(error, options)); - }); + if (cached.length === 0 && options.family === 6 && options.hints & V4MAPPED) { + cached = await this.query(hostname, 4); + map4to6(cached); + } + } - if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) { - proxy.emit('error', new HTTPError(response, options), null, response); - return; + if (options.hints & ADDRCONFIG) { + const {has4, has6} = getIfaceInfo(); + cached = cached.filter(entry => entry.family === 6 ? has6 : has4); } - isFinished = true; + if (options.throwNotFound && cached.length === 0) { + const error = new Error(`ENOTFOUND ${hostname}`); + error.code = 'ENOTFOUND'; + error.hostname = hostname; - response.pipe(output); + throw error; + } - for (const destination of piped) { - if (destination.headersSent) { - continue; - } + const now = Date.now(); - for (const [key, value] of Object.entries(response.headers)) { - // Got gives *decompressed* data. Overriding `content-encoding` header would result in an error. - // It's not possible to decompress already decompressed data, is it? - const allowed = options.decompress ? key !== 'content-encoding' : true; - if (allowed) { - destination.setHeader(key, value); - } - } + cached = cached.filter(entry => !Reflect.has(entry, 'expires') || now < entry.expires); - destination.statusCode = response.statusCode; + if (!options.details) { + cached = cached.map(entry => { + return { + address: entry.address, + family: entry.family + }; + }); } - proxy.emit('response', response); - }); + if (options.all) { + return cached; + } - [ - 'error', - 'request', - 'redirect', - 'uploadProgress', - 'downloadProgress' - ].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args))); - - const pipe = proxy.pipe.bind(proxy); - const unpipe = proxy.unpipe.bind(proxy); - proxy.pipe = (destination, options) => { - if (isFinished) { - throw new Error('Failed to pipe. The response has been emitted already.'); + if (cached.length === 0) { + return undefined; } - const result = pipe(destination, options); + return this._getEntry(cached); + } - if (Reflect.has(destination, 'setHeader')) { - piped.add(destination); + async query(hostname, family) { + let cached = await this.cache.get(`${hostname}:${family}`); + if (!cached) { + cached = await this.queryAndCache(hostname, family); } - return result; - }; + return cached; + } - proxy.unpipe = stream => { - piped.delete(stream); - return unpipe(stream); - }; + async queryAndCache(hostname, family) { + const resolve = family === 4 ? this._resolve4 : this._resolve6; + const entries = await resolve(hostname, {ttl: true}); - return proxy; -}; + if (entries === undefined) { + return []; + } + const now = Date.now(); -/***/ }), + let cacheTtl = 0; + for (const entry of entries) { + cacheTtl = Math.max(cacheTtl, entry.ttl); + entry.family = family; -/***/ 798: -/***/ (function(module, __unusedexports, __webpack_require__) { + if (entry.ttl !== 0) { + entry.expires = now + (entry.ttl * 1000); + } + } -"use strict"; + cacheTtl = Math.min(this.maxTtl, cacheTtl) * 1000; -const pkg = __webpack_require__(482); -const create = __webpack_require__(338); + if (this.maxTtl !== 0 && cacheTtl !== 0) { + await this.cache.set(`${hostname}:${family}`, entries, cacheTtl); + } -const defaults = { - options: { - retry: { - retries: 2, - methods: [ - 'GET', - 'PUT', - 'HEAD', - 'DELETE', - 'OPTIONS', - 'TRACE' - ], - statusCodes: [ - 408, - 413, - 429, - 500, - 502, - 503, - 504 - ], - errorCodes: [ - 'ETIMEDOUT', - 'ECONNRESET', - 'EADDRINUSE', - 'ECONNREFUSED', - 'EPIPE', - 'ENOTFOUND', - 'ENETUNREACH', - 'EAI_AGAIN' - ] - }, - headers: { - 'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)` - }, - hooks: { - beforeRequest: [], - beforeRedirect: [], - beforeRetry: [], - afterResponse: [] - }, - decompress: true, - throwHttpErrors: true, - followRedirect: true, - stream: false, - form: false, - json: false, - cache: false, - useElectronNet: false - }, - mutableDefaults: false -}; + return entries; + } -const got = create(defaults); + _getEntry(entries) { + return entries[Math.floor(Math.random() * entries.length)]; + } +} -module.exports = got; +module.exports = CacheableLookup; +module.exports.default = CacheableLookup; /***/ }), -/***/ 811: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const is = __webpack_require__(534); +/***/ 761: +/***/ (function(module) { -module.exports = url => { - const options = { - protocol: url.protocol, - hostname: url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - href: url.href - }; +module.exports = require("zlib"); - if (is.string(url.port) && url.port.length > 0) { - options.port = Number(url.port); - } +/***/ }), - if (url.username || url.password) { - options.auth = `${url.username}:${url.password}`; - } +/***/ 766: +/***/ (function(__unusedmodule, exports) { - options.path = is.null(url.search) ? url.pathname : `${url.pathname}${url.search}`; +"use strict"; - return options; -}; +Object.defineProperty(exports, "__esModule", { value: true }); +const knownHookEvents = [ + 'beforeError', + 'init', + 'beforeRequest', + 'beforeRedirect', + 'beforeRetry', + 'afterResponse' +]; +exports.default = knownHookEvents; /***/ }), -/***/ 821: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 818: +/***/ (function(module) { -"use strict"; +module.exports = require("tls"); -const {URL} = __webpack_require__(835); -const is = __webpack_require__(534); -const knownHookEvents = __webpack_require__(433); +/***/ }), -const merge = (target, ...sources) => { - for (const source of sources) { - for (const [key, sourceValue] of Object.entries(source)) { - if (is.undefined(sourceValue)) { - continue; - } +/***/ 835: +/***/ (function(module) { - const targetValue = target[key]; - if (is.urlInstance(targetValue) && (is.urlInstance(sourceValue) || is.string(sourceValue))) { - target[key] = new URL(sourceValue, targetValue); - } else if (is.plainObject(sourceValue)) { - if (is.plainObject(targetValue)) { - target[key] = merge({}, targetValue, sourceValue); - } else { - target[key] = merge({}, sourceValue); - } - } else if (is.array(sourceValue)) { - target[key] = merge([], sourceValue); - } else { - target[key] = sourceValue; - } - } - } +module.exports = require("url"); - return target; -}; +/***/ }), -const mergeOptions = (...sources) => { - sources = sources.map(source => source || {}); - const merged = merge({}, ...sources); +/***/ 839: +/***/ (function(__unusedmodule, exports) { - const hooks = {}; - for (const hook of knownHookEvents) { - hooks[hook] = []; - } +"use strict"; - for (const source of sources) { - if (source.hooks) { - for (const hook of knownHookEvents) { - hooks[hook] = hooks[hook].concat(source.hooks[hook]); - } - } - } +Object.defineProperty(exports, "__esModule", { value: true }); +exports.requestSymbol = Symbol('request'); - merged.hooks = hooks; - return merged; -}; +/***/ }), -const mergeInstances = (instances, methods) => { - const handlers = instances.map(instance => instance.defaults.handler); - const size = instances.length - 1; +/***/ 856: +/***/ (function(__unusedmodule, exports, __webpack_require__) { - return { - methods, - options: mergeOptions(...instances.map(instance => instance.defaults.options)), - handler: (options, next) => { - let iteration = -1; - const iterate = options => handlers[++iteration](options, iteration === size ? next : iterate); +"use strict"; - return iterate(options); - } - }; +Object.defineProperty(exports, "__esModule", { value: true }); +const url_1 = __webpack_require__(835); +function validateSearchParams(searchParams) { + for (const value of Object.values(searchParams)) { + if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' && value !== null) { + throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); + } + } +} +const keys = [ + 'protocol', + 'username', + 'password', + 'host', + 'hostname', + 'port', + 'pathname', + 'search', + 'hash' +]; +exports.default = (options) => { + var _a, _b; + let origin; + if (options.path) { + if (options.pathname) { + throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.'); + } + if (options.search) { + throw new TypeError('Parameters `path` and `search` are mutually exclusive.'); + } + if (options.searchParams) { + throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.'); + } + } + if (Reflect.has(options, 'auth')) { + throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.'); + } + if (options.search && options.searchParams) { + throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.'); + } + if (options.href) { + return new url_1.URL(options.href); + } + if (options.origin) { + origin = options.origin; + } + else { + if (!options.protocol) { + throw new TypeError('No URL protocol specified'); + } + origin = `${options.protocol}//${_b = (_a = options.hostname, (_a !== null && _a !== void 0 ? _a : options.host)), (_b !== null && _b !== void 0 ? _b : '')}`; + } + const url = new url_1.URL(origin); + if (options.path) { + const searchIndex = options.path.indexOf('?'); + if (searchIndex === -1) { + options.pathname = options.path; + } + else { + options.pathname = options.path.slice(0, searchIndex); + options.search = options.path.slice(searchIndex + 1); + } + } + if (Reflect.has(options, 'path')) { + delete options.path; + } + for (const key of keys) { + if (Reflect.has(options, key)) { + url[key] = options[key].toString(); + } + } + if (options.searchParams) { + if (typeof options.searchParams !== 'string' && !(options.searchParams instanceof url_1.URLSearchParams)) { + validateSearchParams(options.searchParams); + } + (new url_1.URLSearchParams(options.searchParams)).forEach((value, key) => { + url.searchParams.append(key, value); + }); + } + return url; }; -module.exports = merge; -module.exports.options = mergeOptions; -module.exports.instances = mergeInstances; - - -/***/ }), - -/***/ 835: -/***/ (function(module) { - -module.exports = require("url"); /***/ }), @@ -4263,151 +4530,444 @@ module.exports = require("url"); "use strict"; -const PassThrough = __webpack_require__(413).PassThrough; +const { + pipeline: streamPipeline, + PassThrough: PassThroughStream +} = __webpack_require__(413); const zlib = __webpack_require__(761); const mimicResponse = __webpack_require__(89); -module.exports = response => { - // TODO: Use Array#includes when targeting Node.js 6 - if (['gzip', 'deflate'].indexOf(response.headers['content-encoding']) === -1) { +const decompressResponse = response => { + const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); + + if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { return response; } - const unzip = zlib.createUnzip(); - const stream = new PassThrough(); + // TODO: Remove this when targeting Node.js 12. + const isBrotli = contentEncoding === 'br'; + if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { + return response; + } - mimicResponse(response, stream); + const decompress = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); + const stream = new PassThroughStream(); - unzip.on('error', err => { - if (err.code === 'Z_BUF_ERROR') { + decompress.on('error', error => { + // Ignore empty response + if (error.code === 'Z_BUF_ERROR') { stream.end(); return; } - stream.emit('error', err); + stream.emit('error', error); }); - response.pipe(unzip).pipe(stream); + const finalStream = streamPipeline(response, decompress, stream, () => {}); - return stream; + mimicResponse(response, finalStream); + + return finalStream; }; +module.exports = decompressResponse; + /***/ }), -/***/ 916: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 872: +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const CacheableRequest = __webpack_require__(946); const EventEmitter = __webpack_require__(614); -const getStream = __webpack_require__(145); -const is = __webpack_require__(534); -const PCancelable = __webpack_require__(557); -const requestAsEventEmitter = __webpack_require__(584); -const {HTTPError, ParseError, ReadError} = __webpack_require__(774); -const {options: mergeOptions} = __webpack_require__(821); -const {reNormalize} = __webpack_require__(86); - -const asPromise = options => { - const proxy = new EventEmitter(); - - const promise = new PCancelable((resolve, reject, onCancel) => { - const emitter = requestAsEventEmitter(options); - - onCancel(emitter.abort); - - emitter.on('response', async response => { - proxy.emit('response', response); - - const stream = is.null(options.encoding) ? getStream.buffer(response) : getStream(response, options); - - let data; - try { - data = await stream; - } catch (error) { - reject(new ReadError(error, options)); - return; - } - - const limitStatusCode = options.followRedirect ? 299 : 399; - - response.body = data; - - try { - for (const [index, hook] of Object.entries(options.hooks.afterResponse)) { - // eslint-disable-next-line no-await-in-loop - response = await hook(response, updatedOptions => { - updatedOptions = reNormalize(mergeOptions(options, { - ...updatedOptions, - retry: 0, - throwHttpErrors: false - })); - - // Remove any further hooks for that request, because we we'll call them anyway. - // The loop continues. We don't want duplicates (asPromise recursion). - updatedOptions.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); - - return asPromise(updatedOptions); - }); - } - } catch (error) { - reject(error); - return; - } - - const {statusCode} = response; +const http = __webpack_require__(605); +const stream = __webpack_require__(413); +const url_1 = __webpack_require__(835); +const util_1 = __webpack_require__(669); +const is_1 = __webpack_require__(534); +const http_timer_1 = __webpack_require__(895); +const calculate_retry_delay_1 = __webpack_require__(678); +const errors_1 = __webpack_require__(378); +const get_response_1 = __webpack_require__(234); +const normalize_arguments_1 = __webpack_require__(110); +const progress_1 = __webpack_require__(489); +const timed_out_1 = __webpack_require__(215); +const types_1 = __webpack_require__(839); +const url_to_options_1 = __webpack_require__(278); +const setImmediateAsync = async () => new Promise(resolve => setImmediate(resolve)); +const pipeline = util_1.promisify(stream.pipeline); +const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +exports.default = (options) => { + const emitter = new EventEmitter(); + const requestURL = options.url.toString(); + const redirects = []; + let retryCount = 0; + let currentRequest; + // `request.aborted` is a boolean since v11.0.0: https://github.com/nodejs/node/commit/4b00c4fafaa2ae8c41c1f78823c0feb810ae4723#diff-e3bc37430eb078ccbafe3aa3b570c91a + const isAborted = () => typeof currentRequest.aborted === 'number' || currentRequest.aborted; + const emitError = async (error) => { + try { + for (const hook of options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + emitter.emit('error', error); + } + catch (error_) { + emitter.emit('error', error_); + } + }; + const get = async () => { + let httpOptions = await normalize_arguments_1.normalizeRequestArguments(options); + const handleResponse = async (response) => { + var _a; + try { + /* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */ + if (options.useElectronNet) { + response = new Proxy(response, { + get: (target, name) => { + if (name === 'trailers' || name === 'rawTrailers') { + return []; + } + const value = target[name]; + return is_1.default.function_(value) ? value.bind(target) : value; + } + }); + } + const typedResponse = response; + const { statusCode } = typedResponse; + typedResponse.statusMessage = is_1.default.nonEmptyString(typedResponse.statusMessage) ? typedResponse.statusMessage : http.STATUS_CODES[statusCode]; + typedResponse.url = options.url.toString(); + typedResponse.requestUrl = requestURL; + typedResponse.retryCount = retryCount; + typedResponse.redirectUrls = redirects; + typedResponse.request = { options }; + typedResponse.isFromCache = (_a = typedResponse.fromCache, (_a !== null && _a !== void 0 ? _a : false)); + delete typedResponse.fromCache; + if (!typedResponse.isFromCache) { + typedResponse.ip = response.socket.remoteAddress; + } + const rawCookies = typedResponse.headers['set-cookie']; + if (Reflect.has(options, 'cookieJar') && rawCookies) { + let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, typedResponse.url)); + if (options.ignoreInvalidCookies) { + promises = promises.map(async (p) => p.catch(() => { })); + } + await Promise.all(promises); + } + if (options.followRedirect && Reflect.has(typedResponse.headers, 'location') && redirectCodes.has(statusCode)) { + typedResponse.resume(); // We're being redirected, we don't care about the response. + if (statusCode === 303 || options.methodRewriting === false) { + if (options.method !== 'GET' && options.method !== 'HEAD') { + // Server responded with "see other", indicating that the resource exists at another location, + // and the client should request it from that location via GET or HEAD. + options.method = 'GET'; + } + if (Reflect.has(options, 'body')) { + delete options.body; + } + if (Reflect.has(options, 'json')) { + delete options.json; + } + if (Reflect.has(options, 'form')) { + delete options.form; + } + } + if (redirects.length >= options.maxRedirects) { + throw new errors_1.MaxRedirectsError(typedResponse, options.maxRedirects, options); + } + // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 + const redirectBuffer = Buffer.from(typedResponse.headers.location, 'binary').toString(); + const redirectURL = new url_1.URL(redirectBuffer, options.url); + // Redirecting to a different site, clear cookies. + if (redirectURL.hostname !== options.url.hostname && Reflect.has(options.headers, 'cookie')) { + delete options.headers.cookie; + } + redirects.push(redirectURL.toString()); + options.url = redirectURL; + for (const hook of options.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(options, typedResponse); + } + emitter.emit('redirect', response, options); + await get(); + return; + } + await get_response_1.default(typedResponse, options, emitter); + } + catch (error) { + emitError(error); + } + }; + const handleRequest = async (request) => { + let isPiped = false; + let isFinished = false; + // `request.finished` doesn't indicate whether this has been emitted or not + request.once('finish', () => { + isFinished = true; + }); + currentRequest = request; + const onError = (error) => { + if (error instanceof timed_out_1.TimeoutError) { + error = new errors_1.TimeoutError(error, request.timings, options); + } + else { + error = new errors_1.RequestError(error, options); + } + if (!emitter.retry(error)) { + emitError(error); + } + }; + request.on('error', error => { + if (isPiped) { + // Check if it's caught by `stream.pipeline(...)` + if (!isFinished) { + return; + } + // We need to let `TimedOutTimeoutError` through, because `stream.pipeline(…)` aborts the request automatically. + if (isAborted() && !(error instanceof timed_out_1.TimeoutError)) { + return; + } + } + onError(error); + }); + try { + http_timer_1.default(request); + timed_out_1.default(request, options.timeout, options.url); + emitter.emit('request', request); + const uploadStream = progress_1.createProgressStream('uploadProgress', emitter, httpOptions.headers['content-length']); + isPiped = true; + await pipeline(httpOptions.body, uploadStream, request); + request.emit('upload-complete'); + } + catch (error) { + if (isAborted() && error.message === 'Premature close') { + // The request was aborted on purpose + return; + } + onError(error); + } + }; + if (options.cache) { + // `cacheable-request` doesn't support Node 10 API, fallback. + httpOptions = { + ...httpOptions, + ...url_to_options_1.default(options.url) + }; + // @ts-ignore `cacheable-request` has got invalid types + const cacheRequest = options.cacheableRequest(httpOptions, handleResponse); + cacheRequest.once('error', (error) => { + if (error instanceof CacheableRequest.RequestError) { + emitError(new errors_1.RequestError(error, options)); + } + else { + emitError(new errors_1.CacheError(error, options)); + } + }); + cacheRequest.once('request', handleRequest); + } + else { + // Catches errors thrown by calling `requestFn(…)` + try { + handleRequest(httpOptions[types_1.requestSymbol](options.url, httpOptions, handleResponse)); + } + catch (error) { + emitError(new errors_1.RequestError(error, options)); + } + } + }; + emitter.retry = error => { + let backoff; + retryCount++; + try { + backoff = options.retry.calculateDelay({ + attemptCount: retryCount, + retryOptions: options.retry, + error, + computedValue: calculate_retry_delay_1.default({ + attemptCount: retryCount, + retryOptions: options.retry, + error, + computedValue: 0 + }) + }); + } + catch (error_) { + emitError(error_); + return false; + } + if (backoff) { + const retry = async (options) => { + try { + for (const hook of options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(options, error, retryCount); + } + await get(); + } + catch (error_) { + emitError(error_); + } + }; + setTimeout(retry, backoff, { ...options, forceRefresh: true }); + return true; + } + return false; + }; + emitter.abort = () => { + emitter.prependListener('request', (request) => { + request.abort(); + }); + if (currentRequest) { + currentRequest.abort(); + } + }; + (async () => { + // Promises are executed immediately. + // If there were no `setImmediate` here, + // `promise.json()` would have no effect + // as the request would be sent already. + await setImmediateAsync(); + try { + for (const hook of options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + await hook(options); + } + await get(); + } + catch (error) { + emitError(error); + } + })(); + return emitter; +}; +exports.proxyEvents = (proxy, emitter) => { + const events = [ + 'request', + 'redirect', + 'uploadProgress', + 'downloadProgress' + ]; + for (const event of events) { + emitter.on(event, (...args) => { + proxy.emit(event, ...args); + }); + } +}; - if (options.json && response.body) { - try { - response.body = JSON.parse(response.body); - } catch (error) { - if (statusCode >= 200 && statusCode < 300) { - const parseError = new ParseError(error, statusCode, options, data); - Object.defineProperty(parseError, 'response', {value: response}); - reject(parseError); - return; - } - } - } - if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) { - const error = new HTTPError(response, options); - Object.defineProperty(error, 'response', {value: response}); - if (emitter.retry(error) === false) { - if (options.throwHttpErrors) { - reject(error); - return; - } +/***/ }), - resolve(response); - } +/***/ 881: +/***/ (function(module) { - return; - } +module.exports = require("dns"); - resolve(response); - }); +/***/ }), - emitter.once('error', reject); - [ - 'request', - 'redirect', - 'uploadProgress', - 'downloadProgress' - ].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args))); - }); +/***/ 895: +/***/ (function(module, exports, __webpack_require__) { - promise.on = (name, fn) => { - proxy.on(name, fn); - return promise; - }; +"use strict"; - return promise; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - -module.exports = asPromise; - +Object.defineProperty(exports, "__esModule", { value: true }); +const defer_to_connect_1 = __importDefault(__webpack_require__(958)); +const timer = (request) => { + const timings = { + start: Date.now(), + socket: undefined, + lookup: undefined, + connect: undefined, + secureConnect: undefined, + upload: undefined, + response: undefined, + end: undefined, + error: undefined, + abort: undefined, + phases: { + wait: undefined, + dns: undefined, + tcp: undefined, + tls: undefined, + request: undefined, + firstByte: undefined, + download: undefined, + total: undefined + } + }; + request.timings = timings; + const handleError = (origin) => { + const emit = origin.emit.bind(origin); + origin.emit = (event, ...args) => { + // Catches the `error` event + if (event === 'error') { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + origin.emit = emit; + } + // Saves the original behavior + return emit(event, ...args); + }; + }; + handleError(request); + request.prependOnceListener('abort', () => { + timings.abort = Date.now(); + timings.phases.total = Date.now() - timings.start; + }); + request.prependOnceListener('socket', (socket) => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + socket.prependOnceListener('lookup', lookupListener); + defer_to_connect_1.default(socket, { + connect: () => { + timings.connect = Date.now(); + if (timings.lookup === undefined) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + timings.phases.tcp = timings.connect - timings.lookup; + // This callback is called before flushing any data, + // so we don't need to set `timings.phases.request` here. + }, + secureConnect: () => { + timings.secureConnect = Date.now(); + timings.phases.tls = timings.secureConnect - timings.connect; + } + }); + }); + request.prependOnceListener('finish', () => { + timings.upload = Date.now(); + timings.phases.request = timings.upload - (timings.secureConnect || timings.connect); + }); + request.prependOnceListener('response', (response) => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + response.timings = timings; + handleError(response); + response.prependOnceListener('end', () => { + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + }); + return timings; +}; +exports.default = timer; +// For CommonJS default export support +module.exports = timer; +module.exports.default = timer; +//# sourceMappingURL=index.js.map /***/ }), @@ -4423,7 +4983,7 @@ const normalizeUrl = __webpack_require__(53); const getStream = __webpack_require__(16); const CachePolicy = __webpack_require__(154); const Response = __webpack_require__(93); -const lowercaseKeys = __webpack_require__(97); +const lowercaseKeys = __webpack_require__(474); const cloneResponse = __webpack_require__(325); const Keyv = __webpack_require__(303); @@ -4675,10 +5235,10 @@ module.exports = CacheableRequest; "use strict"; -const {Readable} = __webpack_require__(413); +const {Readable: ReadableStream} = __webpack_require__(413); -module.exports = input => ( - new Readable({ +const toReadableStream = input => ( + new ReadableStream({ read() { this.push(input); this.push(null); @@ -4686,66 +5246,86 @@ module.exports = input => ( }) ); +module.exports = toReadableStream; +// TODO: Remove this for the next major release +module.exports.default = toReadableStream; + /***/ }), -/***/ 966: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 958: +/***/ (function(module, exports, __webpack_require__) { "use strict"; -const {PassThrough} = __webpack_require__(413); - -module.exports = options => { - options = Object.assign({}, options); - - const {array} = options; - let {encoding} = options; - const buffer = encoding === 'buffer'; - let objectMode = false; - - if (array) { - objectMode = !(encoding || buffer); - } else { - encoding = encoding || 'utf8'; - } - - if (buffer) { - encoding = null; - } - - let len = 0; - const ret = []; - const stream = new PassThrough({objectMode}); - - if (encoding) { - stream.setEncoding(encoding); - } - - stream.on('data', chunk => { - ret.push(chunk); - - if (objectMode) { - len = ret.length; - } else { - len += chunk.length; - } - }); - - stream.getBufferedValue = () => { - if (array) { - return ret; - } - - return buffer ? Buffer.concat(ret, len) : ret.join(''); - }; - - stream.getBufferedLength = () => len; - - return stream; +Object.defineProperty(exports, "__esModule", { value: true }); +const tls_1 = __webpack_require__(818); +const deferToConnect = (socket, fn) => { + let listeners; + if (typeof fn === 'function') { + const connect = fn; + listeners = { connect }; + } + else { + listeners = fn; + } + const hasConnectListener = typeof listeners.connect === 'function'; + const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; + const hasCloseListener = typeof listeners.close === 'function'; + const onConnect = () => { + if (hasConnectListener) { + listeners.connect(); + } + if (socket instanceof tls_1.TLSSocket && hasSecureConnectListener) { + if (socket.authorized) { + listeners.secureConnect(); + } + else if (!socket.authorizationError) { + socket.once('secureConnect', listeners.secureConnect); + } + } + if (hasCloseListener) { + socket.once('close', listeners.close); + } + }; + if (socket.writable && !socket.connecting) { + onConnect(); + } + else if (socket.connecting) { + socket.once('connect', onConnect); + } + else if (socket.destroyed && hasCloseListener) { + listeners.close(socket._hadError); + } }; +exports.default = deferToConnect; +// For CommonJS default export support +module.exports = deferToConnect; +module.exports.default = deferToConnect; /***/ }) -/******/ }); \ No newline at end of file +/******/ }, +/******/ function(__webpack_require__) { // webpackRuntimeModules +/******/ "use strict"; +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ !function() { +/******/ __webpack_require__.nmd = function(module) { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ Object.defineProperty(module, 'loaded', { +/******/ enumerable: true, +/******/ get: function() { return module.l; } +/******/ }); +/******/ Object.defineProperty(module, 'id', { +/******/ enumerable: true, +/******/ get: function() { return module.i; } +/******/ }); +/******/ return module; +/******/ }; +/******/ }(); +/******/ +/******/ } +); \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index ef01eca1..bc5de24a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,5 +13,5 @@ services: environment: VAULT_DEV_ROOT_TOKEN_ID: testtoken ports: - - 8201:8201 + - 8201:8200 privileged: true \ No newline at end of file diff --git a/integrationTests/basic/integration.test.js b/integrationTests/basic/integration.test.js index d440a2b4..70f9ce1b 100644 --- a/integrationTests/basic/integration.test.js +++ b/integrationTests/basic/integration.test.js @@ -23,12 +23,11 @@ describe('integration', () => { headers: { 'X-Vault-Token': 'testtoken', }, - body: { + json: { data: { secret: 'SUPERSECRET', }, }, - json: true, }); await got(`${vaultUrl}/v1/secret/data/nested/test`, { @@ -36,12 +35,11 @@ describe('integration', () => { headers: { 'X-Vault-Token': 'testtoken', }, - body: { + json: { data: { otherSecret: 'OTHERSUPERSECRET', }, }, - json: true, }); }); diff --git a/integrationTests/e2e/setup.js b/integrationTests/e2e/setup.js index 8abe9a39..f81e4123 100644 --- a/integrationTests/e2e/setup.js +++ b/integrationTests/e2e/setup.js @@ -14,12 +14,11 @@ const got = require('got'); headers: { 'X-Vault-Token': 'testtoken', }, - body: { + json: { data: { secret: 'SUPERSECRET', }, }, - json: true, }); await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/data/nested/test`, { @@ -27,12 +26,11 @@ const got = require('got'); headers: { 'X-Vault-Token': 'testtoken', }, - body: { + json: { data: { otherSecret: 'OTHERSUPERSECRET', }, }, - json: true, }); } catch (error) { console.log(error); diff --git a/integrationTests/enterprise/enterprise.test.js b/integrationTests/enterprise/enterprise.test.js index a77c95d3..9c69d089 100644 --- a/integrationTests/enterprise/enterprise.test.js +++ b/integrationTests/enterprise/enterprise.test.js @@ -11,60 +11,61 @@ const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env. describe('integration', () => { beforeAll(async () => { - // Verify Connection - await got(`${vaultUrl}/v1/secret/config`, { - headers: { - 'X-Vault-Token': 'testtoken', - }, - }); - - // Create namespace - await got(`${vaultUrl}/v1/sys/namespaces/ns1`, { - method: 'POST', - headers: { - 'X-Vault-Token': 'testtoken', - }, - json: true, - }); - - // Enable secret engine - await got(`${vaultUrl}/v1/sys/mounts/secret`, { - method: 'POST', - headers: { - 'X-Vault-Token': 'testtoken', - 'X-Vault-Namespace': 'ns1', - }, - body: { path: 'secret', type: 'kv', config: {}, options: { version: 2 }, generate_signing_key: true }, - json: true, - }); - - await got(`${vaultUrl}/v1/secret/data/test`, { - method: 'POST', - headers: { - 'X-Vault-Token': 'testtoken', - 'X-Vault-Namespace': 'ns1', - }, - body: { - data: { - secret: 'SUPERSECRET_IN_NAMESPACE', - }, - }, - json: true, - }); - - await got(`${vaultUrl}/v1/secret/data/nested/test`, { - method: 'POST', - headers: { - 'X-Vault-Token': 'testtoken', - 'X-Vault-Namespace': 'ns1', - }, - body: { - data: { - otherSecret: 'OTHERSUPERSECRET_IN_NAMESPACE', - }, - }, - json: true, - }); + try { + // Verify Connection + await got(`${vaultUrl}/v1/secret/config`, { + headers: { + 'X-Vault-Token': 'testtoken', + }, + }); + + // Create namespace + await got(`${vaultUrl}/v1/sys/namespaces/ns1`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + } + }); + + // Enable secret engine + await got(`${vaultUrl}/v1/sys/mounts/secret`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns1', + }, + json: { path: 'secret', type: 'kv', config: {}, options: { version: 2 }, generate_signing_key: true }, + }); + + await got(`${vaultUrl}/v1/secret/data/test`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns1', + }, + json: { + data: { + secret: 'SUPERSECRET_IN_NAMESPACE', + }, + }, + }); + + await got(`${vaultUrl}/v1/secret/data/nested/test`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns1', + }, + json: { + data: { + otherSecret: 'OTHERSUPERSECRET_IN_NAMESPACE', + }, + }, + }); + } catch (e) { + console.error('Failed to setup test', e); + throw e; + } }); beforeEach(() => { @@ -128,3 +129,145 @@ describe('integration', () => { expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET_IN_NAMESPACE'); }); }); + +describe('authenticate with approle', () => { + let roleId; + let secretId; + beforeAll(async () => { + try { + // Verify Connection + await got(`${vaultUrl}/v1/secret/config`, { + headers: { + 'X-Vault-Token': 'testtoken', + }, + }); + + // Create namespace + await got(`${vaultUrl}/v1/sys/namespaces/ns2`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + }, + }); + + // Enable secret engine + await got(`${vaultUrl}/v1/sys/mounts/secret`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + json: { path: 'secret', type: 'kv', config: {}, options: { version: 2 }, generate_signing_key: true }, + }); + + // Add secret + await got(`${vaultUrl}/v1/secret/data/test`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + json: { + data: { + secret: 'SUPERSECRET_WITH_APPROLE', + }, + }, + }); + + // Enable approle + await got(`${vaultUrl}/v1/sys/auth/approle`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + json: { + type: 'approle' + }, + }); + + // Create policies + await got(`${vaultUrl}/v1/sys/policies/acl/test`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + json: { + "name":"test", + "policy":"path \"auth/approle/*\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"auth/approle/role/my-role/role-id\"\n{\n capabilities = [\"create\", \"read\", \"update\", \"delete\", \"list\"]\n}\npath \"auth/approle/role/my-role/secret-id\"\n{\n capabilities = [\"create\", \"read\", \"update\", \"delete\", \"list\"]\n}\n\npath \"secret/data/*\" {\n capabilities = [\"list\"]\n}\npath \"secret/metadata/*\" {\n capabilities = [\"list\"]\n}\n\npath \"secret/data/test\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/metadata/test\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/data/test/*\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/metadata/test/*\" {\n capabilities = [\"read\", \"list\"]\n}\n" + }, + }); + + // Create approle + await got(`${vaultUrl}/v1/auth/approle/role/my-role`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + json: { + policies: 'test' + }, + }); + + // Get role-id + const roldIdResponse = await got(`${vaultUrl}/v1/auth/approle/role/my-role/role-id`, { + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + responseType: 'json', + }); + roleId = roldIdResponse.body.data.role_id; + + // Get secret-id + const secretIdResponse = await got(`${vaultUrl}/v1/auth/approle/role/my-role/secret-id`, { + method: 'POST', + headers: { + 'X-Vault-Token': 'testtoken', + 'X-Vault-Namespace': 'ns2', + }, + responseType: 'json', + }); + secretId = secretIdResponse.body.data.secret_id; + } catch(err) { + console.warn('Create approle', err); + throw err; + } + }); + + beforeEach(() => { + jest.resetAllMocks(); + + when(core.getInput) + .calledWith('method') + .mockReturnValue('approle'); + when(core.getInput) + .calledWith('roleId') + .mockReturnValue(roleId); + when(core.getInput) + .calledWith('secretId') + .mockReturnValue(secretId); + when(core.getInput) + .calledWith('url') + .mockReturnValue(`${vaultUrl}`); + when(core.getInput) + .calledWith('namespace') + .mockReturnValue('ns2'); + }); + + function mockInput(secrets) { + when(core.getInput) + .calledWith('secrets') + .mockReturnValue(secrets); + } + + it('authenticate with approle', async()=> { + mockInput('test secret'); + + await exportSecrets(); + + expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET_WITH_APPROLE'); + }) +}); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index f5b1e23d..5e79d95e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -810,16 +810,16 @@ } }, "@sindresorhus/is": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", - "integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-1.2.0.tgz", + "integrity": "sha512-mwhXGkRV5dlvQc4EgPDxDxO6WuMBVymGFd1CA+2Y+z5dG9MNspoQ+AWjl/Ld1MnpCL8AKbosZlDVohqcIwuWsw==" }, "@szmarczak/http-timer": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", - "integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.0.tgz", + "integrity": "sha512-3yoXv8OtGr/r3R5gaWWNQ3VUoQ5G3Gmo8DXX95V14ZVvE2b7Pj6Ide9uIDON8ym4D/ItyfL9ejohYUPqOyvRXw==", "requires": { - "defer-to-connect": "^1.0.1" + "defer-to-connect": "^1.1.1" } }, "@types/babel__core": { @@ -863,6 +863,17 @@ "@babel/types": "^7.3.0" } }, + "@types/cacheable-request": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.1.tgz", + "integrity": "sha512-ykFq2zmBGOCbpIXtoVbz4SKY5QriWPh3AjyU4G74RYbtt5yOc5OfaY75ftjg7mikMOla1CTGpX3lLbuJh8DTrQ==", + "requires": { + "@types/http-cache-semantics": "*", + "@types/keyv": "*", + "@types/node": "*", + "@types/responselike": "*" + } + }, "@types/events": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", @@ -880,6 +891,11 @@ "@types/node": "*" } }, + "@types/http-cache-semantics": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz", + "integrity": "sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A==" + }, "@types/istanbul-lib-coverage": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz", @@ -920,6 +936,14 @@ "integrity": "sha512-yALhelO3i0hqZwhjtcr6dYyaLoCHbAMshwtj6cGxTvHZAKXHsYGdff6E8EPw3xLKY0ELUTQ69Q1rQiJENnccMA==", "dev": true }, + "@types/keyv": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.1.tgz", + "integrity": "sha512-MPtoySlAZQ37VoLaPcTHCu1RWJ4llDkULYZIzOYxlhxBqYPB0RsRlmMU0R6tahtFe27mIdkHV+551ZWV4PLmVw==", + "requires": { + "@types/node": "*" + } + }, "@types/minimatch": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", @@ -929,8 +953,7 @@ "@types/node": { "version": "12.7.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-12.7.5.tgz", - "integrity": "sha512-9fq4jZVhPNW8r+UYKnxF1e2HkDWOWKM5bC2/7c9wPV835I0aOrVbS/Hw/pWPk2uKrNXQqg9Z959Kz+IYDd5p3w==", - "dev": true + "integrity": "sha512-9fq4jZVhPNW8r+UYKnxF1e2HkDWOWKM5bC2/7c9wPV835I0aOrVbS/Hw/pWPk2uKrNXQqg9Z959Kz+IYDd5p3w==" }, "@types/normalize-package-data": { "version": "2.4.0", @@ -938,6 +961,14 @@ "integrity": "sha512-f5j5b/Gf71L+dbqxIpQ4Z2WlmI/mPJ0fOkGGmFgtb6sAu97EPczzbS3/tJKxmcYDj55OX6ssqwDAWOHIYDRDGA==", "dev": true }, + "@types/responselike": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", + "integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", + "requires": { + "@types/node": "*" + } + }, "@types/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", @@ -1463,10 +1494,18 @@ "unset-value": "^1.0.0" } }, + "cacheable-lookup": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-0.2.1.tgz", + "integrity": "sha512-BQ8MRjxJASEq2q+w0SusPU3B054gS278K8sj58QCLMZIso5qG05+MdCdmXxuyVlfvI8h4bPsNOavVUauVCGxrg==", + "requires": { + "keyv": "^3.1.0" + } + }, "cacheable-request": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", - "integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.0.tgz", + "integrity": "sha512-UVG4gMn3WjnAeFBBx7RFoprgOANIAkMwN5Dta6ONmfSwrCxfm0Ip7g0mIBxIRJZX9aDsoID0Ry3dU5Pr0csKKA==", "requires": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", @@ -1474,7 +1513,7 @@ "keyv": "^3.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^4.1.0", - "responselike": "^1.0.2" + "responselike": "^2.0.0" }, "dependencies": { "get-stream": { @@ -1484,11 +1523,6 @@ "requires": { "pump": "^3.0.0" } - }, - "lowercase-keys": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", - "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" } } }, @@ -1646,6 +1680,13 @@ "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", "requires": { "mimic-response": "^1.0.0" + }, + "dependencies": { + "mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" + } } }, "co": { @@ -1952,11 +1993,11 @@ "dev": true }, "decompress-response": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", - "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-5.0.0.tgz", + "integrity": "sha512-TLZWWybuxWgoW7Lykv+gq9xvzOsUjQ9tF09Tj6NSTYGMTCHNXzrPnD6Hi+TgZq19PyTAGH4Ll/NIM/eTGglnMw==", "requires": { - "mimic-response": "^1.0.0" + "mimic-response": "^2.0.0" } }, "deep-extend": { @@ -1972,9 +2013,9 @@ "dev": true }, "defer-to-connect": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.0.2.tgz", - "integrity": "sha512-k09hcQcTDY+cwgiwa6PYKLm3jlagNzQ+RSvhjzESOGOx+MNOuXkxTfEvPrO1IOQ81tArCFYQgi631clB70RpQw==" + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.1.tgz", + "integrity": "sha512-J7thop4u3mRTkYRQ+Vpfwy2G5Ehoy82I14+14W4YMDLKdWloI9gSzRbV30s/NckQGVJtPkWNcW4oMAUigTdqiQ==" }, "define-properties": { "version": "1.1.3", @@ -3184,6 +3225,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "dev": true, "requires": { "pump": "^3.0.0" } @@ -3282,21 +3324,39 @@ } }, "got": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/got/-/got-9.6.0.tgz", - "integrity": "sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==", - "requires": { - "@sindresorhus/is": "^0.14.0", - "@szmarczak/http-timer": "^1.1.2", - "cacheable-request": "^6.0.0", - "decompress-response": "^3.3.0", + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/got/-/got-10.2.2.tgz", + "integrity": "sha512-QibZN13xHH/mc7H5uuU2xq28xxs8moEPsJrW9AQQX0jAV4DkGdllHDVE9cxw1nntIPFk8xzzOrgJZBg194AWrg==", + "requires": { + "@sindresorhus/is": "^1.0.0", + "@szmarczak/http-timer": "^4.0.0", + "@types/cacheable-request": "^6.0.1", + "cacheable-lookup": "^0.2.1", + "cacheable-request": "^7.0.0", + "decompress-response": "^5.0.0", "duplexer3": "^0.1.4", - "get-stream": "^4.1.0", - "lowercase-keys": "^1.0.1", - "mimic-response": "^1.0.1", - "p-cancelable": "^1.0.0", - "to-readable-stream": "^1.0.0", - "url-parse-lax": "^3.0.0" + "get-stream": "^5.0.0", + "lowercase-keys": "^2.0.0", + "mimic-response": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0", + "to-readable-stream": "^2.0.0", + "type-fest": "^0.8.0" + }, + "dependencies": { + "get-stream": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz", + "integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==", + "requires": { + "pump": "^3.0.0" + } + }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==" + } } }, "graceful-fs": { @@ -4669,9 +4729,9 @@ } }, "lowercase-keys": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", - "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" }, "lru-cache": { "version": "5.1.1", @@ -4889,9 +4949,9 @@ "dev": true }, "mimic-response": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-2.0.0.tgz", + "integrity": "sha512-8ilDoEapqA4uQ3TwS0jakGONKXVJqpy+RpM+3b7pLdOjghCrEiGp9SRkFbUHAmZW9vdnrENWHjaweIoTIJExSQ==" }, "minimatch": { "version": "3.0.4", @@ -8791,9 +8851,9 @@ } }, "p-cancelable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", - "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.0.0.tgz", + "integrity": "sha512-wvPXDmbMmu2ksjkB4Z3nZWTSkJEb9lqVdMaCKpZUGJG9TMiNp9XcbG3fn9fPKjem04fJMJnXoyFPk2FmgiaiNg==" }, "p-each-series": { "version": "1.0.0", @@ -9041,11 +9101,6 @@ "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", "dev": true }, - "prepend-http": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz", - "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=" - }, "pretty-format": { "version": "24.9.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-24.9.0.tgz", @@ -9342,11 +9397,11 @@ "dev": true }, "responselike": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", - "integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.0.tgz", + "integrity": "sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw==", "requires": { - "lowercase-keys": "^1.0.0" + "lowercase-keys": "^2.0.0" } }, "ret": { @@ -10257,9 +10312,9 @@ } }, "to-readable-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", - "integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-2.1.0.tgz", + "integrity": "sha512-o3Qa6DGg1CEXshSdvWNX2sN4QHqg03SPq7U6jPXRahlQdl5dK8oXjkU/2/sGrnOZKeGV1zLSO8qPwyKklPPE7w==" }, "to-regex": { "version": "3.0.2", @@ -10455,14 +10510,6 @@ "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", "dev": true }, - "url-parse-lax": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", - "integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", - "requires": { - "prepend-http": "^2.0.0" - } - }, "use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", diff --git a/package.json b/package.json index 44514bde..ecff1d04 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "homepage": "https://github.com/RichiCoder1/vault-action#readme", "dependencies": { "@actions/core": "^1.1.1", - "got": "^9.6.0" + "got": "^10.2.2" }, "devDependencies": { "@types/jest": "^24.0.18",