@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,2653 @@
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.defaultHeaders = {};
530
+ this.config = config;
531
+ this.executionContext = executionContext;
532
+ this.clientConfig = clientConfig;
533
+ this.tokenManager = tokenManager;
534
+ }
535
+ setDefaultHeaders(headers) {
536
+ this.defaultHeaders = { ...this.defaultHeaders, ...headers };
537
+ }
538
+ /**
539
+ * Gets a valid authentication token, refreshing if necessary.
540
+ * Used internally for API requests and exposed for services that need manual auth headers.
541
+ *
542
+ * @returns The valid token
543
+ * @throws AuthenticationError if no token available or refresh fails
544
+ */
545
+ async getValidToken() {
546
+ return this.tokenManager.getValidToken();
547
+ }
548
+ async getDefaultHeaders() {
549
+ // Get headers from execution context first
550
+ const contextHeaders = this.executionContext.getHeaders();
551
+ // If Authorization header is already set in context, use that
552
+ if (contextHeaders['Authorization']) {
553
+ return {
554
+ ...contextHeaders,
555
+ 'Content-Type': CONTENT_TYPES.JSON,
556
+ ...this.defaultHeaders,
557
+ ...this.clientConfig.headers
558
+ };
559
+ }
560
+ const token = await this.getValidToken();
561
+ return {
562
+ ...contextHeaders,
563
+ 'Authorization': `Bearer ${token}`,
564
+ 'Content-Type': CONTENT_TYPES.JSON,
565
+ ...this.defaultHeaders,
566
+ ...this.clientConfig.headers
567
+ };
568
+ }
569
+ async request(method, path, options = {}) {
570
+ // Ensure path starts with a forward slash
571
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
572
+ // Construct URL with org and tenant names
573
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
574
+ const headers = {
575
+ ...await this.getDefaultHeaders(),
576
+ ...options.headers
577
+ };
578
+ // Convert params to URLSearchParams
579
+ const searchParams = new URLSearchParams();
580
+ if (options.params) {
581
+ Object.entries(options.params).forEach(([key, value]) => {
582
+ searchParams.append(key, value.toString());
583
+ });
584
+ }
585
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
586
+ try {
587
+ const response = await fetch(fullUrl, {
588
+ method,
589
+ headers,
590
+ body: options.body ? JSON.stringify(options.body) : undefined,
591
+ signal: options.signal
592
+ });
593
+ if (!response.ok) {
594
+ const errorInfo = await errorResponseParser.parse(response);
595
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
596
+ }
597
+ if (response.status === 204) {
598
+ return undefined;
599
+ }
600
+ // Handle blob response type for binary data (e.g., file downloads)
601
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
602
+ const blob = await response.blob();
603
+ return blob;
604
+ }
605
+ // Check if we're expecting XML
606
+ const acceptHeader = headers['Accept'] || headers['accept'];
607
+ if (acceptHeader === CONTENT_TYPES.XML) {
608
+ const text = await response.text();
609
+ return text;
610
+ }
611
+ return response.json();
612
+ }
613
+ catch (error) {
614
+ // If it's already one of our errors, re-throw it
615
+ if (error.type && error.type.includes('Error')) {
616
+ throw error;
617
+ }
618
+ // Otherwise, it's likely a network error
619
+ throw ErrorFactory.createNetworkError(error);
620
+ }
621
+ }
622
+ async get(path, options = {}) {
623
+ return this.request('GET', path, options);
624
+ }
625
+ async post(path, data, options = {}) {
626
+ return this.request('POST', path, { ...options, body: data });
627
+ }
628
+ async put(path, data, options = {}) {
629
+ return this.request('PUT', path, { ...options, body: data });
630
+ }
631
+ async patch(path, data, options = {}) {
632
+ return this.request('PATCH', path, { ...options, body: data });
633
+ }
634
+ async delete(path, options = {}) {
635
+ return this.request('DELETE', path, options);
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Pagination types supported by the SDK
641
+ */
642
+ var PaginationType;
643
+ (function (PaginationType) {
644
+ PaginationType["OFFSET"] = "offset";
645
+ PaginationType["TOKEN"] = "token";
646
+ })(PaginationType || (PaginationType = {}));
647
+
648
+ /**
649
+ * Collection of utility functions for working with objects
650
+ */
651
+ /**
652
+ * Filters out undefined values from an object
653
+ * @param obj The source object
654
+ * @returns A new object without undefined values
655
+ *
656
+ * @example
657
+ * ```typescript
658
+ * // Object with undefined values
659
+ * const options = {
660
+ * name: 'test',
661
+ * count: 5,
662
+ * prefix: undefined,
663
+ * suffix: null
664
+ * };
665
+ * const result = filterUndefined(options);
666
+ * // result = { name: 'test', count: 5, suffix: null }
667
+ * ```
668
+ */
669
+ function filterUndefined(obj) {
670
+ const result = {};
671
+ for (const [key, value] of Object.entries(obj)) {
672
+ if (value !== undefined) {
673
+ result[key] = value;
674
+ }
675
+ }
676
+ return result;
677
+ }
678
+ /**
679
+ * Helper function for OData responses that ALWAYS return 200 with array indication
680
+ * Empty array = success, Non-empty array = error
681
+ * Used for task assignment APIs that don't use HTTP status codes for errors
682
+ */
683
+ function processODataArrayResponse(oDataResponse, successData) {
684
+ // Empty array = success
685
+ if (oDataResponse.value.length === 0) {
686
+ return {
687
+ success: true,
688
+ data: successData
689
+ };
690
+ }
691
+ // Non-empty array = error details
692
+ return {
693
+ success: false,
694
+ data: oDataResponse.value
695
+ };
696
+ }
697
+
698
+ /**
699
+ * Utility functions for platform detection
700
+ */
701
+ /**
702
+ * Checks if code is running in a browser environment
703
+ */
704
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
705
+
706
+ /**
707
+ * Base64 encoding/decoding
708
+ */
709
+ /**
710
+ * Encodes a string to base64
711
+ * @param str - The string to encode
712
+ * @returns Base64 encoded string
713
+ */
714
+ function encodeBase64(str) {
715
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
716
+ const encoder = new TextEncoder();
717
+ const data = encoder.encode(str);
718
+ // Convert Uint8Array to base64
719
+ if (isBrowser) {
720
+ // Browser environment
721
+ // Convert Uint8Array to binary string then to base64
722
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
723
+ return btoa(binaryString);
724
+ }
725
+ else {
726
+ // Node.js environment
727
+ return Buffer.from(data).toString('base64');
728
+ }
729
+ }
730
+ /**
731
+ * Decodes a base64 string
732
+ * @param base64 - The base64 string to decode
733
+ * @returns Decoded string
734
+ */
735
+ function decodeBase64(base64) {
736
+ let bytes;
737
+ if (isBrowser) {
738
+ // Browser environment
739
+ const binaryString = atob(base64);
740
+ bytes = new Uint8Array(binaryString.length);
741
+ for (let i = 0; i < binaryString.length; i++) {
742
+ bytes[i] = binaryString.charCodeAt(i);
743
+ }
744
+ }
745
+ else {
746
+ // Node.js environment
747
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
748
+ }
749
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
750
+ const decoder = new TextDecoder();
751
+ return decoder.decode(bytes);
752
+ }
753
+
754
+ /**
755
+ * PaginationManager handles the conversion between uniform cursor-based pagination
756
+ * and the specific pagination type for each service
757
+ */
758
+ class PaginationManager {
759
+ /**
760
+ * Create a pagination cursor for subsequent page requests
761
+ */
762
+ static createCursor({ pageInfo, type }) {
763
+ if (!pageInfo.hasMore) {
764
+ return undefined;
765
+ }
766
+ const cursorData = {
767
+ type,
768
+ pageSize: pageInfo.pageSize,
769
+ };
770
+ switch (type) {
771
+ case PaginationType.OFFSET:
772
+ if (pageInfo.currentPage) {
773
+ cursorData.pageNumber = pageInfo.currentPage + 1;
774
+ }
775
+ break;
776
+ case PaginationType.TOKEN:
777
+ if (pageInfo.continuationToken) {
778
+ cursorData.continuationToken = pageInfo.continuationToken;
779
+ }
780
+ else {
781
+ return undefined; // No continuation token, can't continue
782
+ }
783
+ break;
784
+ }
785
+ return {
786
+ value: encodeBase64(JSON.stringify(cursorData))
787
+ };
788
+ }
789
+ /**
790
+ * Create a paginated response with navigation cursors
791
+ */
792
+ static createPaginatedResponse({ pageInfo, type }, items) {
793
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
794
+ // Create previous page cursor if applicable
795
+ let previousCursor = undefined;
796
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
797
+ const prevCursorData = {
798
+ type,
799
+ pageNumber: pageInfo.currentPage - 1,
800
+ pageSize: pageInfo.pageSize,
801
+ };
802
+ previousCursor = {
803
+ value: encodeBase64(JSON.stringify(prevCursorData))
804
+ };
805
+ }
806
+ // Calculate total pages if we have totalCount and pageSize
807
+ let totalPages = undefined;
808
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
809
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
810
+ }
811
+ // Determine if this pagination type supports page jumping
812
+ const supportsPageJump = type === PaginationType.OFFSET;
813
+ // Create the result object with all fields, then filter out undefined values
814
+ const result = filterUndefined({
815
+ items,
816
+ totalCount: pageInfo.totalCount,
817
+ hasNextPage: pageInfo.hasMore,
818
+ nextCursor: nextCursor,
819
+ previousCursor: previousCursor,
820
+ currentPage: pageInfo.currentPage,
821
+ totalPages,
822
+ supportsPageJump
823
+ });
824
+ return result;
825
+ }
826
+ }
827
+
828
+ /**
829
+ * Creates headers object from key-value pairs
830
+ * @param headersObj - Object containing header key-value pairs
831
+ * @returns Headers object with all values converted to strings
832
+ *
833
+ * @example
834
+ * ```typescript
835
+ * // Single header
836
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
837
+ *
838
+ * // Multiple headers
839
+ * const headers = createHeaders({
840
+ * 'X-UIPATH-FolderKey': '1234567890',
841
+ * 'X-UIPATH-OrganizationUnitId': 123,
842
+ * 'Accept': 'application/json'
843
+ * });
844
+ *
845
+ * // Using constants
846
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
847
+ * const headers = createHeaders({
848
+ * [FOLDER_KEY]: 'abc-123',
849
+ * [FOLDER_ID]: 456
850
+ * });
851
+ *
852
+ * // Empty headers
853
+ * const headers = createHeaders();
854
+ * ```
855
+ */
856
+ function createHeaders(headersObj) {
857
+ const headers = {};
858
+ for (const [key, value] of Object.entries(headersObj)) {
859
+ if (value !== undefined && value !== null) {
860
+ headers[key] = value.toString();
861
+ }
862
+ }
863
+ return headers;
864
+ }
865
+
866
+ /**
867
+ * Common constants used across the SDK
868
+ */
869
+ /**
870
+ * Prefix used for OData query parameters
871
+ */
872
+ const ODATA_PREFIX = '$';
873
+ /**
874
+ * HTTP methods
875
+ */
876
+ const HTTP_METHODS = {
877
+ GET: 'GET',
878
+ POST: 'POST'};
879
+ /**
880
+ * OData pagination constants
881
+ */
882
+ const ODATA_PAGINATION = {
883
+ /** Default field name for items in a paginated OData response */
884
+ ITEMS_FIELD: 'value',
885
+ /** Default field name for total count in a paginated OData response */
886
+ TOTAL_COUNT_FIELD: '@odata.count'
887
+ };
888
+ /**
889
+ * OData OFFSET pagination parameter names (ODATA-style)
890
+ */
891
+ const ODATA_OFFSET_PARAMS = {
892
+ /** OData page size parameter name */
893
+ PAGE_SIZE_PARAM: '$top',
894
+ /** OData offset parameter name */
895
+ OFFSET_PARAM: '$skip',
896
+ /** OData count parameter name */
897
+ COUNT_PARAM: '$count'
898
+ };
899
+ /**
900
+ * Bucket TOKEN pagination parameter names
901
+ */
902
+ const BUCKET_TOKEN_PARAMS = {
903
+ /** Bucket page size parameter name */
904
+ PAGE_SIZE_PARAM: 'takeHint',
905
+ /** Bucket token parameter name */
906
+ TOKEN_PARAM: 'continuationToken'
907
+ };
908
+
909
+ /**
910
+ * Transforms data by mapping fields according to the provided field mapping
911
+ * @param data The source data to transform
912
+ * @param fieldMapping Object mapping source field names to target field names
913
+ * @returns Transformed data with mapped field names
914
+ *
915
+ * @example
916
+ * ```typescript
917
+ * // Single object transformation
918
+ * const data = { id: '123', userName: 'john' };
919
+ * const mapping = { id: 'userId', userName: 'name' };
920
+ * const result = transformData(data, mapping);
921
+ * // result = { userId: '123', name: 'john' }
922
+ *
923
+ * // Array transformation
924
+ * const dataArray = [
925
+ * { id: '123', userName: 'john' },
926
+ * { id: '456', userName: 'jane' }
927
+ * ];
928
+ * const result = transformData(dataArray, mapping);
929
+ * // result = [
930
+ * // { userId: '123', name: 'john' },
931
+ * // { userId: '456', name: 'jane' }
932
+ * // ]
933
+ * ```
934
+ */
935
+ function transformData(data, fieldMapping) {
936
+ // Handle array of objects
937
+ if (Array.isArray(data)) {
938
+ return data.map(item => transformData(item, fieldMapping));
939
+ }
940
+ // Handle single object
941
+ const result = { ...data };
942
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
943
+ if (sourceField in result) {
944
+ const value = result[sourceField];
945
+ delete result[sourceField];
946
+ result[targetField] = value;
947
+ }
948
+ }
949
+ return result;
950
+ }
951
+ /**
952
+ * Converts a string from PascalCase to camelCase
953
+ * @param str The PascalCase string to convert
954
+ * @returns The camelCase version of the string
955
+ *
956
+ * @example
957
+ * ```typescript
958
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
959
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
960
+ * ```
961
+ */
962
+ function pascalToCamelCase(str) {
963
+ if (!str)
964
+ return str;
965
+ return str.charAt(0).toLowerCase() + str.slice(1);
966
+ }
967
+ /**
968
+ * Converts a string from camelCase to PascalCase
969
+ * @param str The camelCase string to convert
970
+ * @returns The PascalCase version of the string
971
+ *
972
+ * @example
973
+ * ```typescript
974
+ * camelToPascalCase('helloWorld'); // 'HelloWorld'
975
+ * camelToPascalCase('taskAssignmentCriteria'); // 'TaskAssignmentCriteria'
976
+ * ```
977
+ */
978
+ function camelToPascalCase(str) {
979
+ if (!str)
980
+ return str;
981
+ return str.charAt(0).toUpperCase() + str.slice(1);
982
+ }
983
+ /**
984
+ * Generic function to transform object keys using a provided case conversion function
985
+ * @param data The object to transform
986
+ * @param convertCase The function to convert each key
987
+ * @returns A new object with transformed keys
988
+ */
989
+ function transformCaseKeys(data, convertCase) {
990
+ // Handle array of objects
991
+ if (Array.isArray(data)) {
992
+ return data.map(item => {
993
+ // If the array element is a primitive (string, number, etc.), return it as is
994
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
995
+ return item;
996
+ }
997
+ // Only recursively transform if it's actually an object
998
+ return transformCaseKeys(item, convertCase);
999
+ });
1000
+ }
1001
+ const result = {};
1002
+ for (const [key, value] of Object.entries(data)) {
1003
+ const transformedKey = convertCase(key);
1004
+ // Recursively transform nested objects and arrays
1005
+ if (value !== null && typeof value === 'object') {
1006
+ result[transformedKey] = transformCaseKeys(value, convertCase);
1007
+ }
1008
+ else {
1009
+ result[transformedKey] = value;
1010
+ }
1011
+ }
1012
+ return result;
1013
+ }
1014
+ /**
1015
+ * Transforms an object's keys from PascalCase to camelCase
1016
+ * @param data The object with PascalCase keys
1017
+ * @returns A new object with all keys converted to camelCase
1018
+ *
1019
+ * @example
1020
+ * ```typescript
1021
+ * // Simple object
1022
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
1023
+ * // Result: { id: "123", taskName: "Invoice" }
1024
+ *
1025
+ * // Nested object
1026
+ * pascalToCamelCaseKeys({
1027
+ * TaskId: "456",
1028
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
1029
+ * });
1030
+ * // Result: {
1031
+ * // taskId: "456",
1032
+ * // taskDetails: { assignedUser: "John", priority: "High" }
1033
+ * // }
1034
+ *
1035
+ * // Array of objects
1036
+ * pascalToCamelCaseKeys([
1037
+ * { Id: "1", IsComplete: false },
1038
+ * { Id: "2", IsComplete: true }
1039
+ * ]);
1040
+ * // Result: [
1041
+ * // { id: "1", isComplete: false },
1042
+ * // { id: "2", isComplete: true }
1043
+ * // ]
1044
+ * ```
1045
+ */
1046
+ function pascalToCamelCaseKeys(data) {
1047
+ return transformCaseKeys(data, pascalToCamelCase);
1048
+ }
1049
+ /**
1050
+ * Transforms an object's keys from camelCase to PascalCase
1051
+ * @param data The object with camelCase keys
1052
+ * @returns A new object with all keys converted to PascalCase
1053
+ *
1054
+ * @example
1055
+ * ```typescript
1056
+ * // Simple object
1057
+ * camelToPascalCaseKeys({ userId: "789", isActive: true });
1058
+ * // Result: { UserId: "789", IsActive: true }
1059
+ *
1060
+ * // Nested object
1061
+ * camelToPascalCaseKeys({
1062
+ * taskId: "ABC123",
1063
+ * submissionData: { customerName: "XYZ Corp" }
1064
+ * });
1065
+ * // Result: {
1066
+ * // TaskId: "ABC123",
1067
+ * // SubmissionData: { CustomerName: "XYZ Corp" }
1068
+ * // }
1069
+ *
1070
+ * // Array of objects
1071
+ * camelToPascalCaseKeys([
1072
+ * { userId: "u1", roleType: "admin" },
1073
+ * { userId: "u2", roleType: "user" }
1074
+ * ]);
1075
+ * // Result: [
1076
+ * // { UserId: "u1", RoleType: "admin" },
1077
+ * // { UserId: "u2", RoleType: "user" }
1078
+ * // ]
1079
+ * ```
1080
+ */
1081
+ function camelToPascalCaseKeys(data) {
1082
+ return transformCaseKeys(data, camelToPascalCase);
1083
+ }
1084
+ /**
1085
+ * Maps a field value in an object using a provided mapping object.
1086
+ * Returns a new object with the mapped field value.
1087
+ *
1088
+ * @param obj The object to map
1089
+ * @param field The field name to map
1090
+ * @param valueMap The mapping object (from input value to output value)
1091
+ * @returns A new object with the mapped field value
1092
+ *
1093
+ * @example
1094
+ * const statusMap = { 0: 'Unassigned', 1: 'Pending', 2: 'Completed' };
1095
+ * const task = { status: 1, id: 123 };
1096
+ * const mapped = mapFieldValue(task, 'status', statusMap);
1097
+ * // mapped = { status: 'Pending', id: 123 }
1098
+ */
1099
+ function _mapFieldValue(obj, field, valueMap) {
1100
+ const lookupKey = String(obj[field]);
1101
+ return {
1102
+ ...obj,
1103
+ [field]: lookupKey in valueMap
1104
+ ? valueMap[lookupKey]
1105
+ : obj[field],
1106
+ };
1107
+ }
1108
+ /**
1109
+ * General API response transformer with optional field value mapping.
1110
+ *
1111
+ * @param data - The API response data to transform
1112
+ * @param options - Optional mapping options:
1113
+ * - field: The field name to map (optional)
1114
+ * - valueMap: The mapping object for the field (optional)
1115
+ * - transform: A function to further transform the data (optional)
1116
+ * @returns The transformed data, with field value mapped if specified
1117
+ *
1118
+ * @example
1119
+ * // Just transform
1120
+ * const result = applyDataTransforms(data);
1121
+ *
1122
+ * // Map a field value, then transform
1123
+ * const result = applyDataTransforms(data, { field: 'status', valueMap: StatusMap });
1124
+ *
1125
+ * // Map a field value, then apply a custom transform
1126
+ * const result = applyDataTransforms(data, { field: 'status', valueMap: StatusMap, transform: customTransform });
1127
+ */
1128
+ function applyDataTransforms(data, options) {
1129
+ let result = data;
1130
+ if (options?.field && options?.valueMap) {
1131
+ result = _mapFieldValue(result, options.field, options.valueMap);
1132
+ }
1133
+ if (options?.transform) {
1134
+ result = options.transform(result);
1135
+ }
1136
+ return result;
1137
+ }
1138
+ /**
1139
+ * Adds a prefix to specified keys in an object, returning a new object.
1140
+ * Only the provided keys are prefixed; all others are left unchanged.
1141
+ *
1142
+ * @param obj The source object
1143
+ * @param prefix The prefix to add (e.g., '$')
1144
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1145
+ * @returns A new object with specified keys prefixed
1146
+ *
1147
+ * @example
1148
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1149
+ */
1150
+ function addPrefixToKeys(obj, prefix, keys) {
1151
+ const result = {};
1152
+ for (const [key, value] of Object.entries(obj)) {
1153
+ if (keys.includes(key)) {
1154
+ result[`${prefix}${key}`] = value;
1155
+ }
1156
+ else {
1157
+ result[key] = value;
1158
+ }
1159
+ }
1160
+ return result;
1161
+ }
1162
+
1163
+ /**
1164
+ * Constants used throughout the pagination system
1165
+ */
1166
+ /** Maximum number of items that can be requested in a single page */
1167
+ const MAX_PAGE_SIZE = 1000;
1168
+ /** Default page size when jumpToPage is used without specifying pageSize */
1169
+ const DEFAULT_PAGE_SIZE = 50;
1170
+ /** Default field name for items in a paginated response */
1171
+ const DEFAULT_ITEMS_FIELD = 'value';
1172
+ /** Default field name for total count in a paginated response */
1173
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1174
+ /**
1175
+ * Limits the page size to the maximum allowed value
1176
+ * @param pageSize - Requested page size
1177
+ * @returns Limited page size value
1178
+ */
1179
+ function getLimitedPageSize(pageSize) {
1180
+ if (pageSize === undefined || pageSize === null) {
1181
+ return DEFAULT_PAGE_SIZE;
1182
+ }
1183
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1184
+ }
1185
+
1186
+ /**
1187
+ * Helper functions for pagination that can be used across services
1188
+ */
1189
+ class PaginationHelpers {
1190
+ /**
1191
+ * Checks if any pagination parameters are provided
1192
+ *
1193
+ * @param options - The options object to check
1194
+ * @returns True if any pagination parameter is defined, false otherwise
1195
+ */
1196
+ static hasPaginationParameters(options = {}) {
1197
+ const { cursor, pageSize, jumpToPage } = options;
1198
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1199
+ }
1200
+ /**
1201
+ * Parse a pagination cursor string into cursor data
1202
+ */
1203
+ static parseCursor(cursorString) {
1204
+ try {
1205
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1206
+ return cursorData;
1207
+ }
1208
+ catch {
1209
+ throw new Error('Invalid pagination cursor');
1210
+ }
1211
+ }
1212
+ /**
1213
+ * Validates cursor format and structure
1214
+ *
1215
+ * @param paginationOptions - The pagination options containing the cursor
1216
+ * @param paginationType - Optional pagination type to validate against
1217
+ */
1218
+ static validateCursor(paginationOptions, paginationType) {
1219
+ if (paginationOptions.cursor !== undefined) {
1220
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1221
+ throw new Error('cursor must contain a valid cursor string');
1222
+ }
1223
+ try {
1224
+ // Try to parse the cursor to validate it
1225
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1226
+ // If type is provided, validate cursor contains expected type information
1227
+ if (paginationType) {
1228
+ if (!cursorData.type) {
1229
+ throw new Error('Invalid cursor: missing pagination type');
1230
+ }
1231
+ // Check pagination type compatibility
1232
+ if (cursorData.type !== paginationType) {
1233
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1234
+ }
1235
+ }
1236
+ }
1237
+ catch (error) {
1238
+ if (error instanceof Error) {
1239
+ // If it's already our error with specific message, pass it through
1240
+ if (error.message.startsWith('Invalid cursor') ||
1241
+ error.message.startsWith('Pagination type mismatch')) {
1242
+ throw error;
1243
+ }
1244
+ }
1245
+ throw new Error('Invalid pagination cursor format');
1246
+ }
1247
+ }
1248
+ }
1249
+ /**
1250
+ * Comprehensive validation for pagination options
1251
+ *
1252
+ * @param options - The pagination options to validate
1253
+ * @param paginationType - The pagination type these options will be used with
1254
+ * @returns Processed pagination parameters ready for use
1255
+ */
1256
+ static validatePaginationOptions(options, paginationType) {
1257
+ // Validate pageSize
1258
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1259
+ throw new Error('pageSize must be a positive number');
1260
+ }
1261
+ // Validate jumpToPage
1262
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1263
+ throw new Error('jumpToPage must be a positive number');
1264
+ }
1265
+ // Validate cursor
1266
+ PaginationHelpers.validateCursor(options, paginationType);
1267
+ // Validate service compatibility
1268
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1269
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1270
+ }
1271
+ // Get processed parameters
1272
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1273
+ }
1274
+ /**
1275
+ * Convert a unified pagination options to service-specific parameters
1276
+ */
1277
+ static getRequestParameters(options, paginationType) {
1278
+ // Handle jumpToPage
1279
+ if (options.jumpToPage !== undefined) {
1280
+ const jumpToPageOptions = {
1281
+ pageSize: options.pageSize,
1282
+ pageNumber: options.jumpToPage
1283
+ };
1284
+ return filterUndefined(jumpToPageOptions);
1285
+ }
1286
+ // If no cursor is provided, it's a first page request
1287
+ if (!options.cursor) {
1288
+ const firstPageOptions = {
1289
+ pageSize: options.pageSize,
1290
+ // Only set pageNumber for OFFSET pagination
1291
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1292
+ };
1293
+ return filterUndefined(firstPageOptions);
1294
+ }
1295
+ // Parse the cursor
1296
+ try {
1297
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1298
+ const cursorBasedOptions = {
1299
+ pageSize: cursorData.pageSize || options.pageSize,
1300
+ pageNumber: cursorData.pageNumber,
1301
+ continuationToken: cursorData.continuationToken,
1302
+ type: cursorData.type,
1303
+ };
1304
+ return filterUndefined(cursorBasedOptions);
1305
+ }
1306
+ catch {
1307
+ throw new Error('Invalid pagination cursor');
1308
+ }
1309
+ }
1310
+ /**
1311
+ * Helper method for paginated resource retrieval
1312
+ *
1313
+ * @param params - Parameters for pagination
1314
+ * @returns Promise resolving to a paginated result
1315
+ */
1316
+ static async getAllPaginated(params) {
1317
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1318
+ const endpoint = getEndpoint(folderId);
1319
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1320
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1321
+ headers,
1322
+ params: additionalParams,
1323
+ pagination: {
1324
+ paginationType: options.paginationType || PaginationType.OFFSET,
1325
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1326
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1327
+ continuationTokenField: options.continuationTokenField,
1328
+ paginationParams: options.paginationParams
1329
+ }
1330
+ });
1331
+ // Parse items - automatically handle JSON string responses
1332
+ const rawItems = paginatedResponse.items;
1333
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1334
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1335
+ return {
1336
+ ...paginatedResponse,
1337
+ items: transformedItems
1338
+ };
1339
+ }
1340
+ /**
1341
+ * Helper method for non-paginated resource retrieval
1342
+ *
1343
+ * @param params - Parameters for non-paginated resource retrieval
1344
+ * @returns Promise resolving to an object with data and totalCount
1345
+ */
1346
+ static async getAllNonPaginated(params) {
1347
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1348
+ // Set default field names
1349
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1350
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1351
+ // Determine endpoint and headers based on folderId
1352
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1353
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1354
+ // Make the API call based on method
1355
+ let response;
1356
+ if (method === HTTP_METHODS.POST) {
1357
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1358
+ }
1359
+ else {
1360
+ response = await serviceAccess.get(endpoint, {
1361
+ params: additionalParams,
1362
+ headers
1363
+ });
1364
+ }
1365
+ // Extract and transform items from response
1366
+ const rawItems = response.data?.[itemsField];
1367
+ const totalCount = response.data?.[totalCountField];
1368
+ // Parse items - automatically handle JSON string responses
1369
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1370
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1371
+ return {
1372
+ items,
1373
+ totalCount
1374
+ };
1375
+ }
1376
+ /**
1377
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1378
+ *
1379
+ * @param config - Configuration for the getAll operation
1380
+ * @param options - Request options including pagination parameters
1381
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1382
+ */
1383
+ static async getAll(config, options) {
1384
+ const optionsWithDefaults = options || {};
1385
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1386
+ // Determine if pagination is requested
1387
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1388
+ // Process parameters (custom processing if provided, otherwise default)
1389
+ let processedOptions = restOptions;
1390
+ if (config.processParametersFn) {
1391
+ processedOptions = config.processParametersFn(restOptions, folderId);
1392
+ }
1393
+ // Apply ODATA prefix to keys (excluding specified keys)
1394
+ const excludeKeys = config.excludeFromPrefix || [];
1395
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1396
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1397
+ // Default pagination options
1398
+ const paginationOptions = {
1399
+ paginationType: PaginationType.OFFSET,
1400
+ itemsField: DEFAULT_ITEMS_FIELD,
1401
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1402
+ ...config.pagination
1403
+ };
1404
+ // Paginated flow
1405
+ if (isPaginationRequested) {
1406
+ return PaginationHelpers.getAllPaginated({
1407
+ serviceAccess: config.serviceAccess,
1408
+ getEndpoint: config.getEndpoint,
1409
+ folderId,
1410
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1411
+ additionalParams: prefixedOptions,
1412
+ transformFn: config.transformFn,
1413
+ method: config.method,
1414
+ options: {
1415
+ ...paginationOptions,
1416
+ paginationParams: config.pagination?.paginationParams
1417
+ }
1418
+ }); // Type assertion needed due to conditional return
1419
+ }
1420
+ // Non-paginated flow
1421
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1422
+ return PaginationHelpers.getAllNonPaginated({
1423
+ serviceAccess: config.serviceAccess,
1424
+ getAllEndpoint: config.getEndpoint(),
1425
+ getByFolderEndpoint: byFolderEndpoint,
1426
+ folderId,
1427
+ additionalParams: prefixedOptions,
1428
+ transformFn: config.transformFn,
1429
+ method: config.method,
1430
+ options: {
1431
+ itemsField: paginationOptions.itemsField,
1432
+ totalCountField: paginationOptions.totalCountField
1433
+ }
1434
+ });
1435
+ }
1436
+ }
1437
+
1438
+ /**
1439
+ * SDK Internals Registry - Internal registry for SDK instances
1440
+ *
1441
+ * This class is NOT exported in the public API.
1442
+ * It provides a secure way to share SDK internals between
1443
+ * the UiPath class and service classes without exposing them publicly.
1444
+ *
1445
+ * @internal
1446
+ */
1447
+ // Global symbol key to ensure WeakMap is shared across module instances
1448
+ // This prevents issues when core and service modules are bundled separately
1449
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1450
+ // Get or create the global WeakMap store
1451
+ const getGlobalStore = () => {
1452
+ const globalObj = globalThis;
1453
+ if (!globalObj[REGISTRY_KEY]) {
1454
+ globalObj[REGISTRY_KEY] = new WeakMap();
1455
+ }
1456
+ return globalObj[REGISTRY_KEY];
1457
+ };
1458
+ /**
1459
+ * Internal registry for SDK private components.
1460
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1461
+ * garbage collected when the SDK instance is no longer referenced.
1462
+ *
1463
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1464
+ * across separately bundled modules (core, entities, tasks, etc.).
1465
+ *
1466
+ * @internal - Not exported in public API
1467
+ */
1468
+ class SDKInternalsRegistry {
1469
+ // Use global store to ensure sharing across module bundles
1470
+ static get store() {
1471
+ return getGlobalStore();
1472
+ }
1473
+ /**
1474
+ * Register SDK instance internals
1475
+ * Called by UiPath constructor
1476
+ */
1477
+ static set(instance, internals) {
1478
+ this.store.set(instance, internals);
1479
+ }
1480
+ /**
1481
+ * Retrieve SDK instance internals
1482
+ * Called by BaseService constructor
1483
+ */
1484
+ static get(instance) {
1485
+ const internals = this.store.get(instance);
1486
+ if (!internals) {
1487
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1488
+ }
1489
+ return internals;
1490
+ }
1491
+ }
1492
+
1493
+ var _BaseService_apiClient;
1494
+ /**
1495
+ * Base class for all UiPath SDK services.
1496
+ *
1497
+ * Provides common functionality for authentication, configuration, and API communication.
1498
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1499
+ *
1500
+ * This class implements the dependency injection pattern where services receive a configured
1501
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1502
+ * including authentication token management.
1503
+ *
1504
+ * @remarks
1505
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1506
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1507
+ *
1508
+ */
1509
+ class BaseService {
1510
+ /**
1511
+ * Creates a base service instance with dependency injection.
1512
+ *
1513
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1514
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1515
+ * and token management internally.
1516
+ *
1517
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1518
+ * Services receive this via dependency injection in the modular pattern.
1519
+ *
1520
+ * @example
1521
+ * ```typescript
1522
+ * // Services automatically call this via super()
1523
+ * export class EntityService extends BaseService {
1524
+ * constructor(instance: IUiPath) {
1525
+ * super(instance); // Initializes the internal ApiClient
1526
+ * }
1527
+ * }
1528
+ *
1529
+ * // Usage in modular pattern
1530
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1531
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1532
+ *
1533
+ * const sdk = new UiPath(config);
1534
+ * await sdk.initialize();
1535
+ * const entities = new Entities(sdk);
1536
+ * ```
1537
+ */
1538
+ constructor(instance) {
1539
+ // Private field - not visible via Object.keys() or any reflection
1540
+ _BaseService_apiClient.set(this, void 0);
1541
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1542
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1543
+ }
1544
+ /**
1545
+ * Gets a valid authentication token, refreshing if necessary.
1546
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1547
+ *
1548
+ * @returns Promise resolving to a valid access token string
1549
+ * @throws AuthenticationError if no token is available or refresh fails
1550
+ */
1551
+ async getValidAuthToken() {
1552
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1553
+ }
1554
+ /**
1555
+ * Creates a service accessor for pagination helpers
1556
+ * This allows pagination helpers to access protected methods without making them public
1557
+ */
1558
+ createPaginationServiceAccess() {
1559
+ return {
1560
+ get: (path, options) => this.get(path, options || {}),
1561
+ post: (path, body, options) => this.post(path, body, options || {}),
1562
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1563
+ };
1564
+ }
1565
+ async request(method, path, options = {}) {
1566
+ switch (method.toUpperCase()) {
1567
+ case 'GET':
1568
+ return this.get(path, options);
1569
+ case 'POST':
1570
+ return this.post(path, options.body, options);
1571
+ case 'PUT':
1572
+ return this.put(path, options.body, options);
1573
+ case 'PATCH':
1574
+ return this.patch(path, options.body, options);
1575
+ case 'DELETE':
1576
+ return this.delete(path, options);
1577
+ default:
1578
+ throw new Error(`Unsupported HTTP method: ${method}`);
1579
+ }
1580
+ }
1581
+ async requestWithSpec(spec) {
1582
+ if (!spec.method || !spec.url) {
1583
+ throw new Error('Request spec must include method and url');
1584
+ }
1585
+ return this.request(spec.method, spec.url, spec);
1586
+ }
1587
+ async get(path, options = {}) {
1588
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1589
+ return { data: response };
1590
+ }
1591
+ async post(path, data, options = {}) {
1592
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1593
+ return { data: response };
1594
+ }
1595
+ async put(path, data, options = {}) {
1596
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1597
+ return { data: response };
1598
+ }
1599
+ async patch(path, data, options = {}) {
1600
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1601
+ return { data: response };
1602
+ }
1603
+ async delete(path, options = {}) {
1604
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1605
+ return { data: response };
1606
+ }
1607
+ /**
1608
+ * Execute a request with cursor-based pagination
1609
+ */
1610
+ async requestWithPagination(method, path, paginationOptions, options) {
1611
+ const paginationType = options.pagination.paginationType;
1612
+ // Validate and prepare pagination parameters
1613
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1614
+ // Prepare request parameters based on pagination type
1615
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1616
+ // For POST requests, merge pagination params into body; for GET, use query params
1617
+ if (method.toUpperCase() === 'POST') {
1618
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1619
+ options.body = {
1620
+ ...existingBody,
1621
+ ...options.params,
1622
+ ...requestParams
1623
+ };
1624
+ }
1625
+ else {
1626
+ // Merge pagination parameters with existing parameters
1627
+ options.params = {
1628
+ ...options.params,
1629
+ ...requestParams
1630
+ };
1631
+ }
1632
+ // Make the request
1633
+ const response = await this.request(method, path, options);
1634
+ // Extract data from the response and create page result
1635
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1636
+ itemsField: options.pagination.itemsField,
1637
+ totalCountField: options.pagination.totalCountField,
1638
+ continuationTokenField: options.pagination.continuationTokenField
1639
+ });
1640
+ }
1641
+ /**
1642
+ * Validates and prepares pagination parameters from options
1643
+ */
1644
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1645
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1646
+ }
1647
+ /**
1648
+ * Prepares request parameters for pagination based on pagination type
1649
+ */
1650
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1651
+ const requestParams = {};
1652
+ let limitedPageSize;
1653
+ const paginationParams = paginationConfig?.paginationParams;
1654
+ switch (paginationType) {
1655
+ case PaginationType.OFFSET:
1656
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1657
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1658
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1659
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1660
+ requestParams[pageSizeParam] = limitedPageSize;
1661
+ if (params.pageNumber && params.pageNumber > 1) {
1662
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1663
+ }
1664
+ // Include total count for ODATA APIs
1665
+ {
1666
+ requestParams[countParam] = true;
1667
+ }
1668
+ break;
1669
+ case PaginationType.TOKEN:
1670
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1671
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1672
+ if (params.pageSize) {
1673
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1674
+ }
1675
+ if (params.continuationToken) {
1676
+ requestParams[tokenParam] = params.continuationToken;
1677
+ }
1678
+ break;
1679
+ }
1680
+ return requestParams;
1681
+ }
1682
+ /**
1683
+ * Creates a paginated response from API response
1684
+ */
1685
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1686
+ // Extract fields from response
1687
+ const itemsField = fields.itemsField ||
1688
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1689
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1690
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1691
+ // Extract items and metadata
1692
+ const items = response.data[itemsField] || [];
1693
+ const totalCount = response.data[totalCountField];
1694
+ const continuationToken = response.data[continuationTokenField];
1695
+ // Determine if there are more pages
1696
+ const hasMore = this.determineHasMorePages(paginationType, {
1697
+ totalCount,
1698
+ pageSize: params.pageSize,
1699
+ currentPage: params.pageNumber || 1,
1700
+ itemsCount: items.length,
1701
+ continuationToken
1702
+ });
1703
+ // Create and return the page result
1704
+ return PaginationManager.createPaginatedResponse({
1705
+ pageInfo: {
1706
+ hasMore,
1707
+ totalCount,
1708
+ currentPage: params.pageNumber,
1709
+ pageSize: params.pageSize,
1710
+ continuationToken
1711
+ },
1712
+ type: paginationType,
1713
+ }, items);
1714
+ }
1715
+ /**
1716
+ * Determines if there are more pages based on pagination type and metadata
1717
+ */
1718
+ determineHasMorePages(paginationType, info) {
1719
+ switch (paginationType) {
1720
+ case PaginationType.OFFSET:
1721
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1722
+ // If totalCount is available, use it for precise calculation
1723
+ if (info.totalCount !== undefined) {
1724
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1725
+ }
1726
+ // Fallback when totalCount is not available
1727
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1728
+ return info.itemsCount === effectivePageSize;
1729
+ case PaginationType.TOKEN:
1730
+ return !!info.continuationToken;
1731
+ default:
1732
+ return false;
1733
+ }
1734
+ }
1735
+ }
1736
+ _BaseService_apiClient = new WeakMap();
1737
+
1738
+ exports.TaskType = void 0;
1739
+ (function (TaskType) {
1740
+ TaskType["Form"] = "FormTask";
1741
+ TaskType["External"] = "ExternalTask";
1742
+ TaskType["App"] = "AppTask";
1743
+ })(exports.TaskType || (exports.TaskType = {}));
1744
+ exports.TaskPriority = void 0;
1745
+ (function (TaskPriority) {
1746
+ TaskPriority["Low"] = "Low";
1747
+ TaskPriority["Medium"] = "Medium";
1748
+ TaskPriority["High"] = "High";
1749
+ TaskPriority["Critical"] = "Critical";
1750
+ })(exports.TaskPriority || (exports.TaskPriority = {}));
1751
+ exports.TaskStatus = void 0;
1752
+ (function (TaskStatus) {
1753
+ TaskStatus["Unassigned"] = "Unassigned";
1754
+ TaskStatus["Pending"] = "Pending";
1755
+ TaskStatus["Completed"] = "Completed";
1756
+ })(exports.TaskStatus || (exports.TaskStatus = {}));
1757
+ exports.TaskSlaCriteria = void 0;
1758
+ (function (TaskSlaCriteria) {
1759
+ TaskSlaCriteria["TaskCreated"] = "TaskCreated";
1760
+ TaskSlaCriteria["TaskAssigned"] = "TaskAssigned";
1761
+ TaskSlaCriteria["TaskCompleted"] = "TaskCompleted";
1762
+ })(exports.TaskSlaCriteria || (exports.TaskSlaCriteria = {}));
1763
+ exports.TaskSlaStatus = void 0;
1764
+ (function (TaskSlaStatus) {
1765
+ TaskSlaStatus["OverdueLater"] = "OverdueLater";
1766
+ TaskSlaStatus["OverdueSoon"] = "OverdueSoon";
1767
+ TaskSlaStatus["Overdue"] = "Overdue";
1768
+ TaskSlaStatus["CompletedInTime"] = "CompletedInTime";
1769
+ })(exports.TaskSlaStatus || (exports.TaskSlaStatus = {}));
1770
+ exports.TaskSourceName = void 0;
1771
+ (function (TaskSourceName) {
1772
+ TaskSourceName["Agent"] = "Agent";
1773
+ TaskSourceName["Workflow"] = "Workflow";
1774
+ TaskSourceName["Maestro"] = "Maestro";
1775
+ TaskSourceName["Default"] = "Default";
1776
+ })(exports.TaskSourceName || (exports.TaskSourceName = {}));
1777
+ /**
1778
+ * Task activity types
1779
+ */
1780
+ exports.TaskActivityType = void 0;
1781
+ (function (TaskActivityType) {
1782
+ TaskActivityType["Created"] = "Created";
1783
+ TaskActivityType["Assigned"] = "Assigned";
1784
+ TaskActivityType["Reassigned"] = "Reassigned";
1785
+ TaskActivityType["Unassigned"] = "Unassigned";
1786
+ TaskActivityType["Saved"] = "Saved";
1787
+ TaskActivityType["Forwarded"] = "Forwarded";
1788
+ TaskActivityType["Completed"] = "Completed";
1789
+ TaskActivityType["Commented"] = "Commented";
1790
+ TaskActivityType["Deleted"] = "Deleted";
1791
+ TaskActivityType["BulkSaved"] = "BulkSaved";
1792
+ TaskActivityType["BulkCompleted"] = "BulkCompleted";
1793
+ TaskActivityType["FirstOpened"] = "FirstOpened";
1794
+ })(exports.TaskActivityType || (exports.TaskActivityType = {}));
1795
+
1796
+ /**
1797
+ * Creates methods for a task
1798
+ *
1799
+ * @param taskData - The task data (response from API)
1800
+ * @param service - The task service instance
1801
+ * @returns Object containing task methods
1802
+ */
1803
+ function createTaskMethods(taskData, service) {
1804
+ return {
1805
+ async assign(options) {
1806
+ if (!taskData.id)
1807
+ throw new Error('Task ID is undefined');
1808
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
1809
+ ? { taskId: taskData.id, userId: options.userId }
1810
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
1811
+ return service.assign(assignmentOptions);
1812
+ },
1813
+ async reassign(options) {
1814
+ if (!taskData.id)
1815
+ throw new Error('Task ID is undefined');
1816
+ const assignmentOptions = 'userId' in options && options.userId !== undefined
1817
+ ? { taskId: taskData.id, userId: options.userId }
1818
+ : { taskId: taskData.id, userNameOrEmail: options.userNameOrEmail };
1819
+ return service.reassign(assignmentOptions);
1820
+ },
1821
+ async unassign() {
1822
+ if (!taskData.id)
1823
+ throw new Error('Task ID is undefined');
1824
+ return service.unassign(taskData.id);
1825
+ },
1826
+ async complete(options) {
1827
+ if (!taskData.id)
1828
+ throw new Error('Task ID is undefined');
1829
+ const folderId = taskData.folderId;
1830
+ if (!folderId)
1831
+ throw new Error('Folder ID is required');
1832
+ return service.complete({
1833
+ type: options.type,
1834
+ taskId: taskData.id,
1835
+ data: options.data,
1836
+ action: options.action
1837
+ }, folderId);
1838
+ }
1839
+ };
1840
+ }
1841
+ /**
1842
+ * Creates an actionable task by combining API task data with operational methods.
1843
+ *
1844
+ * @param taskData - The task data from API
1845
+ * @param service - The task service instance
1846
+ * @returns A task object with added methods
1847
+ */
1848
+ function createTaskWithMethods(taskData, service) {
1849
+ const methods = createTaskMethods(taskData, service);
1850
+ return Object.assign({}, taskData, methods);
1851
+ }
1852
+
1853
+ /**
1854
+ * Maps numeric TaskStatus values (from API) to TaskStatus enum values.
1855
+ * Extend this file with additional field mappings as needed.
1856
+ */
1857
+ const TaskStatusMap = {
1858
+ 0: exports.TaskStatus.Unassigned,
1859
+ 1: exports.TaskStatus.Pending,
1860
+ 2: exports.TaskStatus.Completed,
1861
+ };
1862
+ // Field mapping for time-related fields to ensure consistent naming
1863
+ const TaskMap = {
1864
+ completionTime: 'completedTime',
1865
+ deletionTime: 'deletedTime',
1866
+ lastModificationTime: 'lastModifiedTime',
1867
+ creationTime: 'createdTime',
1868
+ organizationUnitId: 'folderId'
1869
+ };
1870
+ /**
1871
+ * Default expand parameters
1872
+ */
1873
+ const DEFAULT_TASK_EXPAND = 'AssignedToUser,CreatorUser,LastModifierUser';
1874
+
1875
+ /**
1876
+ * Base path constants for different services
1877
+ */
1878
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1879
+
1880
+ /**
1881
+ * Orchestrator Service Endpoints
1882
+ */
1883
+ /**
1884
+ * Task Service (Action Center) Endpoints
1885
+ */
1886
+ const TASK_ENDPOINTS = {
1887
+ CREATE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CreateTask`,
1888
+ GET_TASK_USERS: (folderId) => `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTaskUsers(organizationUnitId=${folderId})`,
1889
+ GET_TASKS_ACROSS_FOLDERS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFolders`,
1890
+ GET_TASKS_ACROSS_FOLDERS_ADMIN: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.GetTasksAcrossFoldersForAdmin`,
1891
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Tasks(${id})`,
1892
+ ASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.AssignTasks`,
1893
+ REASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.ReassignTasks`,
1894
+ UNASSIGN_TASKS: `${ORCHESTRATOR_BASE}/odata/Tasks/UiPath.Server.Configuration.OData.UnassignTasks`,
1895
+ COMPLETE_FORM_TASK: `${ORCHESTRATOR_BASE}/forms/TaskForms/CompleteTask`,
1896
+ COMPLETE_APP_TASK: `${ORCHESTRATOR_BASE}/tasks/AppTasks/CompleteAppTask`,
1897
+ COMPLETE_GENERIC_TASK: `${ORCHESTRATOR_BASE}/tasks/GenericTasks/CompleteTask`,
1898
+ GET_TASK_FORM_BY_ID: `${ORCHESTRATOR_BASE}/forms/TaskForms/GetTaskFormById`,
1899
+ };
1900
+
1901
+ /**
1902
+ * SDK Telemetry constants
1903
+ */
1904
+ // Connection string placeholder that will be replaced during build
1905
+ 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";
1906
+ // SDK Version placeholder
1907
+ const SDK_VERSION = "1.1.0";
1908
+ const VERSION = "Version";
1909
+ const SERVICE = "Service";
1910
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1911
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1912
+ const CLOUD_URL = "CloudUrl";
1913
+ const CLOUD_CLIENT_ID = "CloudClientId";
1914
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1915
+ const APP_NAME = "ApplicationName";
1916
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1917
+ // Service and logger names
1918
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1919
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1920
+ // Event names
1921
+ const SDK_RUN_EVENT = "Sdk.Run";
1922
+ // Default value for unknown/empty attributes
1923
+ const UNKNOWN = "";
1924
+
1925
+ /**
1926
+ * Log exporter that sends ALL logs as Application Insights custom events
1927
+ */
1928
+ class ApplicationInsightsEventExporter {
1929
+ constructor(connectionString) {
1930
+ this.connectionString = connectionString;
1931
+ }
1932
+ export(logs, resultCallback) {
1933
+ try {
1934
+ logs.forEach(logRecord => {
1935
+ this.sendAsCustomEvent(logRecord);
1936
+ });
1937
+ resultCallback({ code: 0 });
1938
+ }
1939
+ catch (error) {
1940
+ console.debug('Failed to export logs to Application Insights:', error);
1941
+ resultCallback({ code: 2, error });
1942
+ }
1943
+ }
1944
+ shutdown() {
1945
+ return Promise.resolve();
1946
+ }
1947
+ sendAsCustomEvent(logRecord) {
1948
+ // Get event name from body or attributes
1949
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1950
+ const payload = {
1951
+ name: 'Microsoft.ApplicationInsights.Event',
1952
+ time: new Date().toISOString(),
1953
+ iKey: this.extractInstrumentationKey(),
1954
+ data: {
1955
+ baseType: 'EventData',
1956
+ baseData: {
1957
+ ver: 2,
1958
+ name: eventName,
1959
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1960
+ }
1961
+ },
1962
+ tags: {
1963
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1964
+ 'ai.cloud.roleInstance': SDK_VERSION
1965
+ }
1966
+ };
1967
+ this.sendToApplicationInsights(payload);
1968
+ }
1969
+ extractInstrumentationKey() {
1970
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1971
+ return match ? match[1] : '';
1972
+ }
1973
+ convertAttributesToProperties(attributes) {
1974
+ const properties = {};
1975
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1976
+ properties[key] = String(value);
1977
+ });
1978
+ return properties;
1979
+ }
1980
+ async sendToApplicationInsights(payload) {
1981
+ try {
1982
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1983
+ if (!ingestionEndpoint) {
1984
+ console.debug('No ingestion endpoint found in connection string');
1985
+ return;
1986
+ }
1987
+ const url = `${ingestionEndpoint}/v2/track`;
1988
+ const response = await fetch(url, {
1989
+ method: 'POST',
1990
+ headers: {
1991
+ 'Content-Type': 'application/json',
1992
+ },
1993
+ body: JSON.stringify(payload)
1994
+ });
1995
+ if (!response.ok) {
1996
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1997
+ }
1998
+ }
1999
+ catch (error) {
2000
+ console.debug('Error sending event telemetry to Application Insights:', error);
2001
+ }
2002
+ }
2003
+ extractIngestionEndpoint() {
2004
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
2005
+ return match ? match[1] : '';
2006
+ }
2007
+ }
2008
+ /**
2009
+ * Singleton telemetry client
2010
+ */
2011
+ class TelemetryClient {
2012
+ constructor() {
2013
+ this.isInitialized = false;
2014
+ }
2015
+ static getInstance() {
2016
+ if (!TelemetryClient.instance) {
2017
+ TelemetryClient.instance = new TelemetryClient();
2018
+ }
2019
+ return TelemetryClient.instance;
2020
+ }
2021
+ /**
2022
+ * Initialize telemetry
2023
+ */
2024
+ initialize(config) {
2025
+ if (this.isInitialized) {
2026
+ return;
2027
+ }
2028
+ this.isInitialized = true;
2029
+ if (config) {
2030
+ this.telemetryContext = config;
2031
+ }
2032
+ try {
2033
+ const connectionString = this.getConnectionString();
2034
+ if (!connectionString) {
2035
+ return;
2036
+ }
2037
+ this.setupTelemetryProvider(connectionString);
2038
+ }
2039
+ catch (error) {
2040
+ // Silent failure - telemetry errors shouldn't break functionality
2041
+ console.debug('Failed to initialize OpenTelemetry:', error);
2042
+ }
2043
+ }
2044
+ getConnectionString() {
2045
+ const connectionString = CONNECTION_STRING;
2046
+ return connectionString;
2047
+ }
2048
+ setupTelemetryProvider(connectionString) {
2049
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
2050
+ const processor = new sdkLogs.BatchLogRecordProcessor(exporter);
2051
+ this.logProvider = new sdkLogs.LoggerProvider({
2052
+ processors: [processor]
2053
+ });
2054
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
2055
+ }
2056
+ /**
2057
+ * Track a telemetry event
2058
+ */
2059
+ track(eventName, name, extraAttributes = {}) {
2060
+ try {
2061
+ // Skip if logger not initialized
2062
+ if (!this.logger) {
2063
+ return;
2064
+ }
2065
+ const finalDisplayName = name || eventName;
2066
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
2067
+ // Emit as log
2068
+ this.logger.emit({
2069
+ body: finalDisplayName,
2070
+ attributes: attributes,
2071
+ timestamp: Date.now(),
2072
+ });
2073
+ }
2074
+ catch (error) {
2075
+ // Silent failure
2076
+ console.debug('Failed to track telemetry event:', error);
2077
+ }
2078
+ }
2079
+ /**
2080
+ * Get enriched attributes for telemetry events
2081
+ */
2082
+ getEnrichedAttributes(extraAttributes, eventName) {
2083
+ const attributes = {
2084
+ [APP_NAME]: SDK_SERVICE_NAME,
2085
+ [VERSION]: SDK_VERSION,
2086
+ [SERVICE]: eventName,
2087
+ [CLOUD_URL]: this.createCloudUrl(),
2088
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
2089
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
2090
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
2091
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
2092
+ ...extraAttributes,
2093
+ };
2094
+ return attributes;
2095
+ }
2096
+ /**
2097
+ * Create cloud URL from base URL, organization ID, and tenant ID
2098
+ */
2099
+ createCloudUrl() {
2100
+ const baseUrl = this.telemetryContext?.baseUrl;
2101
+ const orgId = this.telemetryContext?.orgName;
2102
+ const tenantId = this.telemetryContext?.tenantName;
2103
+ if (!baseUrl || !orgId || !tenantId) {
2104
+ return UNKNOWN;
2105
+ }
2106
+ return `${baseUrl}/${orgId}/${tenantId}`;
2107
+ }
2108
+ }
2109
+ // Export singleton instance
2110
+ const telemetryClient = TelemetryClient.getInstance();
2111
+
2112
+ /**
2113
+ * SDK Track decorator and function for telemetry
2114
+ */
2115
+ /**
2116
+ * Common tracking logic shared between method and function decorators
2117
+ */
2118
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
2119
+ return function (...args) {
2120
+ // Determine if we should track this call
2121
+ let shouldTrack = true;
2122
+ if (opts.condition !== undefined) {
2123
+ if (typeof opts.condition === 'function') {
2124
+ shouldTrack = opts.condition.apply(this, args);
2125
+ }
2126
+ else {
2127
+ shouldTrack = opts.condition;
2128
+ }
2129
+ }
2130
+ // Track the event if enabled
2131
+ if (shouldTrack) {
2132
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
2133
+ const serviceMethod = typeof nameOrOptions === 'string'
2134
+ ? nameOrOptions
2135
+ : fallbackName;
2136
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
2137
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
2138
+ }
2139
+ // Execute the original function
2140
+ return originalFunction.apply(this, args);
2141
+ };
2142
+ }
2143
+ /**
2144
+ * Track decorator that can be used to automatically track function calls
2145
+ *
2146
+ * Usage:
2147
+ * @track("Service.Method")
2148
+ * function myFunction() { ... }
2149
+ *
2150
+ * @track("Queue.GetAll")
2151
+ * async getAll() { ... }
2152
+ *
2153
+ * @track("Tasks.Create")
2154
+ * async create() { ... }
2155
+ *
2156
+ * @track("Assets.Update", { condition: false })
2157
+ * function myFunction() { ... }
2158
+ *
2159
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
2160
+ * function myFunction() { ... }
2161
+ */
2162
+ function track(nameOrOptions, options) {
2163
+ return function decorator(_target, propertyKey, descriptor) {
2164
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2165
+ if (descriptor && typeof descriptor.value === 'function') {
2166
+ // Method decorator
2167
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2168
+ return descriptor;
2169
+ }
2170
+ // Function decorator
2171
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2172
+ };
2173
+ }
2174
+
2175
+ /**
2176
+ * Service for interacting with UiPath Tasks API
2177
+ */
2178
+ class TaskService extends BaseService {
2179
+ constructor() {
2180
+ super(...arguments);
2181
+ /**
2182
+ * Process parameters for task queries with folder filtering
2183
+ * @param options - The REST API options to process
2184
+ * @param folderId - Optional folder ID to filter by
2185
+ * @returns Processed options with folder filtering applied if needed
2186
+ * @private
2187
+ */
2188
+ this.processTaskParameters = (options, folderId) => {
2189
+ // Add default expand parameters
2190
+ const processedOptions = this.addDefaultExpand(options);
2191
+ if (folderId) {
2192
+ // Create or add to existing filter for folder-specific queries
2193
+ if (processedOptions.filter) {
2194
+ processedOptions.filter = `${processedOptions.filter} and organizationUnitId eq ${folderId}`;
2195
+ }
2196
+ else {
2197
+ processedOptions.filter = `organizationUnitId eq ${folderId}`;
2198
+ }
2199
+ }
2200
+ return processedOptions;
2201
+ };
2202
+ }
2203
+ /**
2204
+ * Creates a new task
2205
+ * @param task - The task to be created
2206
+ * @param folderId - Required folder ID
2207
+ * @returns Promise resolving to the created task
2208
+ *
2209
+ * @example
2210
+ * ```typescript
2211
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2212
+ *
2213
+ * const tasks = new Tasks(sdk);
2214
+ * const task = await tasks.create({
2215
+ * title: "My Task",
2216
+ * priority: TaskPriority.Medium,
2217
+ * data: { key: "value" }
2218
+ * }, 123); // folderId is required
2219
+ * ```
2220
+ */
2221
+ async create(task, folderId) {
2222
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2223
+ const externalTask = {
2224
+ ...task,
2225
+ type: exports.TaskType.External //currently only external task is supported
2226
+ };
2227
+ const response = await this.post(TASK_ENDPOINTS.CREATE_GENERIC_TASK, externalTask, { headers });
2228
+ // Transform time fields for consistency
2229
+ const normalizedData = transformData(response.data, TaskMap);
2230
+ const transformedData = applyDataTransforms(normalizedData, { field: 'status', valueMap: TaskStatusMap });
2231
+ return createTaskWithMethods(transformedData, this);
2232
+ }
2233
+ /**
2234
+ * Gets users in the given folder who have Tasks.View and Tasks.Edit permissions
2235
+ *
2236
+ * The method returns either:
2237
+ * - An array of users (when no pagination parameters are provided)
2238
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2239
+ *
2240
+ * @param folderId - The folder ID to get users from
2241
+ * @param options - Optional query and pagination parameters
2242
+ * @returns Promise resolving to an array of users or paginated result
2243
+ *
2244
+ * @example
2245
+ * ```typescript
2246
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2247
+ *
2248
+ * const tasks = new Tasks(sdk);
2249
+ *
2250
+ * // Standard array return
2251
+ * const users = await tasks.getUsers(123);
2252
+ *
2253
+ * // Get users with filtering
2254
+ * const users = await tasks.getUsers(123, {
2255
+ * filter: "name eq 'abc'"
2256
+ * });
2257
+ *
2258
+ * // First page with pagination
2259
+ * const page1 = await tasks.getUsers(123, { pageSize: 10 });
2260
+ *
2261
+ * // Navigate using cursor
2262
+ * if (page1.hasNextPage) {
2263
+ * const page2 = await tasks.getUsers(123, { cursor: page1.nextCursor });
2264
+ * }
2265
+ *
2266
+ * // Jump to specific page
2267
+ * const page5 = await tasks.getUsers(123, {
2268
+ * jumpToPage: 5,
2269
+ * pageSize: 10
2270
+ * });
2271
+ * ```
2272
+ */
2273
+ async getUsers(folderId, options) {
2274
+ // Transformation function for users
2275
+ const transformUserResponse = (user) => pascalToCamelCaseKeys(user);
2276
+ // Add folderId to options so the centralized helper can handle it properly
2277
+ const optionsWithFolder = { ...options, folderId };
2278
+ return PaginationHelpers.getAll({
2279
+ serviceAccess: this.createPaginationServiceAccess(),
2280
+ getEndpoint: (folderId) => TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use folderId from centralized helper
2281
+ getByFolderEndpoint: TASK_ENDPOINTS.GET_TASK_USERS(folderId), // Use the passed folderId
2282
+ transformFn: transformUserResponse,
2283
+ pagination: {
2284
+ paginationType: PaginationType.OFFSET,
2285
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2286
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2287
+ paginationParams: {
2288
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2289
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2290
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
2291
+ }
2292
+ }
2293
+ }, optionsWithFolder);
2294
+ }
2295
+ /**
2296
+ * Gets tasks across folders with optional filtering and folder scoping
2297
+ *
2298
+ * The method returns either:
2299
+ * - An array of tasks (when no pagination parameters are provided)
2300
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
2301
+ *
2302
+ * @param options - Query options including optional folderId, asTaskAdmin flag and pagination options
2303
+ * @returns Promise resolving to an array of tasks or paginated result
2304
+ *
2305
+ * @example
2306
+ * ```typescript
2307
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2308
+ *
2309
+ * const tasks = new Tasks(sdk);
2310
+ *
2311
+ * // Standard array return
2312
+ * const allTasks = await tasks.getAll();
2313
+ *
2314
+ * // Get tasks within a specific folder
2315
+ * const folderTasks = await tasks.getAll({
2316
+ * folderId: 123
2317
+ * });
2318
+ *
2319
+ * // Get tasks with admin permissions
2320
+ * const adminTasks = await tasks.getAll({
2321
+ * asTaskAdmin: true
2322
+ * });
2323
+ *
2324
+ * // First page with pagination
2325
+ * const page1 = await tasks.getAll({ pageSize: 10 });
2326
+ *
2327
+ * // Navigate using cursor
2328
+ * if (page1.hasNextPage) {
2329
+ * const page2 = await tasks.getAll({ cursor: page1.nextCursor });
2330
+ * }
2331
+ *
2332
+ * // Jump to specific page
2333
+ * const page5 = await tasks.getAll({
2334
+ * jumpToPage: 5,
2335
+ * pageSize: 10
2336
+ * });
2337
+ * ```
2338
+ */
2339
+ async getAll(options) {
2340
+ // Determine which endpoint to use based on asTaskAdmin flag
2341
+ const endpoint = options?.asTaskAdmin
2342
+ ? TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS_ADMIN
2343
+ : TASK_ENDPOINTS.GET_TASKS_ACROSS_FOLDERS;
2344
+ // Transformation function for tasks
2345
+ const transformTaskResponse = (task) => {
2346
+ const transformedTask = transformData(pascalToCamelCaseKeys(task), TaskMap);
2347
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
2348
+ };
2349
+ return PaginationHelpers.getAll({
2350
+ serviceAccess: this.createPaginationServiceAccess(),
2351
+ getEndpoint: () => endpoint,
2352
+ transformFn: transformTaskResponse,
2353
+ processParametersFn: this.processTaskParameters,
2354
+ excludeFromPrefix: ['event'], // Exclude 'event' key from ODATA prefix transformation
2355
+ pagination: {
2356
+ paginationType: PaginationType.OFFSET,
2357
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2358
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2359
+ paginationParams: {
2360
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM, // OData OFFSET parameter
2361
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM, // OData OFFSET parameter
2362
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM // OData OFFSET parameter
2363
+ }
2364
+ }
2365
+ }, options);
2366
+ }
2367
+ /**
2368
+ * Gets a task by ID
2369
+ * IMPORTANT: For form tasks, folderId must be provided.
2370
+ *
2371
+ * @param id - The ID of the task to retrieve
2372
+ * @param options - Optional query parameters
2373
+ * @param folderId - Optional folder ID (REQUIRED for form tasks)
2374
+ * @returns Promise resolving to the task (form tasks will return form-specific data)
2375
+ *
2376
+ * @example
2377
+ * ```typescript
2378
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2379
+ *
2380
+ * const tasks = new Tasks(sdk);
2381
+ *
2382
+ * // Get task by ID
2383
+ * const task = await tasks.getById(123);
2384
+ *
2385
+ * // If the task is a form task, it will automatically return form-specific data
2386
+ * ```
2387
+ */
2388
+ async getById(id, options = {}, folderId) {
2389
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2390
+ // Add default expand parameters
2391
+ const modifiedOptions = this.addDefaultExpand(options);
2392
+ // prefix all keys in options
2393
+ const keysToPrefix = Object.keys(modifiedOptions);
2394
+ const apiOptions = addPrefixToKeys(modifiedOptions, ODATA_PREFIX, keysToPrefix);
2395
+ const response = await this.get(TASK_ENDPOINTS.GET_BY_ID(id), {
2396
+ params: apiOptions,
2397
+ headers
2398
+ });
2399
+ // Transform response from PascalCase to camelCase and normalize time fields
2400
+ const transformedTask = transformData(pascalToCamelCaseKeys(response.data), TaskMap);
2401
+ // Check if this is a form task and get form-specific data if it is
2402
+ if (transformedTask.type === exports.TaskType.Form) {
2403
+ const formOptions = { expandOnFormLayout: true };
2404
+ return this.getFormTaskById(id, folderId || transformedTask.folderId, formOptions);
2405
+ }
2406
+ return createTaskWithMethods(applyDataTransforms(transformedTask, { field: 'status', valueMap: TaskStatusMap }), this);
2407
+ }
2408
+ /**
2409
+ * Assigns tasks to users
2410
+ *
2411
+ * @param taskAssignments - Single task assignment or array of task assignments
2412
+ * @returns Promise resolving to array of task assignment results
2413
+ *
2414
+ * @example
2415
+ * ```typescript
2416
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2417
+ *
2418
+ * const tasks = new Tasks(sdk);
2419
+ *
2420
+ * // Assign a single task to a user by ID
2421
+ * const result = await tasks.assign({
2422
+ * taskId: 123,
2423
+ * userId: 456
2424
+ * });
2425
+ *
2426
+ * // Assign a single task to a user by email
2427
+ * const result = await tasks.assign({
2428
+ * taskId: 123,
2429
+ * userNameOrEmail: "user@example.com"
2430
+ * });
2431
+ *
2432
+ * // Assign multiple tasks
2433
+ * const result = await tasks.assign([
2434
+ * {
2435
+ * taskId: 123,
2436
+ * userId: 456
2437
+ * },
2438
+ * {
2439
+ * taskId: 789,
2440
+ * userNameOrEmail: "user@example.com"
2441
+ * }
2442
+ * ]);
2443
+ * ```
2444
+ */
2445
+ async assign(taskAssignments) {
2446
+ // Normalize input to array
2447
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
2448
+ const options = {
2449
+ taskAssignments: assignmentArray
2450
+ };
2451
+ // Convert options to PascalCase for API
2452
+ const pascalOptions = camelToPascalCaseKeys(options);
2453
+ const response = await this.post(TASK_ENDPOINTS.ASSIGN_TASKS, pascalOptions);
2454
+ // Transform response from PascalCase to camelCase
2455
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2456
+ // Process OData array response - empty array = success, non-empty = error
2457
+ return processODataArrayResponse(transformedResponse, assignmentArray);
2458
+ }
2459
+ /**
2460
+ * Reassigns tasks to new users
2461
+ *
2462
+ * @param taskAssignments - Single task assignment or array of task assignments
2463
+ * @returns Promise resolving to array of task assignment results
2464
+ *
2465
+ * @example
2466
+ * ```typescript
2467
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2468
+ *
2469
+ * const tasks = new Tasks(sdk);
2470
+ *
2471
+ * // Reassign a single task to a user by ID
2472
+ * const result = await tasks.reassign({
2473
+ * taskId: 123,
2474
+ * userId: 456
2475
+ * });
2476
+ *
2477
+ * // Reassign a single task to a user by email
2478
+ * const result = await tasks.reassign({
2479
+ * taskId: 123,
2480
+ * userNameOrEmail: "user@example.com"
2481
+ * });
2482
+ *
2483
+ * // Reassign multiple tasks
2484
+ * const result = await tasks.reassign([
2485
+ * {
2486
+ * taskId: 123,
2487
+ * userId: 456
2488
+ * },
2489
+ * {
2490
+ * taskId: 789,
2491
+ * userNameOrEmail: "user@example.com"
2492
+ * }
2493
+ * ]);
2494
+ * ```
2495
+ */
2496
+ async reassign(taskAssignments) {
2497
+ // Normalize input to array
2498
+ const assignmentArray = Array.isArray(taskAssignments) ? taskAssignments : [taskAssignments];
2499
+ const options = {
2500
+ taskAssignments: assignmentArray
2501
+ };
2502
+ // Convert options to PascalCase for API
2503
+ const pascalOptions = camelToPascalCaseKeys(options);
2504
+ const response = await this.post(TASK_ENDPOINTS.REASSIGN_TASKS, pascalOptions);
2505
+ // Transform response from PascalCase to camelCase
2506
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2507
+ // Process OData array response - empty array = success, non-empty = error
2508
+ return processODataArrayResponse(transformedResponse, assignmentArray);
2509
+ }
2510
+ /**
2511
+ * Unassigns tasks (removes current assignees)
2512
+ *
2513
+ * @param taskIds - Single task ID or array of task IDs to unassign
2514
+ * @returns Promise resolving to array of task assignment results
2515
+ *
2516
+ * @example
2517
+ * ```typescript
2518
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2519
+ *
2520
+ * const tasks = new Tasks(sdk);
2521
+ *
2522
+ * // Unassign a single task
2523
+ * const result = await tasks.unassign(123);
2524
+ *
2525
+ * // Unassign multiple tasks
2526
+ * const result = await tasks.unassign([123, 456, 789]);
2527
+ * ```
2528
+ */
2529
+ async unassign(taskIds) {
2530
+ // Normalize input to array
2531
+ const taskIdArray = Array.isArray(taskIds) ? taskIds : [taskIds];
2532
+ const options = {
2533
+ taskIds: taskIdArray
2534
+ };
2535
+ const response = await this.post(TASK_ENDPOINTS.UNASSIGN_TASKS, options);
2536
+ // Transform response from PascalCase to camelCase
2537
+ const transformedResponse = pascalToCamelCaseKeys(response.data);
2538
+ // Process OData array response - empty array = success, non-empty = error
2539
+ // Return the task IDs that were unassigned
2540
+ return processODataArrayResponse(transformedResponse, taskIdArray.map(id => ({ taskId: id })));
2541
+ }
2542
+ /**
2543
+ * Completes a task with the specified type and data
2544
+ *
2545
+ * @param options - The completion options including task type, taskId, data, and action
2546
+ * @param folderId - Required folder ID
2547
+ * @returns Promise resolving to completion result
2548
+ *
2549
+ * @example
2550
+ * ```typescript
2551
+ * import { Tasks } from '@uipath/uipath-typescript/tasks';
2552
+ *
2553
+ * const tasks = new Tasks(sdk);
2554
+ *
2555
+ * // Complete an app task
2556
+ * await tasks.complete({
2557
+ * type: TaskType.App,
2558
+ * taskId: 456,
2559
+ * data: {},
2560
+ * action: "submit"
2561
+ * }, 123); // folderId is required
2562
+ *
2563
+ * // Complete an external task
2564
+ * await tasks.complete({
2565
+ * type: TaskType.External,
2566
+ * taskId: 789
2567
+ * }, 123); // folderId is required
2568
+ * ```
2569
+ */
2570
+ async complete(options, folderId) {
2571
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2572
+ let endpoint;
2573
+ switch (options.type) {
2574
+ case exports.TaskType.Form:
2575
+ endpoint = TASK_ENDPOINTS.COMPLETE_FORM_TASK;
2576
+ break;
2577
+ case exports.TaskType.App:
2578
+ endpoint = TASK_ENDPOINTS.COMPLETE_APP_TASK;
2579
+ break;
2580
+ default:
2581
+ endpoint = TASK_ENDPOINTS.COMPLETE_GENERIC_TASK;
2582
+ break;
2583
+ }
2584
+ // CompleteAppTask returns 204 no content
2585
+ await this.post(endpoint, options, { headers });
2586
+ // Return success with the request context data
2587
+ return {
2588
+ success: true,
2589
+ data: options
2590
+ };
2591
+ }
2592
+ /**
2593
+ * Gets a form task by ID (private method)
2594
+ *
2595
+ * @param id - The ID of the form task to retrieve
2596
+ * @param folderId - Required folder ID
2597
+ * @param options - Optional query parameters
2598
+ * @returns Promise resolving to the form task
2599
+ */
2600
+ async getFormTaskById(id, folderId, options = {}) {
2601
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2602
+ const response = await this.get(TASK_ENDPOINTS.GET_TASK_FORM_BY_ID, {
2603
+ params: {
2604
+ taskId: id,
2605
+ ...options
2606
+ },
2607
+ headers
2608
+ });
2609
+ const transformedFormTask = transformData(response.data, TaskMap);
2610
+ return createTaskWithMethods(applyDataTransforms(transformedFormTask, { field: 'status', valueMap: TaskStatusMap }), this);
2611
+ }
2612
+ /**
2613
+ * Adds default expand parameters to options
2614
+ * @param options - The options object to add default expand to
2615
+ * @returns Options with default expand parameters added
2616
+ * @private
2617
+ */
2618
+ addDefaultExpand(options) {
2619
+ const processedOptions = { ...options };
2620
+ processedOptions.expand = processedOptions.expand
2621
+ ? `${DEFAULT_TASK_EXPAND},${processedOptions.expand}`
2622
+ : DEFAULT_TASK_EXPAND;
2623
+ return processedOptions;
2624
+ }
2625
+ }
2626
+ __decorate([
2627
+ track('Tasks.Create')
2628
+ ], TaskService.prototype, "create", null);
2629
+ __decorate([
2630
+ track('Tasks.GetUsers')
2631
+ ], TaskService.prototype, "getUsers", null);
2632
+ __decorate([
2633
+ track('Tasks.GetAll')
2634
+ ], TaskService.prototype, "getAll", null);
2635
+ __decorate([
2636
+ track('Tasks.GetById')
2637
+ ], TaskService.prototype, "getById", null);
2638
+ __decorate([
2639
+ track('Tasks.Assign')
2640
+ ], TaskService.prototype, "assign", null);
2641
+ __decorate([
2642
+ track('Tasks.Reassign')
2643
+ ], TaskService.prototype, "reassign", null);
2644
+ __decorate([
2645
+ track('Tasks.Unassign')
2646
+ ], TaskService.prototype, "unassign", null);
2647
+ __decorate([
2648
+ track('Tasks.Complete')
2649
+ ], TaskService.prototype, "complete", null);
2650
+
2651
+ exports.TaskService = TaskService;
2652
+ exports.Tasks = TaskService;
2653
+ exports.createTaskWithMethods = createTaskWithMethods;