From f3f4f072428dd788f4594effd99ab52692e671da Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 15:43:16 +0530 Subject: [PATCH 1/8] fix(): node vulnerabilities. Updated npm packages. No more high or above vulnerabilities. --- build/index.js | 2762 ++++++++++++++++++++++++++++++--------------- build/lib.json | 3 +- package-lock.json | 276 +---- package.json | 2 +- 4 files changed, 1922 insertions(+), 1121 deletions(-) diff --git a/build/index.js b/build/index.js index e490ea24..406e36a0 100644 --- a/build/index.js +++ b/build/index.js @@ -5619,8 +5619,9 @@ module.exports = { "use strict"; +var _a, _b; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports._exposeCertSettings = exports._exposeProxySettings = exports._normalizeSeparators = exports._isRooted = exports._getDirectoryName = exports._ensureRooted = exports._isUncPath = exports._loadData = exports._ensurePatternRooted = exports._getFindInfoFromPattern = exports._cloneMatchOptions = exports._legacyFindFiles_convertPatternToRegExp = exports._which = exports._checkPath = exports._exist = exports._debug = exports._error = exports._warning = exports._command = exports._getVariableKey = exports._getVariable = exports._loc = exports._setResourcePath = exports._setErrStream = exports._setStdStream = exports._writeLine = exports._endsWith = exports._startsWith = exports._vault = exports._knownVariableMap = void 0; +exports.isSigPipeError = exports._exposeCertSettings = exports._exposeProxySettings = exports._normalizeSeparators = exports._isRooted = exports._getDirectoryName = exports._ensureRooted = exports._isUncPath = exports._loadData = exports._ensurePatternRooted = exports._getFindInfoFromPattern = exports._cloneMatchOptions = exports._legacyFindFiles_convertPatternToRegExp = exports._which = exports._checkPath = exports._exist = exports._debug = exports._error = exports._warning = exports._command = exports._getVariableKey = exports._getVariable = exports._loc = exports._setResourcePath = exports._setErrStream = exports._setStdStream = exports._writeLine = exports._truncateBeforeSensitiveKeyword = exports._endsWith = exports._startsWith = exports.IssueAuditAction = exports.IssueSource = exports._vault = exports._knownVariableMap = void 0; var fs = __nccwpck_require__(7147); var path = __nccwpck_require__(1017); var os = __nccwpck_require__(2037); @@ -5640,12 +5641,26 @@ var crypto = __nccwpck_require__(6113); * 3) to know the real variable name and not just the formatted env var name. */ exports._knownVariableMap = {}; +var _commandCorrelationId; +//----------------------------------------------------- +// Enums +//----------------------------------------------------- +var IssueSource; +(function (IssueSource) { + IssueSource["CustomerScript"] = "CustomerScript"; + IssueSource["TaskInternal"] = "TaskInternal"; +})(IssueSource = exports.IssueSource || (exports.IssueSource = {})); +var IssueAuditAction; +(function (IssueAuditAction) { + IssueAuditAction[IssueAuditAction["Unknown"] = 0] = "Unknown"; + IssueAuditAction[IssueAuditAction["ShellTasksValidation"] = 1] = "ShellTasksValidation"; +})(IssueAuditAction = exports.IssueAuditAction || (exports.IssueAuditAction = {})); //----------------------------------------------------- // Validation Checks //----------------------------------------------------- // async await needs generators in node 4.x+ if (semver.lt(process.versions.node, '4.2.0')) { - _warning('Tasks require a new agent. Upgrade your agent or node to 4.2.0 or later'); + _warning('Tasks require a new agent. Upgrade your agent or node to 4.2.0 or later', IssueSource.TaskInternal); } //----------------------------------------------------- // String convenience @@ -5658,6 +5673,17 @@ function _endsWith(str, end) { return str.slice(-end.length) == end; } exports._endsWith = _endsWith; +function _truncateBeforeSensitiveKeyword(str, sensitiveKeywordsPattern) { + if (!str) { + return str; + } + var index = str.search(sensitiveKeywordsPattern); + if (index <= 0) { + return str; + } + return "".concat(str.substring(0, index), "..."); +} +exports._truncateBeforeSensitiveKeyword = _truncateBeforeSensitiveKeyword; //----------------------------------------------------- // General Helpers //----------------------------------------------------- @@ -5736,7 +5762,7 @@ function _loadLocStrings(resourceFile, culture) { } } else { - _warning('LIB_ResourceFile does not exist'); + _warning('LIB_ResourceFile does not exist', IssueSource.TaskInternal); } return locStrings; } @@ -5768,10 +5794,9 @@ function _setResourcePath(path, ignoreWarnings) { } else { if (ignoreWarnings) { - _debug(_loc('LIB_ResourceFileAlreadySet', path)); } else { - _warning(_loc('LIB_ResourceFileAlreadySet', path)); + _warning(_loc('LIB_ResourceFileAlreadySet', path), IssueSource.TaskInternal); } } } @@ -5805,10 +5830,10 @@ function _loc(key) { } else { if (Object.keys(_resourceFiles).length <= 0) { - _warning("Resource file haven't been set, can't find loc string for key: " + key); + _warning("Resource file haven't been set, can't find loc string for key: ".concat(key), IssueSource.TaskInternal); } else { - _warning("Can't find loc string for key: " + key); + _warning("Can't find loc string for key: ".concat(key)); } locString = key; } @@ -5868,16 +5893,33 @@ function _command(command, properties, message) { _writeLine(taskCmd.toString()); } exports._command = _command; -function _warning(message) { - _command('task.issue', { 'type': 'warning' }, message); +function _warning(message, source, auditAction) { + if (source === void 0) { source = IssueSource.TaskInternal; } + _command('task.issue', { + 'type': 'warning', + 'source': source, + 'correlationId': _commandCorrelationId, + 'auditAction': auditAction + }, message); } exports._warning = _warning; -function _error(message) { - _command('task.issue', { 'type': 'error' }, message); +function _error(message, source, auditAction) { + if (source === void 0) { source = IssueSource.TaskInternal; } + _command('task.issue', { + 'type': 'error', + 'source': source, + 'correlationId': _commandCorrelationId, + 'auditAction': auditAction + }, message); } exports._error = _error; +var debugMode = ((_a = _getVariable('system.debug')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'true'; +var shouldCheckDebugMode = ((_b = _getVariable('DistributedTask.Tasks.Node.SkipDebugLogsWhenDebugModeOff')) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'true'; function _debug(message) { - _command('task.debug', null, message); + if (!shouldCheckDebugMode + || (shouldCheckDebugMode && debugMode)) { + _command('task.debug', null, message); + } } exports._debug = _debug; // //----------------------------------------------------- @@ -5947,7 +5989,7 @@ function _which(tool, check) { } } } - _debug("which '" + tool + "'"); + _debug("which '".concat(tool, "'")); try { // build the list of extensions to try var extensions = []; @@ -5963,7 +6005,7 @@ function _which(tool, check) { if (_isRooted(tool)) { var filePath = _tryGetExecutablePath(tool, extensions); if (filePath) { - _debug("found: '" + filePath + "'"); + _debug("found: '".concat(filePath, "'")); return filePath; } _debug('not found'); @@ -5994,7 +6036,7 @@ function _which(tool, check) { var directory = directories_1[_d]; var filePath = _tryGetExecutablePath(directory + path.sep + tool, extensions); if (filePath) { - _debug("found: '" + filePath + "'"); + _debug("found: '".concat(filePath, "'")); return filePath; } } @@ -6038,7 +6080,7 @@ function _tryGetExecutablePath(filePath, extensions) { } catch (err) { if (err.code != 'ENOENT') { - _debug("Unexpected error attempting to determine if executable file exists '" + filePath + "': " + err); + _debug("Unexpected error attempting to determine if executable file exists '".concat(filePath, "': ").concat(err)); } } // try each extension @@ -6064,7 +6106,7 @@ function _tryGetExecutablePath(filePath, extensions) { } } catch (err) { - _debug("Unexpected error attempting to determine the actual case of the file '" + filePath_1 + "': " + err); + _debug("Unexpected error attempting to determine the actual case of the file '".concat(filePath_1, "': ").concat(err)); } return filePath_1; } @@ -6077,7 +6119,7 @@ function _tryGetExecutablePath(filePath, extensions) { } catch (err) { if (err.code != 'ENOENT') { - _debug("Unexpected error attempting to determine if executable file exists '" + filePath_1 + "': " + err); + _debug("Unexpected error attempting to determine if executable file exists '".concat(filePath_1, "': ").concat(err)); } } } @@ -6096,7 +6138,7 @@ function _legacyFindFiles_convertPatternToRegExp(pattern) { .replace(/\\\*\\\*/g, '.*') // replace remaining globstars with a wildcard that can span directory separators, e.g. /hello/**dll .replace(/\\\*/g, '[^\/]*') // replace asterisks with a wildcard that cannot span directory separators, e.g. /hello/*.dll .replace(/\\\?/g, '[^\/]'); // replace single character wildcards, e.g. /hello/log?.dll - pattern = "^" + pattern + "$"; + pattern = "^".concat(pattern, "$"); var flags = process.platform == 'win32' ? 'i' : ''; return new RegExp(pattern, flags); } @@ -6262,6 +6304,9 @@ function _loadData() { } } _debug('loaded ' + loaded); + var correlationId = process.env["COMMAND_CORRELATION_ID"]; + delete process.env["COMMAND_CORRELATION_ID"]; + _commandCorrelationId = correlationId ? String(correlationId) : ""; // store public variable metadata var names; try { @@ -6503,6 +6548,14 @@ function _exposeTaskLibSecret(keyFile, secret) { return new Buffer(storageFile).toString('base64') + ':' + new Buffer(encryptedContent).toString('base64'); } } +function isSigPipeError(e) { + var _a; + if (!e || typeof e !== 'object') { + return false; + } + return e.code === 'EPIPE' && ((_a = e.syscall) === null || _a === void 0 ? void 0 : _a.toUpperCase()) === 'WRITE'; +} +exports.isSigPipeError = isSigPipeError; /***/ }), @@ -6513,7 +6566,8 @@ function _exposeTaskLibSecret(keyFile, secret) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.updateReleaseName = exports.addBuildTag = exports.updateBuildNumber = exports.uploadBuildLog = exports.associateArtifact = exports.uploadArtifact = exports.logIssue = exports.logDetail = exports.setProgress = exports.setEndpoint = exports.addAttachment = exports.uploadSummary = exports.prependPath = exports.uploadFile = exports.CodeCoverageEnabler = exports.CodeCoveragePublisher = exports.TestPublisher = exports.getHttpCertConfiguration = exports.getHttpProxyConfiguration = exports.findMatch = exports.filter = exports.match = exports.tool = exports.execSync = exports.exec = exports.rmRF = exports.legacyFindFiles = exports.find = exports.retry = exports.mv = exports.cp = exports.ls = exports.which = exports.resolve = exports.mkdirP = exports.popd = exports.pushd = exports.cd = exports.checkPath = exports.cwd = exports.getAgentMode = exports.getPlatform = exports.osType = exports.writeFile = exports.exist = exports.stats = exports.debug = exports.error = exports.warning = exports.command = exports.setTaskVariable = exports.getTaskVariable = exports.getSecureFileTicket = exports.getSecureFileName = exports.getEndpointAuthorization = exports.getEndpointAuthorizationParameterRequired = exports.getEndpointAuthorizationParameter = exports.getEndpointAuthorizationSchemeRequired = exports.getEndpointAuthorizationScheme = exports.getEndpointDataParameterRequired = exports.getEndpointDataParameter = exports.getEndpointUrlRequired = exports.getEndpointUrl = exports.getPathInputRequired = exports.getPathInput = exports.filePathSupplied = exports.getDelimitedInput = exports.getBoolInput = exports.getInputRequired = exports.getInput = exports.setSecret = exports.setVariable = exports.getVariables = exports.assertAgent = exports.getVariable = exports.loc = exports.setResourcePath = exports.setResult = exports.setErrStream = exports.setStdStream = exports.AgentHostedMode = exports.Platform = exports.FieldType = exports.ArtifactType = exports.IssueType = exports.TaskState = exports.TaskResult = void 0; +exports.getPlatform = exports.osType = exports.writeFile = exports.exist = exports.stats = exports.debug = exports.error = exports.warning = exports.command = exports.setTaskVariable = exports.getTaskVariable = exports.getSecureFileTicket = exports.getSecureFileName = exports.getEndpointAuthorization = exports.getEndpointAuthorizationParameterRequired = exports.getEndpointAuthorizationParameter = exports.getEndpointAuthorizationSchemeRequired = exports.getEndpointAuthorizationScheme = exports.getEndpointDataParameterRequired = exports.getEndpointDataParameter = exports.getEndpointUrlRequired = exports.getEndpointUrl = exports.getPathInputRequired = exports.getPathInput = exports.filePathSupplied = exports.getDelimitedInput = exports.getPipelineFeature = exports.getBoolFeatureFlag = exports.getBoolInput = exports.getInputRequired = exports.getInput = exports.setSecret = exports.setVariable = exports.getVariables = exports.assertAgent = exports.getVariable = exports.loc = exports.setResourcePath = exports.setSanitizedResult = exports.setResult = exports.setErrStream = exports.setStdStream = exports.AgentHostedMode = exports.Platform = exports.IssueSource = exports.FieldType = exports.ArtifactType = exports.IssueType = exports.TaskState = exports.TaskResult = void 0; +exports.updateReleaseName = exports.addBuildTag = exports.updateBuildNumber = exports.uploadBuildLog = exports.associateArtifact = exports.uploadArtifact = exports.logIssue = exports.logDetail = exports.setProgress = exports.setEndpoint = exports.addAttachment = exports.uploadSummary = exports.prependPath = exports.uploadFile = exports.CodeCoverageEnabler = exports.CodeCoveragePublisher = exports.TestPublisher = exports.getHttpCertConfiguration = exports.getHttpProxyConfiguration = exports.findMatch = exports.filter = exports.match = exports.tool = exports.execSync = exports.exec = exports.execAsync = exports.rmRF = exports.legacyFindFiles = exports.find = exports.retry = exports.mv = exports.cp = exports.ls = exports.which = exports.resolve = exports.mkdirP = exports.popd = exports.pushd = exports.cd = exports.checkPath = exports.cwd = exports.getAgentMode = exports.getNodeMajorVersion = void 0; var shell = __nccwpck_require__(3516); var childProcess = __nccwpck_require__(2081); var fs = __nccwpck_require__(7147); @@ -6558,6 +6612,7 @@ var FieldType; FieldType[FieldType["DataParameter"] = 1] = "DataParameter"; FieldType[FieldType["Url"] = 2] = "Url"; })(FieldType = exports.FieldType || (exports.FieldType = {})); +exports.IssueSource = im.IssueSource; /** Platforms supported by our build agent */ var Platform; (function (Platform) { @@ -6576,45 +6631,62 @@ var AgentHostedMode; //----------------------------------------------------- exports.setStdStream = im._setStdStream; exports.setErrStream = im._setErrStream; -//----------------------------------------------------- -// Results -//----------------------------------------------------- -/** - * Sets the result of the task. - * Execution will continue. - * If not set, task will be Succeeded. - * If multiple calls are made to setResult the most pessimistic call wins (Failed) regardless of the order of calls. - * - * @param result TaskResult enum of Succeeded, SucceededWithIssues, Failed, Cancelled or Skipped. - * @param message A message which will be logged as an error issue if the result is Failed. - * @param done Optional. Instructs the agent the task is done. This is helpful when child processes - * may still be running and prevent node from fully exiting. This argument is supported - * from agent version 2.142.0 or higher (otherwise will no-op). - * @returns void - */ function setResult(result, message, done) { - exports.debug('task result: ' + TaskResult[result]); + (0, exports.debug)('task result: ' + TaskResult[result]); // add an error issue if (result == TaskResult.Failed && message) { - exports.error(message); + (0, exports.error)(message, exports.IssueSource.TaskInternal); } else if (result == TaskResult.SucceededWithIssues && message) { - exports.warning(message); + (0, exports.warning)(message, exports.IssueSource.TaskInternal); } // task.complete var properties = { 'result': TaskResult[result] }; if (done) { properties['done'] = 'true'; } - exports.command('task.complete', properties, message); + (0, exports.command)('task.complete', properties, message); } exports.setResult = setResult; +/** + * Sets the result of the task with sanitized message. + * + * @param result TaskResult enum of Succeeded, SucceededWithIssues, Failed, Cancelled or Skipped. + * @param message A message which will be logged as an error issue if the result is Failed. Message will be truncated + * before first occurence of wellknown sensitive keyword. + * @param done Optional. Instructs the agent the task is done. This is helpful when child processes + * may still be running and prevent node from fully exiting. This argument is supported + * from agent version 2.142.0 or higher (otherwise will no-op). + * @returns void + */ +function setSanitizedResult(result, message, done) { + var pattern = /password|key|secret|bearer|authorization|token|pat/i; + var sanitizedMessage = im._truncateBeforeSensitiveKeyword(message, pattern); + setResult(result, sanitizedMessage, done); +} +exports.setSanitizedResult = setSanitizedResult; // // Catching all exceptions // process.on('uncaughtException', function (err) { - setResult(TaskResult.Failed, exports.loc('LIB_UnhandledEx', err.message)); - exports.error(String(err.stack)); + if (!im.isSigPipeError(err)) { + setResult(TaskResult.Failed, (0, exports.loc)('LIB_UnhandledEx', err.message)); + (0, exports.error)(String(err.stack), im.IssueSource.TaskInternal); + } +}); +// +// Catching unhandled rejections from promises and rethrowing them as exceptions +// For example, a promise that is rejected but not handled by a .catch() handler in node 10 +// doesn't cause an uncaughtException but causes in Node 16. +// For types definitions(Error | Any) see https://nodejs.org/docs/latest-v16.x/api/process.html#event-unhandledrejection +// +process.on('unhandledRejection', function (reason) { + if (reason instanceof Error) { + throw reason; + } + else { + throw new Error(reason); + } }); //----------------------------------------------------- // Loc Helpers @@ -6634,9 +6706,9 @@ function assertAgent(minimum) { if (semver.lt(minimum, '2.104.1')) { throw new Error('assertAgent() requires the parameter to be 2.104.1 or higher'); } - var agent = exports.getVariable('Agent.Version'); + var agent = (0, exports.getVariable)('Agent.Version'); if (agent && semver.lt(agent, minimum)) { - throw new Error("Agent version " + minimum + " or higher is required"); + throw new Error("Agent version ".concat(minimum, " or higher is required")); } } exports.assertAgent = assertAgent; @@ -6657,7 +6729,7 @@ function getVariables() { return Object.keys(im._knownVariableMap) .map(function (key) { var info = im._knownVariableMap[key]; - return { name: info.name, value: exports.getVariable(info.name), secret: info.secret }; + return { name: info.name, value: (0, exports.getVariable)(info.name), secret: info.secret }; }); } exports.getVariables = getVariables; @@ -6680,10 +6752,10 @@ function setVariable(name, val, secret, isOutput) { } // store the value var varValue = val || ''; - exports.debug('set ' + name + '=' + (secret && varValue ? '********' : varValue)); + (0, exports.debug)('set ' + name + '=' + (secret && varValue ? '********' : varValue)); if (secret) { - if (varValue && varValue.match(/\r|\n/) && ("" + process.env['SYSTEM_UNSAFEALLOWMULTILINESECRET']).toUpperCase() != 'TRUE') { - throw new Error(exports.loc('LIB_MultilineSecret')); + if (varValue && varValue.match(/\r|\n/) && "".concat(process.env['SYSTEM_UNSAFEALLOWMULTILINESECRET']).toUpperCase() != 'TRUE') { + throw new Error((0, exports.loc)('LIB_MultilineSecret')); } im._vault.storeSecret('SECRET_' + key, varValue); delete process.env[key]; @@ -6694,7 +6766,7 @@ function setVariable(name, val, secret, isOutput) { // store the metadata im._knownVariableMap[key] = { name: name, secret: secret }; // write the setvariable command - exports.command('task.setvariable', { 'variable': name || '', isOutput: (isOutput || false).toString(), 'issecret': (secret || false).toString() }, varValue); + (0, exports.command)('task.setvariable', { 'variable': name || '', isOutput: (isOutput || false).toString(), 'issecret': (secret || false).toString() }, varValue); } exports.setVariable = setVariable; /** @@ -6704,10 +6776,10 @@ exports.setVariable = setVariable; */ function setSecret(val) { if (val) { - if (val.match(/\r|\n/) && ("" + process.env['SYSTEM_UNSAFEALLOWMULTILINESECRET']).toUpperCase() !== 'TRUE') { - throw new Error(exports.loc('LIB_MultilineSecret')); + if (val.match(/\r|\n/) && "".concat(process.env['SYSTEM_UNSAFEALLOWMULTILINESECRET']).toUpperCase() !== 'TRUE') { + throw new Error((0, exports.loc)('LIB_MultilineSecret')); } - exports.command('task.setsecret', {}, val); + (0, exports.command)('task.setsecret', {}, val); } } exports.setSecret = setSecret; @@ -6722,9 +6794,9 @@ exports.setSecret = setSecret; function getInput(name, required) { var inval = im._vault.retrieveSecret('INPUT_' + im._getVariableKey(name)); if (required && !inval) { - throw new Error(exports.loc('LIB_InputRequired', name)); + throw new Error((0, exports.loc)('LIB_InputRequired', name)); } - exports.debug(name + '=' + inval); + (0, exports.debug)(name + '=' + inval); return inval; } exports.getInput = getInput; @@ -6752,6 +6824,43 @@ function getBoolInput(name, required) { return (getInput(name, required) || '').toUpperCase() == "TRUE"; } exports.getBoolInput = getBoolInput; +/** + * Gets the value of an feature flag and converts to a bool. + * @IMPORTANT This method is only for internal Microsoft development. Do not use it for external tasks. + * @param name name of the feature flag to get. + * @param defaultValue default value of the feature flag in case it's not found in env. (optional. Default value = false) + * @returns boolean + * @deprecated Don't use this for new development. Use getPipelineFeature instead. + */ +function getBoolFeatureFlag(ffName, defaultValue) { + if (defaultValue === void 0) { defaultValue = false; } + var ffValue = process.env[ffName]; + if (!ffValue) { + (0, exports.debug)("Feature flag ".concat(ffName, " not found. Returning ").concat(defaultValue, " as default.")); + return defaultValue; + } + (0, exports.debug)("Feature flag ".concat(ffName, " = ").concat(ffValue)); + return ffValue.toLowerCase() === "true"; +} +exports.getBoolFeatureFlag = getBoolFeatureFlag; +/** + * Gets the value of an task feature and converts to a bool. + * @IMPORTANT This method is only for internal Microsoft development. Do not use it for external tasks. + * @param name name of the feature to get. + * @returns boolean + */ +function getPipelineFeature(featureName) { + var variableName = im._getVariableKey("DistributedTask.Tasks.".concat(featureName)); + var featureValue = process.env[variableName]; + if (!featureValue) { + (0, exports.debug)("Feature '".concat(featureName, "' not found. Returning false as default.")); + return false; + } + var boolValue = featureValue.toLowerCase() === "true"; + (0, exports.debug)("Feature '".concat(featureName, "' = '").concat(featureValue, "'. Processed as '").concat(boolValue, "'.")); + return boolValue; +} +exports.getPipelineFeature = getPipelineFeature; /** * Gets the value of an input and splits the value using a delimiter (space, comma, etc). * Empty values are removed. This function is useful for splitting an input containing a simple @@ -6790,9 +6899,9 @@ exports.getDelimitedInput = getDelimitedInput; function filePathSupplied(name) { // normalize paths var pathValue = this.resolve(this.getPathInput(name) || ''); - var repoRoot = this.resolve(exports.getVariable('build.sourcesDirectory') || exports.getVariable('system.defaultWorkingDirectory') || ''); + var repoRoot = this.resolve((0, exports.getVariable)('build.sourcesDirectory') || (0, exports.getVariable)('system.defaultWorkingDirectory') || ''); var supplied = pathValue !== repoRoot; - exports.debug(name + 'path supplied :' + supplied); + (0, exports.debug)(name + 'path supplied :' + supplied); return supplied; } exports.filePathSupplied = filePathSupplied; @@ -6811,7 +6920,7 @@ function getPathInput(name, required, check) { var inval = getInput(name, required); if (inval) { if (check) { - exports.checkPath(inval, name); + (0, exports.checkPath)(inval, name); } } return inval; @@ -6845,9 +6954,9 @@ exports.getPathInputRequired = getPathInputRequired; function getEndpointUrl(id, optional) { var urlval = process.env['ENDPOINT_URL_' + id]; if (!optional && !urlval) { - throw new Error(exports.loc('LIB_EndpointNotExist', id)); + throw new Error((0, exports.loc)('LIB_EndpointNotExist', id)); } - exports.debug(id + '=' + urlval); + (0, exports.debug)(id + '=' + urlval); return urlval; } exports.getEndpointUrl = getEndpointUrl; @@ -6874,9 +6983,9 @@ exports.getEndpointUrlRequired = getEndpointUrlRequired; function getEndpointDataParameter(id, key, optional) { var dataParamVal = process.env['ENDPOINT_DATA_' + id + '_' + key.toUpperCase()]; if (!optional && !dataParamVal) { - throw new Error(exports.loc('LIB_EndpointDataNotExist', id, key)); + throw new Error((0, exports.loc)('LIB_EndpointDataNotExist', id, key)); } - exports.debug(id + ' data ' + key + ' = ' + dataParamVal); + (0, exports.debug)(id + ' data ' + key + ' = ' + dataParamVal); return dataParamVal; } exports.getEndpointDataParameter = getEndpointDataParameter; @@ -6903,9 +7012,9 @@ exports.getEndpointDataParameterRequired = getEndpointDataParameterRequired; function getEndpointAuthorizationScheme(id, optional) { var authScheme = im._vault.retrieveSecret('ENDPOINT_AUTH_SCHEME_' + id); if (!optional && !authScheme) { - throw new Error(exports.loc('LIB_EndpointAuthNotExist', id)); + throw new Error((0, exports.loc)('LIB_EndpointAuthNotExist', id)); } - exports.debug(id + ' auth scheme = ' + authScheme); + (0, exports.debug)(id + ' auth scheme = ' + authScheme); return authScheme; } exports.getEndpointAuthorizationScheme = getEndpointAuthorizationScheme; @@ -6932,9 +7041,9 @@ exports.getEndpointAuthorizationSchemeRequired = getEndpointAuthorizationSchemeR function getEndpointAuthorizationParameter(id, key, optional) { var authParam = im._vault.retrieveSecret('ENDPOINT_AUTH_PARAMETER_' + id + '_' + key.toUpperCase()); if (!optional && !authParam) { - throw new Error(exports.loc('LIB_EndpointAuthNotExist', id)); + throw new Error((0, exports.loc)('LIB_EndpointAuthNotExist', id)); } - exports.debug(id + ' auth param ' + key + ' = ' + authParam); + (0, exports.debug)(id + ' auth param ' + key + ' = ' + authParam); return authParam; } exports.getEndpointAuthorizationParameter = getEndpointAuthorizationParameter; @@ -6961,9 +7070,9 @@ exports.getEndpointAuthorizationParameterRequired = getEndpointAuthorizationPara function getEndpointAuthorization(id, optional) { var aval = im._vault.retrieveSecret('ENDPOINT_AUTH_' + id); if (!optional && !aval) { - setResult(TaskResult.Failed, exports.loc('LIB_EndpointAuthNotExist', id)); + setResult(TaskResult.Failed, (0, exports.loc)('LIB_EndpointAuthNotExist', id)); } - exports.debug(id + ' exists ' + (!!aval)); + (0, exports.debug)(id + ' exists ' + (!!aval)); var auth; try { if (aval) { @@ -6971,7 +7080,7 @@ function getEndpointAuthorization(id, optional) { } } catch (err) { - throw new Error(exports.loc('LIB_InvalidEndpointAuth', aval)); + throw new Error((0, exports.loc)('LIB_InvalidEndpointAuth', aval)); } return auth; } @@ -6987,7 +7096,7 @@ exports.getEndpointAuthorization = getEndpointAuthorization; */ function getSecureFileName(id) { var name = process.env['SECUREFILE_NAME_' + id]; - exports.debug('secure file name for id ' + id + ' = ' + name); + (0, exports.debug)('secure file name for id ' + id + ' = ' + name); return name; } exports.getSecureFileName = getSecureFileName; @@ -6999,7 +7108,7 @@ exports.getSecureFileName = getSecureFileName; */ function getSecureFileTicket(id) { var ticket = im._vault.retrieveSecret('SECUREFILE_TICKET_' + id); - exports.debug('secure file ticket for id ' + id + ' = ' + ticket); + (0, exports.debug)('secure file ticket for id ' + id + ' = ' + ticket); return ticket; } exports.getSecureFileTicket = getSecureFileTicket; @@ -7019,7 +7128,7 @@ function getTaskVariable(name) { if (inval) { inval = inval.trim(); } - exports.debug('task variable: ' + name + '=' + inval); + (0, exports.debug)('task variable: ' + name + '=' + inval); return inval; } exports.getTaskVariable = getTaskVariable; @@ -7038,11 +7147,11 @@ function setTaskVariable(name, val, secret) { var key = im._getVariableKey(name); // store the value var varValue = val || ''; - exports.debug('set task variable: ' + name + '=' + (secret && varValue ? '********' : varValue)); + (0, exports.debug)('set task variable: ' + name + '=' + (secret && varValue ? '********' : varValue)); im._vault.storeSecret('VSTS_TASKVARIABLE_' + key, varValue); delete process.env[key]; // write the command - exports.command('task.settaskvariable', { 'variable': name || '', 'issecret': (secret || false).toString() }, varValue); + (0, exports.command)('task.settaskvariable', { 'variable': name || '', 'issecret': (secret || false).toString() }, varValue); } exports.setTaskVariable = setTaskVariable; //----------------------------------------------------- @@ -7058,9 +7167,9 @@ exports.debug = im._debug; function _checkShell(cmd, continueOnError) { var se = shell.error(); if (se) { - exports.debug(cmd + ' failed'); - var errMsg = exports.loc('LIB_OperationFailed', cmd, se); - exports.debug(errMsg); + (0, exports.debug)(cmd + ' failed'); + var errMsg = (0, exports.loc)('LIB_OperationFailed', cmd, se); + (0, exports.debug)(errMsg); if (!continueOnError) { throw new Error(errMsg); } @@ -7109,16 +7218,33 @@ function getPlatform() { case 'win32': return Platform.Windows; case 'darwin': return Platform.MacOS; case 'linux': return Platform.Linux; - default: throw Error(exports.loc('LIB_PlatformNotSupported', process.platform)); + default: throw Error((0, exports.loc)('LIB_PlatformNotSupported', process.platform)); } } exports.getPlatform = getPlatform; +/** + * Resolves major version of Node.js engine used by the agent. + * @returns {Number} Node's major version. + */ +function getNodeMajorVersion() { + var _a; + var version = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node; + if (!version) { + throw new Error((0, exports.loc)('LIB_UndefinedNodeVersion')); + } + var parts = version.split('.').map(Number); + if (parts.length < 1) { + return NaN; + } + return parts[0]; +} +exports.getNodeMajorVersion = getNodeMajorVersion; /** * Return hosted type of Agent * @returns {AgentHostedMode} */ function getAgentMode() { - var agentCloudId = exports.getVariable('Agent.CloudId'); + var agentCloudId = (0, exports.getVariable)('Agent.CloudId'); if (agentCloudId === undefined) return AgentHostedMode.Unknown; if (agentCloudId) @@ -7180,20 +7306,20 @@ exports.popd = popd; */ function mkdirP(p) { if (!p) { - throw new Error(exports.loc('LIB_ParameterIsRequired', 'p')); + throw new Error((0, exports.loc)('LIB_ParameterIsRequired', 'p')); } // build a stack of directories to create var stack = []; var testDir = p; while (true) { // validate the loop is not out of control - if (stack.length >= (process.env['TASKLIB_TEST_MKDIRP_FAILSAFE'] || 1000)) { + if (stack.length >= Number(process.env['TASKLIB_TEST_MKDIRP_FAILSAFE'] || 1000)) { // let the framework throw - exports.debug('loop is out of control'); + (0, exports.debug)('loop is out of control'); fs.mkdirSync(p); return; } - exports.debug("testing directory '" + testDir + "'"); + (0, exports.debug)("testing directory '".concat(testDir, "'")); var stats_1 = void 0; try { stats_1 = fs.statSync(testDir); @@ -7203,7 +7329,7 @@ function mkdirP(p) { // validate the directory is not the drive root var parentDir = path.dirname(testDir); if (testDir == parentDir) { - throw new Error(exports.loc('LIB_MkdirFailedInvalidDriveRoot', p, testDir)); // Unable to create directory '{p}'. Root directory does not exist: '{testDir}' + throw new Error((0, exports.loc)('LIB_MkdirFailedInvalidDriveRoot', p, testDir)); // Unable to create directory '{p}'. Root directory does not exist: '{testDir}' } // push the dir and test the parent stack.push(testDir); @@ -7211,14 +7337,14 @@ function mkdirP(p) { continue; } else if (err.code == 'UNKNOWN') { - throw new Error(exports.loc('LIB_MkdirFailedInvalidShare', p, testDir)); // Unable to create directory '{p}'. Unable to verify the directory exists: '{testDir}'. If directory is a file share, please verify the share name is correct, the share is online, and the current process has permission to access the share. + throw new Error((0, exports.loc)('LIB_MkdirFailedInvalidShare', p, testDir)); // Unable to create directory '{p}'. Unable to verify the directory exists: '{testDir}'. If directory is a file share, please verify the share name is correct, the share is online, and the current process has permission to access the share. } else { throw err; } } if (!stats_1.isDirectory()) { - throw new Error(exports.loc('LIB_MkdirFailedFileExists', p, testDir)); // Unable to create directory '{p}'. Conflicting file exists: '{testDir}' + throw new Error((0, exports.loc)('LIB_MkdirFailedFileExists', p, testDir)); // Unable to create directory '{p}'. Conflicting file exists: '{testDir}' } // testDir exists break; @@ -7226,12 +7352,12 @@ function mkdirP(p) { // create each directory while (stack.length) { var dir = stack.pop(); // non-null because `stack.length` was truthy - exports.debug("mkdir '" + dir + "'"); + (0, exports.debug)("mkdir '".concat(dir, "'")); try { fs.mkdirSync(dir); } catch (err) { - throw new Error(exports.loc('LIB_MkdirFailed', p, err.message)); // Unable to create directory '{p}'. {err.message} + throw new Error((0, exports.loc)('LIB_MkdirFailed', p, err.message)); // Unable to create directory '{p}'. {err.message} } } } @@ -7249,7 +7375,7 @@ function resolve() { pathSegments[_i] = arguments[_i]; } var absolutePath = path.resolve.apply(this, pathSegments); - exports.debug('Absolute path for pathSegments: ' + pathSegments + ' = ' + absolutePath); + (0, exports.debug)('Absolute path for pathSegments: ' + pathSegments + ' = ' + absolutePath); return absolutePath; } exports.resolve = resolve; @@ -7294,7 +7420,7 @@ function cp(source, dest, options, continueOnError, retryCount) { catch (e) { if (retryCount <= 0) { if (continueOnError) { - exports.warning(e); + (0, exports.warning)(e, exports.IssueSource.TaskInternal); break; } else { @@ -7302,7 +7428,7 @@ function cp(source, dest, options, continueOnError, retryCount) { } } else { - console.log(exports.loc('LIB_CopyFileFailed', retryCount)); + console.log((0, exports.loc)('LIB_CopyFileFailed', retryCount)); retryCount--; } } @@ -7344,7 +7470,7 @@ function retry(func, args, retryOptions) { catch (e) { if (retryOptions.retryCount <= 0) { if (retryOptions.continueOnError) { - exports.warning(e); + (0, exports.warning)(e, exports.IssueSource.TaskInternal); break; } else { @@ -7352,7 +7478,7 @@ function retry(func, args, retryOptions) { } } else { - exports.debug("Attempt to execute function \"" + (func === null || func === void 0 ? void 0 : func.name) + "\" failed, retries left: " + retryOptions.retryCount); + (0, exports.debug)("Attempt to execute function \"".concat(func === null || func === void 0 ? void 0 : func.name, "\" failed, retries left: ").concat(retryOptions.retryCount)); retryOptions.retryCount--; } } @@ -7380,7 +7506,7 @@ function _getStats(path, followSymbolicLink, allowBrokenSymbolicLinks) { if (err.code == 'ENOENT' && allowBrokenSymbolicLinks) { // fallback to lstat (broken symlinks allowed) stats = fs.lstatSync(path); - exports.debug(" " + path + " (broken symlink)"); + (0, exports.debug)(" ".concat(path, " (broken symlink)")); } else { throw err; @@ -7402,14 +7528,14 @@ function _getStats(path, followSymbolicLink, allowBrokenSymbolicLinks) { */ function find(findPath, options) { if (!findPath) { - exports.debug('no path specified'); + (0, exports.debug)('no path specified'); return []; } // normalize the path, otherwise the first result is inconsistently formatted from the rest of the results // because path.join() performs normalization. findPath = path.normalize(findPath); // debug trace the parameters - exports.debug("findPath: '" + findPath + "'"); + (0, exports.debug)("findPath: '".concat(findPath, "'")); options = options || _getDefaultFindOptions(); _debugFindOptions(options); // return empty if not exists @@ -7418,7 +7544,7 @@ function find(findPath, options) { } catch (err) { if (err.code == 'ENOENT') { - exports.debug('0 results'); + (0, exports.debug)('0 results'); return []; } throw err; @@ -7444,7 +7570,7 @@ function find(findPath, options) { } catch (err) { if (err.code == 'ENOENT' && options.skipMissingFiles) { - exports.warning("No such file or directory: \"" + item.path + "\" - skipping."); + (0, exports.warning)("No such file or directory: \"".concat(item.path, "\" - skipping."), exports.IssueSource.TaskInternal); return "continue"; } throw err; @@ -7452,7 +7578,7 @@ function find(findPath, options) { result.push(item.path); // note, isDirectory() returns false for the lstat of a symlink if (stats_2.isDirectory()) { - exports.debug(" " + item.path + " (directory)"); + (0, exports.debug)(" ".concat(item.path, " (directory)")); if (options.followSymbolicLinks) { // get the realpath var realPath_1; @@ -7469,7 +7595,7 @@ function find(findPath, options) { } // test for a cycle if (traversalChain.some(function (x) { return x == realPath_1; })) { - exports.debug(' cycle detected'); + (0, exports.debug)(' cycle detected'); return "continue"; } // update the traversal chain @@ -7484,17 +7610,17 @@ function find(findPath, options) { } } else { - exports.debug(" " + item.path + " (file)"); + (0, exports.debug)(" ".concat(item.path, " (file)")); } }; while (stack.length) { _loop_1(); } - exports.debug(result.length + " results"); + (0, exports.debug)("".concat(result.length, " results")); return result; } catch (err) { - throw new Error(exports.loc('LIB_OperationFailed', 'find', err.message)); + throw new Error((0, exports.loc)('LIB_OperationFailed', 'find', err.message)); } } exports.find = find; @@ -7506,10 +7632,10 @@ var _FindItem = /** @class */ (function () { return _FindItem; }()); function _debugFindOptions(options) { - exports.debug("findOptions.allowBrokenSymbolicLinks: '" + options.allowBrokenSymbolicLinks + "'"); - exports.debug("findOptions.followSpecifiedSymbolicLink: '" + options.followSpecifiedSymbolicLink + "'"); - exports.debug("findOptions.followSymbolicLinks: '" + options.followSymbolicLinks + "'"); - exports.debug("findOptions.skipMissingFiles: '" + options.skipMissingFiles + "'"); + (0, exports.debug)("findOptions.allowBrokenSymbolicLinks: '".concat(options.allowBrokenSymbolicLinks, "'")); + (0, exports.debug)("findOptions.followSpecifiedSymbolicLink: '".concat(options.followSpecifiedSymbolicLink, "'")); + (0, exports.debug)("findOptions.followSymbolicLinks: '".concat(options.followSymbolicLinks, "'")); + (0, exports.debug)("findOptions.skipMissingFiles: '".concat(options.skipMissingFiles, "'")); } function _getDefaultFindOptions() { return { @@ -7533,10 +7659,10 @@ function legacyFindFiles(rootDirectory, pattern, includeFiles, includeDirectorie if (!pattern) { throw new Error('pattern parameter cannot be empty'); } - exports.debug("legacyFindFiles rootDirectory: '" + rootDirectory + "'"); - exports.debug("pattern: '" + pattern + "'"); - exports.debug("includeFiles: '" + includeFiles + "'"); - exports.debug("includeDirectories: '" + includeDirectories + "'"); + (0, exports.debug)("legacyFindFiles rootDirectory: '".concat(rootDirectory, "'")); + (0, exports.debug)("pattern: '".concat(pattern, "'")); + (0, exports.debug)("includeFiles: '".concat(includeFiles, "'")); + (0, exports.debug)("includeDirectories: '".concat(includeDirectories, "'")); if (!includeFiles && !includeDirectories) { includeFiles = true; } @@ -7567,7 +7693,7 @@ function legacyFindFiles(rootDirectory, pattern, includeFiles, includeDirectorie } // validate pattern does not end with a slash if (im._endsWith(pat, '/') || (process.platform == 'win32' && im._endsWith(pat, '\\'))) { - throw new Error(exports.loc('LIB_InvalidPattern', pat)); + throw new Error((0, exports.loc)('LIB_InvalidPattern', pat)); } // root the pattern if (rootDirectory && !path.isAbsolute(pat)) { @@ -7589,27 +7715,27 @@ function legacyFindFiles(rootDirectory, pattern, includeFiles, includeDirectorie // find and apply patterns var count = 0; var result = _legacyFindFiles_getMatchingItems(includePatterns, excludePatterns, !!includeFiles, !!includeDirectories); - exports.debug('all matches:'); + (0, exports.debug)('all matches:'); for (var _b = 0, result_1 = result; _b < result_1.length; _b++) { var resultItem = result_1[_b]; - exports.debug(' ' + resultItem); + (0, exports.debug)(' ' + resultItem); } - exports.debug('total matched: ' + result.length); + (0, exports.debug)('total matched: ' + result.length); return result; } exports.legacyFindFiles = legacyFindFiles; function _legacyFindFiles_getMatchingItems(includePatterns, excludePatterns, includeFiles, includeDirectories) { - exports.debug('getMatchingItems()'); + (0, exports.debug)('getMatchingItems()'); for (var _i = 0, includePatterns_1 = includePatterns; _i < includePatterns_1.length; _i++) { var pattern = includePatterns_1[_i]; - exports.debug("includePattern: '" + pattern + "'"); + (0, exports.debug)("includePattern: '".concat(pattern, "'")); } for (var _a = 0, excludePatterns_1 = excludePatterns; _a < excludePatterns_1.length; _a++) { var pattern = excludePatterns_1[_a]; - exports.debug("excludePattern: " + pattern); + (0, exports.debug)("excludePattern: ".concat(pattern)); } - exports.debug('includeFiles: ' + includeFiles); - exports.debug('includeDirectories: ' + includeDirectories); + (0, exports.debug)('includeFiles: ' + includeFiles); + (0, exports.debug)('includeDirectories: ' + includeDirectories); var allFiles = {}; var _loop_2 = function (pattern) { // determine the directory to search @@ -7652,7 +7778,7 @@ function _legacyFindFiles_getMatchingItems(includePatterns, excludePatterns, inc var normalizedPath = process.platform == 'win32' ? item.replace(/\\/g, '/') : item; // normalize separators // **/times/** will not match C:/fun/times because there isn't a trailing slash // so try both if including directories - var alternatePath = normalizedPath + "/"; // potential bug: it looks like this will result in a false + var alternatePath = "".concat(normalizedPath, "/"); // potential bug: it looks like this will result in a false // positive if the item is a regular file and not a directory var isMatch = false; if (patternRegex.test(normalizedPath) || (includeDirectories && patternRegex.test(alternatePath))) { @@ -7684,25 +7810,25 @@ function _legacyFindFiles_getMatchingItems(includePatterns, excludePatterns, inc * @throws when the file or directory exists but could not be deleted. */ function rmRF(inputPath) { - exports.debug('rm -rf ' + inputPath); + (0, exports.debug)('rm -rf ' + inputPath); if (getPlatform() == Platform.Windows) { // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. try { if (fs.statSync(inputPath).isDirectory()) { - exports.debug('removing directory ' + inputPath); - childProcess.execSync("rd /s /q \"" + inputPath + "\""); + (0, exports.debug)('removing directory ' + inputPath); + childProcess.execSync("rd /s /q \"".concat(inputPath, "\"")); } else { - exports.debug('removing file ' + inputPath); - childProcess.execSync("del /f /a \"" + inputPath + "\""); + (0, exports.debug)('removing file ' + inputPath); + childProcess.execSync("del /f /a \"".concat(inputPath, "\"")); } } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code != 'ENOENT') { - throw new Error(exports.loc('LIB_OperationFailed', 'rmRF', err.message)); + throw new Error((0, exports.loc)('LIB_OperationFailed', 'rmRF', err.message)); } } // Shelling out fails to remove a symlink folder with missing source, this unlink catches that @@ -7713,7 +7839,7 @@ function rmRF(inputPath) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code != 'ENOENT') { - throw new Error(exports.loc('LIB_OperationFailed', 'rmRF', err.message)); + throw new Error((0, exports.loc)('LIB_OperationFailed', 'rmRF', err.message)); } } } @@ -7730,23 +7856,23 @@ function rmRF(inputPath) { if (err.code == 'ENOENT') { return; } - throw new Error(exports.loc('LIB_OperationFailed', 'rmRF', err.message)); + throw new Error((0, exports.loc)('LIB_OperationFailed', 'rmRF', err.message)); } if (lstats.isDirectory()) { - exports.debug('removing directory'); + (0, exports.debug)('removing directory'); shell.rm('-rf', inputPath); var errMsg = shell.error(); if (errMsg) { - throw new Error(exports.loc('LIB_OperationFailed', 'rmRF', errMsg)); + throw new Error((0, exports.loc)('LIB_OperationFailed', 'rmRF', errMsg)); } return; } - exports.debug('removing file'); + (0, exports.debug)('removing file'); try { fs.unlinkSync(inputPath); } catch (err) { - throw new Error(exports.loc('LIB_OperationFailed', 'rmRF', err.message)); + throw new Error((0, exports.loc)('LIB_OperationFailed', 'rmRF', err.message)); } } } @@ -7761,11 +7887,32 @@ exports.rmRF = rmRF; * @param options optional exec options. See IExecOptions * @returns number */ +function execAsync(tool, args, options) { + var tr = this.tool(tool); + if (args) { + if (args instanceof Array) { + tr.arg(args); + } + else if (typeof (args) === 'string') { + tr.line(args); + } + } + return tr.execAsync(options); +} +exports.execAsync = execAsync; +/** + * Exec a tool. Convenience wrapper over ToolRunner to exec with args in one call. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @deprecated Use the {@link execAsync} method that returns a native Javascript Promise instead + * @param tool path to tool to exec + * @param args an arg string or array of args + * @param options optional exec options. See IExecOptions + * @returns number + */ function exec(tool, args, options) { var tr = this.tool(tool); - tr.on('debug', function (data) { - exports.debug(data); - }); if (args) { if (args instanceof Array) { tr.arg(args); @@ -7790,9 +7937,6 @@ exports.exec = exec; */ function execSync(tool, args, options) { var tr = this.tool(tool); - tr.on('debug', function (data) { - exports.debug(data); - }); if (args) { if (args instanceof Array) { tr.arg(args); @@ -7813,7 +7957,7 @@ exports.execSync = execSync; function tool(tool) { var tr = new trm.ToolRunner(tool); tr.on('debug', function (message) { - exports.debug(message); + (0, exports.debug)(message); }); return tr; } @@ -7828,7 +7972,7 @@ exports.tool = tool; */ function match(list, patterns, patternRoot, options) { // trace parameters - exports.debug("patternRoot: '" + patternRoot + "'"); + (0, exports.debug)("patternRoot: '".concat(patternRoot, "'")); options = options || _getDefaultMatchOptions(); // default match options _debugMatchOptions(options); // convert pattern to an array @@ -7840,18 +7984,18 @@ function match(list, patterns, patternRoot, options) { var originalOptions = options; for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { var pattern = patterns_1[_i]; - exports.debug("pattern: '" + pattern + "'"); + (0, exports.debug)("pattern: '".concat(pattern, "'")); // trim and skip empty pattern = (pattern || '').trim(); if (!pattern) { - exports.debug('skipping empty pattern'); + (0, exports.debug)('skipping empty pattern'); continue; } // clone match options var options_1 = im._cloneMatchOptions(originalOptions); // skip comments if (!options_1.nocomment && im._startsWith(pattern, '#')) { - exports.debug('skipping comment'); + (0, exports.debug)('skipping comment'); continue; } // set nocomment - brace expansion could result in a leading '#' @@ -7864,7 +8008,7 @@ function match(list, patterns, patternRoot, options) { } pattern = pattern.substring(negateCount); // trim leading '!' if (negateCount) { - exports.debug("trimmed leading '!'. pattern: '" + pattern + "'"); + (0, exports.debug)("trimmed leading '!'. pattern: '".concat(pattern, "'")); } } var isIncludePattern = negateCount == 0 || @@ -7882,7 +8026,7 @@ function match(list, patterns, patternRoot, options) { else { // convert slashes on Windows before calling braceExpand(). unfortunately this means braces cannot // be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3). - exports.debug('expanding braces'); + (0, exports.debug)('expanding braces'); var convertedPattern = process.platform == 'win32' ? pattern.replace(/\\/g, '/') : pattern; expanded = minimatch.braceExpand(convertedPattern); } @@ -7891,12 +8035,12 @@ function match(list, patterns, patternRoot, options) { for (var _a = 0, expanded_1 = expanded; _a < expanded_1.length; _a++) { var pattern_1 = expanded_1[_a]; if (expanded.length != 1 || pattern_1 != preExpanded) { - exports.debug("pattern: '" + pattern_1 + "'"); + (0, exports.debug)("pattern: '".concat(pattern_1, "'")); } // trim and skip empty pattern_1 = (pattern_1 || '').trim(); if (!pattern_1) { - exports.debug('skipping empty pattern'); + (0, exports.debug)('skipping empty pattern'); continue; } // root the pattern when all of the following conditions are true: @@ -7905,13 +8049,13 @@ function match(list, patterns, patternRoot, options) { // AND matchBase:false or not basename only (!options_1.matchBase || (process.platform == 'win32' ? pattern_1.replace(/\\/g, '/') : pattern_1).indexOf('/') >= 0)) { pattern_1 = im._ensureRooted(patternRoot, pattern_1); - exports.debug("rooted pattern: '" + pattern_1 + "'"); + (0, exports.debug)("rooted pattern: '".concat(pattern_1, "'")); } if (isIncludePattern) { // apply the pattern - exports.debug('applying include pattern against original list'); + (0, exports.debug)('applying include pattern against original list'); var matchResults = minimatch.match(list, pattern_1, options_1); - exports.debug(matchResults.length + ' matches'); + (0, exports.debug)(matchResults.length + ' matches'); // union the results for (var _b = 0, matchResults_1 = matchResults; _b < matchResults_1.length; _b++) { var matchResult = matchResults_1[_b]; @@ -7920,9 +8064,9 @@ function match(list, patterns, patternRoot, options) { } else { // apply the pattern - exports.debug('applying exclude pattern against original list'); + (0, exports.debug)('applying exclude pattern against original list'); var matchResults = minimatch.match(list, pattern_1, options_1); - exports.debug(matchResults.length + ' matches'); + (0, exports.debug)(matchResults.length + ' matches'); // substract the results for (var _c = 0, matchResults_2 = matchResults; _c < matchResults_2.length; _c++) { var matchResult = matchResults_2[_c]; @@ -7933,7 +8077,7 @@ function match(list, patterns, patternRoot, options) { } // return a filtered version of the original list (preserves order and prevents duplication) var result = list.filter(function (item) { return map.hasOwnProperty(item); }); - exports.debug(result.length + ' final results'); + (0, exports.debug)(result.length + ' final results'); return result; } exports.match = match; @@ -7949,17 +8093,17 @@ function filter(pattern, options) { } exports.filter = filter; function _debugMatchOptions(options) { - exports.debug("matchOptions.debug: '" + options.debug + "'"); - exports.debug("matchOptions.nobrace: '" + options.nobrace + "'"); - exports.debug("matchOptions.noglobstar: '" + options.noglobstar + "'"); - exports.debug("matchOptions.dot: '" + options.dot + "'"); - exports.debug("matchOptions.noext: '" + options.noext + "'"); - exports.debug("matchOptions.nocase: '" + options.nocase + "'"); - exports.debug("matchOptions.nonull: '" + options.nonull + "'"); - exports.debug("matchOptions.matchBase: '" + options.matchBase + "'"); - exports.debug("matchOptions.nocomment: '" + options.nocomment + "'"); - exports.debug("matchOptions.nonegate: '" + options.nonegate + "'"); - exports.debug("matchOptions.flipNegate: '" + options.flipNegate + "'"); + (0, exports.debug)("matchOptions.debug: '".concat(options.debug, "'")); + (0, exports.debug)("matchOptions.nobrace: '".concat(options.nobrace, "'")); + (0, exports.debug)("matchOptions.noglobstar: '".concat(options.noglobstar, "'")); + (0, exports.debug)("matchOptions.dot: '".concat(options.dot, "'")); + (0, exports.debug)("matchOptions.noext: '".concat(options.noext, "'")); + (0, exports.debug)("matchOptions.nocase: '".concat(options.nocase, "'")); + (0, exports.debug)("matchOptions.nonull: '".concat(options.nonull, "'")); + (0, exports.debug)("matchOptions.matchBase: '".concat(options.matchBase, "'")); + (0, exports.debug)("matchOptions.nocomment: '".concat(options.nocomment, "'")); + (0, exports.debug)("matchOptions.nonegate: '".concat(options.nonegate, "'")); + (0, exports.debug)("matchOptions.flipNegate: '".concat(options.flipNegate, "'")); } function _getDefaultMatchOptions() { return { @@ -7990,7 +8134,7 @@ function _getDefaultMatchOptions() { function findMatch(defaultRoot, patterns, findOptions, matchOptions) { // apply defaults for parameters and trace defaultRoot = defaultRoot || this.getVariable('system.defaultWorkingDirectory') || process.cwd(); - exports.debug("defaultRoot: '" + defaultRoot + "'"); + (0, exports.debug)("defaultRoot: '".concat(defaultRoot, "'")); patterns = patterns || []; patterns = typeof patterns == 'string' ? [patterns] : patterns; findOptions = findOptions || _getDefaultFindOptions(); @@ -8003,18 +8147,18 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { var originalMatchOptions = matchOptions; for (var _i = 0, _a = (patterns || []); _i < _a.length; _i++) { var pattern = _a[_i]; - exports.debug("pattern: '" + pattern + "'"); + (0, exports.debug)("pattern: '".concat(pattern, "'")); // trim and skip empty pattern = (pattern || '').trim(); if (!pattern) { - exports.debug('skipping empty pattern'); + (0, exports.debug)('skipping empty pattern'); continue; } // clone match options var matchOptions_1 = im._cloneMatchOptions(originalMatchOptions); // skip comments if (!matchOptions_1.nocomment && im._startsWith(pattern, '#')) { - exports.debug('skipping comment'); + (0, exports.debug)('skipping comment'); continue; } // set nocomment - brace expansion could result in a leading '#' @@ -8027,7 +8171,7 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { } pattern = pattern.substring(negateCount); // trim leading '!' if (negateCount) { - exports.debug("trimmed leading '!'. pattern: '" + pattern + "'"); + (0, exports.debug)("trimmed leading '!'. pattern: '".concat(pattern, "'")); } } var isIncludePattern = negateCount == 0 || @@ -8045,7 +8189,7 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { else { // convert slashes on Windows before calling braceExpand(). unfortunately this means braces cannot // be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3). - exports.debug('expanding braces'); + (0, exports.debug)('expanding braces'); var convertedPattern = process.platform == 'win32' ? pattern.replace(/\\/g, '/') : pattern; expanded = minimatch.braceExpand(convertedPattern); } @@ -8054,25 +8198,25 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { for (var _b = 0, expanded_2 = expanded; _b < expanded_2.length; _b++) { var pattern_2 = expanded_2[_b]; if (expanded.length != 1 || pattern_2 != preExpanded) { - exports.debug("pattern: '" + pattern_2 + "'"); + (0, exports.debug)("pattern: '".concat(pattern_2, "'")); } // trim and skip empty pattern_2 = (pattern_2 || '').trim(); if (!pattern_2) { - exports.debug('skipping empty pattern'); + (0, exports.debug)('skipping empty pattern'); continue; } if (isIncludePattern) { // determine the findPath var findInfo = im._getFindInfoFromPattern(defaultRoot, pattern_2, matchOptions_1); var findPath = findInfo.findPath; - exports.debug("findPath: '" + findPath + "'"); + (0, exports.debug)("findPath: '".concat(findPath, "'")); if (!findPath) { - exports.debug('skipping empty path'); + (0, exports.debug)('skipping empty path'); continue; } // perform the find - exports.debug("statOnly: '" + findInfo.statOnly + "'"); + (0, exports.debug)("statOnly: '".concat(findInfo.statOnly, "'")); var findResults = []; if (findInfo.statOnly) { // simply stat the path - all path segments were used to build the path @@ -8084,21 +8228,21 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { if (err.code != 'ENOENT') { throw err; } - exports.debug('ENOENT'); + (0, exports.debug)('ENOENT'); } } else { findResults = find(findPath, findOptions); } - exports.debug("found " + findResults.length + " paths"); + (0, exports.debug)("found ".concat(findResults.length, " paths")); // apply the pattern - exports.debug('applying include pattern'); + (0, exports.debug)('applying include pattern'); if (findInfo.adjustedPattern != pattern_2) { - exports.debug("adjustedPattern: '" + findInfo.adjustedPattern + "'"); + (0, exports.debug)("adjustedPattern: '".concat(findInfo.adjustedPattern, "'")); pattern_2 = findInfo.adjustedPattern; } var matchResults = minimatch.match(findResults, pattern_2, matchOptions_1); - exports.debug(matchResults.length + ' matches'); + (0, exports.debug)(matchResults.length + ' matches'); // union the results for (var _c = 0, matchResults_3 = matchResults; _c < matchResults_3.length; _c++) { var matchResult = matchResults_3[_c]; @@ -8112,17 +8256,17 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { !im._isRooted(pattern_2) && (process.platform == 'win32' ? pattern_2.replace(/\\/g, '/') : pattern_2).indexOf('/') < 0) { // do not root the pattern - exports.debug('matchBase and basename only'); + (0, exports.debug)('matchBase and basename only'); } else { // root the exclude pattern pattern_2 = im._ensurePatternRooted(defaultRoot, pattern_2); - exports.debug("after ensurePatternRooted, pattern: '" + pattern_2 + "'"); + (0, exports.debug)("after ensurePatternRooted, pattern: '".concat(pattern_2, "'")); } // apply the pattern - exports.debug('applying exclude pattern'); + (0, exports.debug)('applying exclude pattern'); var matchResults = minimatch.match(Object.keys(results).map(function (key) { return results[key]; }), pattern_2, matchOptions_1); - exports.debug(matchResults.length + ' matches'); + (0, exports.debug)(matchResults.length + ' matches'); // substract the results for (var _d = 0, matchResults_4 = matchResults; _d < matchResults_4.length; _d++) { var matchResult = matchResults_4[_d]; @@ -8135,7 +8279,7 @@ function findMatch(defaultRoot, patterns, findOptions, matchOptions) { var finalResult = Object.keys(results) .map(function (key) { return results[key]; }) .sort(); - exports.debug(finalResult.length + ' final results'); + (0, exports.debug)(finalResult.length + ' final results'); return finalResult; } exports.findMatch = findMatch; @@ -8148,9 +8292,9 @@ exports.findMatch = findMatch; */ function getProxyFormattedUrl(proxyUrl, proxyUsername, proxyPassword) { var parsedUrl = new URL(proxyUrl); - var proxyAddress = parsedUrl.protocol + "//" + parsedUrl.host; + var proxyAddress = "".concat(parsedUrl.protocol, "//").concat(parsedUrl.host); if (proxyUsername) { - proxyAddress = parsedUrl.protocol + "//" + proxyUsername + ":" + proxyPassword + "@" + parsedUrl.host; + proxyAddress = "".concat(parsedUrl.protocol, "//").concat(proxyUsername, ":").concat(proxyPassword, "@").concat(parsedUrl.host); } return proxyAddress; } @@ -8160,11 +8304,11 @@ function getProxyFormattedUrl(proxyUrl, proxyUsername, proxyPassword) { * @return ProxyConfiguration */ function getHttpProxyConfiguration(requestUrl) { - var proxyUrl = exports.getVariable('Agent.ProxyUrl'); + var proxyUrl = (0, exports.getVariable)('Agent.ProxyUrl'); if (proxyUrl && proxyUrl.length > 0) { - var proxyUsername = exports.getVariable('Agent.ProxyUsername'); - var proxyPassword = exports.getVariable('Agent.ProxyPassword'); - var proxyBypassHosts = JSON.parse(exports.getVariable('Agent.ProxyBypassList') || '[]'); + var proxyUsername = (0, exports.getVariable)('Agent.ProxyUsername'); + var proxyPassword = (0, exports.getVariable)('Agent.ProxyPassword'); + var proxyBypassHosts = JSON.parse((0, exports.getVariable)('Agent.ProxyBypassList') || '[]'); var bypass_1 = false; if (requestUrl) { proxyBypassHosts.forEach(function (bypassHost) { @@ -8198,16 +8342,16 @@ exports.getHttpProxyConfiguration = getHttpProxyConfiguration; * @return CertConfiguration */ function getHttpCertConfiguration() { - var ca = exports.getVariable('Agent.CAInfo'); - var clientCert = exports.getVariable('Agent.ClientCert'); + var ca = (0, exports.getVariable)('Agent.CAInfo'); + var clientCert = (0, exports.getVariable)('Agent.ClientCert'); if (ca || clientCert) { var certConfig = {}; certConfig.caFile = ca; certConfig.certFile = clientCert; if (clientCert) { - var clientCertKey = exports.getVariable('Agent.ClientCertKey'); - var clientCertArchive = exports.getVariable('Agent.ClientCertArchive'); - var clientCertPassword = exports.getVariable('Agent.ClientCertPassword'); + var clientCertKey = (0, exports.getVariable)('Agent.ClientCertKey'); + var clientCertArchive = (0, exports.getVariable)('Agent.ClientCertArchive'); + var clientCertPassword = (0, exports.getVariable)('Agent.ClientCertPassword'); certConfig.keyFile = clientCertKey; certConfig.certArchiveFile = clientCertArchive; certConfig.passphrase = clientCertPassword; @@ -8251,7 +8395,7 @@ var TestPublisher = /** @class */ (function () { properties['resultFiles'] = Array.isArray(resultFiles) ? resultFiles.join() : resultFiles; } properties['testRunSystem'] = testRunSystem; - exports.command('results.publish', properties, ''); + (0, exports.command)('results.publish', properties, ''); }; return TestPublisher; }()); @@ -8276,7 +8420,7 @@ var CodeCoveragePublisher = /** @class */ (function () { if (additionalCodeCoverageFiles) { properties['additionalcodecoveragefiles'] = Array.isArray(additionalCodeCoverageFiles) ? additionalCodeCoverageFiles.join() : additionalCodeCoverageFiles; } - exports.command('codecoverage.publish', properties, ""); + (0, exports.command)('codecoverage.publish', properties, ""); }; return CodeCoveragePublisher; }()); @@ -8292,7 +8436,7 @@ var CodeCoverageEnabler = /** @class */ (function () { CodeCoverageEnabler.prototype.enableCodeCoverage = function (buildProps) { buildProps['buildtool'] = this.buildTool; buildProps['codecoveragetool'] = this.ccTool; - exports.command('codecoverage.enable', buildProps, ""); + (0, exports.command)('codecoverage.enable', buildProps, ""); }; return CodeCoverageEnabler; }()); @@ -8310,7 +8454,7 @@ exports.CodeCoverageEnabler = CodeCoverageEnabler; * @returns void */ function uploadFile(path) { - exports.command("task.uploadfile", null, path); + (0, exports.command)("task.uploadfile", null, path); } exports.uploadFile = uploadFile; /** @@ -8323,7 +8467,7 @@ exports.uploadFile = uploadFile; */ function prependPath(path) { assertAgent("2.115.0"); - exports.command("task.prependpath", null, path); + (0, exports.command)("task.prependpath", null, path); } exports.prependPath = prependPath; /** @@ -8335,7 +8479,7 @@ exports.prependPath = prependPath; * @returns void */ function uploadSummary(path) { - exports.command("task.uploadsummary", null, path); + (0, exports.command)("task.uploadsummary", null, path); } exports.uploadSummary = uploadSummary; /** @@ -8349,7 +8493,7 @@ exports.uploadSummary = uploadSummary; * @returns void */ function addAttachment(type, name, path) { - exports.command("task.addattachment", { "type": type, "name": name }, path); + (0, exports.command)("task.addattachment", { "type": type, "name": name }, path); } exports.addAttachment = addAttachment; /** @@ -8364,7 +8508,7 @@ exports.addAttachment = addAttachment; * @returns void */ function setEndpoint(id, field, key, value) { - exports.command("task.setendpoint", { "id": id, "field": FieldType[field].toLowerCase(), "key": key }, value); + (0, exports.command)("task.setendpoint", { "id": id, "field": FieldType[field].toLowerCase(), "key": key }, value); } exports.setEndpoint = setEndpoint; /** @@ -8375,7 +8519,7 @@ exports.setEndpoint = setEndpoint; * @returns void */ function setProgress(percent, currentOperation) { - exports.command("task.setprogress", { "value": "" + percent }, currentOperation); + (0, exports.command)("task.setprogress", { "value": "".concat(percent) }, currentOperation); } exports.setProgress = setProgress; /** @@ -8407,7 +8551,7 @@ function logDetail(id, message, parentId, recordType, recordName, order, startTi "state": state ? TaskState[state] : undefined, "result": result ? TaskResult[result] : undefined }; - exports.command("task.logdetail", properties, message); + (0, exports.command)("task.logdetail", properties, message); } exports.logDetail = logDetail; /** @@ -8429,7 +8573,7 @@ function logIssue(type, message, sourcePath, lineNumber, columnNumber, errorCode "linenumber": lineNumber ? lineNumber.toString() : undefined, "columnnumber": columnNumber ? columnNumber.toString() : undefined, }; - exports.command("task.logissue", properties, message); + (0, exports.command)("task.logissue", properties, message); } exports.logIssue = logIssue; //----------------------------------------------------- @@ -8447,7 +8591,7 @@ exports.logIssue = logIssue; * @returns void */ function uploadArtifact(containerFolder, path, name) { - exports.command("artifact.upload", { "containerfolder": containerFolder, "artifactname": name }, path); + (0, exports.command)("artifact.upload", { "containerfolder": containerFolder, "artifactname": name }, path); } exports.uploadArtifact = uploadArtifact; /** @@ -8462,7 +8606,7 @@ exports.uploadArtifact = uploadArtifact; * @returns void */ function associateArtifact(name, path, artifactType) { - exports.command("artifact.associate", { "type": ArtifactType[artifactType].toLowerCase(), "artifactname": name }, path); + (0, exports.command)("artifact.associate", { "type": ArtifactType[artifactType].toLowerCase(), "artifactname": name }, path); } exports.associateArtifact = associateArtifact; //----------------------------------------------------- @@ -8475,7 +8619,7 @@ exports.associateArtifact = associateArtifact; * @returns void */ function uploadBuildLog(path) { - exports.command("build.uploadlog", null, path); + (0, exports.command)("build.uploadlog", null, path); } exports.uploadBuildLog = uploadBuildLog; /** @@ -8485,7 +8629,7 @@ exports.uploadBuildLog = uploadBuildLog; * @returns void */ function updateBuildNumber(value) { - exports.command("build.updatebuildnumber", null, value); + (0, exports.command)("build.updatebuildnumber", null, value); } exports.updateBuildNumber = updateBuildNumber; /** @@ -8495,7 +8639,7 @@ exports.updateBuildNumber = updateBuildNumber; * @returns void */ function addBuildTag(value) { - exports.command("build.addbuildtag", null, value); + (0, exports.command)("build.addbuildtag", null, value); } exports.addBuildTag = addBuildTag; //----------------------------------------------------- @@ -8509,7 +8653,7 @@ exports.addBuildTag = addBuildTag; */ function updateReleaseName(name) { assertAgent("2.132.0"); - exports.command("release.updatereleasename", null, name); + (0, exports.command)("release.updatereleasename", null, name); } exports.updateReleaseName = updateReleaseName; //----------------------------------------------------- @@ -8523,7 +8667,7 @@ exports.ToolRunner = trm.ToolRunner; //----------------------------------------------------- // async await needs generators in node 4.x+ if (semver.lt(process.versions.node, '4.2.0')) { - exports.warning('Tasks require a new agent. Upgrade your agent or node to 4.2.0 or later'); + (0, exports.warning)('Tasks require a new agent. Upgrade your agent or node to 4.2.0 or later', exports.IssueSource.TaskInternal); } //------------------------------------------------------------------- // Populate the vault with sensitive data. Inputs and Endpoints @@ -8662,6 +8806,8 @@ var __extends = (this && this.__extends) || (function () { return extendStatics(d, b); }; return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); @@ -8762,7 +8908,7 @@ var ToolRunner = /** @class */ (function (_super) { } // Windows + verbatim else if (options.windowsVerbatimArguments) { - commandParts.push("\"" + toolPath + "\""); + commandParts.push("\"".concat(toolPath, "\"")); commandParts = commandParts.concat(args); } else if (options.shell) { @@ -8789,23 +8935,23 @@ var ToolRunner = /** @class */ (function (_super) { } return cmd; }; - ToolRunner.prototype._processLineBuffer = function (data, strBuffer, onLine) { + ToolRunner.prototype._processLineBuffer = function (data, buffer, onLine) { + var newBuffer = buffer + data.toString(); try { - var s = strBuffer + data.toString(); - var n = s.indexOf(os.EOL); - while (n > -1) { - var line = s.substring(0, n); + var eolIndex = newBuffer.indexOf(os.EOL); + while (eolIndex > -1) { + var line = newBuffer.substring(0, eolIndex); onLine(line); // the rest of the string ... - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); + newBuffer = newBuffer.substring(eolIndex + os.EOL.length); + eolIndex = newBuffer.indexOf(os.EOL); } - strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug('error processing line'); } + return newBuffer; }; /** * Wraps an arg string with specified char if it's not already wrapped @@ -8815,7 +8961,7 @@ var ToolRunner = /** @class */ (function (_super) { */ ToolRunner.prototype._wrapArg = function (arg, wrapChar) { if (!this._isWrapped(arg, wrapChar)) { - return "" + wrapChar + arg + wrapChar; + return "".concat(wrapChar).concat(arg).concat(wrapChar); } return arg; }; @@ -8826,7 +8972,7 @@ var ToolRunner = /** @class */ (function (_super) { */ ToolRunner.prototype._unwrapArg = function (arg, wrapChar) { if (this._isWrapped(arg, wrapChar)) { - var pattern = new RegExp("(^\\\\?" + wrapChar + ")|(\\\\?" + wrapChar + "$)", 'g'); + var pattern = new RegExp("(^\\\\?".concat(wrapChar, ")|(\\\\?").concat(wrapChar, "$)"), 'g'); return arg.trim().replace(pattern, ''); } return arg; @@ -8836,7 +8982,7 @@ var ToolRunner = /** @class */ (function (_super) { * @param arg Input arg string */ ToolRunner.prototype._isWrapped = function (arg, wrapChar) { - var pattern = new RegExp("^\\\\?" + wrapChar + ".+\\\\?" + wrapChar + "$"); + var pattern = new RegExp("^\\\\?".concat(wrapChar, ".+\\\\?").concat(wrapChar, "$")); return pattern.test(arg.trim()); }; ToolRunner.prototype._getSpawnFileName = function (options) { @@ -8854,7 +9000,7 @@ var ToolRunner = /** @class */ (function (_super) { var _this = this; if (process.platform == 'win32') { if (this._isCmdFile()) { - var argline = "/D /S /C \"" + this._windowsQuoteCmdArg(this.toolPath); + var argline = "/D /S /C \"".concat(this._windowsQuoteCmdArg(this.toolPath)); for (var i = 0; i < this.args.length; i++) { argline += ' '; argline += options.windowsVerbatimArguments ? this.args[i] : this._windowsQuoteCmdArg(this.args[i]); @@ -8898,7 +9044,7 @@ var ToolRunner = /** @class */ (function (_super) { if (arguments.length != 1) { throw new Error('Unexpected arguments passed to args.unshift when windowsVerbatimArguments flag is set.'); } - return Array.prototype.unshift.call(args_1, "\"" + arguments[0] + "\""); // quote the file name + return Array.prototype.unshift.call(args_1, "\"".concat(arguments[0], "\"")); // quote the file name }; return args_1; } @@ -9102,7 +9248,7 @@ var ToolRunner = /** @class */ (function (_super) { if (arg.indexOf('"') < 0 && arg.indexOf('\\') < 0) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. - return "\"" + arg + "\""; + return "\"".concat(arg, "\""); } // Expected input/output: // input : hello"world @@ -9164,12 +9310,193 @@ var ToolRunner = /** @class */ (function (_super) { }; ToolRunner.prototype._getSpawnSyncOptions = function (options) { var result = {}; + result.maxBuffer = 1024 * 1024 * 1024; result.cwd = options.cwd; result.env = options.env; result.shell = options.shell; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); return result; }; + ToolRunner.prototype.execWithPipingAsync = function (pipeOutputToTool, options) { + var _this = this; + this._debug('exec tool: ' + this.toolPath); + this._debug('arguments:'); + this.args.forEach(function (arg) { + _this._debug(' ' + arg); + }); + var success = true; + var optionsNonNull = this._cloneExecOptions(options); + if (!optionsNonNull.silent) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); + } + var cp; + var toolPath = pipeOutputToTool.toolPath; + var toolPathFirst; + var successFirst = true; + var returnCodeFirst; + var fileStream; + var waitingEvents = 0; // number of process or stream events we are waiting on to complete + var returnCode = 0; + var error; + toolPathFirst = this.toolPath; + // Following node documentation example from this link on how to pipe output of one process to another + // https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options + //start the child process for both tools + waitingEvents++; + var cpFirst = child.spawn(this._getSpawnFileName(optionsNonNull), this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(optionsNonNull)); + waitingEvents++; + cp = child.spawn(pipeOutputToTool._getSpawnFileName(optionsNonNull), pipeOutputToTool._getSpawnArgs(optionsNonNull), pipeOutputToTool._getSpawnOptions(optionsNonNull)); + fileStream = this.pipeOutputToFile ? fs.createWriteStream(this.pipeOutputToFile) : null; + return new Promise(function (resolve, reject) { + var _a, _b, _c, _d; + if (fileStream) { + waitingEvents++; + fileStream.on('finish', function () { + waitingEvents--; //file write is complete + fileStream = null; + if (waitingEvents == 0) { + if (error) { + reject(error); + } + else { + resolve(returnCode); + } + } + }); + fileStream.on('error', function (err) { + waitingEvents--; //there were errors writing to the file, write is done + _this._debug("Failed to pipe output of ".concat(toolPathFirst, " to file ").concat(_this.pipeOutputToFile, ". Error = ").concat(err)); + fileStream = null; + if (waitingEvents == 0) { + if (error) { + reject(error); + } + else { + resolve(returnCode); + } + } + }); + } + //pipe stdout of first tool to stdin of second tool + (_a = cpFirst.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) { + var _a, _b; + try { + if (fileStream) { + fileStream.write(data); + } + if (!((_a = cp.stdin) === null || _a === void 0 ? void 0 : _a.destroyed)) { + (_b = cp.stdin) === null || _b === void 0 ? void 0 : _b.write(data); + } + } + catch (err) { + _this._debug('Failed to pipe output of ' + toolPathFirst + ' to ' + toolPath); + _this._debug(toolPath + ' might have exited due to errors prematurely. Verify the arguments passed are valid.'); + } + }); + (_b = cpFirst.stderr) === null || _b === void 0 ? void 0 : _b.on('data', function (data) { + if (fileStream) { + fileStream.write(data); + } + successFirst = !optionsNonNull.failOnStdErr; + if (!optionsNonNull.silent) { + var s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; + s.write(data); + } + }); + cpFirst.on('error', function (err) { + var _a; + waitingEvents--; //first process is complete with errors + if (fileStream) { + fileStream.end(); + } + (_a = cp.stdin) === null || _a === void 0 ? void 0 : _a.end(); + error = new Error(toolPathFirst + ' failed. ' + err.message); + if (waitingEvents == 0) { + reject(error); + } + }); + cpFirst.on('close', function (code, signal) { + var _a; + waitingEvents--; //first process is complete + if (code != 0 && !optionsNonNull.ignoreReturnCode) { + successFirst = false; + returnCodeFirst = code; + returnCode = returnCodeFirst; + } + _this._debug('success of first tool:' + successFirst); + if (fileStream) { + fileStream.end(); + } + (_a = cp.stdin) === null || _a === void 0 ? void 0 : _a.end(); + if (waitingEvents == 0) { + if (error) { + reject(error); + } + else { + resolve(returnCode); + } + } + }); + var stdLineBuffer = ''; + (_c = cp.stdout) === null || _c === void 0 ? void 0 : _c.on('data', function (data) { + _this.emit('stdout', data); + if (!optionsNonNull.silent) { + optionsNonNull.outStream.write(data); + } + stdLineBuffer = _this._processLineBuffer(data, stdLineBuffer, function (line) { + _this.emit('stdline', line); + }); + }); + var errLineBuffer = ''; + (_d = cp.stderr) === null || _d === void 0 ? void 0 : _d.on('data', function (data) { + _this.emit('stderr', data); + success = !optionsNonNull.failOnStdErr; + if (!optionsNonNull.silent) { + var s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; + s.write(data); + } + errLineBuffer = _this._processLineBuffer(data, errLineBuffer, function (line) { + _this.emit('errline', line); + }); + }); + cp.on('error', function (err) { + waitingEvents--; //process is done with errors + error = new Error(toolPath + ' failed. ' + err.message); + if (waitingEvents == 0) { + reject(error); + } + }); + cp.on('close', function (code, signal) { + waitingEvents--; //process is complete + _this._debug('rc:' + code); + returnCode = code; + if (stdLineBuffer.length > 0) { + _this.emit('stdline', stdLineBuffer); + } + if (errLineBuffer.length > 0) { + _this.emit('errline', errLineBuffer); + } + if (code != 0 && !optionsNonNull.ignoreReturnCode) { + success = false; + } + _this._debug('success:' + success); + if (!successFirst) { //in the case output is piped to another tool, check exit code of both tools + error = new Error(toolPathFirst + ' failed with return code: ' + returnCodeFirst); + } + else if (!success) { + error = new Error(toolPath + ' failed with return code: ' + code); + } + if (waitingEvents == 0) { + if (error) { + reject(error); + } + else { + resolve(returnCode); + } + } + }); + }); + }; ToolRunner.prototype.execWithPiping = function (pipeOutputToTool, options) { var _this = this; var _a, _b, _c, _d; @@ -9218,7 +9545,7 @@ var ToolRunner = /** @class */ (function (_super) { }); fileStream.on('error', function (err) { waitingEvents--; //there were errors writing to the file, write is done - _this._debug("Failed to pipe output of " + toolPathFirst + " to file " + _this.pipeOutputToFile + ". Error = " + err); + _this._debug("Failed to pipe output of ".concat(toolPathFirst, " to file ").concat(_this.pipeOutputToFile, ". Error = ").concat(err)); fileStream = null; if (waitingEvents == 0) { if (error) { @@ -9288,17 +9615,17 @@ var ToolRunner = /** @class */ (function (_super) { } } }); - var stdbuffer = ''; + var stdLineBuffer = ''; (_c = cp.stdout) === null || _c === void 0 ? void 0 : _c.on('data', function (data) { _this.emit('stdout', data); if (!optionsNonNull.silent) { optionsNonNull.outStream.write(data); } - _this._processLineBuffer(data, stdbuffer, function (line) { + stdLineBuffer = _this._processLineBuffer(data, stdLineBuffer, function (line) { _this.emit('stdline', line); }); }); - var errbuffer = ''; + var errLineBuffer = ''; (_d = cp.stderr) === null || _d === void 0 ? void 0 : _d.on('data', function (data) { _this.emit('stderr', data); success = !optionsNonNull.failOnStdErr; @@ -9306,7 +9633,7 @@ var ToolRunner = /** @class */ (function (_super) { var s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } - _this._processLineBuffer(data, errbuffer, function (line) { + errLineBuffer = _this._processLineBuffer(data, errLineBuffer, function (line) { _this.emit('errline', line); }); }); @@ -9321,11 +9648,11 @@ var ToolRunner = /** @class */ (function (_super) { waitingEvents--; //process is complete _this._debug('rc:' + code); returnCode = code; - if (stdbuffer.length > 0) { - _this.emit('stdline', stdbuffer); + if (stdLineBuffer.length > 0) { + _this.emit('stdline', stdLineBuffer); } - if (errbuffer.length > 0) { - _this.emit('errline', errbuffer); + if (errLineBuffer.length > 0) { + _this.emit('errline', errLineBuffer); } if (code != 0 && !optionsNonNull.ignoreReturnCode) { success = false; @@ -9421,13 +9748,12 @@ var ToolRunner = /** @class */ (function (_super) { * @param options optional exec options. See IExecOptions * @returns number */ - ToolRunner.prototype.exec = function (options) { + ToolRunner.prototype.execAsync = function (options) { var _this = this; var _a, _b, _c; if (this.pipeOutputToTool) { - return this.execWithPiping(this.pipeOutputToTool, options); + return this.execWithPipingAsync(this.pipeOutputToTool, options); } - var defer = Q.defer(); this._debug('exec tool: ' + this.toolPath); this._debug('arguments:'); this.args.forEach(function (arg) { @@ -9441,7 +9767,41 @@ var ToolRunner = /** @class */ (function (_super) { state.on('debug', function (message) { _this._debug(message); }); - var cp = child.spawn(this._getSpawnFileName(options), this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(options)); + var stdLineBuffer = ''; + var errLineBuffer = ''; + var emitDoneEvent = function (resolve, reject) { + state.on('done', function (error, exitCode) { + if (stdLineBuffer.length > 0) { + _this.emit('stdline', stdLineBuffer); + } + if (errLineBuffer.length > 0) { + _this.emit('errline', errLineBuffer); + } + if (cp) { + cp.removeAllListeners(); + } + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + }; + // Edge case when the node itself cant's spawn and emit event + var cp; + try { + cp = child.spawn(this._getSpawnFileName(options), this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(options)); + } + catch (error) { + return new Promise(function (resolve, reject) { + emitDoneEvent(resolve, reject); + state.processError = error.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + } this.childProcess = cp; // it is possible for the child process to end its last line without a new line. // because stdout is buffered, this causes the last line to not get sent to the parent @@ -9451,17 +9811,15 @@ var ToolRunner = /** @class */ (function (_super) { optionsNonNull.outStream.write(os.EOL); } }); - var stdbuffer = ''; (_b = cp.stdout) === null || _b === void 0 ? void 0 : _b.on('data', function (data) { _this.emit('stdout', data); if (!optionsNonNull.silent) { optionsNonNull.outStream.write(data); } - _this._processLineBuffer(data, stdbuffer, function (line) { + stdLineBuffer = _this._processLineBuffer(data, stdLineBuffer, function (line) { _this.emit('stdline', line); }); }); - var errbuffer = ''; (_c = cp.stderr) === null || _c === void 0 ? void 0 : _c.on('data', function (data) { state.processStderr = true; _this.emit('stderr', data); @@ -9469,7 +9827,7 @@ var ToolRunner = /** @class */ (function (_super) { var s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } - _this._processLineBuffer(data, errbuffer, function (line) { + errLineBuffer = _this._processLineBuffer(data, errLineBuffer, function (line) { _this.emit('errline', line); }); }); @@ -9479,64 +9837,162 @@ var ToolRunner = /** @class */ (function (_super) { state.processClosed = true; state.CheckComplete(); }); + // Do not write debug logs here. Sometimes stdio not closed yet and you can damage user output commands. cp.on('exit', function (code, signal) { state.processExitCode = code; + state.processExitSignal = signal; state.processExited = true; - _this._debug("Exit code " + code + " received from tool '" + _this.toolPath + "'"); state.CheckComplete(); }); cp.on('close', function (code, signal) { - state.processExitCode = code; - state.processExited = true; + state.processCloseCode = code; + state.processCloseSignal = signal; state.processClosed = true; - _this._debug("STDIO streams have closed for tool '" + _this.toolPath + "'"); + state.processExited = true; state.CheckComplete(); }); - state.on('done', function (error, exitCode) { - if (stdbuffer.length > 0) { - _this.emit('stdline', stdbuffer); - } - if (errbuffer.length > 0) { - _this.emit('errline', errbuffer); - } - cp.removeAllListeners(); - if (error) { - defer.reject(error); - } - else { - defer.resolve(exitCode); - } - }); - return defer.promise; + return new Promise(emitDoneEvent); }; /** - * Exec a tool synchronously. - * Output will be *not* be streamed to the live console. It will be returned after execution is complete. - * Appropriate for short running tools - * Returns IExecSyncResult with output and return code + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code * + * @deprecated Use the `execAsync` method that returns a native Javascript promise instead * @param tool path to tool to exec - * @param options optional exec options. See IExecSyncOptions - * @returns IExecSyncResult + * @param options optional exec options. See IExecOptions + * @returns number */ - ToolRunner.prototype.execSync = function (options) { + ToolRunner.prototype.exec = function (options) { var _this = this; + var _a, _b, _c; + if (this.pipeOutputToTool) { + return this.execWithPiping(this.pipeOutputToTool, options); + } + var defer = Q.defer(); this._debug('exec tool: ' + this.toolPath); this._debug('arguments:'); this.args.forEach(function (arg) { _this._debug(' ' + arg); }); - var success = true; - options = this._cloneExecOptions(options); - if (!options.silent) { - options.outStream.write(this._getCommandString(options) + os.EOL); + var optionsNonNull = this._cloneExecOptions(options); + if (!optionsNonNull.silent) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } - var r = child.spawnSync(this._getSpawnFileName(options), this._getSpawnArgs(options), this._getSpawnSyncOptions(options)); - if (!options.silent && r.stdout && r.stdout.length > 0) { - options.outStream.write(r.stdout); + var state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', function (message) { + _this._debug(message); + }); + var stdLineBuffer = ''; + var errLineBuffer = ''; + state.on('done', function (error, exitCode) { + if (stdLineBuffer.length > 0) { + _this.emit('stdline', stdLineBuffer); + } + if (errLineBuffer.length > 0) { + _this.emit('errline', errLineBuffer); + } + if (cp) { + cp.removeAllListeners(); + } + if (error) { + defer.reject(error); + } + else { + defer.resolve(exitCode); + } + }); + // Edge case when the node itself cant's spawn and emit event + var cp; + try { + cp = child.spawn(this._getSpawnFileName(options), this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(options)); } - if (!options.silent && r.stderr && r.stderr.length > 0) { - options.errStream.write(r.stderr); + catch (error) { + state.processError = error.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + return defer.promise; + } + this.childProcess = cp; + // it is possible for the child process to end its last line without a new line. + // because stdout is buffered, this causes the last line to not get sent to the parent + // stream. Adding this event forces a flush before the child streams are closed. + (_a = cp.stdout) === null || _a === void 0 ? void 0 : _a.on('finish', function () { + if (!optionsNonNull.silent) { + optionsNonNull.outStream.write(os.EOL); + } + }); + (_b = cp.stdout) === null || _b === void 0 ? void 0 : _b.on('data', function (data) { + _this.emit('stdout', data); + if (!optionsNonNull.silent) { + optionsNonNull.outStream.write(data); + } + stdLineBuffer = _this._processLineBuffer(data, stdLineBuffer, function (line) { + _this.emit('stdline', line); + }); + }); + (_c = cp.stderr) === null || _c === void 0 ? void 0 : _c.on('data', function (data) { + state.processStderr = true; + _this.emit('stderr', data); + if (!optionsNonNull.silent) { + var s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; + s.write(data); + } + errLineBuffer = _this._processLineBuffer(data, errLineBuffer, function (line) { + _this.emit('errline', line); + }); + }); + cp.on('error', function (err) { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + // Do not write debug logs here. Sometimes stdio not closed yet and you can damage user output commands. + cp.on('exit', function (code, signal) { + state.processExitCode = code; + state.processExitSignal = signal; + state.processExited = true; + state.CheckComplete(); + }); + cp.on('close', function (code, signal) { + state.processCloseCode = code; + state.processCloseSignal = signal; + state.processClosed = true; + state.processExited = true; + state.CheckComplete(); + }); + return defer.promise; + }; + /** + * Exec a tool synchronously. + * Output will be *not* be streamed to the live console. It will be returned after execution is complete. + * Appropriate for short running tools + * Returns IExecSyncResult with output and return code + * + * @param tool path to tool to exec + * @param options optional exec options. See IExecSyncOptions + * @returns IExecSyncResult + */ + ToolRunner.prototype.execSync = function (options) { + var _this = this; + this._debug('exec tool: ' + this.toolPath); + this._debug('arguments:'); + this.args.forEach(function (arg) { + _this._debug(' ' + arg); + }); + var success = true; + options = this._cloneExecOptions(options); + if (!options.silent) { + options.outStream.write(this._getCommandString(options) + os.EOL); + } + var r = child.spawnSync(this._getSpawnFileName(options), this._getSpawnArgs(options), this._getSpawnSyncOptions(options)); + if (!options.silent && r.stdout && r.stdout.length > 0) { + options.outStream.write(r.stdout); + } + if (!options.silent && r.stderr && r.stderr.length > 0) { + options.errStream.write(r.stderr); } var res = { code: r.status, error: r.error }; res.stdout = (r.stdout) ? r.stdout.toString() : ''; @@ -9547,9 +10003,11 @@ var ToolRunner = /** @class */ (function (_super) { * Used to close child process by sending SIGNINT signal. * It allows executed script to have some additional logic on SIGINT, before exiting. */ - ToolRunner.prototype.killChildProcess = function () { + ToolRunner.prototype.killChildProcess = function (signal) { + if (signal === void 0) { signal = "SIGTERM"; } if (this.childProcess) { - this.childProcess.kill(); + this._debug("[killChildProcess] Signal ".concat(signal, " received")); + this.childProcess.kill(signal); } }; return ToolRunner; @@ -9590,6 +10048,7 @@ var ExecState = /** @class */ (function (_super) { // determine whether there is an error var error; if (this.processExited) { + this._debug("Process exited with code ".concat(this.processExitCode, " and signal ").concat(this.processExitSignal, " for tool '").concat(this.toolPath, "'")); if (this.processError) { error = new Error(im._loc('LIB_ProcessError', this.toolPath, this.processError)); } @@ -9600,6 +10059,9 @@ var ExecState = /** @class */ (function (_super) { error = new Error(im._loc('LIB_ProcessStderr', this.toolPath)); } } + if (this.processClosed) { + this._debug("STDIO streams have closed and received exit code ".concat(this.processCloseCode, " and signal ").concat(this.processCloseSignal, " for tool '").concat(this.toolPath, "'")); + } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); @@ -9682,7 +10144,7 @@ var Vault = /** @class */ (function () { var iv = ivDataBuffer.slice(0, 16); var encryptedText = ivDataBuffer.slice(16); var decipher = crypto.createDecipheriv(algorithm, key, iv); - var dec = decipher.update(encryptedText, encryptEncoding, unencryptedEncoding); + var dec = decipher.update(encryptedText); var decFinal = decipher.final(unencryptedEncoding); secret = dec + decFinal; } @@ -14704,6 +15166,7 @@ var https = __nccwpck_require__(5687); var parseUrl = (__nccwpck_require__(7310).parse); var fs = __nccwpck_require__(7147); var Stream = (__nccwpck_require__(2781).Stream); +var crypto = __nccwpck_require__(6113); var mime = __nccwpck_require__(3583); var asynckit = __nccwpck_require__(4812); var setToStringTag = __nccwpck_require__(1770); @@ -15041,12 +15504,7 @@ FormData.prototype._generateBoundary = function () { // This generates a 50 character boundary similar to those used by Firefox. // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - - this._boundary = boundary; + this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); }; // Note: getLengthSync DOESN'T calculate streams length @@ -15164,7 +15622,7 @@ FormData.prototype.submit = function (params, cb) { request.removeListener('error', callback); request.removeListener('response', onResponse); - return cb.call(this, error, responce); // eslint-disable-line no-invalid-this + return cb.call(this, error, responce); }; onResponse = callback.bind(this, null); @@ -15188,7 +15646,7 @@ FormData.prototype._error = function (err) { FormData.prototype.toString = function () { return '[object FormData]'; }; -setToStringTag(FormData, 'FormData'); +setToStringTag(FormData.prototype, 'FormData'); // Public API module.exports = FormData; @@ -31594,6 +32052,14 @@ module.exports = require("http"); /***/ }), +/***/ 6281: +/***/ ((module) => { + +"use strict"; +module.exports = require("http2"); + +/***/ }), + /***/ 5687: /***/ ((module) => { @@ -31694,7 +32160,7 @@ module.exports = require("zlib"); /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! Axios v1.9.0 Copyright (c) 2025 Matt Zabriskie and contributors */ +/*! Axios v1.13.5 Copyright (c) 2026 Matt Zabriskie and contributors */ const FormData$1 = __nccwpck_require__(4334); @@ -31703,6 +32169,7 @@ const url = __nccwpck_require__(7310); const proxyFromEnv = __nccwpck_require__(3329); const http = __nccwpck_require__(3685); const https = __nccwpck_require__(5687); +const http2 = __nccwpck_require__(6281); const util = __nccwpck_require__(3837); const followRedirects = __nccwpck_require__(7707); const zlib = __nccwpck_require__(9796); @@ -31717,11 +32184,19 @@ const url__default = /*#__PURE__*/_interopDefaultLegacy(url); const proxyFromEnv__default = /*#__PURE__*/_interopDefaultLegacy(proxyFromEnv); const http__default = /*#__PURE__*/_interopDefaultLegacy(http); const https__default = /*#__PURE__*/_interopDefaultLegacy(https); +const http2__default = /*#__PURE__*/_interopDefaultLegacy(http2); const util__default = /*#__PURE__*/_interopDefaultLegacy(util); const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); +/** + * Create a bound version of a function with a specified `this` context + * + * @param {Function} fn - The function to bind + * @param {*} thisArg - The value to be passed as the `this` parameter + * @returns {Function} A new function that will call the original function with the specified `this` context + */ function bind(fn, thisArg) { return function wrap() { return fn.apply(thisArg, arguments); @@ -31730,30 +32205,30 @@ function bind(fn, thisArg) { // utils is a library of generic helper functions non-specific to axios -const {toString} = Object.prototype; -const {getPrototypeOf} = Object; -const {iterator, toStringTag} = Symbol; +const { toString } = Object.prototype; +const { getPrototypeOf } = Object; +const { iterator, toStringTag } = Symbol; -const kindOf = (cache => thing => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +const kindOf = ((cache) => (thing) => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); })(Object.create(null)); const kindOfTest = (type) => { type = type.toLowerCase(); - return (thing) => kindOf(thing) === type + return (thing) => kindOf(thing) === type; }; -const typeOfTest = type => thing => typeof thing === type; +const typeOfTest = (type) => (thing) => typeof thing === type; /** - * Determine if a value is an Array + * Determine if a value is a non-null object * * @param {Object} val The value to test * * @returns {boolean} True if value is an Array, otherwise false */ -const {isArray} = Array; +const { isArray } = Array; /** * Determine if a value is undefined @@ -31762,7 +32237,7 @@ const {isArray} = Array; * * @returns {boolean} True if the value is undefined, otherwise false */ -const isUndefined = typeOfTest('undefined'); +const isUndefined = typeOfTest("undefined"); /** * Determine if a value is a Buffer @@ -31772,8 +32247,14 @@ const isUndefined = typeOfTest('undefined'); * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); + return ( + val !== null && + !isUndefined(val) && + val.constructor !== null && + !isUndefined(val.constructor) && + isFunction$1(val.constructor.isBuffer) && + val.constructor.isBuffer(val) + ); } /** @@ -31783,8 +32264,7 @@ function isBuffer(val) { * * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ -const isArrayBuffer = kindOfTest('ArrayBuffer'); - +const isArrayBuffer = kindOfTest("ArrayBuffer"); /** * Determine if a value is a view on an ArrayBuffer @@ -31795,10 +32275,10 @@ const isArrayBuffer = kindOfTest('ArrayBuffer'); */ function isArrayBufferView(val) { let result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { result = ArrayBuffer.isView(val); } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + result = val && val.buffer && isArrayBuffer(val.buffer); } return result; } @@ -31810,7 +32290,7 @@ function isArrayBufferView(val) { * * @returns {boolean} True if value is a String, otherwise false */ -const isString = typeOfTest('string'); +const isString = typeOfTest("string"); /** * Determine if a value is a Function @@ -31818,7 +32298,7 @@ const isString = typeOfTest('string'); * @param {*} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ -const isFunction = typeOfTest('function'); +const isFunction$1 = typeOfTest("function"); /** * Determine if a value is a Number @@ -31827,7 +32307,7 @@ const isFunction = typeOfTest('function'); * * @returns {boolean} True if value is a Number, otherwise false */ -const isNumber = typeOfTest('number'); +const isNumber = typeOfTest("number"); /** * Determine if a value is an Object @@ -31836,7 +32316,7 @@ const isNumber = typeOfTest('number'); * * @returns {boolean} True if value is an Object, otherwise false */ -const isObject = (thing) => thing !== null && typeof thing === 'object'; +const isObject = (thing) => thing !== null && typeof thing === "object"; /** * Determine if a value is a Boolean @@ -31844,7 +32324,7 @@ const isObject = (thing) => thing !== null && typeof thing === 'object'; * @param {*} thing The value to test * @returns {boolean} True if value is a Boolean, otherwise false */ -const isBoolean = thing => thing === true || thing === false; +const isBoolean = (thing) => thing === true || thing === false; /** * Determine if a value is a plain Object @@ -31854,12 +32334,42 @@ const isBoolean = thing => thing === true || thing === false; * @returns {boolean} True if value is a plain Object, otherwise false */ const isPlainObject = (val) => { - if (kindOf(val) !== 'object') { + if (kindOf(val) !== "object") { return false; } const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val); + return ( + (prototype === null || + prototype === Object.prototype || + Object.getPrototypeOf(prototype) === null) && + !(toStringTag in val) && + !(iterator in val) + ); +}; + +/** + * Determine if a value is an empty object (safely handles Buffers) + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an empty object, otherwise false + */ +const isEmptyObject = (val) => { + // Early return for non-objects or Buffers to prevent RangeError + if (!isObject(val) || isBuffer(val)) { + return false; + } + + try { + return ( + Object.keys(val).length === 0 && + Object.getPrototypeOf(val) === Object.prototype + ); + } catch (e) { + // Fallback for any other objects that might cause RangeError with Object.keys() + return false; + } }; /** @@ -31869,7 +32379,7 @@ const isPlainObject = (val) => { * * @returns {boolean} True if value is a Date, otherwise false */ -const isDate = kindOfTest('Date'); +const isDate = kindOfTest("Date"); /** * Determine if a value is a File @@ -31878,7 +32388,7 @@ const isDate = kindOfTest('Date'); * * @returns {boolean} True if value is a File, otherwise false */ -const isFile = kindOfTest('File'); +const isFile = kindOfTest("File"); /** * Determine if a value is a Blob @@ -31887,7 +32397,7 @@ const isFile = kindOfTest('File'); * * @returns {boolean} True if value is a Blob, otherwise false */ -const isBlob = kindOfTest('Blob'); +const isBlob = kindOfTest("Blob"); /** * Determine if a value is a FileList @@ -31896,7 +32406,7 @@ const isBlob = kindOfTest('Blob'); * * @returns {boolean} True if value is a File, otherwise false */ -const isFileList = kindOfTest('FileList'); +const isFileList = kindOfTest("FileList"); /** * Determine if a value is a Stream @@ -31905,7 +32415,7 @@ const isFileList = kindOfTest('FileList'); * * @returns {boolean} True if value is a Stream, otherwise false */ -const isStream = (val) => isObject(val) && isFunction(val.pipe); +const isStream = (val) => isObject(val) && isFunction$1(val.pipe); /** * Determine if a value is a FormData @@ -31916,15 +32426,16 @@ const isStream = (val) => isObject(val) && isFunction(val.pipe); */ const isFormData = (thing) => { let kind; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || ( - isFunction(thing.append) && ( - (kind = kindOf(thing)) === 'formdata' || - // detect form-data instance - (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') - ) - ) - ) + return ( + thing && + ((typeof FormData === "function" && thing instanceof FormData) || + (isFunction$1(thing.append) && + ((kind = kindOf(thing)) === "formdata" || + // detect form-data instance + (kind === "object" && + isFunction$1(thing.toString) && + thing.toString() === "[object FormData]")))) + ); }; /** @@ -31934,9 +32445,14 @@ const isFormData = (thing) => { * * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ -const isURLSearchParams = kindOfTest('URLSearchParams'); +const isURLSearchParams = kindOfTest("URLSearchParams"); -const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); +const [isReadableStream, isRequest, isResponse, isHeaders] = [ + "ReadableStream", + "Request", + "Response", + "Headers", +].map(kindOfTest); /** * Trim excess whitespace off the beginning and end of a string @@ -31945,8 +32461,8 @@ const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', * * @returns {String} The String freed of excess whitespace */ -const trim = (str) => str.trim ? - str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); +const trim = (str) => + str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); /** * Iterate over an Array or an Object invoking a function for each item. @@ -31957,15 +32473,16 @@ const trim = (str) => str.trim ? * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * - * @param {Object|Array} obj The object to iterate + * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item * - * @param {Boolean} [allOwnKeys = false] + * @param {Object} [options] + * @param {Boolean} [options.allOwnKeys = false] * @returns {any} */ -function forEach(obj, fn, {allOwnKeys = false} = {}) { +function forEach(obj, fn, { allOwnKeys = false } = {}) { // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { + if (obj === null || typeof obj === "undefined") { return; } @@ -31973,7 +32490,7 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) { let l; // Force an array if not already something iterable - if (typeof obj !== 'object') { + if (typeof obj !== "object") { /*eslint no-param-reassign:0*/ obj = [obj]; } @@ -31984,8 +32501,15 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) { fn.call(null, obj[i], i, obj); } } else { + // Buffer check + if (isBuffer(obj)) { + return; + } + // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const keys = allOwnKeys + ? Object.getOwnPropertyNames(obj) + : Object.keys(obj); const len = keys.length; let key; @@ -31997,6 +32521,10 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) { } function findKey(obj, key) { + if (isBuffer(obj)) { + return null; + } + key = key.toLowerCase(); const keys = Object.keys(obj); let i = keys.length; @@ -32013,10 +32541,15 @@ function findKey(obj, key) { const _global = (() => { /*eslint no-undef:0*/ if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) + return typeof self !== "undefined" + ? self + : typeof window !== "undefined" + ? window + : global; })(); -const isContextDefined = (context) => !isUndefined(context) && context !== _global; +const isContextDefined = (context) => + !isUndefined(context) && context !== _global; /** * Accepts varargs expecting each argument to be an object, then @@ -32028,7 +32561,7 @@ const isContextDefined = (context) => !isUndefined(context) && context !== _glob * Example: * * ```js - * var result = merge({foo: 123}, {foo: 456}); + * const result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * @@ -32037,17 +32570,22 @@ const isContextDefined = (context) => !isUndefined(context) && context !== _glob * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { - const {caseless} = isContextDefined(this) && this || {}; + const { caseless, skipUndefined } = (isContextDefined(this) && this) || {}; const result = {}; const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; + // Skip dangerous property names to prevent prototype pollution + if (key === "__proto__" || key === "constructor" || key === "prototype") { + return; + } + + const targetKey = (caseless && findKey(result, key)) || key; if (isPlainObject(result[targetKey]) && isPlainObject(val)) { result[targetKey] = merge(result[targetKey], val); } else if (isPlainObject(val)) { result[targetKey] = merge({}, val); } else if (isArray(val)) { result[targetKey] = val.slice(); - } else { + } else if (!skipUndefined || !isUndefined(val)) { result[targetKey] = val; } }; @@ -32065,17 +32603,32 @@ function merge(/* obj1, obj2, obj3, ... */) { * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * - * @param {Boolean} [allOwnKeys] + * @param {Object} [options] + * @param {Boolean} [options.allOwnKeys] * @returns {Object} The resulting value of object a */ -const extend = (a, b, thisArg, {allOwnKeys}= {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }, {allOwnKeys}); +const extend = (a, b, thisArg, { allOwnKeys } = {}) => { + forEach( + b, + (val, key) => { + if (thisArg && isFunction$1(val)) { + Object.defineProperty(a, key, { + value: bind(val, thisArg), + writable: true, + enumerable: true, + configurable: true, + }); + } else { + Object.defineProperty(a, key, { + value: val, + writable: true, + enumerable: true, + configurable: true, + }); + } + }, + { allOwnKeys }, + ); return a; }; @@ -32087,7 +32640,7 @@ const extend = (a, b, thisArg, {allOwnKeys}= {}) => { * @returns {string} content value without BOM */ const stripBOM = (content) => { - if (content.charCodeAt(0) === 0xFEFF) { + if (content.charCodeAt(0) === 0xfeff) { content = content.slice(1); } return content; @@ -32103,10 +32656,18 @@ const stripBOM = (content) => { * @returns {void} */ const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, 'super', { - value: superConstructor.prototype + constructor.prototype = Object.create( + superConstructor.prototype, + descriptors, + ); + Object.defineProperty(constructor.prototype, "constructor", { + value: constructor, + writable: true, + enumerable: false, + configurable: true, + }); + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype, }); props && Object.assign(constructor.prototype, props); }; @@ -32135,13 +32696,20 @@ const toFlatObject = (sourceObj, destObj, filter, propFilter) => { i = props.length; while (i-- > 0) { prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + if ( + (!propFilter || propFilter(prop, sourceObj, destObj)) && + !merged[prop] + ) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + } while ( + sourceObj && + (!filter || filter(sourceObj, destObj)) && + sourceObj !== Object.prototype + ); return destObj; }; @@ -32165,7 +32733,6 @@ const endsWith = (str, searchString, position) => { return lastIndex !== -1 && lastIndex === position; }; - /** * Returns new array from array like object or null if failed * @@ -32194,12 +32761,12 @@ const toArray = (thing) => { * @returns {Array} */ // eslint-disable-next-line func-names -const isTypedArray = (TypedArray => { +const isTypedArray = ((TypedArray) => { // eslint-disable-next-line func-names - return thing => { + return (thing) => { return TypedArray && thing instanceof TypedArray; }; -})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); +})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); /** * For each entry in the object, call the function with the key and value. @@ -32242,18 +32809,22 @@ const matchAll = (regExp, str) => { }; /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ -const isHTMLForm = kindOfTest('HTMLFormElement'); +const isHTMLForm = kindOfTest("HTMLFormElement"); -const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { +const toCamelCase = (str) => { + return str + .toLowerCase() + .replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { return p1.toUpperCase() + p2; - } - ); + }); }; /* Creating a function that will check if an object has a property. */ -const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); +const hasOwnProperty = ( + ({ hasOwnProperty }) => + (obj, prop) => + hasOwnProperty.call(obj, prop) +)(Object.prototype); /** * Determine if a value is a RegExp object @@ -32262,7 +32833,7 @@ const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call * * @returns {boolean} True if value is a RegExp object, otherwise false */ -const isRegExp = kindOfTest('RegExp'); +const isRegExp = kindOfTest("RegExp"); const reduceDescriptors = (obj, reducer) => { const descriptors = Object.getOwnPropertyDescriptors(obj); @@ -32286,24 +32857,27 @@ const reduceDescriptors = (obj, reducer) => { const freezeMethods = (obj) => { reduceDescriptors(obj, (descriptor, name) => { // skip restricted props in strict mode - if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + if ( + isFunction$1(obj) && + ["arguments", "caller", "callee"].indexOf(name) !== -1 + ) { return false; } const value = obj[name]; - if (!isFunction(value)) return; + if (!isFunction$1(value)) return; descriptor.enumerable = false; - if ('writable' in descriptor) { + if ("writable" in descriptor) { descriptor.writable = false; return; } if (!descriptor.set) { descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); + throw Error("Can not rewrite read-only method '" + name + "'"); }; } }); @@ -32313,12 +32887,14 @@ const toObjectSet = (arrayOrString, delimiter) => { const obj = {}; const define = (arr) => { - arr.forEach(value => { + arr.forEach((value) => { obj[value] = true; }); }; - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + isArray(arrayOrString) + ? define(arrayOrString) + : define(String(arrayOrString).split(delimiter)); return obj; }; @@ -32326,7 +32902,9 @@ const toObjectSet = (arrayOrString, delimiter) => { const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; + return value != null && Number.isFinite((value = +value)) + ? value + : defaultValue; }; /** @@ -32337,20 +32915,29 @@ const toFiniteNumber = (value, defaultValue) => { * @returns {boolean} */ function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]); + return !!( + thing && + isFunction$1(thing.append) && + thing[toStringTag] === "FormData" && + thing[iterator] + ); } const toJSONObject = (obj) => { const stack = new Array(10); const visit = (source, i) => { - if (isObject(source)) { if (stack.indexOf(source) >= 0) { return; } - if(!('toJSON' in source)) { + //Buffer check + if (isBuffer(source)) { + return source; + } + + if (!("toJSON" in source)) { stack[i] = source; const target = isArray(source) ? [] : {}; @@ -32371,10 +32958,13 @@ const toJSONObject = (obj) => { return visit(obj, 0); }; -const isAsyncFn = kindOfTest('AsyncFunction'); +const isAsyncFn = kindOfTest("AsyncFunction"); const isThenable = (thing) => - thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + thing && + (isObject(thing) || isFunction$1(thing)) && + isFunction$1(thing.then) && + isFunction$1(thing.catch); // original code // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 @@ -32384,31 +32974,34 @@ const _setImmediate = ((setImmediateSupported, postMessageSupported) => { return setImmediate; } - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({source, data}) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); + return postMessageSupported + ? ((token, callbacks) => { + _global.addEventListener( + "message", + ({ source, data }) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, + false, + ); - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); - } - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})( - typeof setImmediate === 'function', - isFunction(_global.postMessage) -); + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + }; + })(`axios@${Math.random()}`, []) + : (cb) => setTimeout(cb); +})(typeof setImmediate === "function", isFunction$1(_global.postMessage)); -const asap = typeof queueMicrotask !== 'undefined' ? - queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); +const asap = + typeof queueMicrotask !== "undefined" + ? queueMicrotask.bind(_global) + : (typeof process !== "undefined" && process.nextTick) || _setImmediate; // ********************* - -const isIterable = (thing) => thing != null && isFunction(thing[iterator]); - +const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]); const utils$1 = { isArray, @@ -32421,6 +33014,7 @@ const utils$1 = { isBoolean, isObject, isPlainObject, + isEmptyObject, isReadableStream, isRequest, isResponse, @@ -32430,7 +33024,7 @@ const utils$1 = { isFile, isBlob, isRegExp, - isFunction, + isFunction: isFunction$1, isStream, isURLSearchParams, isTypedArray, @@ -32466,106 +33060,78 @@ const utils$1 = { isThenable, setImmediate: _setImmediate, asap, - isIterable + isIterable, }; -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * - * @returns {Error} The created error. - */ -function AxiosError(message, code, config, request, response) { - Error.call(this); +class AxiosError extends Error { + static from(error, code, config, request, response, customProps) { + const axiosError = new AxiosError(error.message, code || error.code, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + } - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = (new Error()).stack; - } + /** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ + constructor(message, code, config, request, response) { + super(message); + this.name = 'AxiosError'; + this.isAxiosError = true; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status; + } + } - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status ? response.status : null; - } + toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status, + }; + } } -utils$1.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.status - }; - } -}); - -const prototype$1 = AxiosError.prototype; -const descriptors = {}; - -[ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED', - 'ERR_NOT_SUPPORT', - 'ERR_INVALID_URL' -// eslint-disable-next-line func-names -].forEach(code => { - descriptors[code] = {value: code}; -}); - -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); - -// eslint-disable-next-line func-names -AxiosError.from = (error, code, config, request, response, customProps) => { - const axiosError = Object.create(prototype$1); - - utils$1.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, prop => { - return prop !== 'isAxiosError'; - }); - - AxiosError.call(axiosError, error.message, code, config, request, response); - - axiosError.cause = error; - - axiosError.name = error.name; - - customProps && Object.assign(axiosError, customProps); +// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated. +AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE'; +AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION'; +AxiosError.ECONNABORTED = 'ECONNABORTED'; +AxiosError.ETIMEDOUT = 'ETIMEDOUT'; +AxiosError.ERR_NETWORK = 'ERR_NETWORK'; +AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS'; +AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED'; +AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE'; +AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST'; +AxiosError.ERR_CANCELED = 'ERR_CANCELED'; +AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT'; +AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL'; - return axiosError; -}; +const AxiosError$1 = AxiosError; /** * Determines if the given thing is a array or js object. @@ -32682,8 +33248,12 @@ function toFormData(obj, formData, options) { return value.toISOString(); } + if (utils$1.isBoolean(value)) { + return value.toString(); + } + if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + throw new AxiosError$1('Blob is not supported. Use a Buffer instead.'); } if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { @@ -32844,9 +33414,7 @@ function encode(val) { replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); + replace(/%20/g, '+'); } /** @@ -32859,29 +33427,26 @@ function encode(val) { * @returns {string} The formatted url */ function buildURL(url, params, options) { - /*eslint no-param-reassign:0*/ if (!params) { return url; } - + const _encode = options && options.encode || encode; - if (utils$1.isFunction(options)) { - options = { - serialize: options - }; - } + const _options = utils$1.isFunction(options) ? { + serialize: options + } : options; - const serializeFn = options && options.serialize; + const serializeFn = _options && _options.serialize; let serializedParams; if (serializeFn) { - serializedParams = serializeFn(params, options); + serializedParams = serializeFn(params, _options); } else { serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : - new AxiosURLSearchParams(params, options).toString(_encode); + new AxiosURLSearchParams(params, _options).toString(_encode); } if (serializedParams) { @@ -32906,6 +33471,7 @@ class InterceptorManager { * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` + * @param {Object} options The options for the interceptor, synchronous and runWhen * * @return {Number} An ID used to remove interceptor later */ @@ -32924,7 +33490,7 @@ class InterceptorManager { * * @param {Number} id The ID that was returned by `use` * - * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + * @returns {void} */ eject(id) { if (this.handlers[id]) { @@ -32967,7 +33533,8 @@ const InterceptorManager$1 = InterceptorManager; const transitionalDefaults = { silentJSONParsing: true, forcedJSONParsing: true, - clarifyTimeoutError: false + clarifyTimeoutError: false, + legacyInterceptorReqResOrdering: true }; const URLSearchParams = url__default["default"].URLSearchParams; @@ -33066,7 +33633,7 @@ const platform = { }; function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + return toFormData(data, new platform.classes.URLSearchParams(), { visitor: function(value, key, path, helpers) { if (platform.isNode && utils$1.isBuffer(value)) { this.append(key, value.toString('base64')); @@ -33074,8 +33641,9 @@ function toURLEncodedForm(data, options) { } return helpers.defaultVisitor.apply(this, arguments); - } - }, options)); + }, + ...options + }); } /** @@ -33271,11 +33839,11 @@ const defaults = { const strictJSONParsing = !silentJSONParsing && JSONRequested; try { - return JSON.parse(data); + return JSON.parse(data, this.parseReviver); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } @@ -33709,24 +34277,24 @@ function isCancel(value) { return !!(value && value.__CANCEL__); } -/** - * A `CanceledError` is an object that is thrown when an operation is canceled. - * - * @param {string=} message The message. - * @param {Object=} config The config. - * @param {Object=} request The request. - * - * @returns {CanceledError} The created error. - */ -function CanceledError(message, config, request) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); - this.name = 'CanceledError'; +class CanceledError extends AxiosError$1 { + /** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ + constructor(message, config, request) { + super(message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request); + this.name = 'CanceledError'; + this.__CANCEL__ = true; + } } -utils$1.inherits(CanceledError, AxiosError, { - __CANCEL__: true -}); +const CanceledError$1 = CanceledError; /** * Resolve or reject a Promise based on response status. @@ -33742,9 +34310,9 @@ function settle(resolve, reject, response) { if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { - reject(new AxiosError( + reject(new AxiosError$1( 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response @@ -33763,6 +34331,10 @@ function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. + if (typeof url !== 'string') { + return false; + } + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } @@ -33798,7 +34370,7 @@ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { return requestedURL; } -const VERSION = "1.9.0"; +const VERSION = "1.13.5"; function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); @@ -33831,7 +34403,7 @@ function fromDataURI(uri, asBlob, options) { const match = DATA_URL_PATTERN.exec(uri); if (!match) { - throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); + throw new AxiosError$1('Invalid URL', AxiosError$1.ERR_INVALID_URL); } const mime = match[1]; @@ -33841,7 +34413,7 @@ function fromDataURI(uri, asBlob, options) { if (asBlob) { if (!_Blob) { - throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); + throw new AxiosError$1('Blob is not supported', AxiosError$1.ERR_NOT_SUPPORT); } return new _Blob([buffer], {type: mime}); @@ -33850,7 +34422,7 @@ function fromDataURI(uri, asBlob, options) { return buffer; } - throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); + throw new AxiosError$1('Unsupported protocol ' + protocol, AxiosError$1.ERR_NOT_SUPPORT); } const kInternals = Symbol('internals'); @@ -34226,7 +34798,7 @@ function throttle(fn, freq) { clearTimeout(timer); timer = null; } - fn.apply(null, args); + fn(...args); }; const throttled = (...args) => { @@ -34291,6 +34863,80 @@ const progressEventDecorator = (total, throttled) => { const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); +/** + * Estimate decoded byte length of a data:// URL *without* allocating large buffers. + * - For base64: compute exact decoded size using length and padding; + * handle %XX at the character-count level (no string allocation). + * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound. + * + * @param {string} url + * @returns {number} + */ +function estimateDataURLDecodedBytes(url) { + if (!url || typeof url !== 'string') return 0; + if (!url.startsWith('data:')) return 0; + + const comma = url.indexOf(','); + if (comma < 0) return 0; + + const meta = url.slice(5, comma); + const body = url.slice(comma + 1); + const isBase64 = /;base64/i.test(meta); + + if (isBase64) { + let effectiveLen = body.length; + const len = body.length; // cache length + + for (let i = 0; i < len; i++) { + if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) { + const a = body.charCodeAt(i + 1); + const b = body.charCodeAt(i + 2); + const isHex = + ((a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)) && + ((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102)); + + if (isHex) { + effectiveLen -= 2; + i += 2; + } + } + } + + let pad = 0; + let idx = len - 1; + + const tailIsPct3D = (j) => + j >= 2 && + body.charCodeAt(j - 2) === 37 && // '%' + body.charCodeAt(j - 1) === 51 && // '3' + (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd' + + if (idx >= 0) { + if (body.charCodeAt(idx) === 61 /* '=' */) { + pad++; + idx--; + } else if (tailIsPct3D(idx)) { + pad++; + idx -= 3; + } + } + + if (pad === 1 && idx >= 0) { + if (body.charCodeAt(idx) === 61 /* '=' */) { + pad++; + } else if (tailIsPct3D(idx)) { + pad++; + } + } + + const groups = Math.floor(effectiveLen / 4); + const bytes = groups * 3 - (pad || 0); + return bytes > 0 ? bytes : 0; + } + + return Buffer.byteLength(body, 'utf8'); +} + const zlibOptions = { flush: zlib__default["default"].constants.Z_SYNC_FLUSH, finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH @@ -34311,6 +34957,7 @@ const supportedProtocols = platform.protocols.map(protocol => { return protocol + ':'; }); + const flushOnFinish = (stream, [throttled, flush]) => { stream .on('end', flush) @@ -34319,17 +34966,113 @@ const flushOnFinish = (stream, [throttled, flush]) => { return throttled; }; -/** - * If the proxy or config beforeRedirects functions are defined, call them with the options - * object. - * - * @param {Object} options - The options object that was passed to the request. - * - * @returns {Object} - */ -function dispatchBeforeRedirect(options, responseDetails) { - if (options.beforeRedirects.proxy) { - options.beforeRedirects.proxy(options); +class Http2Sessions { + constructor() { + this.sessions = Object.create(null); + } + + getSession(authority, options) { + options = Object.assign({ + sessionTimeout: 1000 + }, options); + + let authoritySessions = this.sessions[authority]; + + if (authoritySessions) { + let len = authoritySessions.length; + + for (let i = 0; i < len; i++) { + const [sessionHandle, sessionOptions] = authoritySessions[i]; + if (!sessionHandle.destroyed && !sessionHandle.closed && util__default["default"].isDeepStrictEqual(sessionOptions, options)) { + return sessionHandle; + } + } + } + + const session = http2__default["default"].connect(authority, options); + + let removed; + + const removeSession = () => { + if (removed) { + return; + } + + removed = true; + + let entries = authoritySessions, len = entries.length, i = len; + + while (i--) { + if (entries[i][0] === session) { + if (len === 1) { + delete this.sessions[authority]; + } else { + entries.splice(i, 1); + } + return; + } + } + }; + + const originalRequestFn = session.request; + + const {sessionTimeout} = options; + + if(sessionTimeout != null) { + + let timer; + let streamsCount = 0; + + session.request = function () { + const stream = originalRequestFn.apply(this, arguments); + + streamsCount++; + + if (timer) { + clearTimeout(timer); + timer = null; + } + + stream.once('close', () => { + if (!--streamsCount) { + timer = setTimeout(() => { + timer = null; + removeSession(); + }, sessionTimeout); + } + }); + + return stream; + }; + } + + session.once('close', removeSession); + + let entry = [ + session, + options + ]; + + authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry]; + + return session; + } +} + +const http2Sessions = new Http2Sessions(); + + +/** + * If the proxy or config beforeRedirects functions are defined, call them with the options + * object. + * + * @param {Object} options - The options object that was passed to the request. + * + * @returns {Object} + */ +function dispatchBeforeRedirect(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); } if (options.beforeRedirects.config) { options.beforeRedirects.config(options, responseDetails); @@ -34361,12 +35104,16 @@ function setProxy(options, configProxy, location) { if (proxy.auth) { // Support proxy auth object form - if (proxy.auth.username || proxy.auth.password) { + const validProxyAuth = Boolean(proxy.auth.username || proxy.auth.password); + + if (validProxyAuth) { proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); + } else if (typeof proxy.auth === 'object') { + throw new AxiosError$1('Invalid proxy authorization', AxiosError$1.ERR_BAD_OPTION, { proxy }); } - const base64 = Buffer - .from(proxy.auth, 'utf8') - .toString('base64'); + + const base64 = Buffer.from(proxy.auth, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; } @@ -34430,16 +35177,76 @@ const resolveFamily = ({address, family}) => { const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family}); +const http2Transport = { + request(options, cb) { + const authority = options.protocol + '//' + options.hostname + ':' + (options.port ||(options.protocol === 'https:' ? 443 : 80)); + + + const {http2Options, headers} = options; + + const session = http2Sessions.getSession(authority, http2Options); + + const { + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_STATUS + } = http2__default["default"].constants; + + const http2Headers = { + [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''), + [HTTP2_HEADER_METHOD]: options.method, + [HTTP2_HEADER_PATH]: options.path, + }; + + utils$1.forEach(headers, (header, name) => { + name.charAt(0) !== ':' && (http2Headers[name] = header); + }); + + const req = session.request(http2Headers); + + req.once('response', (responseHeaders) => { + const response = req; //duplex + + responseHeaders = Object.assign({}, responseHeaders); + + const status = responseHeaders[HTTP2_HEADER_STATUS]; + + delete responseHeaders[HTTP2_HEADER_STATUS]; + + response.headers = responseHeaders; + + response.statusCode = +status; + + cb(response); + }); + + return req; + } +}; + /*eslint consistent-return:0*/ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { - let {data, lookup, family} = config; + let {data, lookup, family, httpVersion = 1, http2Options} = config; const {responseType, responseEncoding} = config; const method = config.method.toUpperCase(); let isDone; let rejected = false; let req; + httpVersion = +httpVersion; + + if (Number.isNaN(httpVersion)) { + throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); + } + + if (httpVersion !== 1 && httpVersion !== 2) { + throw TypeError(`Unsupported protocol version '${httpVersion}'`); + } + + const isHttp2 = httpVersion === 2; + if (lookup) { const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); // hotfix to support opt.all option which is required for node 20.x @@ -34456,8 +35263,17 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }; } - // temporary internal emitter until the AxiosRequest class will be implemented - const emitter = new events.EventEmitter(); + const abortEmitter = new events.EventEmitter(); + + function abort(reason) { + try { + abortEmitter.emit('abort', !reason || reason.type ? new CanceledError$1(null, config, req) : reason); + } catch(err) { + console.warn('emit error', err); + } + } + + abortEmitter.once('abort', reject); const onFinished = () => { if (config.cancelToken) { @@ -34468,29 +35284,40 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { config.signal.removeEventListener('abort', abort); } - emitter.removeAllListeners(); + abortEmitter.removeAllListeners(); }; - onDone((value, isRejected) => { + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + } + } + + onDone((response, isRejected) => { isDone = true; + if (isRejected) { rejected = true; onFinished(); + return; + } + + const {data} = response; + + if (data instanceof stream__default["default"].Readable || data instanceof stream__default["default"].Duplex) { + const offListeners = stream__default["default"].finished(data, () => { + offListeners(); + onFinished(); + }); + } else { + onFinished(); } }); - function abort(reason) { - emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); - } - emitter.once('abort', reject); - if (config.cancelToken || config.signal) { - config.cancelToken && config.cancelToken.subscribe(abort); - if (config.signal) { - config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); - } - } + // Parse url const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); @@ -34498,6 +35325,21 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const protocol = parsed.protocol || supportedProtocols[0]; if (protocol === 'data:') { + // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set. + if (config.maxContentLength > -1) { + // Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed. + const dataUrl = String(config.url || fullPath || ''); + const estimated = estimateDataURLDecodedBytes(dataUrl); + + if (estimated > config.maxContentLength) { + return reject(new AxiosError$1( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError$1.ERR_BAD_RESPONSE, + config + )); + } + } + let convertedData; if (method !== 'GET') { @@ -34514,7 +35356,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { Blob: config.env && config.env.Blob }); } catch (err) { - throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + throw AxiosError$1.from(err, AxiosError$1.ERR_BAD_REQUEST, config); } if (responseType === 'text') { @@ -34537,9 +35379,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new AxiosError( + return reject(new AxiosError$1( 'Unsupported protocol ' + protocol, - AxiosError.ERR_BAD_REQUEST, + AxiosError$1.ERR_BAD_REQUEST, config )); } @@ -34589,9 +35431,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } else if (utils$1.isString(data)) { data = Buffer.from(data, 'utf-8'); } else { - return reject(new AxiosError( + return reject(new AxiosError$1( 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - AxiosError.ERR_BAD_REQUEST, + AxiosError$1.ERR_BAD_REQUEST, config )); } @@ -34600,9 +35442,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { headers.setContentLength(data.length, false); if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { - return reject(new AxiosError( + return reject(new AxiosError$1( 'Request body larger than maxBodyLength limit', - AxiosError.ERR_BAD_REQUEST, + AxiosError$1.ERR_BAD_REQUEST, config )); } @@ -34681,7 +35523,8 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { protocol, family, beforeRedirect: dispatchBeforeRedirect, - beforeRedirects: {} + beforeRedirects: {}, + http2Options }; // cacheable-lookup integration hotfix @@ -34698,18 +35541,23 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { let transport; const isHttpsRequest = isHttps.test(options.protocol); options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsRequest ? https__default["default"] : http__default["default"]; + + if (isHttp2) { + transport = http2Transport; } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirects.config = config.beforeRedirect; + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsRequest ? https__default["default"] : http__default["default"]; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirects.config = config.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; } - transport = isHttpsRequest ? httpsFollow : httpFollow; } if (config.maxBodyLength > -1) { @@ -34729,7 +35577,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const streams = [res]; - const responseLength = +res.headers['content-length']; + const responseLength = utils$1.toFiniteNumber(res.headers['content-length']); if (onDownloadProgress || maxDownloadRate) { const transformStream = new AxiosTransformStream$1({ @@ -34792,10 +35640,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; - const offListeners = stream__default["default"].finished(responseStream, () => { - offListeners(); - onFinished(); - }); + const response = { status: res.statusCode, @@ -34821,8 +35666,8 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // stream.destroy() emit aborted event before calling reject() on Node.js v16 rejected = true; responseStream.destroy(); - reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + abort(new AxiosError$1('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError$1.ERR_BAD_RESPONSE, config, lastRequest)); } }); @@ -34831,9 +35676,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { return; } - const err = new AxiosError( + const err = new AxiosError$1( 'stream has been aborted', - AxiosError.ERR_BAD_RESPONSE, + AxiosError$1.ERR_BAD_RESPONSE, config, lastRequest ); @@ -34843,7 +35688,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { responseStream.on('error', function handleStreamError(err) { if (req.destroyed) return; - reject(AxiosError.from(err, null, config, lastRequest)); + reject(AxiosError$1.from(err, null, config, lastRequest)); }); responseStream.on('end', function handleStreamEnd() { @@ -34857,13 +35702,13 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } response.data = responseData; } catch (err) { - return reject(AxiosError.from(err, null, config, response.request, response)); + return reject(AxiosError$1.from(err, null, config, response.request, response)); } settle(resolve, reject, response); }); } - emitter.once('abort', err => { + abortEmitter.once('abort', err => { if (!responseStream.destroyed) { responseStream.emit('error', err); responseStream.destroy(); @@ -34871,16 +35716,17 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }); }); - emitter.once('abort', err => { - reject(err); - req.destroy(err); + abortEmitter.once('abort', err => { + if (req.close) { + req.close(); + } else { + req.destroy(err); + } }); // Handle errors req.on('error', function handleRequestError(err) { - // @todo remove - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; - reject(AxiosError.from(err, null, config, req)); + reject(AxiosError$1.from(err, null, config, req)); }); // set tcp keep alive to prevent drop connection by peer @@ -34895,9 +35741,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const timeout = parseInt(config.timeout, 10); if (Number.isNaN(timeout)) { - reject(new AxiosError( + abort(new AxiosError$1( 'error trying to parse `config.timeout` to int', - AxiosError.ERR_BAD_OPTION_VALUE, + AxiosError$1.ERR_BAD_OPTION_VALUE, config, req )); @@ -34917,14 +35763,16 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } - reject(new AxiosError( + abort(new AxiosError$1( timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, config, req )); - abort(); }); + } else { + // explicitly reset the socket timeout value for a possible `keep-alive` request + req.setTimeout(0); } @@ -34944,13 +35792,14 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { data.on('close', () => { if (!ended && !errored) { - abort(new CanceledError('Request stream has been aborted', config, req)); + abort(new CanceledError$1('Request stream has been aborted', config, req)); } }); data.pipe(req); } else { - req.end(data); + data && req.write(data); + req.end(); } }); }; @@ -34972,27 +35821,38 @@ const cookies = platform.hasStandardBrowserEnv ? // Standard browser envs support document.cookie { - write(name, value, expires, path, domain, secure) { - const cookie = [name + '=' + encodeURIComponent(value)]; - - utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); - - utils$1.isString(path) && cookie.push('path=' + path); + write(name, value, expires, path, domain, secure, sameSite) { + if (typeof document === 'undefined') return; - utils$1.isString(domain) && cookie.push('domain=' + domain); + const cookie = [`${name}=${encodeURIComponent(value)}`]; - secure === true && cookie.push('secure'); + if (utils$1.isNumber(expires)) { + cookie.push(`expires=${new Date(expires).toUTCString()}`); + } + if (utils$1.isString(path)) { + cookie.push(`path=${path}`); + } + if (utils$1.isString(domain)) { + cookie.push(`domain=${domain}`); + } + if (secure === true) { + cookie.push('secure'); + } + if (utils$1.isString(sameSite)) { + cookie.push(`SameSite=${sameSite}`); + } document.cookie = cookie.join('; '); }, read(name) { - const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); + if (typeof document === 'undefined') return null; + const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); + return match ? decodeURIComponent(match[1]) : null; }, remove(name) { - this.write(name, '', Date.now() - 86400000); + this.write(name, '', Date.now() - 86400000, '/'); } } @@ -35007,7 +35867,8 @@ const cookies = platform.hasStandardBrowserEnv ? remove() {} }; -const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; +const headersToObject = (thing) => + thing instanceof AxiosHeaders$1 ? { ...thing } : thing; /** * Config-specific merge-function which creates a new config-object @@ -35025,7 +35886,7 @@ function mergeConfig(config1, config2) { function getMergedValue(target, source, prop, caseless) { if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({caseless}, target, source); + return utils$1.merge.call({ caseless }, target, source); } else if (utils$1.isPlainObject(source)) { return utils$1.merge({}, source); } else if (utils$1.isArray(source)) { @@ -35034,12 +35895,11 @@ function mergeConfig(config1, config2) { return source; } - // eslint-disable-next-line consistent-return - function mergeDeepProperties(a, b, prop , caseless) { + function mergeDeepProperties(a, b, prop, caseless) { if (!utils$1.isUndefined(b)) { - return getMergedValue(a, b, prop , caseless); + return getMergedValue(a, b, prop, caseless); } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a, prop , caseless); + return getMergedValue(undefined, a, prop, caseless); } } @@ -35097,14 +35957,27 @@ function mergeConfig(config1, config2) { socketPath: defaultToConfig2, responseEncoding: defaultToConfig2, validateStatus: mergeDirectKeys, - headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + headers: (a, b, prop) => + mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true), }; - utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { - const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); + utils$1.forEach( + Object.keys({ ...config1, ...config2 }), + function computeConfigValue(prop) { + if ( + prop === "__proto__" || + prop === "constructor" || + prop === "prototype" + ) + return; + const merge = utils$1.hasOwnProp(mergeMap, prop) + ? mergeMap[prop] + : mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || + (config[prop] = configValue); + }, + ); return config; } @@ -35112,7 +35985,7 @@ function mergeConfig(config1, config2) { const resolveConfig = (config) => { const newConfig = mergeConfig({}, config); - let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; newConfig.headers = headers = AxiosHeaders$1.from(headers); @@ -35125,17 +35998,21 @@ const resolveConfig = (config) => { ); } - let contentType; - if (utils$1.isFormData(data)) { if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - headers.setContentType(undefined); // Let the browser set it - } else if ((contentType = headers.getContentType()) !== false) { - // fix semicolon duplication issue for ReactNative FormData implementation - const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; - headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + headers.setContentType(undefined); // browser handles it + } else if (utils$1.isFunction(data.getHeaders)) { + // Node.js FormData (like form-data package) + const formHeaders = data.getHeaders(); + // Only set safe headers to avoid overwriting security headers + const allowedHeaders = ['content-type', 'content-length']; + Object.entries(formHeaders).forEach(([key, val]) => { + if (allowedHeaders.includes(key.toLowerCase())) { + headers.set(key, val); + } + }); } - } + } // Add xsrf header // This is only done if running in a standard browser environment. @@ -35245,22 +36122,25 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { return; } - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request)); // Clean up request request = null; }; // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); - - // Clean up request - request = null; + request.onerror = function handleError(event) { + // Browsers deliver a ProgressEvent in XHR onerror + // (message may be empty; when present, surface it) + // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event + const msg = event && event.message ? event.message : 'Network Error'; + const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request); + // attach the underlying event for consumers who want details + err.event = event || null; + reject(err); + request = null; }; - + // Handle timeout request.ontimeout = function handleTimeout() { let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; @@ -35268,9 +36148,9 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { if (_config.timeoutErrorMessage) { timeoutErrorMessage = _config.timeoutErrorMessage; } - reject(new AxiosError( + reject(new AxiosError$1( timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, config, request)); @@ -35320,7 +36200,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { if (!request) { return; } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel); request.abort(); request = null; }; @@ -35334,7 +36214,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { const protocol = parseProtocol(_config.url); if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config)); return; } @@ -35357,13 +36237,13 @@ const composeSignals = (signals, timeout) => { aborted = true; unsubscribe(); const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err)); } }; let timer = timeout && setTimeout(() => { timer = null; - onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); + onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT)); }, timeout); const unsubscribe = () => { @@ -35476,14 +36356,18 @@ const trackStream = (stream, chunkSize, onProgress, onFinish) => { }) }; -const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; -const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const {isFunction} = utils$1; + +const globalFetchAPI = (({Request, Response}) => ({ + Request, Response +}))(utils$1.global); + +const { + ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1 +} = utils$1.global; -// used only inside the fetch adapter -const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? - ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : - async (str) => new Uint8Array(await new Response(str).arrayBuffer()) -); const test = (fn, ...args) => { try { @@ -35493,278 +36377,380 @@ const test = (fn, ...args) => { } }; -const supportsRequestStream = isReadableStreamSupported && test(() => { - let duplexAccessed = false; +const factory = (env) => { + env = utils$1.merge.call({ + skipUndefined: true + }, globalFetchAPI, env); - const hasContentType = new Request(platform.origin, { - body: new ReadableStream(), - method: 'POST', - get duplex() { - duplexAccessed = true; - return 'half'; - }, - }).headers.has('Content-Type'); + const {fetch: envFetch, Request, Response} = env; + const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function'; + const isRequestSupported = isFunction(Request); + const isResponseSupported = isFunction(Response); - return duplexAccessed && !hasContentType; -}); + if (!isFetchSupported) { + return false; + } -const DEFAULT_CHUNK_SIZE = 64 * 1024; + const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1); -const supportsResponseStream = isReadableStreamSupported && - test(() => utils$1.isReadableStream(new Response('').body)); + const encodeText = isFetchSupported && (typeof TextEncoder$1 === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : + async (str) => new Uint8Array(await new Request(str).arrayBuffer()) + ); + const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { + let duplexAccessed = false; -const resolvers = { - stream: supportsResponseStream && ((res) => res.body) -}; + const hasContentType = new Request(platform.origin, { + body: new ReadableStream$1(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); -isFetchSupported && (((res) => { - ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { - !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : - (_, config) => { - throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - }); + return duplexAccessed && !hasContentType; }); -})(new Response)); -const getBodyLength = async (body) => { - if (body == null) { - return 0; - } + const supportsResponseStream = isResponseSupported && isReadableStreamSupported && + test(() => utils$1.isReadableStream(new Response('').body)); - if(utils$1.isBlob(body)) { - return body.size; - } + const resolvers = { + stream: supportsResponseStream && ((res) => res.body) + }; - if(utils$1.isSpecCompliantForm(body)) { - const _request = new Request(platform.origin, { - method: 'POST', - body, + isFetchSupported && ((() => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = (res, config) => { + let method = res && res[type]; + + if (method) { + return method.call(res); + } + + throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config); + }); }); - return (await _request.arrayBuffer()).byteLength; - } + })()); - if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { - return body.byteLength; - } + const getBodyLength = async (body) => { + if (body == null) { + return 0; + } - if(utils$1.isURLSearchParams(body)) { - body = body + ''; - } + if (utils$1.isBlob(body)) { + return body.size; + } - if(utils$1.isString(body)) { - return (await encodeText(body)).byteLength; - } -}; + if (utils$1.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } -const resolveBodyLength = async (headers, body) => { - const length = utils$1.toFiniteNumber(headers.getContentLength()); + if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } - return length == null ? getBodyLength(body) : length; -}; + if (utils$1.isURLSearchParams(body)) { + body = body + ''; + } + + if (utils$1.isString(body)) { + return (await encodeText(body)).byteLength; + } + }; + + const resolveBodyLength = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); -const fetchAdapter = isFetchSupported && (async (config) => { - let { - url, - method, - data, - signal, - cancelToken, - timeout, - onDownloadProgress, - onUploadProgress, - responseType, - headers, - withCredentials = 'same-origin', - fetchOptions - } = resolveConfig(config); + return length == null ? getBodyLength(body) : length; + }; - responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + return async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); - let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let _fetch = envFetch || fetch; - let request; + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request = null; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { composedSignal.unsubscribe(); - }); + }); - let requestContentLength; + let requestContentLength; - try { - if ( - onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && - (requestContentLength = await resolveBodyLength(headers, data)) !== 0 - ) { - let _request = new Request(url, { - method: 'POST', - body: data, - duplex: "half" - }); + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); - let contentTypeHeader; + let contentTypeHeader; - if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { - headers.setContentType(contentTypeHeader); - } + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } - if (_request.body) { - const [onProgress, flush] = progressEventDecorator( - requestContentLength, - progressEventReducer(asyncDecorator(onUploadProgress)) - ); + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); - data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } } - } - if (!utils$1.isString(withCredentials)) { - withCredentials = withCredentials ? 'include' : 'omit'; - } + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } - // Cloudflare Workers throws when credentials are defined - // see https://github.com/cloudflare/workerd/issues/902 - const isCredentialsSupported = "credentials" in Request.prototype; - request = new Request(url, { - ...fetchOptions, - signal: composedSignal, - method: method.toUpperCase(), - headers: headers.normalize().toJSON(), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : undefined - }); + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype; - let response = await fetch(request); + const resolvedOptions = { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }; - const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + request = isRequestSupported && new Request(url, resolvedOptions); - if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { - const options = {}; + let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions)); - ['status', 'statusText', 'headers'].forEach(prop => { - options[prop] = response[prop]; - }); + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); - const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; - const [onProgress, flush] = onDownloadProgress && progressEventDecorator( - responseContentLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true) - ) || []; + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); - response = new Response( - trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), - options - ); - } + const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); - responseType = responseType || 'text'; + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; - let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } - !isStreamResponse && unsubscribe && unsubscribe(); + responseType = responseType || 'text'; - return await new Promise((resolve, reject) => { - settle(resolve, reject, { - data: responseData, - headers: AxiosHeaders$1.from(response.headers), - status: response.status, - statusText: response.statusText, - config, - request - }); - }) - } catch (err) { - unsubscribe && unsubscribe(); + let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); - if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { - throw Object.assign( - new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), - { - cause: err.cause || err - } - ) + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }); + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request, err && err.response), + { + cause: err.cause || err + } + ) + } + + throw AxiosError$1.from(err, err && err.code, config, request, err && err.response); } + } +}; + +const seedCache = new Map(); + +const getFetch = (config) => { + let env = (config && config.env) || {}; + const {fetch, Request, Response} = env; + const seeds = [ + Request, Response, fetch + ]; + + let len = seeds.length, i = len, + seed, target, map = seedCache; + + while (i--) { + seed = seeds[i]; + target = map.get(seed); + + target === undefined && map.set(seed, target = (i ? new Map() : factory(env))); - throw AxiosError.from(err, err && err.code, config, request); + map = target; } -}); + return target; +}; + +getFetch(); + +/** + * Known adapters mapping. + * Provides environment-specific adapters for Axios: + * - `http` for Node.js + * - `xhr` for browsers + * - `fetch` for fetch API-based requests + * + * @type {Object} + */ const knownAdapters = { http: httpAdapter, xhr: xhrAdapter, - fetch: fetchAdapter + fetch: { + get: getFetch, + } }; +// Assign adapter names for easier debugging and identification utils$1.forEach(knownAdapters, (fn, value) => { if (fn) { try { - Object.defineProperty(fn, 'name', {value}); + Object.defineProperty(fn, 'name', { value }); } catch (e) { // eslint-disable-next-line no-empty } - Object.defineProperty(fn, 'adapterName', {value}); + Object.defineProperty(fn, 'adapterName', { value }); } }); +/** + * Render a rejection reason string for unknown or unsupported adapters + * + * @param {string} reason + * @returns {string} + */ const renderReason = (reason) => `- ${reason}`; +/** + * Check if the adapter is resolved (function, null, or false) + * + * @param {Function|null|false} adapter + * @returns {boolean} + */ const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; -const adapters = { - getAdapter: (adapters) => { - adapters = utils$1.isArray(adapters) ? adapters : [adapters]; +/** + * Get the first suitable adapter from the provided list. + * Tries each adapter in order until a supported one is found. + * Throws an AxiosError if no adapter is suitable. + * + * @param {Array|string|Function} adapters - Adapter(s) by name or function. + * @param {Object} config - Axios request configuration + * @throws {AxiosError} If no suitable adapter is available + * @returns {Function} The resolved adapter function + */ +function getAdapter(adapters, config) { + adapters = utils$1.isArray(adapters) ? adapters : [adapters]; - const {length} = adapters; - let nameOrAdapter; - let adapter; + const { length } = adapters; + let nameOrAdapter; + let adapter; - const rejectedReasons = {}; + const rejectedReasons = {}; - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; - adapter = nameOrAdapter; + adapter = nameOrAdapter; - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; - if (adapter === undefined) { - throw new AxiosError(`Unknown adapter '${id}'`); - } - } - - if (adapter) { - break; + if (adapter === undefined) { + throw new AxiosError$1(`Unknown adapter '${id}'`); } + } - rejectedReasons[id || '#' + i] = adapter; + if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) { + break; } - if (!adapter) { + rejectedReasons[id || '#' + i] = adapter; + } - const reasons = Object.entries(rejectedReasons) - .map(([id, state]) => `adapter ${id} ` + - (state === false ? 'is not supported by the environment' : 'is not available in the build') - ); + if (!adapter) { + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); - let s = length ? - (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : - 'as no adapter specified'; + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; - throw new AxiosError( - `There is no suitable adapter to dispatch the request ` + s, - 'ERR_NOT_SUPPORT' - ); - } + throw new AxiosError$1( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } - return adapter; - }, + return adapter; +} + +/** + * Exports Axios adapters and utility to resolve an adapter + */ +const adapters = { + /** + * Resolve an adapter from a list of adapter names or functions. + * @type {Function} + */ + getAdapter, + + /** + * Exposes all known adapters + * @type {Object} + */ adapters: knownAdapters }; @@ -35781,7 +36767,7 @@ function throwIfCancellationRequested(config) { } if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); + throw new CanceledError$1(null, config); } } @@ -35807,7 +36793,7 @@ function dispatchRequest(config) { config.headers.setContentType('application/x-www-form-urlencoded', false); } - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config); return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); @@ -35869,9 +36855,9 @@ validators$1.transitional = function transitional(validator, version, message) { // eslint-disable-next-line func-names return (value, opt, opts) => { if (validator === false) { - throw new AxiosError( + throw new AxiosError$1( formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED + AxiosError$1.ERR_DEPRECATED ); } @@ -35910,7 +36896,7 @@ validators$1.spelling = function spelling(correctSpelling) { function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE); } const keys = Object.keys(options); let i = keys.length; @@ -35921,12 +36907,12 @@ function assertOptions(options, schema, allowUnknown) { const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION); } } } @@ -36007,7 +36993,8 @@ class Axios { validator.assertOptions(transitional, { silentJSONParsing: validators.transitional(validators.boolean), forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) + clarifyTimeoutError: validators.transitional(validators.boolean), + legacyInterceptorReqResOrdering: validators.transitional(validators.boolean) }, false); } @@ -36064,7 +37051,14 @@ class Axios { synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + const transitional = config.transitional || transitionalDefaults; + const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering; + + if (legacyInterceptorReqResOrdering) { + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + } else { + requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + } }); const responseInterceptorChain = []; @@ -36078,8 +37072,8 @@ class Axios { if (!synchronousRequestInterceptors) { const chain = [dispatchRequest.bind(this), undefined]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); + chain.unshift(...requestInterceptorChain); + chain.push(...responseInterceptorChain); len = chain.length; promise = Promise.resolve(config); @@ -36095,8 +37089,6 @@ class Axios { let newConfig = config; - i = 0; - while (i < len) { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; @@ -36221,7 +37213,7 @@ class CancelToken { return; } - token.reason = new CanceledError(message, config, request); + token.reason = new CanceledError$1(message, config, request); resolvePromise(token.reason); }); } @@ -36305,7 +37297,7 @@ const CancelToken$1 = CancelToken; * * ```js * function f(x, y, z) {} - * var args = [1, 2, 3]; + * const args = [1, 2, 3]; * f.apply(null, args); * ``` * @@ -36400,6 +37392,12 @@ const HttpStatusCode = { LoopDetected: 508, NotExtended: 510, NetworkAuthenticationRequired: 511, + WebServerIsDown: 521, + ConnectionTimedOut: 522, + OriginIsUnreachable: 523, + TimeoutOccurred: 524, + SslHandshakeFailed: 525, + InvalidSslCertificate: 526, }; Object.entries(HttpStatusCode).forEach(([key, value]) => { @@ -36440,14 +37438,14 @@ const axios = createInstance(defaults$1); axios.Axios = Axios$1; // Expose Cancel & CancelToken -axios.CanceledError = CanceledError; +axios.CanceledError = CanceledError$1; axios.CancelToken = CancelToken$1; axios.isCancel = isCancel; axios.VERSION = VERSION; axios.toFormData = toFormData; // Expose AxiosError class -axios.AxiosError = AxiosError; +axios.AxiosError = AxiosError$1; // alias for CanceledError for backward compatibility axios.Cancel = axios.CanceledError; diff --git a/build/lib.json b/build/lib.json index 333fa147..45ffe071 100644 --- a/build/lib.json +++ b/build/lib.json @@ -32,6 +32,7 @@ "LIB_UseFirstGlobMatch": "Multiple workspace matches. using first.", "LIB_MergeTestResultNotSupported": "Merging test results from multiple files to one test run is not supported on this version of build agent for OSX/Linux, each test result file will be published as a separate test run in VSO/TFS.", "LIB_PlatformNotSupported": "Platform not supported: %s", - "LIB_CopyFileFailed": "Error while copying the file. Attempts left: %s" + "LIB_CopyFileFailed": "Error while copying the file. Attempts left: %s", + "LIB_UndefinedNodeVersion": "Node version is undefined." } } diff --git a/package-lock.json b/package-lock.json index 9eb43faa..1db8aad1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@actions/core": "^1.10.0", "@actions/glob": "^0.3.0", "@actions/tool-cache": "^2.0.1", - "@digicert/ssm-client-tools-installer": "^1.6.1", + "@digicert/ssm-client-tools-installer": "github:digicert/ssm-client-tools-installer#DOSTM-9007-fix", "azure-pipelines-task-lib": "^5.2.0" }, "devDependencies": { @@ -364,16 +364,15 @@ } }, "node_modules/@digicert/ssm-client-tools-installer": { - "version": "1.6.1", - "resolved": "https://npm.pkg.github.com/download/@digicert/ssm-client-tools-installer/1.6.1/930ac9cbefd8bd81148cdd3baa28aeb684497c5a", - "integrity": "sha512-EsUIj5NtNpt7/BuKXBpP9BOHKpsiH7DUlabWW9S5QYuoHwEjnxFIyu6D33gRPWcukHYBlcBGQjfUjEUYPDxLEg==", + "version": "1.0.0", + "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#9825ec0701cd04bae8587075d64c7b35872a2b02", "license": "ISC", "dependencies": { "@actions/core": "^1.10.0", "@semantic-release/github": "^12.0.2", - "axios": "1.9.0", - "azure-pipelines-task-lib": "^3.4.0", - "azure-pipelines-tool-lib": "^1.3.2", + "axios": "1.13.5", + "azure-pipelines-task-lib": "4.17.3", + "azure-pipelines-tool-lib": "^2.0.10", "dotenv": "^16.0.1", "extract-zip": "^2.0.1", "proper-lockfile": "^4.1.2", @@ -381,17 +380,17 @@ } }, "node_modules/@digicert/ssm-client-tools-installer/node_modules/azure-pipelines-task-lib": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/azure-pipelines-task-lib/-/azure-pipelines-task-lib-3.4.0.tgz", - "integrity": "sha512-3eC4OTFw+7xD7A2aUhxR/j+jRlTI+vVfS0CGxt1pCLs4c/KmY0tQWgbqjD3157kmiucWxELBvgZHaD2gCBe9fg==", + "version": "4.17.3", + "resolved": "https://registry.npmjs.org/azure-pipelines-task-lib/-/azure-pipelines-task-lib-4.17.3.tgz", + "integrity": "sha512-UxfH5pk3uOHTi9TtLtdDyugQVkFES5A836ZEePjcs3jYyxm3EJ6IlFYq6gbfd6mNBhrM9fxG2u/MFYIJ+Z0cxQ==", "license": "MIT", "dependencies": { + "adm-zip": "^0.5.10", "minimatch": "3.0.5", - "mockery": "^2.1.0", + "nodejs-file-downloader": "^4.11.1", "q": "^1.5.1", - "semver": "^5.1.0", + "semver": "^5.7.2", "shelljs": "^0.8.5", - "sync-request": "6.1.0", "uuid": "^3.0.1" } }, @@ -984,15 +983,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@types/concat-stream": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/@types/concat-stream/-/concat-stream-1.6.1.tgz", - "integrity": "sha512-eHE4cQPoj6ngxBZMvVf6Hw7Mh4jMW4U9lpGmS5GBPB9RYxlFg+CHaVN7ErNY4W9XfLIEn20b4VDYaIrbq0q4uA==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/eslint": { "version": "9.6.1", "dev": true, @@ -1016,15 +1006,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/form-data": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/@types/form-data/-/form-data-0.0.33.tgz", - "integrity": "sha512-8BSvG1kGm83cyJITQMZSulnl6QV8jqAGreJsc5tPu1Jq0vTSOiY/k24Wx82JRpWwZSqrala6sd5rWi6aNXvqcw==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/json-schema": { "version": "7.0.15", "dev": true, @@ -1032,6 +1013,7 @@ }, "node_modules/@types/node": { "version": "18.11.9", + "devOptional": true, "license": "MIT" }, "node_modules/@types/normalize-package-data": { @@ -1050,12 +1032,6 @@ "@types/retry": "*" } }, - "node_modules/@types/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", - "license": "MIT" - }, "node_modules/@types/retry": { "version": "0.12.5", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.5.tgz", @@ -1419,12 +1395,6 @@ "integrity": "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==", "license": "MIT" }, - "node_modules/asap": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", - "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", - "license": "MIT" - }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -1432,13 +1402,13 @@ "license": "MIT" }, "node_modules/axios": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", - "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", + "version": "1.13.5", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.5.tgz", + "integrity": "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.6", - "form-data": "^4.0.0", + "follow-redirects": "^1.15.11", + "form-data": "^4.0.5", "proxy-from-env": "^1.1.0" } }, @@ -1470,14 +1440,14 @@ } }, "node_modules/azure-pipelines-tool-lib": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/azure-pipelines-tool-lib/-/azure-pipelines-tool-lib-1.3.2.tgz", - "integrity": "sha512-PtYcd3E2ouwZhLuaOpWA00FYoLjRuJs1V8mNu3u6lBnqeYd4jh/8VL/of6nchm8f2NM6Div+EEnbOcmWvcptPg==", + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/azure-pipelines-tool-lib/-/azure-pipelines-tool-lib-2.0.10.tgz", + "integrity": "sha512-UiwgFUjbooyEpDQX/0eY6teTUjKXD5VDbe3USpLaFpjbzxI2/XglboA9fj86dQBFvMx6NVg0LKYtECflfYiJOQ==", "license": "MIT", "dependencies": { "@types/semver": "^5.3.0", "@types/uuid": "^3.4.5", - "azure-pipelines-task-lib": "^3.1.10", + "azure-pipelines-task-lib": "^4.1.0", "semver": "^5.7.0", "semver-compare": "^1.0.0", "typed-rest-client": "^1.8.6", @@ -1485,17 +1455,17 @@ } }, "node_modules/azure-pipelines-tool-lib/node_modules/azure-pipelines-task-lib": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/azure-pipelines-task-lib/-/azure-pipelines-task-lib-3.4.0.tgz", - "integrity": "sha512-3eC4OTFw+7xD7A2aUhxR/j+jRlTI+vVfS0CGxt1pCLs4c/KmY0tQWgbqjD3157kmiucWxELBvgZHaD2gCBe9fg==", + "version": "4.17.3", + "resolved": "https://registry.npmjs.org/azure-pipelines-task-lib/-/azure-pipelines-task-lib-4.17.3.tgz", + "integrity": "sha512-UxfH5pk3uOHTi9TtLtdDyugQVkFES5A836ZEePjcs3jYyxm3EJ6IlFYq6gbfd6mNBhrM9fxG2u/MFYIJ+Z0cxQ==", "license": "MIT", "dependencies": { + "adm-zip": "^0.5.10", "minimatch": "3.0.5", - "mockery": "^2.1.0", + "nodejs-file-downloader": "^4.11.1", "q": "^1.5.1", - "semver": "^5.1.0", + "semver": "^5.7.2", "shelljs": "^0.8.5", - "sync-request": "6.1.0", "uuid": "^3.0.1" } }, @@ -1610,6 +1580,7 @@ }, "node_modules/buffer-from": { "version": "1.1.2", + "dev": true, "license": "MIT" }, "node_modules/call-bind-apply-helpers": { @@ -1669,12 +1640,6 @@ ], "license": "CC-BY-4.0" }, - "node_modules/caseless": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", - "license": "Apache-2.0" - }, "node_modules/chalk": { "version": "5.6.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", @@ -1981,21 +1946,6 @@ "version": "0.0.1", "license": "MIT" }, - "node_modules/concat-stream": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "engines": [ - "node >= 0.8" - ], - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^2.2.2", - "typedarray": "^0.0.6" - } - }, "node_modules/concurrently": { "version": "9.2.0", "dev": true, @@ -2739,6 +2689,7 @@ }, "node_modules/fastest-levenshtein": { "version": "1.0.16", + "dev": true, "license": "MIT", "engines": { "node": ">= 4.9.1" @@ -2835,7 +2786,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.15.9", + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", "funding": [ { "type": "individual", @@ -2853,9 +2806,9 @@ } }, "node_modules/form-data": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.3.tgz", - "integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", + "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", @@ -2967,15 +2920,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/get-port": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/get-port/-/get-port-3.2.0.tgz", - "integrity": "sha512-x5UJKlgeUiNT8nyo/AcnwLnZuZNcSjSw0kogRB+Whd1fjjFq4B1hySFxSFWWSn4mIBzg3sRNUDFYc4g5gjPoLg==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/get-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", @@ -3186,21 +3130,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/http-basic": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/http-basic/-/http-basic-8.1.3.tgz", - "integrity": "sha512-/EcDMwJZh3mABI2NhGfHOGOeOZITqfkEO4p/xK+l3NpyncIHUQBoMvCSF/b5GqvKtySC2srL/GGG3+EtlqlmCw==", - "license": "MIT", - "dependencies": { - "caseless": "^0.12.0", - "concat-stream": "^1.6.2", - "http-response-object": "^3.0.1", - "parse-cache-control": "^1.0.1" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -3214,21 +3143,6 @@ "node": ">= 14" } }, - "node_modules/http-response-object": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/http-response-object/-/http-response-object-3.0.2.tgz", - "integrity": "sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==", - "license": "MIT", - "dependencies": { - "@types/node": "^10.0.3" - } - }, - "node_modules/http-response-object/node_modules/@types/node": { - "version": "10.17.60", - "resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz", - "integrity": "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==", - "license": "MIT" - }, "node_modules/https-proxy-agent": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", @@ -3892,11 +3806,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/mockery": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mockery/-/mockery-2.1.0.tgz", - "integrity": "sha512-9VkOmxKlWXoDO/h1jDZaS4lH33aWfRiJiNT/tKj+8OGzrcFDLo8d0syGdbsc3Bc4GvRXPb+NMMvojotmuGJTvA==" - }, "node_modules/ms": { "version": "2.1.2", "license": "MIT" @@ -6143,11 +6052,6 @@ "node": ">=6" } }, - "node_modules/parse-cache-control": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parse-cache-control/-/parse-cache-control-1.0.1.tgz", - "integrity": "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==" - }, "node_modules/parse-json": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-8.3.0.tgz", @@ -6386,15 +6290,6 @@ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "license": "MIT" }, - "node_modules/promise": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/promise/-/promise-8.3.0.tgz", - "integrity": "sha512-rZPNPKTOYVNEEKFaq1HqTgOwZD+4/YHS5ukLzQCypkj+OkYx7iv0mA91lJlpPPZ8vMau3IIGj5Qlwrx+8iiSmg==", - "license": "MIT", - "dependencies": { - "asap": "~2.0.6" - } - }, "node_modules/proper-lockfile": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", @@ -6445,9 +6340,9 @@ } }, "node_modules/qs": { - "version": "6.14.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", - "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" @@ -7219,29 +7114,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/sync-request": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/sync-request/-/sync-request-6.1.0.tgz", - "integrity": "sha512-8fjNkrNlNCrVc/av+Jn+xxqfCjYaBoHqCsDz6mt030UMxJGr+GSfCV1dQt2gRtlL63+VPidwDVLr7V2OcTSdRw==", - "license": "MIT", - "dependencies": { - "http-response-object": "^3.0.1", - "sync-rpc": "^1.2.1", - "then-request": "^6.0.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/sync-rpc": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/sync-rpc/-/sync-rpc-1.3.6.tgz", - "integrity": "sha512-J8jTXuZzRlvU7HemDgHi3pGnh/rkoqR/OZSjhTyyZrEkkYQbk7Z33AXp37mkPfPpfdOuj7Ex3H/TJM1z48uPQw==", - "license": "MIT", - "dependencies": { - "get-port": "^3.1.0" - } - }, "node_modules/tagged-tag": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", @@ -7363,70 +7235,6 @@ } } }, - "node_modules/then-request": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/then-request/-/then-request-6.0.2.tgz", - "integrity": "sha512-3ZBiG7JvP3wbDzA9iNY5zJQcHL4jn/0BWtXIkagfz7QgOL/LqjCEOBQuJNZfu0XYnv5JhKh+cDxCPM4ILrqruA==", - "license": "MIT", - "dependencies": { - "@types/concat-stream": "^1.6.0", - "@types/form-data": "0.0.33", - "@types/node": "^8.0.0", - "@types/qs": "^6.2.31", - "caseless": "~0.12.0", - "concat-stream": "^1.6.0", - "form-data": "^2.2.0", - "http-basic": "^8.1.1", - "http-response-object": "^3.0.1", - "promise": "^8.0.0", - "qs": "^6.4.0" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/then-request/node_modules/@types/node": { - "version": "8.10.66", - "resolved": "https://registry.npmjs.org/@types/node/-/node-8.10.66.tgz", - "integrity": "sha512-tktOkFUA4kXx2hhhrB8bIFb5TbwzS4uOhKEmwiD+NoiL0qtP2OQ9mFldbgD4dV1djrlBYP6eBuQZiWjuHUpqFw==", - "license": "MIT" - }, - "node_modules/then-request/node_modules/form-data": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.3.tgz", - "integrity": "sha512-XHIrMD0NpDrNM/Ckf7XJiBbLl57KEhT3+i3yY+eWm+cqYZJQTZrKo8Y8AWKnuV5GT4scfuUGt9LzNoIx3dU1nQ==", - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "mime-types": "^2.1.35", - "safe-buffer": "^5.2.1" - }, - "engines": { - "node": ">= 0.12" - } - }, - "node_modules/then-request/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/thenify": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", @@ -7637,12 +7445,6 @@ "underscore": "^1.12.1" } }, - "node_modules/typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", - "license": "MIT" - }, "node_modules/typescript": { "version": "4.9.3", "dev": true, diff --git a/package.json b/package.json index 355eb83f..3b8e51f8 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@actions/core": "^1.10.0", "@actions/glob": "^0.3.0", "@actions/tool-cache": "^2.0.1", - "@digicert/ssm-client-tools-installer": "^1.6.1", + "@digicert/ssm-client-tools-installer": "github:digicert/ssm-client-tools-installer#DOSTM-9007-fix", "azure-pipelines-task-lib": "^5.2.0" }, "devDependencies": { From 20950bddaf8a01231e38d894119754886a655294 Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 17:54:06 +0530 Subject: [PATCH 2/8] fix: enhance installation error handling and validate directory existence --- build/index.js | 35 ++++++++++++++++++++++++++++++++++- package-lock.json | 2 +- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/build/index.js b/build/index.js index 406e36a0..7065dcde 100644 --- a/build/index.js +++ b/build/index.js @@ -4368,6 +4368,11 @@ async function installWindowsTools(installationPath, toolToBeUsed, usecase, outp //pkcs11 library installation if (usecase != "gpg-signing" && extractPath != "") { const pkcs11FileName = "smpkcs11.dll"; + // Validate that the extract path exists before attempting to create config files + if (!(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.error(`Cannot create config file: installation directory does not exist at ${extractPath}`); + throw new Error(`Installation failed: directory not found at ${extractPath}. MSI installation may have failed.`); + } //Configures the pkcs#11 configFilePath = await (0, services_1.getConfigFilePath)(pkcs11FileName, extractPath); } @@ -4896,6 +4901,16 @@ async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolTo if (toolToBeUsed.includes(".msi")) { console.log(`Force installing the tool : ${toolToBeUsed}`); extractPath = path_1.default.join(tempDirectoryPath, toolToBeUsed.replace(".msi", "")); + // Create the installation directory before running msiexec + // MSI may require the directory to exist beforehand + if (!(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.log(`Creating installation directory: ${extractPath}`); + const { generateDirectory } = __nccwpck_require__(7755); + const result = generateDirectory(extractPath, "MSI Installation"); + if (result === "false") { + throw new Error(`Failed to create installation directory at ${extractPath}`); + } + } //tool to run .msi file const msiRunner = tl .tool("msiexec") @@ -4908,9 +4923,16 @@ async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolTo const regReturnCode = await msiRunner.exec(); //Please provide admin privileges if the regReturnCode is 1625-30 if (regReturnCode != 0) { + console.error(`MSI installation failed with exit code ${regReturnCode}.`); + console.error(`Common causes: insufficient permissions, conflicting installations, or unsupported INSTALLDIR parameter.`); throw new Error(`Installation of msi failed with return code ${regReturnCode}`); } console.log("installation of smctl returned code", regReturnCode); + // Verify the installation directory exists and has content after MSI installation + if (!(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.error(`Installation directory does not exist after MSI installation: ${extractPath}`); + throw new Error(`MSI installation succeeded but directory was not created at ${extractPath}`); + } } if (!shouldCheckIfToolsInstalled()) { //tool for locating installations Where the installation is already in place @@ -5403,7 +5425,18 @@ function extractAndValidateApiKey() { const getConfigFilePath = async (pkcs11FileName, extractPath) => { const configFilePath = path_1.default.join(extractPath, "pkcs11properties.cfg"); console.info("The pkcs11 library path set is ", path_1.default.join(extractPath, pkcs11FileName), "and config file path is ", configFilePath); - fs_1.default.writeFileSync(configFilePath, `name=signingmanager\r\nlibrary=${path_1.default.join(extractPath, pkcs11FileName)}\r\nslotListIndex=0`); + // Verify the directory exists before attempting to write the config file + if (!(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.error(`Cannot create config file: directory does not exist at ${extractPath}`); + throw new Error(`Configuration failed: installation directory not found at ${extractPath}`); + } + // Verify the pkcs11 library file exists + const pkcs11LibPath = path_1.default.join(extractPath, pkcs11FileName); + if (!(0, fileSystemUtils_1.isFileExistSync)(pkcs11LibPath)) { + console.error(`PKCS11 library file not found at ${pkcs11LibPath}. MSI installation may have failed or installed to a different location.`); + throw new Error(`PKCS11 library file not found at ${pkcs11LibPath}`); + } + fs_1.default.writeFileSync(configFilePath, `name=signingmanager\r\nlibrary=${pkcs11LibPath}\r\nslotListIndex=0`); return configFilePath; }; exports.getConfigFilePath = getConfigFilePath; diff --git a/package-lock.json b/package-lock.json index 1db8aad1..815d9680 100644 --- a/package-lock.json +++ b/package-lock.json @@ -365,7 +365,7 @@ }, "node_modules/@digicert/ssm-client-tools-installer": { "version": "1.0.0", - "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#9825ec0701cd04bae8587075d64c7b35872a2b02", + "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#128108b0afb3c447248288f10ae4f2c7497e6cc4", "license": "ISC", "dependencies": { "@actions/core": "^1.10.0", From 7c66a9c07a947bb78c0766a0849009d0a34ea3b0 Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 18:06:16 +0530 Subject: [PATCH 3/8] fix: add fallback function to locate MSI installation and improve error handling --- build/index.js | 100 ++++++++++++++++++++++++++++++---------------- package-lock.json | 2 +- 2 files changed, 66 insertions(+), 36 deletions(-) diff --git a/build/index.js b/build/index.js index 7065dcde..d0da3e37 100644 --- a/build/index.js +++ b/build/index.js @@ -4892,6 +4892,28 @@ const checkInstallerTobeDownloaded = (tempDirectoryPath, toolToBeUsed) => { } return downloadFlag; }; +// Fallback function to find MSI installation in common locations +async function findInstallationPath(tempDirectoryPath, toolToBeUsed) { + const fs = __nccwpck_require__(7147); + // Common installation paths for DigiCert tools + const commonPaths = [ + path_1.default.join(process.env.ProgramFiles || "C:\\Program Files", "DigiCert", "DigiCert One Signing Manager Tools"), + path_1.default.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "DigiCert", "DigiCert One Signing Manager Tools"), + path_1.default.join(process.env.LOCALAPPDATA || "", "DigiCert", "DigiCert One Signing Manager Tools"), + path_1.default.join(tempDirectoryPath, "DigiCert One Signing Manager Tools"), + path_1.default.join(tempDirectoryPath, toolToBeUsed.replace(".msi", "")), + ]; + console.log("Searching for installation in common paths..."); + for (const commonPath of commonPaths) { + if (commonPath && (0, fileSystemUtils_1.isFileExistSync)(commonPath)) { + console.log(`Found installation at: ${commonPath}`); + return commonPath; + } + } + console.error("Could not find installation in any common paths"); + console.log("Searched paths:", commonPaths.filter(p => p)); + throw new Error("MSI installed successfully but could not locate installation directory. Please check Windows Programs list for 'DigiCert One Signing Manager Tools'."); +} async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolToBeUsed) { let extractPath = ""; if (tl.getVariable(utils_1.appConst.VAR_FORCE_INSTALL_TOOL) === "true") { @@ -4900,55 +4922,63 @@ async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolTo //checking for .msi files if (toolToBeUsed.includes(".msi")) { console.log(`Force installing the tool : ${toolToBeUsed}`); - extractPath = path_1.default.join(tempDirectoryPath, toolToBeUsed.replace(".msi", "")); - // Create the installation directory before running msiexec - // MSI may require the directory to exist beforehand - if (!(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { - console.log(`Creating installation directory: ${extractPath}`); - const { generateDirectory } = __nccwpck_require__(7755); - const result = generateDirectory(extractPath, "MSI Installation"); - if (result === "false") { - throw new Error(`Failed to create installation directory at ${extractPath}`); - } - } - //tool to run .msi file + // Let MSI install to its default location (don't use INSTALLDIR) + // Many MSIs have hardcoded paths and don't support custom install directories + console.log("Installing MSI to default location (MSI may not support custom paths)"); + //tool to run .msi file - removed INSTALLDIR parameter const msiRunner = tl .tool("msiexec") .arg([ `/i`, `${tempDirectoryPath}\\${toolToBeUsed}`, "/quiet", - `INSTALLDIR=${extractPath}`, + "/norestart" ]); const regReturnCode = await msiRunner.exec(); //Please provide admin privileges if the regReturnCode is 1625-30 if (regReturnCode != 0) { console.error(`MSI installation failed with exit code ${regReturnCode}.`); - console.error(`Common causes: insufficient permissions, conflicting installations, or unsupported INSTALLDIR parameter.`); + console.error(`Common causes: insufficient permissions (try running as administrator), conflicting installations, or corrupted MSI file.`); throw new Error(`Installation of msi failed with return code ${regReturnCode}`); } - console.log("installation of smctl returned code", regReturnCode); - // Verify the installation directory exists and has content after MSI installation - if (!(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { - console.error(`Installation directory does not exist after MSI installation: ${extractPath}`); - throw new Error(`MSI installation succeeded but directory was not created at ${extractPath}`); + console.log("MSI installation completed successfully with code", regReturnCode); + // Query the actual installation location from Windows registry + console.log("Querying actual installation location using wmic..."); + try { + const installationLocation = tl + .tool("wmic") + .arg([ + "product", + "where", + "Vendor='DigiCert Inc.' and name='DigiCert One Signing Manager Tools'", + "get", + "installlocation", + "/format:list", + ]) + .execSync(); + const { stdout } = installationLocation; + if (stdout && stdout.includes("=")) { + extractPath = stdout.split("=")[1].trim(); + console.log(`Found installation at: ${extractPath}`); + } + else { + console.warn("wmic query returned no valid installation location"); + console.log("wmic output:", stdout); + // Fallback to common installation paths + extractPath = await findInstallationPath(tempDirectoryPath, toolToBeUsed); + } } - } - if (!shouldCheckIfToolsInstalled()) { - //tool for locating installations Where the installation is already in place - const installationLocation = tl - .tool("wmic") - .arg([ - "product", - "where", - "Vendor='DigiCert Inc.' and name='DigiCert One Signing Manager Tools'", - "get", - "installlocation", - "/format:list", - ]) - .execSync(); - const { stdout } = installationLocation; - extractPath = stdout.split("=")[1].trim(); + catch (wmicError) { + console.warn("Failed to query installation location with wmic:", wmicError); + // Fallback to common installation paths + extractPath = await findInstallationPath(tempDirectoryPath, toolToBeUsed); + } + // Verify the installation directory exists + if (!extractPath || !(0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.error(`Installation directory not found after MSI installation: ${extractPath}`); + throw new Error(`MSI installation succeeded but could not locate installation directory`); + } + console.log(`Verified installation directory exists at: ${extractPath}`); } const downloadToolHash = await (0, fileSystemUtils_1.getFileChecksum)(clientToolsDownloadPath); (0, fileSystemUtils_1.writeFileWithContent)(path_1.default.join(tempDirectoryPath, utils_1.appConst.HASH_FILE_NAME), (0, utils_1.getLocalFileName)(toolToBeUsed), `${(0, utils_1.getLocalFileName)(toolToBeUsed)}=${downloadToolHash}\r\n`); diff --git a/package-lock.json b/package-lock.json index 815d9680..7ba0292d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -365,7 +365,7 @@ }, "node_modules/@digicert/ssm-client-tools-installer": { "version": "1.0.0", - "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#128108b0afb3c447248288f10ae4f2c7497e6cc4", + "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#77256308e8b3e93cae5043574e50f928e396f5c4", "license": "ISC", "dependencies": { "@actions/core": "^1.10.0", From d3fad693c8490645a88fcef03c97dee56a6e231c Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 18:14:48 +0530 Subject: [PATCH 4/8] fix: improve error handling during installation and check for existing installations --- build/index.js | 58 +++++++++++++++++++++++++++++++++++++++++++---- package-lock.json | 2 +- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/build/index.js b/build/index.js index d0da3e37..20af7b5c 100644 --- a/build/index.js +++ b/build/index.js @@ -4833,11 +4833,13 @@ async function runWinToolBasedInstallationOrExtraction(toolToBeUsed, tempDirecto error.code === "ELOCKED") { console.log(`File ${tempDirectoryPath} is currently locked. Retrying in a moment...`); // Implement a retry mechanism (e.g., using setTimeout or a retry library) - await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 1 second + await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds extractPath = await processExtract(clientToolsDownloadPath, tempDirectoryPath, toolToBeUsed[i]); // Retry the operation } else { console.error(`Error processing file ${tempDirectoryPath}:`, error); + // Re-throw the error so it's not silently swallowed + throw error; } } } @@ -4848,11 +4850,17 @@ async function runWinToolBasedInstallationOrExtraction(toolToBeUsed, tempDirecto } catch (error) { console.error(`Error processing file ${tempDirectoryPath}:`, error); - } - finally { - // Release lock from the tempDirectory + // Re-throw the error after releasing the lock await lockfile.unlock(tempDirectoryPath); console.log(`Lock released for ${tempDirectoryPath}.`); + throw error; + } + finally { + // Release lock from the tempDirectory if not already released + if (await lockfile.check(tempDirectoryPath)) { + await lockfile.unlock(tempDirectoryPath); + console.log(`Lock released for ${tempDirectoryPath}.`); + } } return extractPath; } @@ -4922,6 +4930,46 @@ async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolTo //checking for .msi files if (toolToBeUsed.includes(".msi")) { console.log(`Force installing the tool : ${toolToBeUsed}`); + // Check if there's an existing installation and try to uninstall it first + console.log("Checking for existing installations..."); + try { + const checkInstall = tl + .tool("wmic") + .arg([ + "product", + "where", + "name='DigiCert One Signing Manager Tools'", + "get", + "name,version" + ]) + .execSync(); + if (checkInstall.stdout && checkInstall.stdout.includes("DigiCert")) { + console.log("Existing installation found. Attempting to uninstall..."); + const uninstallRunner = tl + .tool("msiexec") + .arg([ + `/x`, + `${tempDirectoryPath}\\${toolToBeUsed}`, + "/quiet", + "/norestart" + ]); + const uninstallCode = await uninstallRunner.exec(); + if (uninstallCode === 0) { + console.log("Previous installation uninstalled successfully"); + // Wait a bit for Windows Installer to clean up + await new Promise((resolve) => setTimeout(resolve, 3000)); + } + else { + console.warn(`Uninstall returned code ${uninstallCode}, continuing with installation...`); + } + } + else { + console.log("No existing installation found."); + } + } + catch (checkError) { + console.log("Could not check for existing installation, continuing..."); + } // Let MSI install to its default location (don't use INSTALLDIR) // Many MSIs have hardcoded paths and don't support custom install directories console.log("Installing MSI to default location (MSI may not support custom paths)"); @@ -4996,6 +5044,8 @@ async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolTo } else { console.error(`Error processing file ${tempDirectoryPath}:`, error); + // Re-throw the error to propagate it up + throw error; } } } diff --git a/package-lock.json b/package-lock.json index 7ba0292d..d6682a37 100644 --- a/package-lock.json +++ b/package-lock.json @@ -365,7 +365,7 @@ }, "node_modules/@digicert/ssm-client-tools-installer": { "version": "1.0.0", - "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#77256308e8b3e93cae5043574e50f928e396f5c4", + "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#39b8f079cabd52040d8897178acbd968c7b00dee", "license": "ISC", "dependencies": { "@actions/core": "^1.10.0", From 480ffe0903bcf8c1464a184ef56ee9fc2ac92338 Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 18:36:57 +0530 Subject: [PATCH 5/8] fix: enhance installation process by checking for existing MSI and updating package-lock.json --- build/index.js | 53 +++++++++++++++++++++++++++++++++++++++++++++-- package-lock.json | 2 +- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/build/index.js b/build/index.js index 20af7b5c..be100a16 100644 --- a/build/index.js +++ b/build/index.js @@ -4844,7 +4844,9 @@ async function runWinToolBasedInstallationOrExtraction(toolToBeUsed, tempDirecto } } else { - extractPath = path_1.default.join(tempDirectoryPath, toolToBeUsed[i].replace(".msi", "")); + // Download was skipped because MSI file already exists. + console.log("MSI file already exists, looking for existing installation location..."); + extractPath = await findExistingInstallationPath(tempDirectoryPath, toolToBeUsed[i]); } } } @@ -4922,6 +4924,51 @@ async function findInstallationPath(tempDirectoryPath, toolToBeUsed) { console.log("Searched paths:", commonPaths.filter(p => p)); throw new Error("MSI installed successfully but could not locate installation directory. Please check Windows Programs list for 'DigiCert One Signing Manager Tools'."); } +// Find existing installation path by querying wmic first, then falling back to common paths +async function findExistingInstallationPath(tempDirectoryPath, toolToBeUsed) { + let extractPath = ""; + // First try wmic to get actual install location + try { + console.log("Querying installation location using wmic..."); + const installationLocation = tl + .tool("wmic") + .arg([ + "product", + "where", + "Vendor='DigiCert Inc.' and name='DigiCert One Signing Manager Tools'", + "get", + "installlocation", + "/format:list", + ]) + .execSync(); + const { stdout } = installationLocation; + if (stdout && stdout.includes("=")) { + extractPath = stdout.split("=")[1].trim(); + if (extractPath && (0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.log(`Found existing installation at: ${extractPath}`); + return extractPath; + } + } + console.log("wmic did not return a valid installation path"); + } + catch (wmicError) { + console.warn("Failed to query installation location with wmic:", wmicError); + } + // Fallback to common paths + try { + extractPath = await findInstallationPath(tempDirectoryPath, toolToBeUsed); + return extractPath; + } + catch (fallbackError) { + // Last resort: use the old conventional path + extractPath = path_1.default.join(tempDirectoryPath, toolToBeUsed.replace(".msi", "")); + if ((0, fileSystemUtils_1.isFileExistSync)(extractPath)) { + console.log(`Found installation at conventional path: ${extractPath}`); + return extractPath; + } + throw new Error(`Could not locate DigiCert tools installation. The tool may need to be installed first. Set force-download-tools to true to force reinstallation.`); + } +} async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolToBeUsed) { let extractPath = ""; if (tl.getVariable(utils_1.appConst.VAR_FORCE_INSTALL_TOOL) === "true") { @@ -5050,7 +5097,9 @@ async function processExtract(clientToolsDownloadPath, tempDirectoryPath, toolTo } } else { - extractPath = path_1.default.join(tempDirectoryPath, toolToBeUsed.replace(".msi", "")); + // forceInstallTool is not set - find the existing installation + console.log("No force install requested, looking for existing installation..."); + extractPath = await findExistingInstallationPath(tempDirectoryPath, toolToBeUsed); } return extractPath; } diff --git a/package-lock.json b/package-lock.json index d6682a37..19d50fa6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -365,7 +365,7 @@ }, "node_modules/@digicert/ssm-client-tools-installer": { "version": "1.0.0", - "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#39b8f079cabd52040d8897178acbd968c7b00dee", + "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#d69bca67afcd9edd93c8def1a767cbc27806b803", "license": "ISC", "dependencies": { "@actions/core": "^1.10.0", From 8ce37750c7a5a5e6d5fba4c65fac2d0a91d33210 Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 18:44:21 +0530 Subject: [PATCH 6/8] fix: improve tool installation handling for Windows MSI paths to avoid caching errors --- build/index.js | 28 ++++++++++++++++++++++------ src/index.ts | 34 ++++++++++++++++++++++++---------- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/build/index.js b/build/index.js index be100a16..a04c9622 100644 --- a/build/index.js +++ b/build/index.js @@ -32013,9 +32013,17 @@ const toolInstaller = async (toolName, toolPath = "") => { let cacheDir; switch (toolName) { case con.SIGN_TOOL_SMCTL: { - cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); - core.addPath(cacheDir); - core.debug(`tools cache has been updated with the path: ${cacheDir}`); + // On Windows, MSI installations provide a directory path that's already extracted + // Skip caching and use the path directly to avoid "not a supported archive" error + if (isWinPlatform && toolPath) { + core.addPath(toolPath); + core.debug(`Added MSI installation path to PATH: ${toolPath}`); + } + else { + cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); + core.addPath(cacheDir); + core.debug(`tools cache has been updated with the path: ${cacheDir}`); + } break; } case con.SIGN_TOOL_SIGNTOOL: { @@ -32038,9 +32046,17 @@ const toolInstaller = async (toolName, toolPath = "") => { break; } case con.SIGN_TOOL_SSM_SCD: { - cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); - core.addPath(cacheDir); - core.debug(`tools cache has been updated with the path: ${cacheDir}`); + // On Windows, MSI installations provide a directory path that's already extracted + // Skip caching and use the path directly to avoid "not a supported archive" error + if (isWinPlatform && toolPath) { + core.addPath(toolPath); + core.debug(`Added MSI installation path to PATH: ${toolPath}`); + } + else { + cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); + core.addPath(cacheDir); + core.debug(`tools cache has been updated with the path: ${cacheDir}`); + } break; } case con.SIGN_TOOL_NUGET: { diff --git a/src/index.ts b/src/index.ts index 7a3044c3..e45f6257 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,13 +16,20 @@ const toolInstaller = async (toolName: string, toolPath: string = "") => { let cacheDir; switch (toolName) { case con.SIGN_TOOL_SMCTL: { - cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); - core.addPath(cacheDir); - core.debug(`tools cache has been updated with the path: ${cacheDir}`); + // On Windows, MSI installations provide a directory path that's already extracted + // Skip caching and use the path directly to avoid "not a supported archive" error + if (isWinPlatform && toolPath) { + core.addPath(toolPath); + core.debug(`Added MSI installation path to PATH: ${toolPath}`); + } else { + cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); + core.addPath(cacheDir); + core.debug(`tools cache has been updated with the path: ${cacheDir}`); + } break; } case con.SIGN_TOOL_SIGNTOOL: { - var sign = ""; + var sign = ""; if (fs.existsSync(con.WIN_KIT_BASE_PATH)) { console.log(`The WinKit directory exists!`); let versions = utils.getAllSdkVersions(con.WIN_KIT_BASE_PATH, new Array()); @@ -32,7 +39,7 @@ const toolInstaller = async (toolName: string, toolPath: string = "") => { console.log(`Latest Win SDK Version is : `, versions[latestSdkVerIdx]); console.log(`Using the latest Win SDK version ${versions[latestSdkVerIdx]} for signing!`); sign = con.WIN_KIT_BASE_PATH + versions[latestSdkVerIdx] + con.ARCH_TYPE_DIR; - + cacheDir = await tc.cacheDir(sign, toolName, "latest"); core.addPath(cacheDir); core.debug(`tools cache has been updated with the path: ${cacheDir}`); @@ -42,9 +49,16 @@ const toolInstaller = async (toolName: string, toolPath: string = "") => { break; } case con.SIGN_TOOL_SSM_SCD: { - cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); - core.addPath(cacheDir); - core.debug(`tools cache has been updated with the path: ${cacheDir}`); + // On Windows, MSI installations provide a directory path that's already extracted + // Skip caching and use the path directly to avoid "not a supported archive" error + if (isWinPlatform && toolPath) { + core.addPath(toolPath); + core.debug(`Added MSI installation path to PATH: ${toolPath}`); + } else { + cacheDir = await tc.cacheDir(toolPath, toolName, "latest"); + core.addPath(cacheDir); + core.debug(`tools cache has been updated with the path: ${cacheDir}`); + } break; } case con.SIGN_TOOL_NUGET: { @@ -72,8 +86,8 @@ const toolInstaller = async (toolName: string, toolPath: string = "") => { } // Extract tar const extractPath = isWinPlatform - ? await tc.extractZip(downloadPath) - : await tc.extractTar(downloadPath); + ? await tc.extractZip(downloadPath) + : await tc.extractTar(downloadPath); cacheDir = await tc.cacheDir(extractPath, toolName, "latest"); core.addPath(cacheDir); core.debug(`tools cache has been updated with the path: ${cacheDir}`); From 69d3603461997ae6ee3ebf72a41f661b78510970 Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 13 Feb 2026 19:03:20 +0530 Subject: [PATCH 7/8] fix: rename downloaded file to .zip for Windows extraction compatibility --- build/index.js | 9 ++++++++- src/index.ts | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/build/index.js b/build/index.js index a04c9622..98db9b6e 100644 --- a/build/index.js +++ b/build/index.js @@ -32081,7 +32081,14 @@ const toolInstaller = async (toolName, toolPath = "") => { core.debug(err); throw new Error(`failed to download Mage v: ${err.message}`); } - // Extract tar + // On Windows, PowerShell 5.1's Expand-Archive requires a .zip extension. + // tc.downloadTool() saves to a temp GUID filename without extension, + // so rename it before extracting. + if (isWinPlatform && !downloadPath.endsWith(".zip")) { + const zipPath = downloadPath + ".zip"; + fs_1.default.renameSync(downloadPath, zipPath); + downloadPath = zipPath; + } const extractPath = isWinPlatform ? await tc.extractZip(downloadPath) : await tc.extractTar(downloadPath); diff --git a/src/index.ts b/src/index.ts index e45f6257..cc03b39b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -84,7 +84,14 @@ const toolInstaller = async (toolName: string, toolPath: string = "") => { throw new Error(`failed to download Mage v: ${err.message}`); } - // Extract tar + // On Windows, PowerShell 5.1's Expand-Archive requires a .zip extension. + // tc.downloadTool() saves to a temp GUID filename without extension, + // so rename it before extracting. + if (isWinPlatform && !downloadPath.endsWith(".zip")) { + const zipPath = downloadPath + ".zip"; + fs.renameSync(downloadPath, zipPath); + downloadPath = zipPath; + } const extractPath = isWinPlatform ? await tc.extractZip(downloadPath) : await tc.extractTar(downloadPath); From e23a02a0fb9829be893a57c5eb4e675357891794 Mon Sep 17 00:00:00 2001 From: UtkarshBagariaDigicert Date: Fri, 6 Mar 2026 12:19:36 +0530 Subject: [PATCH 8/8] fix: npm package upgrade to mitigate vulnerabilities --- package-lock.json | 7 ++++--- package.json | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 19d50fa6..29fc4e74 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@actions/core": "^1.10.0", "@actions/glob": "^0.3.0", "@actions/tool-cache": "^2.0.1", - "@digicert/ssm-client-tools-installer": "github:digicert/ssm-client-tools-installer#DOSTM-9007-fix", + "@digicert/ssm-client-tools-installer": "^1.6.2", "azure-pipelines-task-lib": "^5.2.0" }, "devDependencies": { @@ -364,8 +364,9 @@ } }, "node_modules/@digicert/ssm-client-tools-installer": { - "version": "1.0.0", - "resolved": "git+ssh://git@github.com/digicert/ssm-client-tools-installer.git#d69bca67afcd9edd93c8def1a767cbc27806b803", + "version": "1.6.2", + "resolved": "https://npm.pkg.github.com/download/@digicert/ssm-client-tools-installer/1.6.2/95cdd4259946514165dedcd43f8deac4338077cf", + "integrity": "sha512-y1Pj+i5GiFNy67XkhkxSaU24zjY3nXd+Sw8CXdYP7WTcrLafLCZODHzyEOd5OAw29vV6fmCKtvO4CsLlkf8cwQ==", "license": "ISC", "dependencies": { "@actions/core": "^1.10.0", diff --git a/package.json b/package.json index 3b8e51f8..5962a0d0 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@actions/core": "^1.10.0", "@actions/glob": "^0.3.0", "@actions/tool-cache": "^2.0.1", - "@digicert/ssm-client-tools-installer": "github:digicert/ssm-client-tools-installer#DOSTM-9007-fix", + "@digicert/ssm-client-tools-installer": "^1.6.2", "azure-pipelines-task-lib": "^5.2.0" }, "devDependencies": {