@uipath/uipath-typescript 1.3.1 → 1.3.3
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.
- package/dist/assets/index.cjs +14 -8
- package/dist/assets/index.mjs +14 -8
- package/dist/attachments/index.cjs +14 -8
- package/dist/attachments/index.mjs +14 -8
- package/dist/buckets/index.cjs +14 -8
- package/dist/buckets/index.mjs +14 -8
- package/dist/cases/index.cjs +34 -13
- package/dist/cases/index.d.ts +15 -0
- package/dist/cases/index.mjs +34 -13
- package/dist/conversational-agent/index.cjs +32 -8
- package/dist/conversational-agent/index.d.ts +26 -0
- package/dist/conversational-agent/index.mjs +32 -8
- package/dist/core/index.cjs +21 -4
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.mjs +21 -4
- package/dist/entities/index.cjs +14 -8
- package/dist/entities/index.mjs +14 -8
- package/dist/feedback/index.cjs +1904 -0
- package/dist/feedback/index.d.ts +475 -0
- package/dist/feedback/index.mjs +1902 -0
- package/dist/index.cjs +369 -192
- package/dist/index.d.ts +277 -12
- package/dist/index.mjs +370 -193
- package/dist/index.umd.js +369 -192
- package/dist/jobs/index.cjs +331 -8
- package/dist/jobs/index.d.ts +168 -2
- package/dist/jobs/index.mjs +332 -9
- package/dist/maestro-processes/index.cjs +14 -8
- package/dist/maestro-processes/index.mjs +14 -8
- package/dist/processes/index.cjs +14 -8
- package/dist/processes/index.mjs +14 -8
- package/dist/queues/index.cjs +14 -8
- package/dist/queues/index.mjs +14 -8
- package/dist/tasks/index.cjs +34 -13
- package/dist/tasks/index.d.ts +25 -10
- package/dist/tasks/index.mjs +35 -14
- package/package.json +12 -1
|
@@ -0,0 +1,1904 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var sdkLogs = require('@opentelemetry/sdk-logs');
|
|
4
|
+
|
|
5
|
+
/******************************************************************************
|
|
6
|
+
Copyright (c) Microsoft Corporation.
|
|
7
|
+
|
|
8
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
9
|
+
purpose with or without fee is hereby granted.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
12
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
13
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
14
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
15
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
16
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
17
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
18
|
+
***************************************************************************** */
|
|
19
|
+
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
function __decorate(decorators, target, key, desc) {
|
|
23
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
24
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
25
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
26
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function __classPrivateFieldGet(receiver, state, kind, f) {
|
|
30
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
31
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
32
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function __classPrivateFieldSet(receiver, state, value, kind, f) {
|
|
36
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
37
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
38
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
39
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
43
|
+
var e = new Error(message);
|
|
44
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Type guards for error response types
|
|
49
|
+
*/
|
|
50
|
+
function isOrchestratorError(error) {
|
|
51
|
+
return typeof error === 'object' &&
|
|
52
|
+
error !== null &&
|
|
53
|
+
'message' in error &&
|
|
54
|
+
'errorCode' in error &&
|
|
55
|
+
typeof error.message === 'string' &&
|
|
56
|
+
typeof error.errorCode === 'number';
|
|
57
|
+
}
|
|
58
|
+
function isEntityError(error) {
|
|
59
|
+
return typeof error === 'object' &&
|
|
60
|
+
error !== null &&
|
|
61
|
+
'error' in error &&
|
|
62
|
+
typeof error.error === 'string';
|
|
63
|
+
}
|
|
64
|
+
function isPimsError(error) {
|
|
65
|
+
return typeof error === 'object' &&
|
|
66
|
+
error !== null &&
|
|
67
|
+
'type' in error &&
|
|
68
|
+
'title' in error &&
|
|
69
|
+
'status' in error &&
|
|
70
|
+
typeof error.type === 'string' &&
|
|
71
|
+
typeof error.title === 'string' &&
|
|
72
|
+
typeof error.status === 'number';
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* HTTP status code constants for error handling
|
|
77
|
+
*/
|
|
78
|
+
const HttpStatus = {
|
|
79
|
+
// Client errors (4xx)
|
|
80
|
+
BAD_REQUEST: 400,
|
|
81
|
+
UNAUTHORIZED: 401,
|
|
82
|
+
FORBIDDEN: 403,
|
|
83
|
+
NOT_FOUND: 404,
|
|
84
|
+
TOO_MANY_REQUESTS: 429,
|
|
85
|
+
// Server errors (5xx)
|
|
86
|
+
INTERNAL_SERVER_ERROR: 500,
|
|
87
|
+
BAD_GATEWAY: 502,
|
|
88
|
+
SERVICE_UNAVAILABLE: 503,
|
|
89
|
+
GATEWAY_TIMEOUT: 504
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Error type constants for consistent error identification
|
|
93
|
+
*/
|
|
94
|
+
const ErrorType = {
|
|
95
|
+
AUTHENTICATION: 'AuthenticationError',
|
|
96
|
+
AUTHORIZATION: 'AuthorizationError',
|
|
97
|
+
VALIDATION: 'ValidationError',
|
|
98
|
+
NOT_FOUND: 'NotFoundError',
|
|
99
|
+
RATE_LIMIT: 'RateLimitError',
|
|
100
|
+
SERVER: 'ServerError',
|
|
101
|
+
NETWORK: 'NetworkError'
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* HTTP header constants for error handling
|
|
105
|
+
*/
|
|
106
|
+
const HttpHeaders = {
|
|
107
|
+
X_REQUEST_ID: 'x-request-id'
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Standard error message constants
|
|
111
|
+
*/
|
|
112
|
+
const ErrorMessages = {
|
|
113
|
+
// Authentication errors
|
|
114
|
+
AUTHENTICATION_FAILED: 'Authentication failed',
|
|
115
|
+
// Authorization errors
|
|
116
|
+
ACCESS_DENIED: 'Access denied',
|
|
117
|
+
// Validation errors
|
|
118
|
+
VALIDATION_FAILED: 'Validation failed',
|
|
119
|
+
// Not found errors
|
|
120
|
+
RESOURCE_NOT_FOUND: 'Resource not found',
|
|
121
|
+
// Rate limit errors
|
|
122
|
+
RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
|
|
123
|
+
// Server errors
|
|
124
|
+
INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
|
|
125
|
+
// Network errors
|
|
126
|
+
NETWORK_ERROR: 'Network error occurred',
|
|
127
|
+
REQUEST_TIMEOUT: 'Request timed out',
|
|
128
|
+
REQUEST_ABORTED: 'Request was aborted',
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Error name constants for network error identification
|
|
132
|
+
*/
|
|
133
|
+
const ErrorNames = {
|
|
134
|
+
ABORT_ERROR: 'AbortError'};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Parser for Orchestrator/Task error format
|
|
138
|
+
*/
|
|
139
|
+
class OrchestratorErrorParser {
|
|
140
|
+
canParse(errorBody) {
|
|
141
|
+
return isOrchestratorError(errorBody);
|
|
142
|
+
}
|
|
143
|
+
parse(errorBody, response) {
|
|
144
|
+
const error = errorBody;
|
|
145
|
+
return {
|
|
146
|
+
message: error.message,
|
|
147
|
+
code: response?.status?.toString(),
|
|
148
|
+
details: {
|
|
149
|
+
errorCode: error.errorCode,
|
|
150
|
+
traceId: error.traceId,
|
|
151
|
+
originalResponse: error
|
|
152
|
+
},
|
|
153
|
+
requestId: error.traceId
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Parser for Entity (Data Fabric) error format
|
|
159
|
+
*/
|
|
160
|
+
class EntityErrorParser {
|
|
161
|
+
canParse(errorBody) {
|
|
162
|
+
return isEntityError(errorBody);
|
|
163
|
+
}
|
|
164
|
+
parse(errorBody, response) {
|
|
165
|
+
const error = errorBody;
|
|
166
|
+
return {
|
|
167
|
+
message: error.error,
|
|
168
|
+
code: response?.status?.toString(),
|
|
169
|
+
details: {
|
|
170
|
+
error: error.error,
|
|
171
|
+
traceId: error.traceId,
|
|
172
|
+
originalResponse: error
|
|
173
|
+
},
|
|
174
|
+
requestId: error.traceId
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Parser for PIMS error format
|
|
180
|
+
*/
|
|
181
|
+
class PimsErrorParser {
|
|
182
|
+
canParse(errorBody) {
|
|
183
|
+
return isPimsError(errorBody);
|
|
184
|
+
}
|
|
185
|
+
parse(errorBody, response) {
|
|
186
|
+
const error = errorBody;
|
|
187
|
+
let message = error.title;
|
|
188
|
+
// If there are validation errors, append them to the message for better visibility
|
|
189
|
+
if (error.errors && Object.keys(error.errors).length > 0) {
|
|
190
|
+
const errorMessages = Object.entries(error.errors)
|
|
191
|
+
.map(([field, messages]) => `${field}: ${messages.join(', ')}`)
|
|
192
|
+
.join('; ');
|
|
193
|
+
message += `. Validation errors: ${errorMessages}`;
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
message,
|
|
197
|
+
code: response?.status?.toString(),
|
|
198
|
+
details: {
|
|
199
|
+
type: error.type,
|
|
200
|
+
title: error.title,
|
|
201
|
+
status: error.status,
|
|
202
|
+
errors: error.errors,
|
|
203
|
+
traceId: error.traceId,
|
|
204
|
+
originalResponse: error
|
|
205
|
+
},
|
|
206
|
+
requestId: error.traceId
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Fallback parser for unrecognized formats
|
|
212
|
+
*/
|
|
213
|
+
class GenericErrorParser {
|
|
214
|
+
canParse(_errorBody) {
|
|
215
|
+
return true; // Always can parse as last resort
|
|
216
|
+
}
|
|
217
|
+
parse(errorBody, response) {
|
|
218
|
+
// For unknown error formats, just pass through the raw error with fallback message
|
|
219
|
+
const message = response?.statusText || 'An error occurred';
|
|
220
|
+
return {
|
|
221
|
+
message,
|
|
222
|
+
code: response?.status?.toString(),
|
|
223
|
+
details: {
|
|
224
|
+
originalResponse: errorBody
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Main error response parser using Chain of Responsibility pattern
|
|
231
|
+
*
|
|
232
|
+
* This parser standardizes error responses from different UiPath services into a
|
|
233
|
+
* consistent format, regardless of the original error structure.
|
|
234
|
+
*
|
|
235
|
+
* Supported formats:
|
|
236
|
+
* 1. Orchestrator/Task: { message, errorCode, traceId }
|
|
237
|
+
* 2. Entity (Data Fabric): { error, traceId }
|
|
238
|
+
* 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
|
|
239
|
+
* 4. Generic: Fallback for any other format
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* const parser = new ErrorResponseParser();
|
|
243
|
+
* const errorInfo = await parser.parse(response);
|
|
244
|
+
* // errorInfo will have consistent structure regardless of service
|
|
245
|
+
*/
|
|
246
|
+
class ErrorResponseParser {
|
|
247
|
+
constructor() {
|
|
248
|
+
this.strategies = [
|
|
249
|
+
new OrchestratorErrorParser(),
|
|
250
|
+
new EntityErrorParser(),
|
|
251
|
+
new PimsErrorParser(),
|
|
252
|
+
new GenericErrorParser() // Must be last
|
|
253
|
+
];
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Parses error response body into standardized format
|
|
257
|
+
* @param response - The HTTP response object
|
|
258
|
+
* @returns Standardized error information
|
|
259
|
+
*/
|
|
260
|
+
async parse(response) {
|
|
261
|
+
try {
|
|
262
|
+
const errorBody = await response.json();
|
|
263
|
+
// Find the first strategy that can parse this error format
|
|
264
|
+
const strategy = this.strategies.find(s => s.canParse(errorBody));
|
|
265
|
+
// GenericErrorParser always returns true, so this will never be null
|
|
266
|
+
return strategy.parse(errorBody, response);
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// Handle non-JSON responses
|
|
270
|
+
const responseText = await response.text().catch(() => '');
|
|
271
|
+
return {
|
|
272
|
+
message: response.statusText,
|
|
273
|
+
code: response.status.toString(),
|
|
274
|
+
details: {
|
|
275
|
+
parseError: 'Failed to parse error response as JSON',
|
|
276
|
+
responseText
|
|
277
|
+
},
|
|
278
|
+
requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
// Export singleton instance
|
|
284
|
+
const errorResponseParser = new ErrorResponseParser();
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Base error class for all UiPath SDK errors
|
|
288
|
+
* Extends Error for standard error handling compatibility
|
|
289
|
+
*/
|
|
290
|
+
class UiPathError extends Error {
|
|
291
|
+
constructor(type, params) {
|
|
292
|
+
super(params.message);
|
|
293
|
+
this.name = type;
|
|
294
|
+
this.type = type;
|
|
295
|
+
this.statusCode = params.statusCode;
|
|
296
|
+
this.requestId = params.requestId;
|
|
297
|
+
this.timestamp = new Date();
|
|
298
|
+
// Maintains proper stack trace for where our error was thrown
|
|
299
|
+
if (Error.captureStackTrace) {
|
|
300
|
+
Error.captureStackTrace(this, this.constructor);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Returns a clean JSON representation of the error
|
|
305
|
+
*/
|
|
306
|
+
toJSON() {
|
|
307
|
+
return {
|
|
308
|
+
type: this.type,
|
|
309
|
+
message: this.message,
|
|
310
|
+
statusCode: this.statusCode,
|
|
311
|
+
requestId: this.requestId,
|
|
312
|
+
timestamp: this.timestamp
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Returns detailed debug information including stack trace
|
|
317
|
+
*/
|
|
318
|
+
getDebugInfo() {
|
|
319
|
+
return {
|
|
320
|
+
...this.toJSON(),
|
|
321
|
+
stack: this.stack
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Error thrown when authentication fails (401 errors)
|
|
328
|
+
* Common scenarios:
|
|
329
|
+
* - Invalid credentials
|
|
330
|
+
* - Expired token
|
|
331
|
+
* - Missing authentication
|
|
332
|
+
*/
|
|
333
|
+
class AuthenticationError extends UiPathError {
|
|
334
|
+
constructor(params = {}) {
|
|
335
|
+
super(ErrorType.AUTHENTICATION, {
|
|
336
|
+
message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
|
|
337
|
+
statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
|
|
338
|
+
requestId: params.requestId
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Error thrown when authorization fails (403 errors)
|
|
345
|
+
* Common scenarios:
|
|
346
|
+
* - Insufficient permissions
|
|
347
|
+
* - Access denied to resource
|
|
348
|
+
* - Invalid scope
|
|
349
|
+
*/
|
|
350
|
+
class AuthorizationError extends UiPathError {
|
|
351
|
+
constructor(params = {}) {
|
|
352
|
+
super(ErrorType.AUTHORIZATION, {
|
|
353
|
+
message: params.message || ErrorMessages.ACCESS_DENIED,
|
|
354
|
+
statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
|
|
355
|
+
requestId: params.requestId
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Error thrown when validation fails (400 errors or client-side validation)
|
|
362
|
+
* Common scenarios:
|
|
363
|
+
* - Invalid input parameters
|
|
364
|
+
* - Missing required fields
|
|
365
|
+
* - Invalid data format
|
|
366
|
+
*/
|
|
367
|
+
class ValidationError extends UiPathError {
|
|
368
|
+
constructor(params = {}) {
|
|
369
|
+
super(ErrorType.VALIDATION, {
|
|
370
|
+
message: params.message || ErrorMessages.VALIDATION_FAILED,
|
|
371
|
+
statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
|
|
372
|
+
requestId: params.requestId
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Error thrown when a resource is not found (404 errors)
|
|
379
|
+
* Common scenarios:
|
|
380
|
+
* - Resource doesn't exist
|
|
381
|
+
* - Invalid ID provided
|
|
382
|
+
* - Resource deleted
|
|
383
|
+
*/
|
|
384
|
+
class NotFoundError extends UiPathError {
|
|
385
|
+
constructor(params = {}) {
|
|
386
|
+
super(ErrorType.NOT_FOUND, {
|
|
387
|
+
message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
|
|
388
|
+
statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
|
|
389
|
+
requestId: params.requestId
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Error thrown when rate limit is exceeded (429 errors)
|
|
396
|
+
* Common scenarios:
|
|
397
|
+
* - Too many requests in a time window
|
|
398
|
+
* - API throttling
|
|
399
|
+
*/
|
|
400
|
+
class RateLimitError extends UiPathError {
|
|
401
|
+
constructor(params = {}) {
|
|
402
|
+
super(ErrorType.RATE_LIMIT, {
|
|
403
|
+
message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
|
|
404
|
+
statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
|
|
405
|
+
requestId: params.requestId
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Error thrown when server encounters an error (5xx errors)
|
|
412
|
+
* Common scenarios:
|
|
413
|
+
* - Internal server error
|
|
414
|
+
* - Service unavailable
|
|
415
|
+
* - Gateway timeout
|
|
416
|
+
*/
|
|
417
|
+
class ServerError extends UiPathError {
|
|
418
|
+
constructor(params = {}) {
|
|
419
|
+
super(ErrorType.SERVER, {
|
|
420
|
+
message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
|
|
421
|
+
statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
|
|
422
|
+
requestId: params.requestId
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Checks if this is a temporary error that might succeed on retry
|
|
427
|
+
*/
|
|
428
|
+
get isRetryable() {
|
|
429
|
+
return this.statusCode === HttpStatus.BAD_GATEWAY ||
|
|
430
|
+
this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
|
|
431
|
+
this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Error thrown when network/connection issues occur
|
|
437
|
+
* Common scenarios:
|
|
438
|
+
* - Connection timeout
|
|
439
|
+
* - DNS resolution failure
|
|
440
|
+
* - Network unreachable
|
|
441
|
+
* - Request aborted
|
|
442
|
+
*/
|
|
443
|
+
class NetworkError extends UiPathError {
|
|
444
|
+
constructor(params = {}) {
|
|
445
|
+
super(ErrorType.NETWORK, {
|
|
446
|
+
message: params.message || ErrorMessages.NETWORK_ERROR,
|
|
447
|
+
statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
|
|
448
|
+
requestId: params.requestId
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Factory for creating typed errors based on HTTP status codes
|
|
455
|
+
* Follows the Factory pattern for clean error instantiation
|
|
456
|
+
*/
|
|
457
|
+
class ErrorFactory {
|
|
458
|
+
/**
|
|
459
|
+
* Creates appropriate error instance based on HTTP status code
|
|
460
|
+
*/
|
|
461
|
+
static createFromHttpStatus(statusCode, errorInfo) {
|
|
462
|
+
const { message, requestId } = errorInfo;
|
|
463
|
+
// Map status codes to error types
|
|
464
|
+
switch (statusCode) {
|
|
465
|
+
case HttpStatus.BAD_REQUEST:
|
|
466
|
+
return new ValidationError({ message, statusCode, requestId });
|
|
467
|
+
case HttpStatus.UNAUTHORIZED:
|
|
468
|
+
return new AuthenticationError({ message, statusCode, requestId });
|
|
469
|
+
case HttpStatus.FORBIDDEN:
|
|
470
|
+
return new AuthorizationError({ message, statusCode, requestId });
|
|
471
|
+
case HttpStatus.NOT_FOUND:
|
|
472
|
+
return new NotFoundError({ message, statusCode, requestId });
|
|
473
|
+
case HttpStatus.TOO_MANY_REQUESTS:
|
|
474
|
+
return new RateLimitError({ message, statusCode, requestId });
|
|
475
|
+
default:
|
|
476
|
+
// For 5xx errors or any other status code
|
|
477
|
+
if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
|
|
478
|
+
return new ServerError({ message, statusCode, requestId });
|
|
479
|
+
}
|
|
480
|
+
// For unknown client errors, treat as validation error
|
|
481
|
+
return new ValidationError({
|
|
482
|
+
message: `${message} (HTTP ${statusCode})`,
|
|
483
|
+
statusCode,
|
|
484
|
+
requestId
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Creates a NetworkError from a fetch/network error
|
|
490
|
+
*/
|
|
491
|
+
static createNetworkError(error) {
|
|
492
|
+
let message = ErrorMessages.NETWORK_ERROR;
|
|
493
|
+
if (error instanceof Error) {
|
|
494
|
+
if (error.name === ErrorNames.ABORT_ERROR) {
|
|
495
|
+
message = ErrorMessages.REQUEST_ABORTED;
|
|
496
|
+
}
|
|
497
|
+
else if (error.message.includes('timeout')) {
|
|
498
|
+
message = ErrorMessages.REQUEST_TIMEOUT;
|
|
499
|
+
}
|
|
500
|
+
else {
|
|
501
|
+
message = error.message;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return new NetworkError({ message });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
|
|
509
|
+
/**
|
|
510
|
+
* Content type constants for HTTP requests/responses
|
|
511
|
+
*/
|
|
512
|
+
const CONTENT_TYPES = {
|
|
513
|
+
JSON: 'application/json',
|
|
514
|
+
XML: 'application/xml',
|
|
515
|
+
OCTET_STREAM: 'application/octet-stream'
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* Response type constants for HTTP requests
|
|
519
|
+
*/
|
|
520
|
+
const RESPONSE_TYPES = {
|
|
521
|
+
JSON: 'json',
|
|
522
|
+
TEXT: 'text',
|
|
523
|
+
BLOB: 'blob',
|
|
524
|
+
ARRAYBUFFER: 'arraybuffer'
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
class ApiClient {
|
|
528
|
+
constructor(config, executionContext, tokenManager, clientConfig = {}) {
|
|
529
|
+
this.config = config;
|
|
530
|
+
this.executionContext = executionContext;
|
|
531
|
+
this.clientConfig = clientConfig;
|
|
532
|
+
this.tokenManager = tokenManager;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
536
|
+
* Used internally for API requests and exposed for services that need manual auth headers.
|
|
537
|
+
*
|
|
538
|
+
* @returns The valid token
|
|
539
|
+
* @throws AuthenticationError if no token available or refresh fails
|
|
540
|
+
*/
|
|
541
|
+
async getValidToken() {
|
|
542
|
+
return this.tokenManager.getValidToken();
|
|
543
|
+
}
|
|
544
|
+
async getDefaultHeaders() {
|
|
545
|
+
const token = await this.getValidToken();
|
|
546
|
+
return {
|
|
547
|
+
'Authorization': `Bearer ${token}`,
|
|
548
|
+
'Content-Type': CONTENT_TYPES.JSON,
|
|
549
|
+
...this.clientConfig.headers
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
async request(method, path, options = {}) {
|
|
553
|
+
// Ensure path starts with a forward slash
|
|
554
|
+
const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
|
|
555
|
+
// Construct URL with org and tenant names
|
|
556
|
+
const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
|
|
557
|
+
const isFormData = options.body instanceof FormData;
|
|
558
|
+
const defaultHeaders = await this.getDefaultHeaders();
|
|
559
|
+
if (isFormData) {
|
|
560
|
+
delete defaultHeaders['Content-Type'];
|
|
561
|
+
}
|
|
562
|
+
const headers = {
|
|
563
|
+
...defaultHeaders,
|
|
564
|
+
...options.headers
|
|
565
|
+
};
|
|
566
|
+
// Convert params to URLSearchParams
|
|
567
|
+
const searchParams = new URLSearchParams();
|
|
568
|
+
if (options.params) {
|
|
569
|
+
Object.entries(options.params).forEach(([key, value]) => {
|
|
570
|
+
searchParams.append(key, value.toString());
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
|
|
574
|
+
let body = undefined;
|
|
575
|
+
if (options.body) {
|
|
576
|
+
body = isFormData ? options.body : JSON.stringify(options.body);
|
|
577
|
+
}
|
|
578
|
+
try {
|
|
579
|
+
const response = await fetch(fullUrl, {
|
|
580
|
+
method,
|
|
581
|
+
headers,
|
|
582
|
+
body,
|
|
583
|
+
signal: options.signal
|
|
584
|
+
});
|
|
585
|
+
if (!response.ok) {
|
|
586
|
+
const errorInfo = await errorResponseParser.parse(response);
|
|
587
|
+
throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
|
|
588
|
+
}
|
|
589
|
+
if (response.status === 204) {
|
|
590
|
+
return undefined;
|
|
591
|
+
}
|
|
592
|
+
// Handle blob response type for binary data (e.g., file downloads)
|
|
593
|
+
if (options.responseType === RESPONSE_TYPES.BLOB) {
|
|
594
|
+
const blob = await response.blob();
|
|
595
|
+
return blob;
|
|
596
|
+
}
|
|
597
|
+
// Check if we're expecting XML
|
|
598
|
+
const acceptHeader = headers['Accept'] || headers['accept'];
|
|
599
|
+
if (acceptHeader === CONTENT_TYPES.XML) {
|
|
600
|
+
const text = await response.text();
|
|
601
|
+
return text;
|
|
602
|
+
}
|
|
603
|
+
const text = await response.text();
|
|
604
|
+
if (!text) {
|
|
605
|
+
return undefined;
|
|
606
|
+
}
|
|
607
|
+
return JSON.parse(text);
|
|
608
|
+
}
|
|
609
|
+
catch (error) {
|
|
610
|
+
// If it's already one of our errors, re-throw it
|
|
611
|
+
if (error.type && error.type.includes('Error')) {
|
|
612
|
+
throw error;
|
|
613
|
+
}
|
|
614
|
+
// Otherwise, it's likely a network error
|
|
615
|
+
throw ErrorFactory.createNetworkError(error);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
async get(path, options = {}) {
|
|
619
|
+
return this.request('GET', path, options);
|
|
620
|
+
}
|
|
621
|
+
async post(path, data, options = {}) {
|
|
622
|
+
return this.request('POST', path, { ...options, body: data });
|
|
623
|
+
}
|
|
624
|
+
async put(path, data, options = {}) {
|
|
625
|
+
return this.request('PUT', path, { ...options, body: data });
|
|
626
|
+
}
|
|
627
|
+
async patch(path, data, options = {}) {
|
|
628
|
+
return this.request('PATCH', path, { ...options, body: data });
|
|
629
|
+
}
|
|
630
|
+
async delete(path, options = {}) {
|
|
631
|
+
return this.request('DELETE', path, options);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* Pagination types supported by the SDK
|
|
637
|
+
*/
|
|
638
|
+
var PaginationType;
|
|
639
|
+
(function (PaginationType) {
|
|
640
|
+
PaginationType["OFFSET"] = "offset";
|
|
641
|
+
PaginationType["TOKEN"] = "token";
|
|
642
|
+
})(PaginationType || (PaginationType = {}));
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Collection of utility functions for working with objects
|
|
646
|
+
*/
|
|
647
|
+
/**
|
|
648
|
+
* Filters out undefined values from an object
|
|
649
|
+
* @param obj The source object
|
|
650
|
+
* @returns A new object without undefined values
|
|
651
|
+
*
|
|
652
|
+
* @example
|
|
653
|
+
* ```typescript
|
|
654
|
+
* // Object with undefined values
|
|
655
|
+
* const options = {
|
|
656
|
+
* name: 'test',
|
|
657
|
+
* count: 5,
|
|
658
|
+
* prefix: undefined,
|
|
659
|
+
* suffix: null
|
|
660
|
+
* };
|
|
661
|
+
* const result = filterUndefined(options);
|
|
662
|
+
* // result = { name: 'test', count: 5, suffix: null }
|
|
663
|
+
* ```
|
|
664
|
+
*/
|
|
665
|
+
function filterUndefined(obj) {
|
|
666
|
+
const result = {};
|
|
667
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
668
|
+
if (value !== undefined) {
|
|
669
|
+
result[key] = value;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
return result;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Utility functions for platform detection
|
|
677
|
+
*/
|
|
678
|
+
/**
|
|
679
|
+
* Checks if code is running in a browser environment
|
|
680
|
+
*/
|
|
681
|
+
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
682
|
+
isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Base64 encoding/decoding
|
|
686
|
+
*/
|
|
687
|
+
/**
|
|
688
|
+
* Encodes a string to base64
|
|
689
|
+
* @param str - The string to encode
|
|
690
|
+
* @returns Base64 encoded string
|
|
691
|
+
*/
|
|
692
|
+
function encodeBase64(str) {
|
|
693
|
+
// TextEncoder for UTF-8 encoding (works in both browser and Node.js)
|
|
694
|
+
const encoder = new TextEncoder();
|
|
695
|
+
const data = encoder.encode(str);
|
|
696
|
+
// Convert Uint8Array to base64
|
|
697
|
+
if (isBrowser) {
|
|
698
|
+
// Browser environment
|
|
699
|
+
// Convert Uint8Array to binary string then to base64
|
|
700
|
+
const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
|
|
701
|
+
return btoa(binaryString);
|
|
702
|
+
}
|
|
703
|
+
else {
|
|
704
|
+
// Node.js environment
|
|
705
|
+
return Buffer.from(data).toString('base64');
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Decodes a base64 string
|
|
710
|
+
* @param base64 - The base64 string to decode
|
|
711
|
+
* @returns Decoded string
|
|
712
|
+
*/
|
|
713
|
+
function decodeBase64(base64) {
|
|
714
|
+
let bytes;
|
|
715
|
+
if (isBrowser) {
|
|
716
|
+
// Browser environment
|
|
717
|
+
const binaryString = atob(base64);
|
|
718
|
+
bytes = new Uint8Array(binaryString.length);
|
|
719
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
720
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
// Node.js environment
|
|
725
|
+
bytes = new Uint8Array(Buffer.from(base64, 'base64'));
|
|
726
|
+
}
|
|
727
|
+
// TextDecoder for UTF-8 decoding (works in both browser and Node.js)
|
|
728
|
+
const decoder = new TextDecoder();
|
|
729
|
+
return decoder.decode(bytes);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* PaginationManager handles the conversion between uniform cursor-based pagination
|
|
734
|
+
* and the specific pagination type for each service
|
|
735
|
+
*/
|
|
736
|
+
class PaginationManager {
|
|
737
|
+
/**
|
|
738
|
+
* Create a pagination cursor for subsequent page requests
|
|
739
|
+
*/
|
|
740
|
+
static createCursor({ pageInfo, type }) {
|
|
741
|
+
if (!pageInfo.hasMore) {
|
|
742
|
+
return undefined;
|
|
743
|
+
}
|
|
744
|
+
const cursorData = {
|
|
745
|
+
type,
|
|
746
|
+
pageSize: pageInfo.pageSize,
|
|
747
|
+
};
|
|
748
|
+
switch (type) {
|
|
749
|
+
case PaginationType.OFFSET:
|
|
750
|
+
if (pageInfo.currentPage) {
|
|
751
|
+
cursorData.pageNumber = pageInfo.currentPage + 1;
|
|
752
|
+
}
|
|
753
|
+
break;
|
|
754
|
+
case PaginationType.TOKEN:
|
|
755
|
+
if (pageInfo.continuationToken) {
|
|
756
|
+
cursorData.continuationToken = pageInfo.continuationToken;
|
|
757
|
+
}
|
|
758
|
+
else {
|
|
759
|
+
return undefined; // No continuation token, can't continue
|
|
760
|
+
}
|
|
761
|
+
break;
|
|
762
|
+
}
|
|
763
|
+
return {
|
|
764
|
+
value: encodeBase64(JSON.stringify(cursorData))
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Create a paginated response with navigation cursors
|
|
769
|
+
*/
|
|
770
|
+
static createPaginatedResponse({ pageInfo, type }, items) {
|
|
771
|
+
const nextCursor = PaginationManager.createCursor({ pageInfo, type });
|
|
772
|
+
// Create previous page cursor if applicable
|
|
773
|
+
let previousCursor = undefined;
|
|
774
|
+
if (pageInfo.currentPage && pageInfo.currentPage > 1) {
|
|
775
|
+
const prevCursorData = {
|
|
776
|
+
type,
|
|
777
|
+
pageNumber: pageInfo.currentPage - 1,
|
|
778
|
+
pageSize: pageInfo.pageSize,
|
|
779
|
+
};
|
|
780
|
+
previousCursor = {
|
|
781
|
+
value: encodeBase64(JSON.stringify(prevCursorData))
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
// Calculate total pages if we have totalCount and pageSize
|
|
785
|
+
let totalPages = undefined;
|
|
786
|
+
if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
|
|
787
|
+
totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
|
|
788
|
+
}
|
|
789
|
+
// Determine if this pagination type supports page jumping
|
|
790
|
+
const supportsPageJump = type === PaginationType.OFFSET;
|
|
791
|
+
// Create the result object with all fields, then filter out undefined values
|
|
792
|
+
const result = filterUndefined({
|
|
793
|
+
items,
|
|
794
|
+
totalCount: pageInfo.totalCount,
|
|
795
|
+
hasNextPage: pageInfo.hasMore,
|
|
796
|
+
nextCursor: nextCursor,
|
|
797
|
+
previousCursor: previousCursor,
|
|
798
|
+
currentPage: pageInfo.currentPage,
|
|
799
|
+
totalPages,
|
|
800
|
+
supportsPageJump
|
|
801
|
+
});
|
|
802
|
+
return result;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Creates headers object from key-value pairs
|
|
808
|
+
* @param headersObj - Object containing header key-value pairs
|
|
809
|
+
* @returns Headers object with all values converted to strings
|
|
810
|
+
*
|
|
811
|
+
* @example
|
|
812
|
+
* ```typescript
|
|
813
|
+
* // Single header
|
|
814
|
+
* const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
|
|
815
|
+
*
|
|
816
|
+
* // Multiple headers
|
|
817
|
+
* const headers = createHeaders({
|
|
818
|
+
* 'X-UIPATH-FolderKey': '1234567890',
|
|
819
|
+
* 'X-UIPATH-OrganizationUnitId': 123,
|
|
820
|
+
* 'Accept': 'application/json'
|
|
821
|
+
* });
|
|
822
|
+
*
|
|
823
|
+
* // Using constants
|
|
824
|
+
* import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
|
|
825
|
+
* const headers = createHeaders({
|
|
826
|
+
* [FOLDER_KEY]: 'abc-123',
|
|
827
|
+
* [FOLDER_ID]: 456
|
|
828
|
+
* });
|
|
829
|
+
*
|
|
830
|
+
* // Empty headers
|
|
831
|
+
* const headers = createHeaders();
|
|
832
|
+
* ```
|
|
833
|
+
*/
|
|
834
|
+
function createHeaders(headersObj) {
|
|
835
|
+
const headers = {};
|
|
836
|
+
for (const [key, value] of Object.entries(headersObj)) {
|
|
837
|
+
if (value !== undefined && value !== null) {
|
|
838
|
+
headers[key] = value.toString();
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
return headers;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Common constants used across the SDK
|
|
846
|
+
*/
|
|
847
|
+
/**
|
|
848
|
+
* Prefix used for OData query parameters
|
|
849
|
+
*/
|
|
850
|
+
const ODATA_PREFIX = '$';
|
|
851
|
+
/**
|
|
852
|
+
* HTTP methods
|
|
853
|
+
*/
|
|
854
|
+
const HTTP_METHODS = {
|
|
855
|
+
GET: 'GET',
|
|
856
|
+
POST: 'POST'};
|
|
857
|
+
/**
|
|
858
|
+
* OData OFFSET pagination parameter names (ODATA-style)
|
|
859
|
+
*/
|
|
860
|
+
const ODATA_OFFSET_PARAMS = {
|
|
861
|
+
/** OData page size parameter name */
|
|
862
|
+
PAGE_SIZE_PARAM: '$top',
|
|
863
|
+
/** OData offset parameter name */
|
|
864
|
+
OFFSET_PARAM: '$skip',
|
|
865
|
+
/** OData count parameter name */
|
|
866
|
+
COUNT_PARAM: '$count'
|
|
867
|
+
};
|
|
868
|
+
/**
|
|
869
|
+
* Feedback OFFSET pagination parameter names (take/skip style)
|
|
870
|
+
*/
|
|
871
|
+
const FEEDBACK_OFFSET_PARAMS = {
|
|
872
|
+
/** Feedback page size parameter name */
|
|
873
|
+
PAGE_SIZE_PARAM: 'take',
|
|
874
|
+
/** Feedback offset parameter name */
|
|
875
|
+
OFFSET_PARAM: 'skip',
|
|
876
|
+
/** Feedback count parameter (not used) */
|
|
877
|
+
COUNT_PARAM: undefined
|
|
878
|
+
};
|
|
879
|
+
/**
|
|
880
|
+
* Bucket TOKEN pagination parameter names
|
|
881
|
+
*/
|
|
882
|
+
const BUCKET_TOKEN_PARAMS = {
|
|
883
|
+
/** Bucket page size parameter name */
|
|
884
|
+
PAGE_SIZE_PARAM: 'takeHint',
|
|
885
|
+
/** Bucket token parameter name */
|
|
886
|
+
TOKEN_PARAM: 'continuationToken'
|
|
887
|
+
};
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Transforms data by mapping fields according to the provided field mapping
|
|
891
|
+
* @param data The source data to transform
|
|
892
|
+
* @param fieldMapping Object mapping source field names to target field names
|
|
893
|
+
* @returns Transformed data with mapped field names
|
|
894
|
+
*
|
|
895
|
+
* @example
|
|
896
|
+
* ```typescript
|
|
897
|
+
* // Single object transformation
|
|
898
|
+
* const data = { id: '123', userName: 'john' };
|
|
899
|
+
* const mapping = { id: 'userId', userName: 'name' };
|
|
900
|
+
* const result = transformData(data, mapping);
|
|
901
|
+
* // result = { userId: '123', name: 'john' }
|
|
902
|
+
*
|
|
903
|
+
* // Array transformation
|
|
904
|
+
* const dataArray = [
|
|
905
|
+
* { id: '123', userName: 'john' },
|
|
906
|
+
* { id: '456', userName: 'jane' }
|
|
907
|
+
* ];
|
|
908
|
+
* const result = transformData(dataArray, mapping);
|
|
909
|
+
* // result = [
|
|
910
|
+
* // { userId: '123', name: 'john' },
|
|
911
|
+
* // { userId: '456', name: 'jane' }
|
|
912
|
+
* // ]
|
|
913
|
+
* ```
|
|
914
|
+
*/
|
|
915
|
+
function transformData(data, fieldMapping) {
|
|
916
|
+
// Handle array of objects
|
|
917
|
+
if (Array.isArray(data)) {
|
|
918
|
+
return data.map(item => transformData(item, fieldMapping));
|
|
919
|
+
}
|
|
920
|
+
// Handle single object
|
|
921
|
+
const result = { ...data };
|
|
922
|
+
for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
|
|
923
|
+
if (sourceField in result) {
|
|
924
|
+
const value = result[sourceField];
|
|
925
|
+
delete result[sourceField];
|
|
926
|
+
result[targetField] = value;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
return result;
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Adds a prefix to specified keys in an object, returning a new object.
|
|
933
|
+
* Only the provided keys are prefixed; all others are left unchanged.
|
|
934
|
+
*
|
|
935
|
+
* @param obj The source object
|
|
936
|
+
* @param prefix The prefix to add (e.g., '$')
|
|
937
|
+
* @param keys The keys to prefix (e.g., ['expand', 'filter'])
|
|
938
|
+
* @returns A new object with specified keys prefixed
|
|
939
|
+
*
|
|
940
|
+
* @example
|
|
941
|
+
* addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
|
|
942
|
+
*/
|
|
943
|
+
function addPrefixToKeys(obj, prefix, keys) {
|
|
944
|
+
const result = {};
|
|
945
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
946
|
+
if (keys.includes(key)) {
|
|
947
|
+
result[`${prefix}${key}`] = value;
|
|
948
|
+
}
|
|
949
|
+
else {
|
|
950
|
+
result[key] = value;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return result;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* Constants used throughout the pagination system
|
|
958
|
+
*/
|
|
959
|
+
/** Maximum number of items that can be requested in a single page */
|
|
960
|
+
const MAX_PAGE_SIZE = 1000;
|
|
961
|
+
/** Default page size when jumpToPage is used without specifying pageSize */
|
|
962
|
+
const DEFAULT_PAGE_SIZE = 50;
|
|
963
|
+
/** Default field name for items in a paginated response */
|
|
964
|
+
const DEFAULT_ITEMS_FIELD = 'value';
|
|
965
|
+
/** Default field name for total count in a paginated response */
|
|
966
|
+
const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
|
|
967
|
+
/**
|
|
968
|
+
* Limits the page size to the maximum allowed value
|
|
969
|
+
* @param pageSize - Requested page size
|
|
970
|
+
* @returns Limited page size value
|
|
971
|
+
*/
|
|
972
|
+
function getLimitedPageSize(pageSize) {
|
|
973
|
+
if (pageSize === undefined || pageSize === null) {
|
|
974
|
+
return DEFAULT_PAGE_SIZE;
|
|
975
|
+
}
|
|
976
|
+
return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* Helper functions for pagination that can be used across services
|
|
981
|
+
*/
|
|
982
|
+
class PaginationHelpers {
|
|
983
|
+
/**
|
|
984
|
+
* Checks if any pagination parameters are provided
|
|
985
|
+
*
|
|
986
|
+
* @param options - The options object to check
|
|
987
|
+
* @returns True if any pagination parameter is defined, false otherwise
|
|
988
|
+
*/
|
|
989
|
+
static hasPaginationParameters(options = {}) {
|
|
990
|
+
const { cursor, pageSize, jumpToPage } = options;
|
|
991
|
+
return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Parse a pagination cursor string into cursor data
|
|
995
|
+
*/
|
|
996
|
+
static parseCursor(cursorString) {
|
|
997
|
+
try {
|
|
998
|
+
const cursorData = JSON.parse(decodeBase64(cursorString));
|
|
999
|
+
return cursorData;
|
|
1000
|
+
}
|
|
1001
|
+
catch {
|
|
1002
|
+
throw new Error('Invalid pagination cursor');
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Validates cursor format and structure
|
|
1007
|
+
*
|
|
1008
|
+
* @param paginationOptions - The pagination options containing the cursor
|
|
1009
|
+
* @param paginationType - Optional pagination type to validate against
|
|
1010
|
+
*/
|
|
1011
|
+
static validateCursor(paginationOptions, paginationType) {
|
|
1012
|
+
if (paginationOptions.cursor !== undefined) {
|
|
1013
|
+
if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
|
|
1014
|
+
throw new Error('cursor must contain a valid cursor string');
|
|
1015
|
+
}
|
|
1016
|
+
try {
|
|
1017
|
+
// Try to parse the cursor to validate it
|
|
1018
|
+
const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
|
|
1019
|
+
// If type is provided, validate cursor contains expected type information
|
|
1020
|
+
if (paginationType) {
|
|
1021
|
+
if (!cursorData.type) {
|
|
1022
|
+
throw new Error('Invalid cursor: missing pagination type');
|
|
1023
|
+
}
|
|
1024
|
+
// Check pagination type compatibility
|
|
1025
|
+
if (cursorData.type !== paginationType) {
|
|
1026
|
+
throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
catch (error) {
|
|
1031
|
+
if (error instanceof Error) {
|
|
1032
|
+
// If it's already our error with specific message, pass it through
|
|
1033
|
+
if (error.message.startsWith('Invalid cursor') ||
|
|
1034
|
+
error.message.startsWith('Pagination type mismatch')) {
|
|
1035
|
+
throw error;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
throw new Error('Invalid pagination cursor format');
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Comprehensive validation for pagination options
|
|
1044
|
+
*
|
|
1045
|
+
* @param options - The pagination options to validate
|
|
1046
|
+
* @param paginationType - The pagination type these options will be used with
|
|
1047
|
+
* @returns Processed pagination parameters ready for use
|
|
1048
|
+
*/
|
|
1049
|
+
static validatePaginationOptions(options, paginationType) {
|
|
1050
|
+
// Validate pageSize
|
|
1051
|
+
if (options.pageSize !== undefined && options.pageSize <= 0) {
|
|
1052
|
+
throw new Error('pageSize must be a positive number');
|
|
1053
|
+
}
|
|
1054
|
+
// Validate jumpToPage
|
|
1055
|
+
if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
|
|
1056
|
+
throw new Error('jumpToPage must be a positive number');
|
|
1057
|
+
}
|
|
1058
|
+
// Validate cursor
|
|
1059
|
+
PaginationHelpers.validateCursor(options, paginationType);
|
|
1060
|
+
// Validate service compatibility
|
|
1061
|
+
if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
|
|
1062
|
+
throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
|
|
1063
|
+
}
|
|
1064
|
+
// Get processed parameters
|
|
1065
|
+
return PaginationHelpers.getRequestParameters(options, paginationType);
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Convert a unified pagination options to service-specific parameters
|
|
1069
|
+
*/
|
|
1070
|
+
static getRequestParameters(options, paginationType) {
|
|
1071
|
+
// Handle jumpToPage
|
|
1072
|
+
if (options.jumpToPage !== undefined) {
|
|
1073
|
+
const jumpToPageOptions = {
|
|
1074
|
+
pageSize: options.pageSize,
|
|
1075
|
+
pageNumber: options.jumpToPage
|
|
1076
|
+
};
|
|
1077
|
+
return filterUndefined(jumpToPageOptions);
|
|
1078
|
+
}
|
|
1079
|
+
// If no cursor is provided, it's a first page request
|
|
1080
|
+
if (!options.cursor) {
|
|
1081
|
+
const firstPageOptions = {
|
|
1082
|
+
pageSize: options.pageSize,
|
|
1083
|
+
// Only set pageNumber for OFFSET pagination
|
|
1084
|
+
pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
|
|
1085
|
+
};
|
|
1086
|
+
return filterUndefined(firstPageOptions);
|
|
1087
|
+
}
|
|
1088
|
+
// Parse the cursor
|
|
1089
|
+
try {
|
|
1090
|
+
const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
|
|
1091
|
+
const cursorBasedOptions = {
|
|
1092
|
+
pageSize: cursorData.pageSize || options.pageSize,
|
|
1093
|
+
pageNumber: cursorData.pageNumber,
|
|
1094
|
+
continuationToken: cursorData.continuationToken,
|
|
1095
|
+
type: cursorData.type,
|
|
1096
|
+
};
|
|
1097
|
+
return filterUndefined(cursorBasedOptions);
|
|
1098
|
+
}
|
|
1099
|
+
catch {
|
|
1100
|
+
throw new Error('Invalid pagination cursor');
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Helper method for paginated resource retrieval
|
|
1105
|
+
*
|
|
1106
|
+
* @param params - Parameters for pagination
|
|
1107
|
+
* @returns Promise resolving to a paginated result
|
|
1108
|
+
*/
|
|
1109
|
+
static async getAllPaginated(params) {
|
|
1110
|
+
const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1111
|
+
const endpoint = getEndpoint(folderId);
|
|
1112
|
+
const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
|
|
1113
|
+
const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
|
|
1114
|
+
headers,
|
|
1115
|
+
params: additionalParams,
|
|
1116
|
+
pagination: {
|
|
1117
|
+
paginationType: options.paginationType || PaginationType.OFFSET,
|
|
1118
|
+
itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
|
|
1119
|
+
totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
|
|
1120
|
+
continuationTokenField: options.continuationTokenField,
|
|
1121
|
+
paginationParams: options.paginationParams
|
|
1122
|
+
}
|
|
1123
|
+
});
|
|
1124
|
+
// Parse items - automatically handle JSON string responses
|
|
1125
|
+
const rawItems = paginatedResponse.items;
|
|
1126
|
+
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1127
|
+
const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1128
|
+
return {
|
|
1129
|
+
...paginatedResponse,
|
|
1130
|
+
items: transformedItems
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Helper method for non-paginated resource retrieval
|
|
1135
|
+
*
|
|
1136
|
+
* @param params - Parameters for non-paginated resource retrieval
|
|
1137
|
+
* @returns Promise resolving to an object with data and totalCount
|
|
1138
|
+
*/
|
|
1139
|
+
static async getAllNonPaginated(params) {
|
|
1140
|
+
const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
|
|
1141
|
+
// Set default field names
|
|
1142
|
+
const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
|
|
1143
|
+
const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
|
|
1144
|
+
// Determine endpoint and headers based on folderId
|
|
1145
|
+
const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
|
|
1146
|
+
const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
|
|
1147
|
+
// Make the API call based on method
|
|
1148
|
+
let response;
|
|
1149
|
+
if (method === HTTP_METHODS.POST) {
|
|
1150
|
+
response = await serviceAccess.post(endpoint, additionalParams, { headers });
|
|
1151
|
+
}
|
|
1152
|
+
else {
|
|
1153
|
+
response = await serviceAccess.get(endpoint, {
|
|
1154
|
+
params: additionalParams,
|
|
1155
|
+
headers
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
// Extract and transform items from response
|
|
1159
|
+
// Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
|
|
1160
|
+
const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
|
|
1161
|
+
const totalCount = Array.isArray(response.data) ? undefined : response.data?.[totalCountField];
|
|
1162
|
+
// Parse items - automatically handle JSON string responses
|
|
1163
|
+
const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
|
|
1164
|
+
const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
|
|
1165
|
+
return {
|
|
1166
|
+
items,
|
|
1167
|
+
totalCount
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Centralized getAll implementation that handles both paginated and non-paginated requests
|
|
1172
|
+
*
|
|
1173
|
+
* @param config - Configuration for the getAll operation
|
|
1174
|
+
* @param options - Request options including pagination parameters
|
|
1175
|
+
* @returns Promise resolving to either paginated or non-paginated response based on options
|
|
1176
|
+
*/
|
|
1177
|
+
static async getAll(config, options) {
|
|
1178
|
+
const optionsWithDefaults = options || {};
|
|
1179
|
+
const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
|
|
1180
|
+
// Determine if pagination is requested
|
|
1181
|
+
const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
|
|
1182
|
+
// Process parameters (custom processing if provided, otherwise default)
|
|
1183
|
+
let processedOptions = restOptions;
|
|
1184
|
+
if (config.processParametersFn) {
|
|
1185
|
+
processedOptions = config.processParametersFn(restOptions, folderId);
|
|
1186
|
+
}
|
|
1187
|
+
// Apply ODATA prefix to keys (excluding specified keys)
|
|
1188
|
+
const excludeKeys = config.excludeFromPrefix || [];
|
|
1189
|
+
const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
|
|
1190
|
+
const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
|
|
1191
|
+
// Default pagination options
|
|
1192
|
+
const paginationOptions = {
|
|
1193
|
+
paginationType: PaginationType.OFFSET,
|
|
1194
|
+
itemsField: DEFAULT_ITEMS_FIELD,
|
|
1195
|
+
totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
|
|
1196
|
+
...config.pagination
|
|
1197
|
+
};
|
|
1198
|
+
// Paginated flow
|
|
1199
|
+
if (isPaginationRequested) {
|
|
1200
|
+
return PaginationHelpers.getAllPaginated({
|
|
1201
|
+
serviceAccess: config.serviceAccess,
|
|
1202
|
+
getEndpoint: config.getEndpoint,
|
|
1203
|
+
folderId,
|
|
1204
|
+
paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
|
|
1205
|
+
additionalParams: prefixedOptions,
|
|
1206
|
+
transformFn: config.transformFn,
|
|
1207
|
+
method: config.method,
|
|
1208
|
+
options: {
|
|
1209
|
+
...paginationOptions,
|
|
1210
|
+
paginationParams: config.pagination?.paginationParams
|
|
1211
|
+
}
|
|
1212
|
+
}); // Type assertion needed due to conditional return
|
|
1213
|
+
}
|
|
1214
|
+
// Non-paginated flow
|
|
1215
|
+
const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
|
|
1216
|
+
return PaginationHelpers.getAllNonPaginated({
|
|
1217
|
+
serviceAccess: config.serviceAccess,
|
|
1218
|
+
getAllEndpoint: config.getEndpoint(),
|
|
1219
|
+
getByFolderEndpoint: byFolderEndpoint,
|
|
1220
|
+
folderId,
|
|
1221
|
+
additionalParams: prefixedOptions,
|
|
1222
|
+
transformFn: config.transformFn,
|
|
1223
|
+
method: config.method,
|
|
1224
|
+
options: {
|
|
1225
|
+
itemsField: paginationOptions.itemsField,
|
|
1226
|
+
totalCountField: paginationOptions.totalCountField
|
|
1227
|
+
}
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* SDK Internals Registry - Internal registry for SDK instances
|
|
1234
|
+
*
|
|
1235
|
+
* This class is NOT exported in the public API.
|
|
1236
|
+
* It provides a secure way to share SDK internals between
|
|
1237
|
+
* the UiPath class and service classes without exposing them publicly.
|
|
1238
|
+
*
|
|
1239
|
+
* @internal
|
|
1240
|
+
*/
|
|
1241
|
+
// Global symbol key to ensure WeakMap is shared across module instances
|
|
1242
|
+
// This prevents issues when core and service modules are bundled separately
|
|
1243
|
+
const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
|
|
1244
|
+
// Get or create the global WeakMap store
|
|
1245
|
+
const getGlobalStore = () => {
|
|
1246
|
+
const globalObj = globalThis;
|
|
1247
|
+
if (!globalObj[REGISTRY_KEY]) {
|
|
1248
|
+
globalObj[REGISTRY_KEY] = new WeakMap();
|
|
1249
|
+
}
|
|
1250
|
+
return globalObj[REGISTRY_KEY];
|
|
1251
|
+
};
|
|
1252
|
+
/**
|
|
1253
|
+
* Internal registry for SDK private components.
|
|
1254
|
+
* Uses WeakMap to prevent memory leaks - entries are automatically
|
|
1255
|
+
* garbage collected when the SDK instance is no longer referenced.
|
|
1256
|
+
*
|
|
1257
|
+
* Uses a global singleton pattern to ensure the same WeakMap is shared
|
|
1258
|
+
* across separately bundled modules (core, entities, tasks, etc.).
|
|
1259
|
+
*
|
|
1260
|
+
* @internal - Not exported in public API
|
|
1261
|
+
*/
|
|
1262
|
+
class SDKInternalsRegistry {
|
|
1263
|
+
// Use global store to ensure sharing across module bundles
|
|
1264
|
+
static get store() {
|
|
1265
|
+
return getGlobalStore();
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Register SDK instance internals
|
|
1269
|
+
* Called by UiPath constructor
|
|
1270
|
+
*/
|
|
1271
|
+
static set(instance, internals) {
|
|
1272
|
+
this.store.set(instance, internals);
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Retrieve SDK instance internals
|
|
1276
|
+
* Called by BaseService constructor
|
|
1277
|
+
*/
|
|
1278
|
+
static get(instance) {
|
|
1279
|
+
const internals = this.store.get(instance);
|
|
1280
|
+
if (!internals) {
|
|
1281
|
+
throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
|
|
1282
|
+
}
|
|
1283
|
+
return internals;
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
var _BaseService_apiClient;
|
|
1288
|
+
/**
|
|
1289
|
+
* Base class for all UiPath SDK services.
|
|
1290
|
+
*
|
|
1291
|
+
* Provides common functionality for authentication, configuration, and API communication.
|
|
1292
|
+
* All service classes extend this base to inherit dependency injection and HTTP client access.
|
|
1293
|
+
*
|
|
1294
|
+
* This class implements the dependency injection pattern where services receive a configured
|
|
1295
|
+
* UiPath instance. The ApiClient is created internally and handles all HTTP operations
|
|
1296
|
+
* including authentication token management.
|
|
1297
|
+
*
|
|
1298
|
+
* @remarks
|
|
1299
|
+
* Service classes should extend this base and call `super(uiPath)` in their constructor.
|
|
1300
|
+
* Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
|
|
1301
|
+
*
|
|
1302
|
+
*/
|
|
1303
|
+
class BaseService {
|
|
1304
|
+
/**
|
|
1305
|
+
* Creates a base service instance with dependency injection.
|
|
1306
|
+
*
|
|
1307
|
+
* Extracts configuration, execution context, and token manager from the UiPath instance
|
|
1308
|
+
* to initialize an authenticated API client. The ApiClient handles all HTTP operations
|
|
1309
|
+
* and token management internally.
|
|
1310
|
+
*
|
|
1311
|
+
* @param instance - UiPath SDK instance providing authentication and configuration.
|
|
1312
|
+
* Services receive this via dependency injection in the modular pattern.
|
|
1313
|
+
* @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
|
|
1314
|
+
* CAS external-app auth)
|
|
1315
|
+
*
|
|
1316
|
+
* @example
|
|
1317
|
+
* ```typescript
|
|
1318
|
+
* // Services automatically call this via super()
|
|
1319
|
+
* export class EntityService extends BaseService {
|
|
1320
|
+
* constructor(instance: IUiPath) {
|
|
1321
|
+
* super(instance); // Initializes the internal ApiClient
|
|
1322
|
+
* }
|
|
1323
|
+
* }
|
|
1324
|
+
*
|
|
1325
|
+
* // Usage in modular pattern
|
|
1326
|
+
* import { UiPath } from '@uipath/uipath-typescript/core';
|
|
1327
|
+
* import { Entities } from '@uipath/uipath-typescript/entities';
|
|
1328
|
+
*
|
|
1329
|
+
* const sdk = new UiPath(config);
|
|
1330
|
+
* await sdk.initialize();
|
|
1331
|
+
* const entities = new Entities(sdk);
|
|
1332
|
+
* ```
|
|
1333
|
+
*/
|
|
1334
|
+
constructor(instance, headers) {
|
|
1335
|
+
// Private field - not visible via Object.keys() or any reflection
|
|
1336
|
+
_BaseService_apiClient.set(this, void 0);
|
|
1337
|
+
const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
|
|
1338
|
+
__classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Gets a valid authentication token, refreshing if necessary.
|
|
1342
|
+
* Use this when you need to manually add Authorization headers (e.g., direct uploads).
|
|
1343
|
+
*
|
|
1344
|
+
* @returns Promise resolving to a valid access token string
|
|
1345
|
+
* @throws AuthenticationError if no token is available or refresh fails
|
|
1346
|
+
*/
|
|
1347
|
+
async getValidAuthToken() {
|
|
1348
|
+
return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Creates a service accessor for pagination helpers
|
|
1352
|
+
* This allows pagination helpers to access protected methods without making them public
|
|
1353
|
+
*/
|
|
1354
|
+
createPaginationServiceAccess() {
|
|
1355
|
+
return {
|
|
1356
|
+
get: (path, options) => this.get(path, options || {}),
|
|
1357
|
+
post: (path, body, options) => this.post(path, body, options || {}),
|
|
1358
|
+
requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
async request(method, path, options = {}) {
|
|
1362
|
+
switch (method.toUpperCase()) {
|
|
1363
|
+
case 'GET':
|
|
1364
|
+
return this.get(path, options);
|
|
1365
|
+
case 'POST':
|
|
1366
|
+
return this.post(path, options.body, options);
|
|
1367
|
+
case 'PUT':
|
|
1368
|
+
return this.put(path, options.body, options);
|
|
1369
|
+
case 'PATCH':
|
|
1370
|
+
return this.patch(path, options.body, options);
|
|
1371
|
+
case 'DELETE':
|
|
1372
|
+
return this.delete(path, options);
|
|
1373
|
+
default:
|
|
1374
|
+
throw new Error(`Unsupported HTTP method: ${method}`);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
async requestWithSpec(spec) {
|
|
1378
|
+
if (!spec.method || !spec.url) {
|
|
1379
|
+
throw new Error('Request spec must include method and url');
|
|
1380
|
+
}
|
|
1381
|
+
return this.request(spec.method, spec.url, spec);
|
|
1382
|
+
}
|
|
1383
|
+
async get(path, options = {}) {
|
|
1384
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
|
|
1385
|
+
return { data: response };
|
|
1386
|
+
}
|
|
1387
|
+
async post(path, data, options = {}) {
|
|
1388
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
|
|
1389
|
+
return { data: response };
|
|
1390
|
+
}
|
|
1391
|
+
async put(path, data, options = {}) {
|
|
1392
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
|
|
1393
|
+
return { data: response };
|
|
1394
|
+
}
|
|
1395
|
+
async patch(path, data, options = {}) {
|
|
1396
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
|
|
1397
|
+
return { data: response };
|
|
1398
|
+
}
|
|
1399
|
+
async delete(path, options = {}) {
|
|
1400
|
+
const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
|
|
1401
|
+
return { data: response };
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Execute a request with cursor-based pagination
|
|
1405
|
+
*/
|
|
1406
|
+
async requestWithPagination(method, path, paginationOptions, options) {
|
|
1407
|
+
const paginationType = options.pagination.paginationType;
|
|
1408
|
+
// Validate and prepare pagination parameters
|
|
1409
|
+
const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
|
|
1410
|
+
// Prepare request parameters based on pagination type
|
|
1411
|
+
const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
|
|
1412
|
+
// For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
|
|
1413
|
+
if (method.toUpperCase() === 'POST') {
|
|
1414
|
+
const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
|
|
1415
|
+
options.body = {
|
|
1416
|
+
...existingBody,
|
|
1417
|
+
...options.params,
|
|
1418
|
+
...requestParams
|
|
1419
|
+
};
|
|
1420
|
+
options.params = undefined;
|
|
1421
|
+
}
|
|
1422
|
+
else {
|
|
1423
|
+
// Merge pagination parameters with existing parameters
|
|
1424
|
+
options.params = {
|
|
1425
|
+
...options.params,
|
|
1426
|
+
...requestParams
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
// Make the request
|
|
1430
|
+
const response = await this.request(method, path, options);
|
|
1431
|
+
// Extract data from the response and create page result
|
|
1432
|
+
return this.createPaginatedResponseFromResponse(response, params, paginationType, {
|
|
1433
|
+
itemsField: options.pagination.itemsField,
|
|
1434
|
+
totalCountField: options.pagination.totalCountField,
|
|
1435
|
+
continuationTokenField: options.pagination.continuationTokenField
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Validates and prepares pagination parameters from options
|
|
1440
|
+
*/
|
|
1441
|
+
validateAndPreparePaginationParams(paginationType, paginationOptions) {
|
|
1442
|
+
return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Prepares request parameters for pagination based on pagination type
|
|
1446
|
+
*/
|
|
1447
|
+
preparePaginationRequestParams(paginationType, params, paginationConfig) {
|
|
1448
|
+
const requestParams = {};
|
|
1449
|
+
let limitedPageSize;
|
|
1450
|
+
const paginationParams = paginationConfig?.paginationParams;
|
|
1451
|
+
switch (paginationType) {
|
|
1452
|
+
case PaginationType.OFFSET:
|
|
1453
|
+
limitedPageSize = getLimitedPageSize(params.pageSize);
|
|
1454
|
+
const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
|
|
1455
|
+
const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
|
|
1456
|
+
const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
|
|
1457
|
+
requestParams[pageSizeParam] = limitedPageSize;
|
|
1458
|
+
if (params.pageNumber && params.pageNumber > 1) {
|
|
1459
|
+
requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
|
|
1460
|
+
}
|
|
1461
|
+
{
|
|
1462
|
+
requestParams[countParam] = true;
|
|
1463
|
+
}
|
|
1464
|
+
break;
|
|
1465
|
+
case PaginationType.TOKEN:
|
|
1466
|
+
const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
|
|
1467
|
+
const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
|
|
1468
|
+
if (params.pageSize) {
|
|
1469
|
+
requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
|
|
1470
|
+
}
|
|
1471
|
+
if (params.continuationToken) {
|
|
1472
|
+
requestParams[tokenParam] = params.continuationToken;
|
|
1473
|
+
}
|
|
1474
|
+
break;
|
|
1475
|
+
}
|
|
1476
|
+
return requestParams;
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Creates a paginated response from API response
|
|
1480
|
+
*/
|
|
1481
|
+
createPaginatedResponseFromResponse(response, params, paginationType, fields) {
|
|
1482
|
+
// Extract fields from response
|
|
1483
|
+
const itemsField = fields.itemsField ||
|
|
1484
|
+
(paginationType === PaginationType.TOKEN ? 'items' : 'value');
|
|
1485
|
+
const totalCountField = fields.totalCountField || 'totalRecordCount';
|
|
1486
|
+
const continuationTokenField = fields.continuationTokenField || 'continuationToken';
|
|
1487
|
+
// Extract items and metadata
|
|
1488
|
+
// Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
|
|
1489
|
+
const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
|
|
1490
|
+
const totalCount = Array.isArray(response.data) ? undefined : response.data[totalCountField];
|
|
1491
|
+
const continuationToken = response.data[continuationTokenField];
|
|
1492
|
+
// Determine if there are more pages
|
|
1493
|
+
const hasMore = this.determineHasMorePages(paginationType, {
|
|
1494
|
+
totalCount,
|
|
1495
|
+
pageSize: params.pageSize,
|
|
1496
|
+
currentPage: params.pageNumber || 1,
|
|
1497
|
+
itemsCount: items.length,
|
|
1498
|
+
continuationToken
|
|
1499
|
+
});
|
|
1500
|
+
// Create and return the page result
|
|
1501
|
+
return PaginationManager.createPaginatedResponse({
|
|
1502
|
+
pageInfo: {
|
|
1503
|
+
hasMore,
|
|
1504
|
+
totalCount,
|
|
1505
|
+
currentPage: params.pageNumber,
|
|
1506
|
+
pageSize: params.pageSize,
|
|
1507
|
+
continuationToken
|
|
1508
|
+
},
|
|
1509
|
+
type: paginationType,
|
|
1510
|
+
}, items);
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Determines if there are more pages based on pagination type and metadata
|
|
1514
|
+
*/
|
|
1515
|
+
determineHasMorePages(paginationType, info) {
|
|
1516
|
+
switch (paginationType) {
|
|
1517
|
+
case PaginationType.OFFSET:
|
|
1518
|
+
const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
1519
|
+
// If totalCount is available, use it for precise calculation
|
|
1520
|
+
if (info.totalCount !== undefined) {
|
|
1521
|
+
return (info.currentPage * effectivePageSize) < info.totalCount;
|
|
1522
|
+
}
|
|
1523
|
+
// Fallback when totalCount is not available
|
|
1524
|
+
// NOTE: This code path should rarely be executed as the APIs typically return totalCount
|
|
1525
|
+
return info.itemsCount === effectivePageSize;
|
|
1526
|
+
case PaginationType.TOKEN:
|
|
1527
|
+
return !!info.continuationToken;
|
|
1528
|
+
default:
|
|
1529
|
+
return false;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
_BaseService_apiClient = new WeakMap();
|
|
1534
|
+
|
|
1535
|
+
/**
|
|
1536
|
+
* Maps fields for Feedback entities to ensure consistent naming.
|
|
1537
|
+
*/
|
|
1538
|
+
const FeedbackMap = {
|
|
1539
|
+
createdAt: 'createdTime',
|
|
1540
|
+
updatedAt: 'updatedTime',
|
|
1541
|
+
};
|
|
1542
|
+
|
|
1543
|
+
/**
|
|
1544
|
+
* Base path constants for different services
|
|
1545
|
+
*/
|
|
1546
|
+
const LLMOPS_BASE = 'llmopstenant_';
|
|
1547
|
+
|
|
1548
|
+
/**
|
|
1549
|
+
* Agent Feedback Service Endpoints
|
|
1550
|
+
*/
|
|
1551
|
+
const FEEDBACK_ENDPOINTS = {
|
|
1552
|
+
GET_ALL: `${LLMOPS_BASE}/api/Feedback`,
|
|
1553
|
+
};
|
|
1554
|
+
|
|
1555
|
+
/**
|
|
1556
|
+
* SDK Telemetry constants
|
|
1557
|
+
*/
|
|
1558
|
+
// Connection string placeholder that will be replaced during build
|
|
1559
|
+
const CONNECTION_STRING = "InstrumentationKey=a6efa11d-1feb-4508-9738-e13e12dcae5e;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=7c58eb1c-9581-4ba6-839e-11725848a037";
|
|
1560
|
+
// SDK Version placeholder
|
|
1561
|
+
const SDK_VERSION = "1.3.3";
|
|
1562
|
+
const VERSION = "Version";
|
|
1563
|
+
const SERVICE = "Service";
|
|
1564
|
+
const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
|
|
1565
|
+
const CLOUD_TENANT_NAME = "CloudTenantName";
|
|
1566
|
+
const CLOUD_URL = "CloudUrl";
|
|
1567
|
+
const CLOUD_CLIENT_ID = "CloudClientId";
|
|
1568
|
+
const CLOUD_REDIRECT_URI = "CloudRedirectUri";
|
|
1569
|
+
const APP_NAME = "ApplicationName";
|
|
1570
|
+
const CLOUD_ROLE_NAME = "uipath-ts-sdk";
|
|
1571
|
+
// Service and logger names
|
|
1572
|
+
const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
|
|
1573
|
+
const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
|
|
1574
|
+
// Event names
|
|
1575
|
+
const SDK_RUN_EVENT = "Sdk.Run";
|
|
1576
|
+
// Default value for unknown/empty attributes
|
|
1577
|
+
const UNKNOWN = "";
|
|
1578
|
+
|
|
1579
|
+
/**
|
|
1580
|
+
* Log exporter that sends ALL logs as Application Insights custom events
|
|
1581
|
+
*/
|
|
1582
|
+
class ApplicationInsightsEventExporter {
|
|
1583
|
+
constructor(connectionString) {
|
|
1584
|
+
this.connectionString = connectionString;
|
|
1585
|
+
}
|
|
1586
|
+
export(logs, resultCallback) {
|
|
1587
|
+
try {
|
|
1588
|
+
logs.forEach(logRecord => {
|
|
1589
|
+
this.sendAsCustomEvent(logRecord);
|
|
1590
|
+
});
|
|
1591
|
+
resultCallback({ code: 0 });
|
|
1592
|
+
}
|
|
1593
|
+
catch (error) {
|
|
1594
|
+
console.debug('Failed to export logs to Application Insights:', error);
|
|
1595
|
+
resultCallback({ code: 2, error });
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
shutdown() {
|
|
1599
|
+
return Promise.resolve();
|
|
1600
|
+
}
|
|
1601
|
+
sendAsCustomEvent(logRecord) {
|
|
1602
|
+
// Get event name from body or attributes
|
|
1603
|
+
const eventName = logRecord.body || SDK_RUN_EVENT;
|
|
1604
|
+
const payload = {
|
|
1605
|
+
name: 'Microsoft.ApplicationInsights.Event',
|
|
1606
|
+
time: new Date().toISOString(),
|
|
1607
|
+
iKey: this.extractInstrumentationKey(),
|
|
1608
|
+
data: {
|
|
1609
|
+
baseType: 'EventData',
|
|
1610
|
+
baseData: {
|
|
1611
|
+
ver: 2,
|
|
1612
|
+
name: eventName,
|
|
1613
|
+
properties: this.convertAttributesToProperties(logRecord.attributes || {})
|
|
1614
|
+
}
|
|
1615
|
+
},
|
|
1616
|
+
tags: {
|
|
1617
|
+
'ai.cloud.role': CLOUD_ROLE_NAME,
|
|
1618
|
+
'ai.cloud.roleInstance': SDK_VERSION
|
|
1619
|
+
}
|
|
1620
|
+
};
|
|
1621
|
+
this.sendToApplicationInsights(payload);
|
|
1622
|
+
}
|
|
1623
|
+
extractInstrumentationKey() {
|
|
1624
|
+
const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
|
|
1625
|
+
return match ? match[1] : '';
|
|
1626
|
+
}
|
|
1627
|
+
convertAttributesToProperties(attributes) {
|
|
1628
|
+
const properties = {};
|
|
1629
|
+
Object.entries(attributes || {}).forEach(([key, value]) => {
|
|
1630
|
+
properties[key] = String(value);
|
|
1631
|
+
});
|
|
1632
|
+
return properties;
|
|
1633
|
+
}
|
|
1634
|
+
async sendToApplicationInsights(payload) {
|
|
1635
|
+
try {
|
|
1636
|
+
const ingestionEndpoint = this.extractIngestionEndpoint();
|
|
1637
|
+
if (!ingestionEndpoint) {
|
|
1638
|
+
console.debug('No ingestion endpoint found in connection string');
|
|
1639
|
+
return;
|
|
1640
|
+
}
|
|
1641
|
+
const url = `${ingestionEndpoint}/v2/track`;
|
|
1642
|
+
const response = await fetch(url, {
|
|
1643
|
+
method: 'POST',
|
|
1644
|
+
headers: {
|
|
1645
|
+
'Content-Type': 'application/json',
|
|
1646
|
+
},
|
|
1647
|
+
body: JSON.stringify(payload)
|
|
1648
|
+
});
|
|
1649
|
+
if (!response.ok) {
|
|
1650
|
+
console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
catch (error) {
|
|
1654
|
+
console.debug('Error sending event telemetry to Application Insights:', error);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
extractIngestionEndpoint() {
|
|
1658
|
+
const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
|
|
1659
|
+
return match ? match[1] : '';
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Singleton telemetry client
|
|
1664
|
+
*/
|
|
1665
|
+
class TelemetryClient {
|
|
1666
|
+
constructor() {
|
|
1667
|
+
this.isInitialized = false;
|
|
1668
|
+
}
|
|
1669
|
+
static getInstance() {
|
|
1670
|
+
if (!TelemetryClient.instance) {
|
|
1671
|
+
TelemetryClient.instance = new TelemetryClient();
|
|
1672
|
+
}
|
|
1673
|
+
return TelemetryClient.instance;
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Initialize telemetry
|
|
1677
|
+
*/
|
|
1678
|
+
initialize(config) {
|
|
1679
|
+
if (this.isInitialized) {
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
this.isInitialized = true;
|
|
1683
|
+
if (config) {
|
|
1684
|
+
this.telemetryContext = config;
|
|
1685
|
+
}
|
|
1686
|
+
try {
|
|
1687
|
+
const connectionString = this.getConnectionString();
|
|
1688
|
+
if (!connectionString) {
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
this.setupTelemetryProvider(connectionString);
|
|
1692
|
+
}
|
|
1693
|
+
catch (error) {
|
|
1694
|
+
// Silent failure - telemetry errors shouldn't break functionality
|
|
1695
|
+
console.debug('Failed to initialize OpenTelemetry:', error);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
getConnectionString() {
|
|
1699
|
+
const connectionString = CONNECTION_STRING;
|
|
1700
|
+
return connectionString;
|
|
1701
|
+
}
|
|
1702
|
+
setupTelemetryProvider(connectionString) {
|
|
1703
|
+
const exporter = new ApplicationInsightsEventExporter(connectionString);
|
|
1704
|
+
const processor = new sdkLogs.BatchLogRecordProcessor(exporter);
|
|
1705
|
+
this.logProvider = new sdkLogs.LoggerProvider({
|
|
1706
|
+
processors: [processor]
|
|
1707
|
+
});
|
|
1708
|
+
this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
|
|
1709
|
+
}
|
|
1710
|
+
/**
|
|
1711
|
+
* Track a telemetry event
|
|
1712
|
+
*/
|
|
1713
|
+
track(eventName, name, extraAttributes = {}) {
|
|
1714
|
+
try {
|
|
1715
|
+
// Skip if logger not initialized
|
|
1716
|
+
if (!this.logger) {
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
const finalDisplayName = name || eventName;
|
|
1720
|
+
const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
|
|
1721
|
+
// Emit as log
|
|
1722
|
+
this.logger.emit({
|
|
1723
|
+
body: finalDisplayName,
|
|
1724
|
+
attributes: attributes,
|
|
1725
|
+
timestamp: Date.now(),
|
|
1726
|
+
});
|
|
1727
|
+
}
|
|
1728
|
+
catch (error) {
|
|
1729
|
+
// Silent failure
|
|
1730
|
+
console.debug('Failed to track telemetry event:', error);
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Get enriched attributes for telemetry events
|
|
1735
|
+
*/
|
|
1736
|
+
getEnrichedAttributes(extraAttributes, eventName) {
|
|
1737
|
+
const attributes = {
|
|
1738
|
+
[APP_NAME]: SDK_SERVICE_NAME,
|
|
1739
|
+
[VERSION]: SDK_VERSION,
|
|
1740
|
+
[SERVICE]: eventName,
|
|
1741
|
+
[CLOUD_URL]: this.createCloudUrl(),
|
|
1742
|
+
[CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
|
|
1743
|
+
[CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
|
|
1744
|
+
[CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
|
|
1745
|
+
[CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
|
|
1746
|
+
...extraAttributes,
|
|
1747
|
+
};
|
|
1748
|
+
return attributes;
|
|
1749
|
+
}
|
|
1750
|
+
/**
|
|
1751
|
+
* Create cloud URL from base URL, organization ID, and tenant ID
|
|
1752
|
+
*/
|
|
1753
|
+
createCloudUrl() {
|
|
1754
|
+
const baseUrl = this.telemetryContext?.baseUrl;
|
|
1755
|
+
const orgId = this.telemetryContext?.orgName;
|
|
1756
|
+
const tenantId = this.telemetryContext?.tenantName;
|
|
1757
|
+
if (!baseUrl || !orgId || !tenantId) {
|
|
1758
|
+
return UNKNOWN;
|
|
1759
|
+
}
|
|
1760
|
+
return `${baseUrl}/${orgId}/${tenantId}`;
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
// Export singleton instance
|
|
1764
|
+
const telemetryClient = TelemetryClient.getInstance();
|
|
1765
|
+
|
|
1766
|
+
/**
|
|
1767
|
+
* SDK Track decorator and function for telemetry
|
|
1768
|
+
*/
|
|
1769
|
+
/**
|
|
1770
|
+
* Common tracking logic shared between method and function decorators
|
|
1771
|
+
*/
|
|
1772
|
+
function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
|
|
1773
|
+
return function (...args) {
|
|
1774
|
+
// Determine if we should track this call
|
|
1775
|
+
let shouldTrack = true;
|
|
1776
|
+
if (opts.condition !== undefined) {
|
|
1777
|
+
if (typeof opts.condition === 'function') {
|
|
1778
|
+
shouldTrack = opts.condition.apply(this, args);
|
|
1779
|
+
}
|
|
1780
|
+
else {
|
|
1781
|
+
shouldTrack = opts.condition;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
// Track the event if enabled
|
|
1785
|
+
if (shouldTrack) {
|
|
1786
|
+
// Use the full name provided in the decorator (e.g., "Queue.GetAll")
|
|
1787
|
+
const serviceMethod = nameOrOptions
|
|
1788
|
+
;
|
|
1789
|
+
// Use 'Sdk.Run' as the name and serviceMethod as the service
|
|
1790
|
+
telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
|
|
1791
|
+
}
|
|
1792
|
+
// Execute the original function
|
|
1793
|
+
return originalFunction.apply(this, args);
|
|
1794
|
+
};
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* Track decorator that can be used to automatically track function calls
|
|
1798
|
+
*
|
|
1799
|
+
* Usage:
|
|
1800
|
+
* @track("Service.Method")
|
|
1801
|
+
* function myFunction() { ... }
|
|
1802
|
+
*
|
|
1803
|
+
* @track("Queue.GetAll")
|
|
1804
|
+
* async getAll() { ... }
|
|
1805
|
+
*
|
|
1806
|
+
* @track("Tasks.Create")
|
|
1807
|
+
* async create() { ... }
|
|
1808
|
+
*
|
|
1809
|
+
* @track("Assets.Update", { condition: false })
|
|
1810
|
+
* function myFunction() { ... }
|
|
1811
|
+
*
|
|
1812
|
+
* @track("Processes.Start", { attributes: { customProp: "value" } })
|
|
1813
|
+
* function myFunction() { ... }
|
|
1814
|
+
*/
|
|
1815
|
+
function track(nameOrOptions, options) {
|
|
1816
|
+
return function decorator(_target, propertyKey, descriptor) {
|
|
1817
|
+
const opts = {};
|
|
1818
|
+
if (descriptor && typeof descriptor.value === 'function') {
|
|
1819
|
+
// Method decorator
|
|
1820
|
+
descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
|
|
1821
|
+
return descriptor;
|
|
1822
|
+
}
|
|
1823
|
+
// Function decorator
|
|
1824
|
+
return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
/**
|
|
1829
|
+
* Service for interacting with UiPath Agent Feedback API
|
|
1830
|
+
*/
|
|
1831
|
+
class FeedbackService extends BaseService {
|
|
1832
|
+
/**
|
|
1833
|
+
* Gets all feedback across all agents in the tenant, with optional filters.
|
|
1834
|
+
*
|
|
1835
|
+
* Retrieves a list of feedback entries, optionally filtered by agent, trace, span, status, or agent version.
|
|
1836
|
+
* When no pagination options are provided, the API returns up to 100 items. When pagination options are provided without a pageSize, the SDK defaults to 50 items per page.
|
|
1837
|
+
*
|
|
1838
|
+
* @param options - Optional query parameters for filtering and pagination
|
|
1839
|
+
* @returns Promise resolving to {@link NonPaginatedResponse} of {@link FeedbackGetResponse} without pagination options, or {@link PaginatedResponse} of {@link FeedbackGetResponse} when pagination options are used.
|
|
1840
|
+
* @example
|
|
1841
|
+
* ```typescript
|
|
1842
|
+
* import { Feedback, FeedbackStatus } from '@uipath/uipath-typescript/feedback';
|
|
1843
|
+
*
|
|
1844
|
+
* // Get all feedback (default pagination: returns first 50 items)
|
|
1845
|
+
* const allFeedback = await feedback.getAll();
|
|
1846
|
+
*
|
|
1847
|
+
* // Get the agentId from a feedback entry
|
|
1848
|
+
* const agentId = allFeedback.items[0].agentId;
|
|
1849
|
+
*
|
|
1850
|
+
* // Get feedback for a specific agent
|
|
1851
|
+
* const agentFeedback = await feedback.getAll({
|
|
1852
|
+
* agentId,
|
|
1853
|
+
* });
|
|
1854
|
+
*
|
|
1855
|
+
* // First page with pagination
|
|
1856
|
+
* const page1 = await feedback.getAll({ pageSize: 10 });
|
|
1857
|
+
*
|
|
1858
|
+
* // Navigate using cursor
|
|
1859
|
+
* if (page1.hasNextPage) {
|
|
1860
|
+
* const page2 = await feedback.getAll({ cursor: page1.nextCursor });
|
|
1861
|
+
* }
|
|
1862
|
+
*
|
|
1863
|
+
* // Filter by status
|
|
1864
|
+
* const activeFeedback = await feedback.getAll({
|
|
1865
|
+
* status: FeedbackStatus.Pending,
|
|
1866
|
+
* });
|
|
1867
|
+
* ```
|
|
1868
|
+
*/
|
|
1869
|
+
async getAll(options) {
|
|
1870
|
+
const transformFeedbackResponse = (item) => transformData(item, FeedbackMap);
|
|
1871
|
+
return PaginationHelpers.getAll({
|
|
1872
|
+
serviceAccess: this.createPaginationServiceAccess(),
|
|
1873
|
+
getEndpoint: () => FEEDBACK_ENDPOINTS.GET_ALL,
|
|
1874
|
+
transformFn: transformFeedbackResponse,
|
|
1875
|
+
pagination: {
|
|
1876
|
+
paginationType: PaginationType.OFFSET,
|
|
1877
|
+
paginationParams: {
|
|
1878
|
+
pageSizeParam: FEEDBACK_OFFSET_PARAMS.PAGE_SIZE_PARAM,
|
|
1879
|
+
offsetParam: FEEDBACK_OFFSET_PARAMS.OFFSET_PARAM,
|
|
1880
|
+
countParam: FEEDBACK_OFFSET_PARAMS.COUNT_PARAM,
|
|
1881
|
+
},
|
|
1882
|
+
},
|
|
1883
|
+
excludeFromPrefix: Object.keys(options || {}),
|
|
1884
|
+
}, options);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
__decorate([
|
|
1888
|
+
track('Feedback.GetAll')
|
|
1889
|
+
], FeedbackService.prototype, "getAll", null);
|
|
1890
|
+
|
|
1891
|
+
/**
|
|
1892
|
+
* Status of a feedback entry in the review workflow
|
|
1893
|
+
*/
|
|
1894
|
+
exports.FeedbackStatus = void 0;
|
|
1895
|
+
(function (FeedbackStatus) {
|
|
1896
|
+
/** Feedback is awaiting review */
|
|
1897
|
+
FeedbackStatus[FeedbackStatus["Pending"] = 0] = "Pending";
|
|
1898
|
+
/** Feedback has been approved and confirmed */
|
|
1899
|
+
FeedbackStatus[FeedbackStatus["Approved"] = 1] = "Approved";
|
|
1900
|
+
/** Feedback has been dismissed */
|
|
1901
|
+
FeedbackStatus[FeedbackStatus["Dismissed"] = 2] = "Dismissed";
|
|
1902
|
+
})(exports.FeedbackStatus || (exports.FeedbackStatus = {}));
|
|
1903
|
+
|
|
1904
|
+
exports.Feedback = FeedbackService;
|