@reportportal/client-javascript 5.5.12 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +22 -0
  2. package/VERSION +1 -1
  3. package/build/commons/config.d.ts +5 -0
  4. package/build/commons/config.js +125 -0
  5. package/build/commons/config.js.map +1 -0
  6. package/build/commons/errors.d.ts +9 -0
  7. package/build/commons/errors.js +28 -0
  8. package/build/commons/errors.js.map +1 -0
  9. package/build/constants/events.d.ts +9 -0
  10. package/build/constants/events.js +14 -0
  11. package/build/constants/events.js.map +1 -0
  12. package/build/constants/index.d.ts +7 -0
  13. package/build/constants/index.js +19 -0
  14. package/build/constants/index.js.map +1 -0
  15. package/build/constants/launchModes.d.ts +4 -0
  16. package/build/constants/launchModes.js +9 -0
  17. package/build/constants/launchModes.js.map +1 -0
  18. package/build/constants/logLevels.d.ts +9 -0
  19. package/build/constants/logLevels.js +13 -0
  20. package/build/constants/logLevels.js.map +1 -0
  21. package/build/constants/mergeTypes.d.ts +4 -0
  22. package/build/constants/mergeTypes.js +9 -0
  23. package/build/constants/mergeTypes.js.map +1 -0
  24. package/build/constants/outputs.d.ts +2 -0
  25. package/build/constants/outputs.js +35 -0
  26. package/build/constants/outputs.js.map +1 -0
  27. package/build/constants/statuses.d.ts +14 -0
  28. package/build/constants/statuses.js +19 -0
  29. package/build/constants/statuses.js.map +1 -0
  30. package/build/constants/testItemTypes.d.ts +17 -0
  31. package/build/constants/testItemTypes.js +22 -0
  32. package/build/constants/testItemTypes.js.map +1 -0
  33. package/build/helpers.d.ts +22 -0
  34. package/build/helpers.js +110 -0
  35. package/build/helpers.js.map +1 -0
  36. package/build/logger.d.ts +2 -0
  37. package/build/logger.js +28 -0
  38. package/build/logger.js.map +1 -0
  39. package/build/models/common.d.ts +37 -0
  40. package/build/models/common.js +3 -0
  41. package/build/models/common.js.map +1 -0
  42. package/build/models/config.d.ts +97 -0
  43. package/build/models/config.js +3 -0
  44. package/build/models/config.js.map +1 -0
  45. package/build/models/index.d.ts +5 -0
  46. package/build/models/index.js +22 -0
  47. package/build/models/index.js.map +1 -0
  48. package/build/models/reporting.d.ts +11 -0
  49. package/build/models/reporting.js +3 -0
  50. package/build/models/reporting.js.map +1 -0
  51. package/build/models/requests.d.ts +84 -0
  52. package/build/models/requests.js +3 -0
  53. package/build/models/requests.js.map +1 -0
  54. package/build/models/responses.d.ts +87 -0
  55. package/build/models/responses.js +3 -0
  56. package/build/models/responses.js.map +1 -0
  57. package/build/oauth.d.ts +42 -0
  58. package/build/oauth.js +182 -0
  59. package/build/oauth.js.map +1 -0
  60. package/build/pjson.d.ts +2 -0
  61. package/build/pjson.js +28 -0
  62. package/build/pjson.js.map +1 -0
  63. package/build/proxyHelper.d.ts +28 -0
  64. package/build/proxyHelper.js +173 -0
  65. package/build/proxyHelper.js.map +1 -0
  66. package/build/publicReportingAPI.d.ts +37 -0
  67. package/build/publicReportingAPI.js +56 -0
  68. package/build/publicReportingAPI.js.map +1 -0
  69. package/build/report-portal-client.d.ts +99 -0
  70. package/build/report-portal-client.js +607 -0
  71. package/build/report-portal-client.js.map +1 -0
  72. package/build/rest.d.ts +23 -0
  73. package/build/rest.js +205 -0
  74. package/build/rest.js.map +1 -0
  75. package/build/statistics/client-id.d.ts +1 -0
  76. package/build/statistics/client-id.js +73 -0
  77. package/build/statistics/client-id.js.map +1 -0
  78. package/build/statistics/constants.d.ts +11 -0
  79. package/build/statistics/constants.js +52 -0
  80. package/build/statistics/constants.js.map +1 -0
  81. package/build/statistics/statistics.d.ts +19 -0
  82. package/build/statistics/statistics.js +57 -0
  83. package/build/statistics/statistics.js.map +1 -0
  84. package/constants.d.ts +1 -0
  85. package/constants.js +1 -0
  86. package/helpers.d.ts +2 -0
  87. package/helpers.js +1 -0
  88. package/models.d.ts +1 -0
  89. package/package.json +82 -15
  90. package/publicReportingAPI.d.ts +2 -0
  91. package/publicReportingAPI.js +1 -0
  92. package/index.d.ts +0 -443
  93. package/lib/commons/config.js +0 -133
  94. package/lib/commons/errors.js +0 -29
  95. package/lib/constants/events.js +0 -11
  96. package/lib/constants/outputs.js +0 -13
  97. package/lib/constants/statuses.js +0 -12
  98. package/lib/helpers.js +0 -111
  99. package/lib/logger.js +0 -41
  100. package/lib/oauth.js +0 -226
  101. package/lib/proxyHelper.js +0 -232
  102. package/lib/publicReportingAPI.js +0 -92
  103. package/lib/report-portal-client.js +0 -905
  104. package/lib/rest.js +0 -218
  105. package/statistics/client-id.js +0 -46
  106. package/statistics/constants.js +0 -49
  107. package/statistics/statistics.js +0 -63
