UNPKG

@sap/cli-core

Version:

Command-Line Interface (CLI) Core Module

81 lines (80 loc) 3.13 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetch = exports.DEFAULTS = void 0; const axios_1 = __importDefault(require("axios")); const https_proxy_agent_1 = require("https-proxy-agent"); const config_1 = require("../../config"); const logger_1 = require("../../logger"); const constants_1 = require("../../constants"); const utils_1 = require("./utils"); const core_1 = require("../../config/core"); const utils_2 = require("../../logger/utils"); exports.DEFAULTS = { maxBodyLength: -1, maxContentLength: -1, maxRedirects: 0, // must be set to 0 because maxBodyLength: -1 won't work otherwise, see github.com/axios/axios/issues/4263, }; const HEADERS_ETAG = "x-sap-cli-core-discovery-etag"; const getLogger = () => (0, logger_1.get)("http"); const HTTPS_PROXY = process.env.https_proxy ?? process.env.HTTPS_PROXY; const setEtag = (headers) => { const { debug } = getLogger(); if (headers?.[HEADERS_ETAG]) { (0, config_1.set)({ etag: headers[HEADERS_ETAG] }); } else { debug("header %s is not available", HEADERS_ETAG); } }; const getCsrfTokenFromConfig = () => { const cnfg = (0, config_1.get)(); return cnfg[constants_1.X_CSRF_TOKEN] ? { [constants_1.X_CSRF_TOKEN]: cnfg[constants_1.X_CSRF_TOKEN] } : {}; }; const fetch = async (config) => { const cnfg = (0, config_1.get)(); const logger = getLogger(); const { debug, output, trace, error } = logger; try { (0, utils_2.logVerbose)(logger, "%s %s", config.method.toUpperCase(), config.url); debug("http config: %s", JSON.stringify(config)); const httpsAgent = HTTPS_PROXY ? new https_proxy_agent_1.HttpsProxyAgent(HTTPS_PROXY) : null; if (httpsAgent && cnfg.verbose) { output(`using https proxy agent for https proxy`); debug(`using https proxy agent for https proxy ${HTTPS_PROXY}`); } else { debug("no https proxy defined via environment variable https_proxy"); } const res = await (0, axios_1.default)({ httpsAgent, proxy: false, ...config, ...exports.DEFAULTS, headers: { ...getCsrfTokenFromConfig(), ...config.headers, "User-Agent": `${(0, core_1.getPackageName)()}+${(0, core_1.getVersion)()}`, }, }); if (cnfg.verbose) { (0, utils_2.logVerbose)(logger, "%d %s", res.status, res.statusText); (0, utils_1.printCorrelationId)(res); } trace("response", res); setEtag(res.headers); return res; } catch (err) { error("error while executing http request", err.toString(), err.response); if (cnfg.verbose) { (0, utils_1.printError)(err); (0, utils_1.printCorrelationId)(err.response); } setEtag(err.response?.headers); throw err; } }; exports.fetch = fetch;