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