package/lib/helpers.js DELETED
@@ -1,111 +0,0 @@
1
- const fs = require('fs');
2
- const glob = require('glob');
3
- const os = require('os');
4
- const RestClient = require('./rest');
5
- const pjson = require('../package.json');
6
-
7
- const MIN = 3;
8
- const MAX = 256;
9
- const PJSON_VERSION = pjson.version;
10
- const PJSON_NAME = pjson.name;
11
-
12
- const getUUIDFromFileName = (filename) => filename.match(/rplaunch-(.*)\.tmp/)[1];
13
-
14
- const formatName = (name) => {
15
- const len = name.length;
16
- // eslint-disable-next-line no-mixed-operators
17
- return (len < MIN ? name + new Array(MIN - len + 1).join('.') : name).slice(-MAX);
18
- };
19
-
20
- const now = () => {
21
- return new Date().valueOf();
22
- };
23
-
24
- // TODO: deprecate and remove
25
- const getServerResult = (url, request, options, method) => {
26
- return new RestClient(options).request(method, url, request, options);
27
- };
28
-
29
- const readLaunchesFromFile = () => {
30
- const files = glob.sync('rplaunch-*.tmp');
31
- const ids = files.map(getUUIDFromFileName);
32
-
33
- return ids;
34
- };
35
-
36
- const saveLaunchIdToFile = (launchId) => {
37
- const filename = `rplaunch-${launchId}.tmp`;
38
- fs.open(filename, 'w', (err) => {
39
- if (err) {
40
- throw err;
41
- }
42
- });
43
- };
44
-
45
- const getSystemAttribute = () => {
46
- const osType = os.type();
47
- const osArchitecture = os.arch();
48
- const RAMSize = os.totalmem();
49
- const nodeVersion = process.version;
50
- const systemAttr = [
51
- {
52
- key: 'client',
53
- value: `${PJSON_NAME}|${PJSON_VERSION}`,
54
- system: true,
55
- },
56
- {
57
- key: 'os',
58
- value: `${osType}|${osArchitecture}`,
59
- system: true,
60
- },
61
- {
62
- key: 'RAMSize',
63
- value: RAMSize,
64
- system: true,
65
- },
66
- {
67
- key: 'nodeJS',
68
- value: nodeVersion,
69
- system: true,
70
- },
71
- ];
72
-
73
- return systemAttr;
74
- };
75
-
76
- const generateTestCaseId = (codeRef, params) => {
77
- if (!codeRef) {
78
- return;
79
- }
80
-
81
- if (!params) {
82
- return codeRef;
83
- }
84
-
85
- const parameters = params.reduce(
86
- (result, item) => (item.value ? result.concat(item.value) : result),
87
- [],
88
- );
89
-
90
- return `${codeRef}[${parameters}]`;
91
- };
92
-
93
- const saveLaunchUuidToFile = (launchUuid) => {
94
- const filename = `rp-launch-uuid-${launchUuid}.tmp`;
95
- fs.open(filename, 'w', (err) => {
96
- if (err) {
97
- throw err;
98
- }
99
- });
100
- };
101
-
102
- module.exports = {
103
- formatName,
104
- now,
105
- getServerResult,
106
- readLaunchesFromFile,
107
- saveLaunchIdToFile,
108
- getSystemAttribute,
109
- generateTestCaseId,
110
- saveLaunchUuidToFile,
111
- };
package/lib/logger.js DELETED
@@ -1,41 +0,0 @@
1
- const addLogger = (axiosInstance) => {
2
- axiosInstance.interceptors.request.use((config) => {
3
- const startDate = new Date();
4
- // eslint-disable-next-line no-param-reassign
5
- config.startTime = startDate.valueOf();
6
-
7
- console.log(`Request method=${config.method} url=${config.url} [${startDate.toISOString()}]`);
8
-
9
- return config;
10
- });
11
-
12
- axiosInstance.interceptors.response.use(
13
- (response) => {
14
- const date = new Date();
15
- const { status, config } = response;
16
-
17
- console.log(
18
- `Response status=${status} url=${config.url} time=${
19
- date.valueOf() - config.startTime
20
- }ms [${date.toISOString()}]`,
21
- );
22
-
23
- return response;
24
- },
25
- (error) => {
26
- const date = new Date();
27
- const { response, config } = error;
28
- const status = response ? response.status : null;
29
-
30
- console.log(
31
- `Response ${status ? `status=${status}` : `message='${error.message}'`} url=${
32
- config.url
33
- } time=${date.valueOf() - config.startTime}ms [${date.toISOString()}]`,
34
- );
35
-
36
- return Promise.reject(error);
37
- },
38
- );
39
- };
40
-
41
- module.exports = { addLogger };
package/lib/oauth.js DELETED
@@ -1,226 +0,0 @@
1
- const axios = require('axios');
2
- const { getProxyAgentForUrl } = require('./proxyHelper');
3
-
4
- const TOKEN_REFRESH_THRESHOLD_MS = 60000;
5
- const DEFAULT_TOKEN_EXPIRATION_MS = 3600000; // 1 hour in milliseconds
6
- const SECOND_IN_MS = 1000;
7
- const GRANT_TYPE_PASSWORD = 'password';
8
- const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
9
-
10
- class OAuthInterceptor {
11
- /**
12
- * OAuth 2.0 Password Grant Flow Interceptor
13
- * @param {Object} config - OAuth configuration
14
- * @param {string} config.tokenEndpoint - OAuth token endpoint URL
15
- * @param {string} config.username - Username for password grant
16
- * @param {string} config.password - Password for password grant
17
- * @param {string} config.clientId - OAuth client ID
18
- * @param {string} [config.clientSecret] - OAuth client secret (optional)
19
- * @param {string} [config.scope] - OAuth scope (optional)
20
- * @param {boolean} [config.debug] - Enable debug logging
21
- * @param {Object} [config.restClientConfig] - REST client configuration for proxy support
22
- */
23
- constructor(config) {
24
- this.tokenEndpoint = config.tokenEndpoint;
25
- this.username = config.username;
26
- this.password = config.password;
27
- this.clientId = config.clientId;
28
- this.clientSecret = config.clientSecret;
29
- this.scope = config.scope;
30
- this.restClientConfig = config.restClientConfig || {};
31
- this.debug = this.restClientConfig.debug || false;
32
-
33
- this.accessToken = null;
34
- this.refreshToken = null;
35
- this.tokenExpiresAt = null;
36
- this.tokenRenewPromise = null;
37
- }
38
-
39
- logDebug(message, data = '') {
40
- if (this.debug) {
41
- console.log(`[OAuth] ${message}`, data);
42
- }
43
- }
44
-
45
- /**
46
- * Obtains or refreshes the access token
47
- * @returns {Promise<string>} Access token
48
- */
49
- async getAccessToken() {
50
- if (this.tokenRenewPromise) {
51
- this.logDebug('Waiting for ongoing token refresh');
52
- return this.tokenRenewPromise;
53
- }
54
-
55
- if (this.accessToken && this.tokenExpiresAt) {
56
- const now = Date.now();
57
- const timeUntilExpiry = this.tokenExpiresAt - now;
58
-
59
- if (timeUntilExpiry > TOKEN_REFRESH_THRESHOLD_MS) {
60
- this.logDebug('Using existing valid token');
61
- return this.accessToken;
62
- }
63
-
64
- this.logDebug('Token expiring soon, refreshing');
65
- }
66
-
67
- this.tokenRenewPromise = this.renewToken();
68
-
69
- try {
70
- const token = await this.tokenRenewPromise;
71
- return token;
72
- } catch (error) {
73
- this.logDebug('Error during token refresh', error);
74
- throw error;
75
- } finally {
76
- this.tokenRenewPromise = null;
77
- }
78
- }
79
-
80
- /**
81
- * Refreshes the access token using password grant or refresh token grant
82
- * @returns {Promise<string>} Access token
83
- */
84
- async renewToken() {
85
- try {
86
- return await this.requestToken(
87
- this.refreshToken ? GRANT_TYPE_REFRESH_TOKEN : GRANT_TYPE_PASSWORD,
88
- );
89
- } catch (error) {
90
- // If refresh token grant failed, try password grant as fallback
91
- if (this.refreshToken) {
92
- this.logDebug('Refresh token failed, falling back to password grant');
93
- console.warn(
94
- '[OAuth] Refresh token expired or invalid, re-authenticating with password grant',
95
- );
96
- this.refreshToken = null; // Clear invalid refresh token
97
-
98
- try {
99
- return await this.requestToken(GRANT_TYPE_PASSWORD);
100
- } catch (fallbackError) {
101
- const errorMessage = fallbackError.response
102
- ? `OAuth password grant fallback failed: ${
103
- fallbackError.response.status
104
- } - ${JSON.stringify(fallbackError.response.data)}`
105
- : `OAuth password grant fallback failed: ${fallbackError.message}`;
106
-
107
- console.error(`[OAuth] ${errorMessage}`);
108
- throw new Error(errorMessage);
109
- }
110
- }
111
-
112
- // No fallback available, rethrow original error
113
- const errorMessage = error.response
114
- ? `OAuth token request failed: ${error.response.status} - ${JSON.stringify(
115
- error.response.data,
116
- )}`
117
- : `OAuth token request failed: ${error.message}`;
118
-
119
- console.error(`[OAuth] ${errorMessage}`);
120
- throw new Error(errorMessage);
121
- }
122
- }
123
-
124
- /**
125
- * Requests a token using the specified grant type
126
- * @param {string} grantType - Either 'password' or 'refresh_token'
127
- * @returns {Promise<string>} Access token
128
- * @private
129
- */
130
- async requestToken(grantType) {
131
- const params = new URLSearchParams();
132
- params.append('client_id', this.clientId);
133
- params.append('grant_type', grantType);
134
-
135
- if (grantType === GRANT_TYPE_REFRESH_TOKEN) {
136
- this.logDebug('Requesting new access token using refresh_token');
137
- params.append('refresh_token', this.refreshToken);
138
- } else {
139
- this.logDebug('Requesting access token using username and password');
140
- params.append('username', this.username);
141
- params.append('password', this.password);
142
- }
143
-
144
- if (this.clientSecret) {
145
- params.append('client_secret', this.clientSecret);
146
- }
147
- if (this.scope) {
148
- params.append('scope', this.scope);
149
- }
150
-
151
- // Get proxy agent for token endpoint
152
- // Only apply if custom agents are not explicitly provided
153
- const hasCustomAgents = this.restClientConfig.httpsAgent || this.restClientConfig.httpAgent;
154
- const proxyAgents = hasCustomAgents
155
- ? {}
156
- : getProxyAgentForUrl(this.tokenEndpoint, this.restClientConfig);
157
- const usingProxyAgent = Object.keys(proxyAgents).length > 0;
158
-
159
- if (this.debug && usingProxyAgent) {
160
- this.logDebug(`Making token request to ${this.tokenEndpoint} with proxy agent`);
161
- }
162
-
163
- const response = await axios.post(this.tokenEndpoint, params, {
164
- headers: {
165
- 'Content-Type': 'application/x-www-form-urlencoded',
166
- },
167
- ...proxyAgents,
168
- // Custom agents from restClientConfig (if provided) take precedence
169
- ...(this.restClientConfig.httpsAgent && { httpsAgent: this.restClientConfig.httpsAgent }),
170
- ...(this.restClientConfig.httpAgent && { httpAgent: this.restClientConfig.httpAgent }),
171
- // Explicitly disable axios built-in proxy when using custom agents
172
- ...(usingProxyAgent && { proxy: false }),
173
- });
174
-
175
- const {
176
- access_token: accessToken,
177
- refresh_token: refreshToken,
178
- expires_in: expiresIn,
179
- } = response.data;
180
-
181
- if (!accessToken) {
182
- throw new Error('No access token received from OAuth server');
183
- }
184
-
185
- this.accessToken = accessToken;
186
-
187
- if (refreshToken) {
188
- this.refreshToken = refreshToken;
189
- this.logDebug('Refresh token stored for future use');
190
- }
191
-
192
- if (expiresIn) {
193
- this.tokenExpiresAt = Date.now() + expiresIn * SECOND_IN_MS;
194
- this.logDebug(`Token obtained, expires in ${expiresIn} seconds`);
195
- } else {
196
- this.tokenExpiresAt = Date.now() + DEFAULT_TOKEN_EXPIRATION_MS;
197
- this.logDebug('Token obtained, no expiration provided, assuming 1 hour');
198
- }
199
-
200
- return this.accessToken;
201
- }
202
-
203
- /**
204
- * Attaches the interceptor to an axios instance
205
- * @param {Object} axiosInstance - Axios instance to attach interceptor to
206
- */
207
- attach(axiosInstance) {
208
- axiosInstance.interceptors.request.use(
209
- async (config) => {
210
- try {
211
- const token = await this.getAccessToken();
212
- // eslint-disable-next-line no-param-reassign
213
- config.headers.Authorization = `Bearer ${token}`;
214
- this.logDebug(`Request to ${config.url} with OAuth token`);
215
- return config;
216
- } catch (error) {
217
- console.error('[OAuth] Failed to obtain access token, request may fail:', error.message);
218
- return config;
219
- }
220
- },
221
- (error) => Promise.reject(error),
222
- );
223
- }
224
- }
225
-
226
- module.exports = OAuthInterceptor;
@@ -1,232 +0,0 @@
1
- const { getProxyForUrl } = require('proxy-from-env');
2
- const { HttpsProxyAgent } = require('https-proxy-agent');
3
- const { HttpProxyAgent } = require('http-proxy-agent');
4
- const http = require('http');
5
- const https = require('https');
6
-
7
- /**
8
- * Sanitizes a URL by removing credentials (username/password) for safe logging
9
- * @param {string} urlString - The URL to sanitize
10
- * @returns {string} - Sanitized URL with credentials replaced by [REDACTED]
11
- */
12
- function sanitizeUrlForLogging(urlString) {
13
- try {
14
- const urlObj = new URL(urlString);
15
- if (urlObj.username || urlObj.password) {
16
- // Replace credentials with [REDACTED]
17
- urlObj.username = '[REDACTED]';
18
- urlObj.password = '';
19
- return urlObj.toString();
20
- }
21
- return urlString;
22
- } catch (error) {
23
- // If URL parsing fails, return as-is (likely not a URL)
24
- return urlString;
25
- }
26
- }
27
-
28
- /**
29
- * Checks if a URL should bypass proxy based on NO_PROXY patterns
30
- * @param {string} url - The URL to check
31
- * @param {string} noProxy - Comma-separated list of domains/patterns to bypass
32
- * @returns {boolean} - True if proxy should be bypassed
33
- */
34
- function shouldBypassProxy(url, noProxy) {
35
- if (!noProxy) return false;
36
-
37
- try {
38
- const urlObj = new URL(url);
39
- const hostname = urlObj.hostname.toLowerCase();
40
-
41
- // Split NO_PROXY entries and clean them
42
- const patterns = noProxy
43
- .split(',')
44
- .map((entry) => entry.trim().toLowerCase())
45
- .filter(Boolean);
46
-
47
- return patterns.some((pattern) => {
48
- // Special case: * means bypass all
49
- if (pattern === '*') return true;
50
-
51
- // Pattern with leading dot (.example.com) - only matches subdomains
52
- if (pattern.startsWith('.')) {
53
- const cleanPattern = pattern.slice(1);
54
- // Should match sub.example.com but NOT example.com
55
- return hostname.endsWith(`.${cleanPattern}`);
56
- }
57
-
58
- // Pattern without leading dot (example.com) - matches domain and subdomains
59
- // Exact match
60
- if (hostname === pattern) return true;
61
-
62
- // Suffix match (example.com matches sub.example.com)
63
- if (hostname.endsWith(`.${pattern}`)) return true;
64
-
65
- return false;
66
- });
67
- } catch (error) {
68
- // If URL parsing fails, don't bypass proxy
69
- return false;
70
- }
71
- }
72
-
73
- /**
74
- * Gets proxy configuration for a given URL
75
- * Checks both environment variables and explicit config
76
- * @param {string} url - The target URL
77
- * @param {object} proxyConfig - Explicit proxy configuration from restClientConfig
78
- * @returns {object|null} - Proxy URL and bypass info, or null if no proxy
79
- */
80
- function getProxyConfig(url, proxyConfig = {}) {
81
- const urlObj = new URL(url);
82
-
83
- // Check NO_PROXY from config or environment
84
- const noProxyFromConfig = proxyConfig.noProxy;
85
- const noProxyFromEnv = process.env.NO_PROXY || process.env.no_proxy || '';
86
- const noProxy = noProxyFromConfig || noProxyFromEnv;
87
-
88
- if (proxyConfig.debug) {
89
- console.log('[ProxyHelper] getProxyConfig called:');
90
- console.log(' URL:', url);
91
- console.log(' Hostname:', urlObj.hostname);
92
- console.log(' noProxy from config:', noProxyFromConfig);
93
- console.log(' noProxy from env:', noProxyFromEnv);
94
- console.log(' Final noProxy:', noProxy);
95
- }
96
-
97
- // Check if URL should bypass proxy
98
- const shouldBypass = shouldBypassProxy(url, noProxy);
99
- if (proxyConfig.debug) {
100
- console.log(' Should bypass proxy:', shouldBypass);
101
- }
102
-
103
- if (shouldBypass) {
104
- return null;
105
- }
106
-
107
- // If proxy is explicitly disabled
108
- if (proxyConfig.proxy === false) {
109
- return null;
110
- }
111
-
112
- // Priority 1: Explicit proxy configuration object
113
- if (proxyConfig.proxy && typeof proxyConfig.proxy === 'object') {
114
- const { protocol: proxyProtocol, host, port, auth } = proxyConfig.proxy;
115
- if (host && port) {
116
- let proxyUrl = `${proxyProtocol || 'http'}://${host}:${port}`;
117
- if (auth) {
118
- const { username, password } = auth;
119
- proxyUrl = `${proxyProtocol || 'http'}://${username}:${password}@${host}:${port}`;
120
- }
121
- return { proxyUrl };
122
- }
123
- }
124
-
125
- // Priority 2: Explicit proxy URL string
126
- if (typeof proxyConfig.proxy === 'string') {
127
- return { proxyUrl: proxyConfig.proxy };
128
- }
129
-
130
- // Priority 3: Environment variables (with NO_PROXY support via proxy-from-env)
131
- const proxyUrlFromEnv = getProxyForUrl(url);
132
- if (proxyUrlFromEnv) {
133
- return { proxyUrl: proxyUrlFromEnv };
134
- }
135
-
136
- return null;
137
- }
138
-
139
- // Cache for proxy agents to enable connection reuse
140
- const agentCache = new Map();
141
-
142
- /**
143
- * Creates a cache key for proxy agents based on proxy URL and protocol
144
- * @param {string} proxyUrl - The proxy URL
145
- * @param {boolean} isHttps - Whether target is HTTPS
146
- * @returns {string} - Cache key
147
- */
148
- function getAgentCacheKey(proxyUrl, isHttps) {
149
- return `${isHttps ? 'https' : 'http'}:${proxyUrl}`;
150
- }
151
-
152
- /**
153
- * Creates an HTTP/HTTPS agent with proxy configuration for a specific URL
154
- * Agents are cached and reused to enable connection pooling and keepAlive
155
- * @param {string} url - The target URL for the request
156
- * @param {object} restClientConfig - The rest client configuration
157
- * @returns {object} - Object with httpAgent and/or httpsAgent
158
- */
159
- function createProxyAgents(url, restClientConfig = {}) {
160
- const urlObj = new URL(url);
161
- const isHttps = urlObj.protocol === 'https:';
162
- const proxyConfig = getProxyConfig(url, restClientConfig);
163
-
164
- // Agent options for connection reuse and keepAlive
165
- const agentOptions = {
166
- keepAlive: true,
167
- keepAliveMsecs: 3000,
168
- maxSockets: 50,
169
- maxFreeSockets: 10,
170
- };
171
-
172
- if (!proxyConfig) {
173
- if (restClientConfig.debug) {
174
- console.log('[ProxyHelper] No proxy for URL (bypassed or not configured):', url);
175
- console.log(' Using default agent to prevent axios from using env proxy');
176
- }
177
-
178
- const cacheKey = getAgentCacheKey('no-proxy', isHttps);
179
- if (agentCache.has(cacheKey)) {
180
- return agentCache.get(cacheKey);
181
- }
182
-
183
- // Return a default agent to prevent axios from using HTTP_PROXY/HTTPS_PROXY env vars
184
- // This ensures that URLs in noProxy truly bypass the proxy
185
- const agents = isHttps
186
- ? { httpsAgent: new https.Agent(agentOptions) }
187
- : { httpAgent: new http.Agent(agentOptions) };
188
- agentCache.set(cacheKey, agents);
189
- return agents;
190
- }
191
-
192
- const { proxyUrl } = proxyConfig;
193
-
194
- const cacheKey = getAgentCacheKey(proxyUrl, isHttps);
195
- if (agentCache.has(cacheKey)) {
196
- if (restClientConfig.debug) {
197
- console.log('[ProxyHelper] Reusing cached proxy agent:', sanitizeUrlForLogging(proxyUrl));
198
- }
199
- return agentCache.get(cacheKey);
200
- }
201
-
202
- if (restClientConfig.debug) {
203
- console.log('[ProxyHelper] Creating proxy agent:');
204
- console.log(' URL:', url);
205
- console.log(' Proxy URL:', sanitizeUrlForLogging(proxyUrl));
206
- }
207
-
208
- const agents = isHttps
209
- ? { httpsAgent: new HttpsProxyAgent(proxyUrl, agentOptions) }
210
- : { httpAgent: new HttpProxyAgent(proxyUrl, agentOptions) };
211
-
212
- agentCache.set(cacheKey, agents);
213
- return agents;
214
- }
215
-
216
- /**
217
- * Gets proxy agent for a specific request URL
218
- * This is the main function to be used in axios requests
219
- * @param {string} url - The target URL for the request
220
- * @param {object} restClientConfig - The rest client configuration
221
- * @returns {object} - Object with agent configuration for axios
222
- */
223
- function getProxyAgentForUrl(url, restClientConfig = {}) {
224
- return createProxyAgents(url, restClientConfig);
225
- }
226
-
227
- module.exports = {
228
- shouldBypassProxy,
229
- getProxyConfig,
230
- createProxyAgents,
231
- getProxyAgentForUrl,
232
- };
@@ -1,92 +0,0 @@
1
- const { EVENTS } = require('./constants/events');
2
-
3
- /**
4
- * Public API to emit additional events to RP JS agents.
5
- */
6
- class PublicReportingAPI {
7
- /**
8
- * Emit set description event.
9
- * @param {String} text - description of current test/suite.
10
- * @param {String} suite - suite description, optional.
11
- */
12
- static setDescription(text, suite) {
13
- process.emit(EVENTS.SET_DESCRIPTION, { text, suite });
14
- }
15
-
16
- /**
17
- * Emit add attributes event.
18
- * @param {Array} attributes - array of attributes, should looks like this:
19
- * [{
20
- * key: "attrKey",
21
- * value: "attrValue",
22
- * }]
23
- *
24
- * @param {String} suite - suite description, optional.
25
- */
26
- static addAttributes(attributes, suite) {
27
- process.emit(EVENTS.ADD_ATTRIBUTES, { attributes, suite });
28
- }
29
-
30
- /**
31
- * Emit send log to test item event.
32
- * @param {Object} log - log object should looks like this:
33
- * {
34
- * level: "INFO",
35
- * message: "log message",
36
- * file: {
37
- * name: "filename",
38
- * type: "image/png", // media type
39
- * content: data, // file content represented as 64base string
40
- * },
41
- * }
42
- * @param {String} suite - suite description, optional.
43
- */
44
- static addLog(log, suite) {
45
- process.emit(EVENTS.ADD_LOG, { log, suite });
46
- }
47
-
48
- /**
49
- * Emit send log to current launch event.
50
- * @param {Object} log - log object should looks like this:
51
- * {
52
- * level: "INFO",
53
- * message: "log message",
54
- * file: {
55
- * name: "filename",
56
- * type: "image/png", // media type
57
- * content: data, // file content represented as 64base string
58
- * },
59
- * }
60
- */
61
- static addLaunchLog(log) {
62
- process.emit(EVENTS.ADD_LAUNCH_LOG, log);
63
- }
64
-
65
- /**
66
- * Emit set testCaseId event.
67
- * @param {String} testCaseId - testCaseId of current test/suite.
68
- * @param {String} suite - suite description, optional.
69
- */
70
- static setTestCaseId(testCaseId, suite) {
71
- process.emit(EVENTS.SET_TEST_CASE_ID, { testCaseId, suite });
72
- }
73
-
74
- /**
75
- * Emit set status to current launch event.
76
- * @param {String} status - status of current launch.
77
- */
78
- static setLaunchStatus(status) {
79
- process.emit(EVENTS.SET_LAUNCH_STATUS, status);
80
- }
81
-
82
- /**
83
- * Emit set status event.
84
- * @param {String} status - status of current test/suite.
85
- * @param {String} suite - suite description, optional.
86
- */
87
- static setStatus(status, suite) {
88
- process.emit(EVENTS.SET_STATUS, { status, suite });
89
- }
90
- }
91
-
92
- module.exports = PublicReportingAPI;