5
0
Fork 0
mirror of https://github.com/hashicorp/vault-action.git synced 2025-11-07 07:06:56 +00:00
vault-action/dist/index.js
Antoine Méausoone 3b9239de79
feat(authenticate): add approle auth method (#10)
* feat(authenticate): add approle auth method

* docs(readme): update readme

* fix: update index.js

* fix: update got to 10.2.2 to fix ncc

* chore: clean up code slightly

* chore: update tests to use got correctly

* chore(test): fix integration tests

* chore: streamline method logic

* chore: make role and secret required in approle

Co-authored-by: Sébastien FAUVART <sebastien.fauvart@gmail.com>
Co-authored-by: Richard Simpson <richardsimpson@outlook.com>
2020-01-28 19:10:19 -06:00

5331 lines
No EOL
164 KiB
JavaScript

module.exports =
/******/ (function(modules, runtime) { // webpackBootstrap
/******/ "use strict";
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ __webpack_require__.ab = __dirname + "/";
/******/
/******/ // the startup function
/******/ function startup() {
/******/ // Load entry module and return exports
/******/ return __webpack_require__(104);
/******/ };
/******/ // initialize runtime
/******/ runtime(__webpack_require__);
/******/
/******/ // run startup
/******/ return startup();
/******/ })
/************************************************************************/
/******/ ({
/***/ 9:
/***/ (function(module, __unusedexports, __webpack_require__) {
var once = __webpack_require__(49);
var noop = function() {};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === 'function';
};
var isChildProcess = function(stream) {
return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
};
var eos = function(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
};
var onfinish = function() {
writable = false;
if (!readable) callback.call(stream);
};
var onend = function() {
readable = false;
if (!writable) callback.call(stream);
};
var onexit = function(exitCode) {
callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
};
var onerror = function(err) {
callback.call(stream, err);
};
var onclose = function() {
if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
};
var onrequest = function() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();
else stream.on('request', onrequest);
} else if (writable && !ws) { // legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
if (isChildProcess(stream)) stream.on('exit', onexit);
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', onerror);
stream.on('close', onclose);
return function() {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('exit', onexit);
stream.removeListener('end', onend);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
};
};
module.exports = eos;
/***/ }),
/***/ 11:
/***/ (function(module) {
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
/***/ }),
/***/ 16:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const pump = __webpack_require__(453);
const bufferStream = __webpack_require__(375);
class MaxBufferError extends Error {
constructor() {
super('maxBuffer exceeded');
this.name = 'MaxBufferError';
}
}
async function getStream(inputStream, options) {
if (!inputStream) {
return Promise.reject(new Error('Expected a stream'));
}
options = {
maxBuffer: Infinity,
...options
};
const {maxBuffer} = options;
let stream;
await 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());
}
});
});
return stream.getBufferedValue();
}
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;
/***/ }),
/***/ 49:
/***/ (function(module, __unusedexports, __webpack_require__) {
var wrappy = __webpack_require__(11)
module.exports = wrappy(once)
module.exports.strict = wrappy(onceStrict)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
Object.defineProperty(Function.prototype, 'onceStrict', {
value: function () {
return onceStrict(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
function onceStrict (fn) {
var f = function () {
if (f.called)
throw new Error(f.onceError)
f.called = true
return f.value = fn.apply(this, arguments)
}
var name = fn.name || 'Function wrapped with `once`'
f.onceError = name + " shouldn't be called more than once"
f.called = false
return f
}
/***/ }),
/***/ 53:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
// TODO: Use the `URL` global when targeting Node.js 10
const URLParser = typeof URL === 'undefined' ? __webpack_require__(835).URL : URL;
const testParameter = (name, filters) => {
return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name);
};
const normalizeDataURL = (urlString, {stripHash}) => {
const parts = urlString.match(/^data:(.*?),(.*?)(?:#(.*))?$/);
if (!parts) {
throw new Error(`Invalid URL: ${urlString}`);
}
const mediaType = parts[1].split(';');
const body = parts[2];
const hash = stripHash ? '' : parts[3];
let base64 = false;
if (mediaType[mediaType.length - 1] === 'base64') {
mediaType.pop();
base64 = true;
}
// Lowercase MIME type
const mimeType = (mediaType.shift() || '').toLowerCase();
const attributes = mediaType
.filter(Boolean)
.map(attribute => {
let [key, value = ''] = attribute.split('=').map(string => string.trim());
// Lowercase `charset`
if (key === 'charset') {
value = value.toLowerCase();
}
return `${key}${value ? `=${value}` : ''}`;
});
const normalizedMediaType = [
...attributes
];
if (base64) {
normalizedMediaType.push('base64');
}
if (normalizedMediaType.length !== 0 || mimeType) {
normalizedMediaType.unshift(mimeType);
}
return `data:${normalizedMediaType.join(';')},${base64 ? body.trim() : body}${hash ? `#${hash}` : ''}`;
};
const normalizeUrl = (urlString, options) => {
options = {
defaultProtocol: 'http:',
normalizeProtocol: true,
forceHttp: false,
forceHttps: false,
stripAuthentication: true,
stripHash: false,
stripWWW: true,
removeQueryParameters: [/^utm_\w+/i],
removeTrailingSlash: true,
removeDirectoryIndex: false,
sortQueryParameters: true,
...options
};
// TODO: Remove this at some point in the future
if (Reflect.has(options, 'normalizeHttps')) {
throw new Error('options.normalizeHttps is renamed to options.forceHttp');
}
if (Reflect.has(options, 'normalizeHttp')) {
throw new Error('options.normalizeHttp is renamed to options.forceHttps');
}
if (Reflect.has(options, 'stripFragment')) {
throw new Error('options.stripFragment is renamed to options.stripHash');
}
urlString = urlString.trim();
// Data URL
if (/^data:/i.test(urlString)) {
return normalizeDataURL(urlString, options);
}
const hasRelativeProtocol = urlString.startsWith('//');
const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
// Prepend protocol
if (!isRelativeUrl) {
urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol);
}
const urlObj = new URLParser(urlString);
if (options.forceHttp && options.forceHttps) {
throw new Error('The `forceHttp` and `forceHttps` options cannot be used together');
}
if (options.forceHttp && urlObj.protocol === 'https:') {
urlObj.protocol = 'http:';
}
if (options.forceHttps && urlObj.protocol === 'http:') {
urlObj.protocol = 'https:';
}
// Remove auth
if (options.stripAuthentication) {
urlObj.username = '';
urlObj.password = '';
}
// Remove hash
if (options.stripHash) {
urlObj.hash = '';
}
// Remove duplicate slashes if not preceded by a protocol
if (urlObj.pathname) {
// TODO: Use the following instead when targeting Node.js 10
// `urlObj.pathname = urlObj.pathname.replace(/(?<!https?:)\/{2,}/g, '/');`
urlObj.pathname = urlObj.pathname.replace(/((?!:).|^)\/{2,}/g, (_, p1) => {
if (/^(?!\/)/g.test(p1)) {
return `${p1}/`;
}
return '/';
});
}
// Decode URI octets
if (urlObj.pathname) {
urlObj.pathname = decodeURI(urlObj.pathname);
}
// Remove directory index
if (options.removeDirectoryIndex === true) {
options.removeDirectoryIndex = [/^index\.[a-z]+$/];
}
if (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {
let pathComponents = urlObj.pathname.split('/');
const lastComponent = pathComponents[pathComponents.length - 1];
if (testParameter(lastComponent, options.removeDirectoryIndex)) {
pathComponents = pathComponents.slice(0, pathComponents.length - 1);
urlObj.pathname = pathComponents.slice(1).join('/') + '/';
}
}
if (urlObj.hostname) {
// Remove trailing dot
urlObj.hostname = urlObj.hostname.replace(/\.$/, '');
// Remove `www.`
if (options.stripWWW && /^www\.([a-z\-\d]{2,63})\.([a-z.]{2,5})$/.test(urlObj.hostname)) {
// Each label should be max 63 at length (min: 2).
// The extension should be max 5 at length (min: 2).
// Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
}
}
// Remove query unwanted parameters
if (Array.isArray(options.removeQueryParameters)) {
for (const key of [...urlObj.searchParams.keys()]) {
if (testParameter(key, options.removeQueryParameters)) {
urlObj.searchParams.delete(key);
}
}
}
// Sort query parameters
if (options.sortQueryParameters) {
urlObj.searchParams.sort();
}
if (options.removeTrailingSlash) {
urlObj.pathname = urlObj.pathname.replace(/\/$/, '');
}
// Take advantage of many of the Node `url` normalizations
urlString = urlObj.toString();
// Remove ending `/`
if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '') {
urlString = urlString.replace(/\/$/, '');
}
// Restore relative protocol, if applicable
if (hasRelativeProtocol && !options.normalizeProtocol) {
urlString = urlString.replace(/^http:\/\//, '//');
}
// Remove http/https
if (options.stripProtocol) {
urlString = urlString.replace(/^(?:https?:)?\/\//, '');
}
return urlString;
};
module.exports = normalizeUrl;
// TODO: Remove this for the next major release
module.exports.default = normalizeUrl;
/***/ }),
/***/ 72:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const {PassThrough: PassThroughStream} = __webpack_require__(413);
module.exports = options => {
options = {...options};
const {array} = options;
let {encoding} = options;
const isBuffer = encoding === 'buffer';
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || 'utf8';
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({objectMode});
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on('data', chunk => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
};
stream.getBufferedLength = () => length;
return stream;
};
/***/ }),
/***/ 77:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 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;
/***/ }),
/***/ 87:
/***/ (function(module) {
module.exports = require("os");
/***/ }),
/***/ 89:
/***/ (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 knownProperties = [
'aborted',
'complete',
'destroy',
'headers',
'httpVersion',
'httpVersionMinor',
'httpVersionMajor',
'method',
'rawHeaders',
'rawTrailers',
'setTimeout',
'socket',
'statusCode',
'statusMessage',
'trailers',
'url'
];
module.exports = (fromStream, toStream) => {
const fromProps = new Set(Object.keys(fromStream).concat(knownProperties));
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];
}
};
/***/ }),
/***/ 93:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const Readable = __webpack_require__(413).Readable;
const lowercaseKeys = __webpack_require__(474);
class Response extends Readable {
constructor(statusCode, headers, body, url) {
if (typeof statusCode !== 'number') {
throw new TypeError('Argument `statusCode` should be a number');
}
if (typeof headers !== 'object') {
throw new TypeError('Argument `headers` should be an object');
}
if (!(body instanceof Buffer)) {
throw new TypeError('Argument `body` should be a buffer');
}
if (typeof url !== 'string') {
throw new TypeError('Argument `url` should be a string');
}
super();
this.statusCode = statusCode;
this.headers = lowercaseKeys(headers);
this.body = body;
this.url = url;
}
_read() {
this.push(this.body);
this.push(null);
}
}
module.exports = Response;
/***/ }),
/***/ 104:
/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) {
const core = __webpack_require__(470);
const { exportSecrets } = __webpack_require__(751);
(async () => {
try {
await core.group('Get Vault Secrets', exportSecrets);
} catch (error) {
core.setFailed(error.message);
}
})();
/***/ }),
/***/ 110:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* module decorator */ module = __webpack_require__.nmd(module);
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 = /(?<socketPath>.+?):(?<path>.+)/.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;
};
/***/ }),
/***/ 154:
/***/ (function(module) {
"use strict";
// rfc7231 6.1
const statusCodeCacheableByDefault = [
200,
203,
204,
206,
300,
301,
404,
405,
410,
414,
501,
];
// This implementation does not understand partial responses (206)
const understoodStatuses = [
200,
203,
204,
300,
301,
302,
303,
307,
308,
404,
405,
410,
414,
501,
];
const hopByHopHeaders = {
date: true, // included, because we add Age update Date
connection: true,
'keep-alive': true,
'proxy-authenticate': true,
'proxy-authorization': true,
te: true,
trailer: true,
'transfer-encoding': true,
upgrade: true,
};
const excludedFromRevalidationUpdate = {
// Since the old body is reused, it doesn't make sense to change properties of the body
'content-length': true,
'content-encoding': true,
'transfer-encoding': true,
'content-range': true,
};
function parseCacheControl(header) {
const cc = {};
if (!header) return cc;
// TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),
// the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale
const parts = header.trim().split(/\s*,\s*/); // TODO: lame parsing
for (const part of parts) {
const [k, v] = part.split(/\s*=\s*/, 2);
cc[k] = v === undefined ? true : v.replace(/^"|"$/g, ''); // TODO: lame unquoting
}
return cc;
}
function formatCacheControl(cc) {
let parts = [];
for (const k in cc) {
const v = cc[k];
parts.push(v === true ? k : k + '=' + v);
}
if (!parts.length) {
return undefined;
}
return parts.join(', ');
}
module.exports = class CachePolicy {
constructor(
req,
res,
{
shared,
cacheHeuristic,
immutableMinTimeToLive,
ignoreCargoCult,
trustServerDate,
_fromObject,
} = {}
) {
if (_fromObject) {
this._fromObject(_fromObject);
return;
}
if (!res || !res.headers) {
throw Error('Response headers missing');
}
this._assertRequestHasHeaders(req);
this._responseTime = this.now();
this._isShared = shared !== false;
this._trustServerDate =
undefined !== trustServerDate ? trustServerDate : true;
this._cacheHeuristic =
undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
this._immutableMinTtl =
undefined !== immutableMinTimeToLive
? immutableMinTimeToLive
: 24 * 3600 * 1000;
this._status = 'status' in res ? res.status : 200;
this._resHeaders = res.headers;
this._rescc = parseCacheControl(res.headers['cache-control']);
this._method = 'method' in req ? req.method : 'GET';
this._url = req.url;
this._host = req.headers.host;
this._noAuthorization = !req.headers.authorization;
this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used
this._reqcc = parseCacheControl(req.headers['cache-control']);
// Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,
// so there's no point stricly adhering to the blindly copy&pasted directives.
if (
ignoreCargoCult &&
'pre-check' in this._rescc &&
'post-check' in this._rescc
) {
delete this._rescc['pre-check'];
delete this._rescc['post-check'];
delete this._rescc['no-cache'];
delete this._rescc['no-store'];
delete this._rescc['must-revalidate'];
this._resHeaders = Object.assign({}, this._resHeaders, {
'cache-control': formatCacheControl(this._rescc),
});
delete this._resHeaders.expires;
delete this._resHeaders.pragma;
}
// When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive
// as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1).
if (
res.headers['cache-control'] == null &&
/no-cache/.test(res.headers.pragma)
) {
this._rescc['no-cache'] = true;
}
}
now() {
return Date.now();
}
storable() {
// The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.
return !!(
!this._reqcc['no-store'] &&
// A cache MUST NOT store a response to any request, unless:
// The request method is understood by the cache and defined as being cacheable, and
('GET' === this._method ||
'HEAD' === this._method ||
('POST' === this._method && this._hasExplicitExpiration())) &&
// the response status code is understood by the cache, and
understoodStatuses.indexOf(this._status) !== -1 &&
// the "no-store" cache directive does not appear in request or response header fields, and
!this._rescc['no-store'] &&
// the "private" response directive does not appear in the response, if the cache is shared, and
(!this._isShared || !this._rescc.private) &&
// the Authorization header field does not appear in the request, if the cache is shared,
(!this._isShared ||
this._noAuthorization ||
this._allowsStoringAuthenticated()) &&
// the response either:
// contains an Expires header field, or
(this._resHeaders.expires ||
// contains a max-age response directive, or
// contains a s-maxage response directive and the cache is shared, or
// contains a public response directive.
this._rescc.public ||
this._rescc['max-age'] ||
this._rescc['s-maxage'] ||
// has a status code that is defined as cacheable by default
statusCodeCacheableByDefault.indexOf(this._status) !== -1)
);
}
_hasExplicitExpiration() {
// 4.2.1 Calculating Freshness Lifetime
return (
(this._isShared && this._rescc['s-maxage']) ||
this._rescc['max-age'] ||
this._resHeaders.expires
);
}
_assertRequestHasHeaders(req) {
if (!req || !req.headers) {
throw Error('Request headers missing');
}
}
satisfiesWithoutRevalidation(req) {
this._assertRequestHasHeaders(req);
// When presented with a request, a cache MUST NOT reuse a stored response, unless:
// the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,
// unless the stored response is successfully validated (Section 4.3), and
const requestCC = parseCacheControl(req.headers['cache-control']);
if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {
return false;
}
if (requestCC['max-age'] && this.age() > requestCC['max-age']) {
return false;
}
if (
requestCC['min-fresh'] &&
this.timeToLive() < 1000 * requestCC['min-fresh']
) {
return false;
}
// the stored response is either:
// fresh, or allowed to be served stale
if (this.stale()) {
const allowsStale =
requestCC['max-stale'] &&
!this._rescc['must-revalidate'] &&
(true === requestCC['max-stale'] ||
requestCC['max-stale'] > this.age() - this.maxAge());
if (!allowsStale) {
return false;
}
}
return this._requestMatches(req, false);
}
_requestMatches(req, allowHeadMethod) {
// The presented effective request URI and that of the stored response match, and
return (
(!this._url || this._url === req.url) &&
this._host === req.headers.host &&
// the request method associated with the stored response allows it to be used for the presented request, and
(!req.method ||
this._method === req.method ||
(allowHeadMethod && 'HEAD' === req.method)) &&
// selecting header fields nominated by the stored response (if any) match those presented, and
this._varyMatches(req)
);
}
_allowsStoringAuthenticated() {
// following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.
return (
this._rescc['must-revalidate'] ||
this._rescc.public ||
this._rescc['s-maxage']
);
}
_varyMatches(req) {
if (!this._resHeaders.vary) {
return true;
}
// A Vary header field-value of "*" always fails to match
if (this._resHeaders.vary === '*') {
return false;
}
const fields = this._resHeaders.vary
.trim()
.toLowerCase()
.split(/\s*,\s*/);
for (const name of fields) {
if (req.headers[name] !== this._reqHeaders[name]) return false;
}
return true;
}
_copyWithoutHopByHopHeaders(inHeaders) {
const headers = {};
for (const name in inHeaders) {
if (hopByHopHeaders[name]) continue;
headers[name] = inHeaders[name];
}
// 9.1. Connection
if (inHeaders.connection) {
const tokens = inHeaders.connection.trim().split(/\s*,\s*/);
for (const name of tokens) {
delete headers[name];
}
}
if (headers.warning) {
const warnings = headers.warning.split(/,/).filter(warning => {
return !/^\s*1[0-9][0-9]/.test(warning);
});
if (!warnings.length) {
delete headers.warning;
} else {
headers.warning = warnings.join(',').trim();
}
}
return headers;
}
responseHeaders() {
const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
const age = this.age();
// A cache SHOULD generate 113 warning if it heuristically chose a freshness
// lifetime greater than 24 hours and the response's age is greater than 24 hours.
if (
age > 3600 * 24 &&
!this._hasExplicitExpiration() &&
this.maxAge() > 3600 * 24
) {
headers.warning =
(headers.warning ? `${headers.warning}, ` : '') +
'113 - "rfc7234 5.5.4"';
}
headers.age = `${Math.round(age)}`;
headers.date = new Date(this.now()).toUTCString();
return headers;
}
/**
* Value of the Date response header or current time if Date was demed invalid
* @return timestamp
*/
date() {
if (this._trustServerDate) {
return this._serverDate();
}
return this._responseTime;
}
_serverDate() {
const dateValue = Date.parse(this._resHeaders.date);
if (isFinite(dateValue)) {
const maxClockDrift = 8 * 3600 * 1000;
const clockDrift = Math.abs(this._responseTime - dateValue);
if (clockDrift < maxClockDrift) {
return dateValue;
}
}
return this._responseTime;
}
/**
* Value of the Age header, in seconds, updated for the current time.
* May be fractional.
*
* @return Number
*/
age() {
let age = Math.max(0, (this._responseTime - this.date()) / 1000);
if (this._resHeaders.age) {
let ageValue = this._ageValue();
if (ageValue > age) age = ageValue;
}
const residentTime = (this.now() - this._responseTime) / 1000;
return age + residentTime;
}
_ageValue() {
const ageValue = parseInt(this._resHeaders.age);
return isFinite(ageValue) ? ageValue : 0;
}
/**
* Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
*
* For an up-to-date value, see `timeToLive()`.
*
* @return Number
*/
maxAge() {
if (!this.storable() || this._rescc['no-cache']) {
return 0;
}
// Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default
// so this implementation requires explicit opt-in via public header
if (
this._isShared &&
(this._resHeaders['set-cookie'] &&
!this._rescc.public &&
!this._rescc.immutable)
) {
return 0;
}
if (this._resHeaders.vary === '*') {
return 0;
}
if (this._isShared) {
if (this._rescc['proxy-revalidate']) {
return 0;
}
// if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
if (this._rescc['s-maxage']) {
return parseInt(this._rescc['s-maxage'], 10);
}
}
// If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
if (this._rescc['max-age']) {
return parseInt(this._rescc['max-age'], 10);
}
const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
const dateValue = this._serverDate();
if (this._resHeaders.expires) {
const expires = Date.parse(this._resHeaders.expires);
// A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
if (Number.isNaN(expires) || expires < dateValue) {
return 0;
}
return Math.max(defaultMinTtl, (expires - dateValue) / 1000);
}
if (this._resHeaders['last-modified']) {
const lastModified = Date.parse(this._resHeaders['last-modified']);
if (isFinite(lastModified) && dateValue > lastModified) {
return Math.max(
defaultMinTtl,
((dateValue - lastModified) / 1000) * this._cacheHeuristic
);
}
}
return defaultMinTtl;
}
timeToLive() {
return Math.max(0, this.maxAge() - this.age()) * 1000;
}
stale() {
return this.maxAge() <= this.age();
}
static fromObject(obj) {
return new this(undefined, undefined, { _fromObject: obj });
}
_fromObject(obj) {
if (this._responseTime) throw Error('Reinitialized');
if (!obj || obj.v !== 1) throw Error('Invalid serialization');
this._responseTime = obj.t;
this._isShared = obj.sh;
this._cacheHeuristic = obj.ch;
this._immutableMinTtl =
obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;
this._status = obj.st;
this._resHeaders = obj.resh;
this._rescc = obj.rescc;
this._method = obj.m;
this._url = obj.u;
this._host = obj.h;
this._noAuthorization = obj.a;
this._reqHeaders = obj.reqh;
this._reqcc = obj.reqcc;
}
toObject() {
return {
v: 1,
t: this._responseTime,
sh: this._isShared,
ch: this._cacheHeuristic,
imm: this._immutableMinTtl,
st: this._status,
resh: this._resHeaders,
rescc: this._rescc,
m: this._method,
u: this._url,
h: this._host,
a: this._noAuthorization,
reqh: this._reqHeaders,
reqcc: this._reqcc,
};
}
/**
* Headers for sending to the origin server to revalidate stale response.
* Allows server to return 304 to allow reuse of the previous response.
*
* Hop by hop headers are always stripped.
* Revalidation headers may be added or removed, depending on request.
*/
revalidationHeaders(incomingReq) {
this._assertRequestHasHeaders(incomingReq);
const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
// This implementation does not understand range requests
delete headers['if-range'];
if (!this._requestMatches(incomingReq, true) || !this.storable()) {
// revalidation allowed via HEAD
// not for the same resource, or wasn't allowed to be cached anyway
delete headers['if-none-match'];
delete headers['if-modified-since'];
return headers;
}
/* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */
if (this._resHeaders.etag) {
headers['if-none-match'] = headers['if-none-match']
? `${headers['if-none-match']}, ${this._resHeaders.etag}`
: this._resHeaders.etag;
}
// Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.
const forbidsWeakValidators =
headers['accept-ranges'] ||
headers['if-match'] ||
headers['if-unmodified-since'] ||
(this._method && this._method != 'GET');
/* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.
Note: This implementation does not understand partial responses (206) */
if (forbidsWeakValidators) {
delete headers['if-modified-since'];
if (headers['if-none-match']) {
const etags = headers['if-none-match']
.split(/,/)
.filter(etag => {
return !/^\s*W\//.test(etag);
});
if (!etags.length) {
delete headers['if-none-match'];
} else {
headers['if-none-match'] = etags.join(',').trim();
}
}
} else if (
this._resHeaders['last-modified'] &&
!headers['if-modified-since']
) {
headers['if-modified-since'] = this._resHeaders['last-modified'];
}
return headers;
}
/**
* Creates new CachePolicy with information combined from the previews response,
* and the new revalidation response.
*
* Returns {policy, modified} where modified is a boolean indicating
* whether the response body has been modified, and old cached body can't be used.
*
* @return {Object} {policy: CachePolicy, modified: Boolean}
*/
revalidatedPolicy(request, response) {
this._assertRequestHasHeaders(request);
if (!response || !response.headers) {
throw Error('Response headers missing');
}
// These aren't going to be supported exactly, since one CachePolicy object
// doesn't know about all the other cached objects.
let matches = false;
if (response.status !== undefined && response.status != 304) {
matches = false;
} else if (
response.headers.etag &&
!/^\s*W\//.test(response.headers.etag)
) {
// "All of the stored responses with the same strong validator are selected.
// If none of the stored responses contain the same strong validator,
// then the cache MUST NOT use the new response to update any stored responses."
matches =
this._resHeaders.etag &&
this._resHeaders.etag.replace(/^\s*W\//, '') ===
response.headers.etag;
} else if (this._resHeaders.etag && response.headers.etag) {
// "If the new response contains a weak validator and that validator corresponds
// to one of the cache's stored responses,
// then the most recent of those matching stored responses is selected for update."
matches =
this._resHeaders.etag.replace(/^\s*W\//, '') ===
response.headers.etag.replace(/^\s*W\//, '');
} else if (this._resHeaders['last-modified']) {
matches =
this._resHeaders['last-modified'] ===
response.headers['last-modified'];
} else {
// If the new response does not include any form of validator (such as in the case where
// a client generates an If-Modified-Since request from a source other than the Last-Modified
// response header field), and there is only one stored response, and that stored response also
// lacks a validator, then that stored response is selected for update.
if (
!this._resHeaders.etag &&
!this._resHeaders['last-modified'] &&
!response.headers.etag &&
!response.headers['last-modified']
) {
matches = true;
}
}
if (!matches) {
return {
policy: new this.constructor(request, response),
// Client receiving 304 without body, even if it's invalid/mismatched has no option
// but to reuse a cached body. We don't have a good way to tell clients to do
// error recovery in such case.
modified: response.status != 304,
matches: false,
};
}
// use other header fields provided in the 304 (Not Modified) response to replace all instances
// of the corresponding header fields in the stored response.
const headers = {};
for (const k in this._resHeaders) {
headers[k] =
k in response.headers && !excludedFromRevalidationUpdate[k]
? response.headers[k]
: this._resHeaders[k];
}
const newResponse = Object.assign({}, response, {
status: this._status,
method: this._method,
headers,
});
return {
policy: new this.constructor(request, newResponse, {
shared: this._isShared,
cacheHeuristic: this._cacheHeuristic,
immutableMinTimeToLive: this._immutableMinTtl,
trustServerDate: this._trustServerDate,
}),
modified: false,
matches: true,
};
}
};
/***/ }),
/***/ 164:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
/***/ }),
/***/ 205:
/***/ (function(__unusedmodule, exports) {
//TODO: handle reviver/dehydrate function like normal
//and handle indentation, like normal.
//if anyone needs this... please send pull request.
exports.stringify = function stringify (o) {
if('undefined' == typeof o) return o
if(o && Buffer.isBuffer(o))
return JSON.stringify(':base64:' + o.toString('base64'))
if(o && o.toJSON)
o = o.toJSON()
if(o && 'object' === typeof o) {
var s = ''
var array = Array.isArray(o)
s = array ? '[' : '{'
var first = true
for(var k in o) {
var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k])
if(Object.hasOwnProperty.call(o, k) && !ignore) {
if(!first)
s += ','
first = false
if (array) {
if(o[k] == undefined)
s += 'null'
else
s += stringify(o[k])
} else if (o[k] !== void(0)) {
s += stringify(k) + ':' + stringify(o[k])
}
}
}
s += array ? ']' : '}'
return s
} else if ('string' === typeof o) {
return JSON.stringify(/^:/.test(o) ? ':' + o : o)
} else if ('undefined' === typeof o) {
return 'null';
} else
return JSON.stringify(o)
}
exports.parse = function (s) {
return JSON.parse(s, function (key, value) {
if('string' === typeof value) {
if(/^:base64:/.test(value))
return new Buffer(value.substring(8), 'base64')
else
return /^:/.test(value) ? value.substring(1) : value
}
return value
})
}
/***/ }),
/***/ 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:
/***/ (function(module) {
module.exports = require("https");
/***/ }),
/***/ 215:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
};
/***/ }),
/***/ 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);
/***/ }),
/***/ 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;
};
/***/ }),
/***/ 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 = {
redis: '@keyv/redis',
mongodb: '@keyv/mongo',
mongo: '@keyv/mongo',
sqlite: '@keyv/sqlite',
postgresql: '@keyv/postgres',
postgres: '@keyv/postgres',
mysql: '@keyv/mysql'
};
if (opts.adapter || opts.uri) {
const adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0];
return new (require(adapters[adapter]))(opts);
}
return new Map();
};
class Keyv extends EventEmitter {
constructor(uri, opts) {
super();
this.opts = Object.assign(
{
namespace: 'keyv',
serialize: JSONB.stringify,
deserialize: JSONB.parse
},
(typeof uri === 'string') ? { uri } : uri,
opts
);
if (!this.opts.store) {
const adapterOpts = Object.assign({}, this.opts);
this.opts.store = loadStore(adapterOpts);
}
if (typeof this.opts.store.on === 'function') {
this.opts.store.on('error', err => this.emit('error', err));
}
this.opts.store.namespace = this.opts.namespace;
}
_getKeyPrefix(key) {
return `${this.opts.namespace}:${key}`;
}
get(key) {
key = this._getKeyPrefix(key);
const store = this.opts.store;
return Promise.resolve()
.then(() => store.get(key))
.then(data => {
data = (typeof data === 'string') ? this.opts.deserialize(data) : data;
if (data === undefined) {
return undefined;
}
if (typeof data.expires === 'number' && Date.now() > data.expires) {
this.delete(key);
return undefined;
}
return data.value;
});
}
set(key, value, ttl) {
key = this._getKeyPrefix(key);
if (typeof ttl === 'undefined') {
ttl = this.opts.ttl;
}
if (ttl === 0) {
ttl = undefined;
}
const store = this.opts.store;
return Promise.resolve()
.then(() => {
const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;
value = { value, expires };
return store.set(key, this.opts.serialize(value), ttl);
})
.then(() => true);
}
delete(key) {
key = this._getKeyPrefix(key);
const store = this.opts.store;
return Promise.resolve()
.then(() => store.delete(key));
}
clear() {
const store = this.opts.store;
return Promise.resolve()
.then(() => store.clear());
}
}
module.exports = Keyv;
/***/ }),
/***/ 323:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
/***/ }),
/***/ 325:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const PassThrough = __webpack_require__(413).PassThrough;
const mimicResponse = __webpack_require__(210);
const cloneResponse = response => {
if (!(response && response.pipe)) {
throw new TypeError('Parameter `response` must be a response stream.');
}
const clone = new PassThrough();
mimicResponse(response, clone);
return response.pipe(clone);
};
module.exports = cloneResponse;
/***/ }),
/***/ 375:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const {PassThrough: PassThroughStream} = __webpack_require__(413);
module.exports = options => {
options = {...options};
const {array} = options;
let {encoding} = options;
const isBuffer = encoding === 'buffer';
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || 'utf8';
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({objectMode});
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on('data', chunk => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
};
stream.getBufferedLength = () => length;
return stream;
};
/***/ }),
/***/ 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:
/***/ (function(module) {
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:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const os = __webpack_require__(87);
/**
* Commands
*
* Command Format:
* ##[name key=value;key=value]message
*
* Examples:
* ##[warning]This is the user warning message
* ##[set-secret name=mypassword]definitelyNotAPassword!
*/
function issueCommand(command, properties, message) {
const cmd = new Command(command, properties, message);
process.stdout.write(cmd.toString() + os.EOL);
}
exports.issueCommand = issueCommand;
function issue(name, message = '') {
issueCommand(name, {}, message);
}
exports.issue = issue;
const CMD_STRING = '::';
class Command {
constructor(command, properties, message) {
if (!command) {
command = 'missing.command';
}
this.command = command;
this.properties = properties;
this.message = message;
}
toString() {
let cmdStr = CMD_STRING + this.command;
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' ';
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key];
if (val) {
// safely append the val - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
cmdStr += `${key}=${escape(`${val || ''}`)},`;
}
}
}
}
cmdStr += CMD_STRING;
// safely append the message - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
const message = `${this.message || ''}`;
cmdStr += escapeData(message);
return cmdStr;
}
}
function escapeData(s) {
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
}
function escape(s) {
return s
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
.replace(/]/g, '%5D')
.replace(/;/g, '%3B');
}
//# sourceMappingURL=command.js.map
/***/ }),
/***/ 453:
/***/ (function(module, __unusedexports, __webpack_require__) {
var once = __webpack_require__(49)
var eos = __webpack_require__(9)
var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes
var noop = function () {}
var ancient = /^v?\.0/.test(process.version)
var isFn = function (fn) {
return typeof fn === 'function'
}
var isFS = function (stream) {
if (!ancient) return false // newer node version do not need to care about fs is a special way
if (!fs) return false // browser
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
}
var isRequest = function (stream) {
return stream.setHeader && isFn(stream.abort)
}
var destroyer = function (stream, reading, writing, callback) {
callback = once(callback)
var closed = false
stream.on('close', function () {
closed = true
})
eos(stream, {readable: reading, writable: writing}, function (err) {
if (err) return callback(err)
closed = true
callback()
})
var destroyed = false
return function (err) {
if (closed) return
if (destroyed) return
destroyed = true
if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
if (isFn(stream.destroy)) return stream.destroy()
callback(err || new Error('stream was destroyed'))
}
}
var call = function (fn) {
fn()
}
var pipe = function (from, to) {
return from.pipe(to)
}
var pump = function () {
var streams = Array.prototype.slice.call(arguments)
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
if (Array.isArray(streams[0])) streams = streams[0]
if (streams.length < 2) throw new Error('pump requires two streams per minimum')
var error
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1
var writing = i > 0
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err
if (err) destroys.forEach(call)
if (reading) return
destroys.forEach(call)
callback(error)
})
})
return streams.reduce(pipe)
}
module.exports = pump
/***/ }),
/***/ 470:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = __webpack_require__(431);
const os = __webpack_require__(87);
const path = __webpack_require__(622);
/**
* The code to exit an action
*/
var ExitCode;
(function (ExitCode) {
/**
* A code indicating that the action was successful
*/
ExitCode[ExitCode["Success"] = 0] = "Success";
/**
* A code indicating that the action was a failure
*/
ExitCode[ExitCode["Failure"] = 1] = "Failure";
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
//-----------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------
/**
* sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable
*/
function exportVariable(name, val) {
process.env[name] = val;
command_1.issueCommand('set-env', { name }, val);
}
exports.exportVariable = exportVariable;
/**
* exports the variable and registers a secret which will get masked from logs
* @param name the name of the variable to set
* @param val value of the secret
*/
function exportSecret(name, val) {
exportVariable(name, val);
// the runner will error with not implemented
// leaving the function but raising the error earlier
command_1.issueCommand('set-secret', {}, val);
throw new Error('Not implemented.');
}
exports.exportSecret = exportSecret;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
*/
function addPath(inputPath) {
command_1.issueCommand('add-path', {}, inputPath);
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
}
exports.addPath = addPath;
/**
* Gets the value of an input. The value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
function getInput(name, options) {
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}
exports.getInput = getInput;
/**
* Sets the value of an output.
*
* @param name name of the output to set
* @param value value to store
*/
function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value);
}
exports.setOutput = setOutput;
//-----------------------------------------------------------------------
// Results
//-----------------------------------------------------------------------
/**
* Sets the action status to failed.
* When the action exits it will be with an exit code of 1
* @param message add error issue message
*/
function setFailed(message) {
process.exitCode = ExitCode.Failure;
error(message);
}
exports.setFailed = setFailed;
//-----------------------------------------------------------------------
// Logging Commands
//-----------------------------------------------------------------------
/**
* Writes debug message to user log
* @param message debug message
*/
function debug(message) {
command_1.issueCommand('debug', {}, message);
}
exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message
*/
function error(message) {
command_1.issue('error', message);
}
exports.error = error;
/**
* Adds an warning issue
* @param message warning issue message
*/
function warning(message) {
command_1.issue('warning', message);
}
exports.warning = warning;
/**
* Writes info to log with console.log.
* @param message info message
*/
function info(message) {
process.stdout.write(message + os.EOL);
}
exports.info = info;
/**
* Begin an output group.
*
* Output until the next `groupEnd` will be foldable in this group
*
* @param name The name of the output group
*/
function startGroup(name) {
command_1.issue('group', name);
}
exports.startGroup = startGroup;
/**
* End an output group.
*/
function endGroup() {
command_1.issue('endgroup');
}
exports.endGroup = endGroup;
/**
* Wrap an asynchronous function call in a group.
*
* Returns the same type as the function itself.
*
* @param name The name of the group
* @param fn The function to wrap in the group
*/
function group(name, fn) {
return __awaiter(this, void 0, void 0, function* () {
startGroup(name);
let result;
try {
result = yield fn();
}
finally {
endGroup();
}
return result;
});
}
exports.group = group;
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 474:
/***/ (function(module) {
"use strict";
module.exports = object => {
const result = {};
for (const [key, value] of Object.entries(object)) {
result[key.toLowerCase()] = value;
}
return result;
};
/***/ }),
/***/ 489:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
/***/ }),
/***/ 534:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/// <reference lib="esnext"/>
/// <reference lib="dom"/>
Object.defineProperty(exports, "__esModule", { value: true });
// TODO: Use the `URL` global when targeting Node.js 10
const URLGlobal = typeof URL === 'undefined' ? __webpack_require__(835).URL : URL;
const { toString } = Object.prototype;
const isOfType = (type) => (value) => typeof value === type;
const getObjectType = (value) => {
const objectName = toString.call(value).slice(8, -1);
if (objectName) {
return objectName;
}
return undefined;
};
const isObjectOfType = (type) => (value) => getObjectType(value) === type;
function is(value) {
switch (value) {
case null:
return "null" /* null */;
case true:
case false:
return "boolean" /* boolean */;
default:
}
switch (typeof value) {
case 'undefined':
return "undefined" /* undefined */;
case 'string':
return "string" /* string */;
case 'number':
return "number" /* number */;
case 'bigint':
return "bigint" /* bigint */;
case 'symbol':
return "symbol" /* symbol */;
default:
}
if (is.function_(value)) {
return "Function" /* Function */;
}
if (is.observable(value)) {
return "Observable" /* Observable */;
}
if (is.array(value)) {
return "Array" /* Array */;
}
if (is.buffer(value)) {
return "Buffer" /* Buffer */;
}
const tagType = getObjectType(value);
if (tagType) {
return tagType;
}
if (value instanceof String || value instanceof Boolean || value instanceof Number) {
throw new TypeError('Please don\'t use object wrappers for primitive types');
}
return "Object" /* Object */;
}
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;
}
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, {
class: {
value: is.class_
},
function: {
value: is.function_
},
null: {
value: is.null_
}
});
exports.default = is;
// For CommonJS default export support
module.exports = is;
module.exports.default = is;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 557:
/***/ (function(module) {
"use strict";
class CancelError extends Error {
constructor(reason) {
super(reason || 'Promise was canceled');
this.name = 'CancelError';
}
get isCanceled() {
return true;
}
}
class PCancelable {
static fn(userFn) {
return (...arguments_) => {
return new PCancelable((resolve, reject, onCancel) => {
arguments_.push(onCancel);
// eslint-disable-next-line promise/prefer-await-to-then
userFn(...arguments_).then(resolve, reject);
});
};
}
constructor(executor) {
this._cancelHandlers = [];
this._isPending = true;
this._isCanceled = false;
this._rejectOnCancel = true;
this._promise = new Promise((resolve, reject) => {
this._reject = reject;
const onResolve = value => {
this._isPending = false;
resolve(value);
};
const onReject = error => {
this._isPending = false;
reject(error);
};
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: boolean => {
this._rejectOnCancel = boolean;
}
}
});
return executor(onResolve, onReject, onCancel);
});
}
then(onFulfilled, onRejected) {
// eslint-disable-next-line promise/prefer-await-to-then
return this._promise.then(onFulfilled, onRejected);
}
catch(onRejected) {
return this._promise.catch(onRejected);
}
finally(onFinally) {
return this._promise.finally(onFinally);
}
cancel(reason) {
if (!this._isPending || this._isCanceled) {
return;
}
if (this._cancelHandlers.length > 0) {
try {
for (const handler of this._cancelHandlers) {
handler();
}
} catch (error) {
this._reject(error);
}
}
this._isCanceled = true;
if (this._rejectOnCancel) {
this._reject(new CancelError(reason));
}
}
get isCanceled() {
return this._isCanceled;
}
}
Object.setPrototypeOf(PCancelable.prototype, Promise.prototype);
module.exports = PCancelable;
module.exports.CancelError = CancelError;
/***/ }),
/***/ 605:
/***/ (function(module) {
module.exports = require("http");
/***/ }),
/***/ 614:
/***/ (function(module) {
module.exports = require("events");
/***/ }),
/***/ 616:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
/***/ }),
/***/ 620:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const zlib = __webpack_require__(761);
exports.default = typeof zlib.createBrotliDecompress === 'function';
/***/ }),
/***/ 622:
/***/ (function(module) {
module.exports = require("path");
/***/ }),
/***/ 631:
/***/ (function(module) {
module.exports = require("net");
/***/ }),
/***/ 668:
/***/ (function(__unusedmodule, exports) {
"use strict";
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;
}
};
};
/***/ }),
/***/ 669:
/***/ (function(module) {
module.exports = require("util");
/***/ }),
/***/ 678:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
/***/ }),
/***/ 705:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const pump = __webpack_require__(453);
const bufferStream = __webpack_require__(72);
class MaxBufferError extends Error {
constructor() {
super('maxBuffer exceeded');
this.name = 'MaxBufferError';
}
}
async function getStream(inputStream, options) {
if (!inputStream) {
return Promise.reject(new Error('Expected a stream'));
}
options = {
maxBuffer: Infinity,
...options
};
const {maxBuffer} = options;
let stream;
await 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());
}
});
});
return stream.getBufferedValue();
}
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;
/***/ }),
/***/ 718:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
var stream = __webpack_require__(413);
function DuplexWrapper(options, writable, readable) {
if (typeof readable === "undefined") {
readable = writable;
writable = options;
options = null;
}
stream.Duplex.call(this, options);
if (typeof readable.read !== "function") {
readable = (new stream.Readable(options)).wrap(readable);
}
this._writable = writable;
this._readable = readable;
this._waiting = false;
var self = this;
writable.once("finish", function() {
self.end();
});
this.once("finish", function() {
writable.end();
});
readable.on("readable", function() {
if (self._waiting) {
self._waiting = false;
self._read();
}
});
readable.once("end", function() {
self.push(null);
});
if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) {
writable.on("error", function(err) {
self.emit("error", err);
});
readable.on("error", function(err) {
self.emit("error", err);
});
}
}
DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}});
DuplexWrapper.prototype._write = function _write(input, encoding, done) {
this._writable.write(input, encoding, done);
};
DuplexWrapper.prototype._read = function _read() {
var buf;
var reads = 0;
while ((buf = this._readable.read()) !== null) {
this.push(buf);
reads++;
}
if (reads === 0) {
this._waiting = true;
}
};
module.exports = function duplex2(options, writable, readable) {
return new DuplexWrapper(options, writable, readable);
};
module.exports.DuplexWrapper = DuplexWrapper;
/***/ }),
/***/ 747:
/***/ (function(module) {
module.exports = require("fs");
/***/ }),
/***/ 751:
/***/ (function(module, __unusedexports, __webpack_require__) {
const core = __webpack_require__(470);
const command = __webpack_require__(431);
const got = __webpack_require__(77);
const AUTH_METHODS = ['approle', 'token'];
async function exportSecrets() {
const vaultUrl = core.getInput('url', { 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;
}
const result = await got(`${vaultUrl}/v1/secret/data/${secretPath}`, requestOptions);
const parsedResponse = JSON.parse(result.body);
const vaultKeyData = parsedResponse.data;
const versionData = vaultKeyData.data;
const value = versionData[secretKey];
command.issue('add-mask', value);
core.exportVariable(outputName, `${value}`);
core.debug(`${secretPath} => ${outputName}`);
}
};
/**
* Parses a secrets input string into key paths and their resulting environment variable name.
* @param {string} secretsInput
*/
function parseSecretsInput(secretsInput) {
const secrets = secretsInput
.split(';')
.filter(key => !!key)
.map(key => key.trim())
.filter(key => key.length !== 0);
/** @type {{ secretPath: string; outputName: string; dataKey: string; }[]} */
const output = [];
for (const secret of secrets) {
let path = secret;
let outputName = null;
const renameSigilIndex = secret.lastIndexOf('|');
if (renameSigilIndex > -1) {
path = secret.substring(0, renameSigilIndex).trim();
outputName = secret.substring(renameSigilIndex + 1).trim();
if (outputName.length < 1) {
throw Error(`You must provide a value when mapping a secret to a name. Input: "${secret}"`);
}
}
const pathParts = path
.split(/\s+/)
.map(part => part.trim())
.filter(part => part.length !== 0);
if (pathParts.length !== 2) {
throw Error(`You must provide a valid path and key. Input: "${secret}"`)
}
const [secretPath, secretKey] = pathParts;
// If we're not using a mapped name, normalize the key path into a variable name.
if (!outputName) {
outputName = normalizeOutputKey(secretKey);
}
output.push({
secretPath,
outputName,
secretKey
});
}
return output;
}
/**
* Replaces any forward-slash characters to
* @param {string} dataKey
*/
function normalizeOutputKey(dataKey) {
return dataKey.replace('/', '__').replace(/[^\w-]/, '').toUpperCase();
}
module.exports = {
exportSecrets,
parseSecretsInput,
normalizeOutputKey
};
/***/ }),
/***/ 753:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const {Resolver, V4MAPPED, ADDRCONFIG} = __webpack_require__(881);
const {promisify} = __webpack_require__(669);
const os = __webpack_require__(87);
const Keyv = __webpack_require__(303);
const map4to6 = entries => {
for (const entry of entries) {
entry.address = `::ffff:${entry.address}`;
entry.family = 6;
}
};
const getIfaceInfo = () => {
let has4 = false;
let has6 = false;
for (const device of Object.values(os.networkInterfaces())) {
for (const iface of device) {
if (iface.internal) {
continue;
}
if (iface.family === 'IPv6') {
has6 = true;
} else {
has4 = true;
}
if (has4 && has6) {
break;
}
}
}
return {has4, has6};
};
class CacheableLookup {
constructor(options = {}) {
const {cacheAdapter} = options;
this.cache = new Keyv({
uri: typeof cacheAdapter === 'string' && cacheAdapter,
store: typeof cacheAdapter !== 'string' && cacheAdapter,
namespace: 'cached-lookup'
});
this.maxTtl = options.maxTtl === 0 ? 0 : (options.maxTtl || Infinity);
this._resolver = options.resolver || new Resolver();
this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver));
this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver));
this.lookup = this.lookup.bind(this);
this.lookupAsync = this.lookupAsync.bind(this);
}
set servers(servers) {
this._resolver.setServers(servers);
}
get servers() {
return this._resolver.getServers();
}
lookup(hostname, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.lookupAsync(hostname, {...options, throwNotFound: true}).then(result => {
if (options.all) {
callback(null, result);
} else {
callback(null, result.address, result.family);
}
}).catch(callback);
}
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);
if (cached.length === 0 && options.family === 6 && options.hints & V4MAPPED) {
cached = await this.query(hostname, 4);
map4to6(cached);
}
}
if (options.hints & ADDRCONFIG) {
const {has4, has6} = getIfaceInfo();
cached = cached.filter(entry => entry.family === 6 ? has6 : has4);
}
if (options.throwNotFound && cached.length === 0) {
const error = new Error(`ENOTFOUND ${hostname}`);
error.code = 'ENOTFOUND';
error.hostname = hostname;
throw error;
}
const now = Date.now();
cached = cached.filter(entry => !Reflect.has(entry, 'expires') || now < entry.expires);
if (!options.details) {
cached = cached.map(entry => {
return {
address: entry.address,
family: entry.family
};
});
}
if (options.all) {
return cached;
}
if (cached.length === 0) {
return undefined;
}
return this._getEntry(cached);
}
async query(hostname, family) {
let cached = await this.cache.get(`${hostname}:${family}`);
if (!cached) {
cached = await this.queryAndCache(hostname, family);
}
return cached;
}
async queryAndCache(hostname, family) {
const resolve = family === 4 ? this._resolve4 : this._resolve6;
const entries = await resolve(hostname, {ttl: true});
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;
if (entry.ttl !== 0) {
entry.expires = now + (entry.ttl * 1000);
}
}
cacheTtl = Math.min(this.maxTtl, cacheTtl) * 1000;
if (this.maxTtl !== 0 && cacheTtl !== 0) {
await this.cache.set(`${hostname}:${family}`, entries, cacheTtl);
}
return entries;
}
_getEntry(entries) {
return entries[Math.floor(Math.random() * entries.length)];
}
}
module.exports = CacheableLookup;
module.exports.default = CacheableLookup;
/***/ }),
/***/ 761:
/***/ (function(module) {
module.exports = require("zlib");
/***/ }),
/***/ 766:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const knownHookEvents = [
'beforeError',
'init',
'beforeRequest',
'beforeRedirect',
'beforeRetry',
'afterResponse'
];
exports.default = knownHookEvents;
/***/ }),
/***/ 818:
/***/ (function(module) {
module.exports = require("tls");
/***/ }),
/***/ 835:
/***/ (function(module) {
module.exports = require("url");
/***/ }),
/***/ 839:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestSymbol = Symbol('request');
/***/ }),
/***/ 856:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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;
};
/***/ }),
/***/ 861:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const {
pipeline: streamPipeline,
PassThrough: PassThroughStream
} = __webpack_require__(413);
const zlib = __webpack_require__(761);
const mimicResponse = __webpack_require__(89);
const decompressResponse = response => {
const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {
return response;
}
// TODO: Remove this when targeting Node.js 12.
const isBrotli = contentEncoding === 'br';
if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {
return response;
}
const decompress = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
const stream = new PassThroughStream();
decompress.on('error', error => {
// Ignore empty response
if (error.code === 'Z_BUF_ERROR') {
stream.end();
return;
}
stream.emit('error', error);
});
const finalStream = streamPipeline(response, decompress, stream, () => {});
mimicResponse(response, finalStream);
return finalStream;
};
module.exports = decompressResponse;
/***/ }),
/***/ 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 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);
});
}
};
/***/ }),
/***/ 881:
/***/ (function(module) {
module.exports = require("dns");
/***/ }),
/***/ 895:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
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
/***/ }),
/***/ 946:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const EventEmitter = __webpack_require__(614);
const urlLib = __webpack_require__(835);
const normalizeUrl = __webpack_require__(53);
const getStream = __webpack_require__(16);
const CachePolicy = __webpack_require__(154);
const Response = __webpack_require__(93);
const lowercaseKeys = __webpack_require__(474);
const cloneResponse = __webpack_require__(325);
const Keyv = __webpack_require__(303);
class CacheableRequest {
constructor(request, cacheAdapter) {
if (typeof request !== 'function') {
throw new TypeError('Parameter `request` must be a function');
}
this.cache = new Keyv({
uri: typeof cacheAdapter === 'string' && cacheAdapter,
store: typeof cacheAdapter !== 'string' && cacheAdapter,
namespace: 'cacheable-request'
});
return this.createCacheableRequest(request);
}
createCacheableRequest(request) {
return (opts, cb) => {
let url;
if (typeof opts === 'string') {
url = normalizeUrlObject(urlLib.parse(opts));
opts = {};
} else if (opts instanceof urlLib.URL) {
url = normalizeUrlObject(urlLib.parse(opts.toString()));
opts = {};
} else {
const [pathname, ...searchParts] = (opts.path || '').split('?');
const search = searchParts.length > 0 ?
`?${searchParts.join('?')}` :
'';
url = normalizeUrlObject({ ...opts, pathname, search });
}
opts = {
headers: {},
method: 'GET',
cache: true,
strictTtl: false,
automaticFailover: false,
...opts,
...urlObjectToRequestOptions(url)
};
opts.headers = lowercaseKeys(opts.headers);
const ee = new EventEmitter();
const normalizedUrlString = normalizeUrl(
urlLib.format(url),
{
stripWWW: false,
removeTrailingSlash: false,
stripAuthentication: false
}
);
const key = `${opts.method}:${normalizedUrlString}`;
let revalidate = false;
let madeRequest = false;
const makeRequest = opts => {
madeRequest = true;
let requestErrored = false;
let requestErrorCallback;
const requestErrorPromise = new Promise(resolve => {
requestErrorCallback = () => {
if (!requestErrored) {
requestErrored = true;
resolve();
}
};
});
const handler = response => {
if (revalidate && !opts.forceRefresh) {
response.status = response.statusCode;
const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response);
if (!revalidatedPolicy.modified) {
const headers = revalidatedPolicy.policy.responseHeaders();
response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url);
response.cachePolicy = revalidatedPolicy.policy;
response.fromCache = true;
}
}
if (!response.fromCache) {
response.cachePolicy = new CachePolicy(opts, response, opts);
response.fromCache = false;
}
let clonedResponse;
if (opts.cache && response.cachePolicy.storable()) {
clonedResponse = cloneResponse(response);
(async () => {
try {
const bodyPromise = getStream.buffer(response);
await Promise.race([
requestErrorPromise,
new Promise(resolve => response.once('end', resolve))
]);
if (requestErrored) {
return;
}
const body = await bodyPromise;
const value = {
cachePolicy: response.cachePolicy.toObject(),
url: response.url,
statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
body
};
let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined;
if (opts.maxTtl) {
ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl;
}
await this.cache.set(key, value, ttl);
} catch (error) {
ee.emit('error', new CacheableRequest.CacheError(error));
}
})();
} else if (opts.cache && revalidate) {
(async () => {
try {
await this.cache.delete(key);
} catch (error) {
ee.emit('error', new CacheableRequest.CacheError(error));
}
})();
}
ee.emit('response', clonedResponse || response);
if (typeof cb === 'function') {
cb(clonedResponse || response);
}
};
try {
const req = request(opts, handler);
req.once('error', requestErrorCallback);
req.once('abort', requestErrorCallback);
ee.emit('request', req);
} catch (error) {
ee.emit('error', new CacheableRequest.RequestError(error));
}
};
(async () => {
const get = async opts => {
await Promise.resolve();
const cacheEntry = opts.cache ? await this.cache.get(key) : undefined;
if (typeof cacheEntry === 'undefined') {
return makeRequest(opts);
}
const policy = CachePolicy.fromObject(cacheEntry.cachePolicy);
if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) {
const headers = policy.responseHeaders();
const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url);
response.cachePolicy = policy;
response.fromCache = true;
ee.emit('response', response);
if (typeof cb === 'function') {
cb(response);
}
} else {
revalidate = cacheEntry;
opts.headers = policy.revalidationHeaders(opts);
makeRequest(opts);
}
};
const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error));
this.cache.once('error', errorHandler);
ee.on('response', () => this.cache.removeListener('error', errorHandler));
try {
await get(opts);
} catch (error) {
if (opts.automaticFailover && !madeRequest) {
makeRequest(opts);
}
ee.emit('error', new CacheableRequest.CacheError(error));
}
})();
return ee;
};
}
}
function urlObjectToRequestOptions(url) {
const options = { ...url };
options.path = `${url.pathname || '/'}${url.search || ''}`;
delete options.pathname;
delete options.search;
return options;
}
function normalizeUrlObject(url) {
// If url was parsed by url.parse or new URL:
// - hostname will be set
// - host will be hostname[:port]
// - port will be set if it was explicit in the parsed string
// Otherwise, url was from request options:
// - hostname or host may be set
// - host shall not have port encoded
return {
protocol: url.protocol,
auth: url.auth,
hostname: url.hostname || url.host || 'localhost',
port: url.port,
pathname: url.pathname,
search: url.search
};
}
CacheableRequest.RequestError = class extends Error {
constructor(error) {
super(error.message);
this.name = 'RequestError';
Object.assign(this, error);
}
};
CacheableRequest.CacheError = class extends Error {
constructor(error) {
super(error.message);
this.name = 'CacheError';
Object.assign(this, error);
}
};
module.exports = CacheableRequest;
/***/ }),
/***/ 952:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const {Readable: ReadableStream} = __webpack_require__(413);
const toReadableStream = input => (
new ReadableStream({
read() {
this.push(input);
this.push(null);
}
})
);
module.exports = toReadableStream;
// TODO: Remove this for the next major release
module.exports.default = toReadableStream;
/***/ }),
/***/ 958:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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;
/***/ })
/******/ },
/******/ 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;
/******/ };
/******/ }();
/******/
/******/ }
);