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