@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,2721 @@
1
+ import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+
20
+ function __decorate(decorators, target, key, desc) {
21
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
23
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+
27
+ function __classPrivateFieldGet(receiver, state, kind, f) {
28
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
29
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
30
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
31
+ }
32
+
33
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
34
+ if (kind === "m") throw new TypeError("Private method is not writable");
35
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
36
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
37
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
38
+ }
39
+
40
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
41
+ var e = new Error(message);
42
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
43
+ };
44
+
45
+ /**
46
+ * Type guards for error response types
47
+ */
48
+ function isOrchestratorError(error) {
49
+ return typeof error === 'object' &&
50
+ error !== null &&
51
+ 'message' in error &&
52
+ 'errorCode' in error &&
53
+ typeof error.message === 'string' &&
54
+ typeof error.errorCode === 'number';
55
+ }
56
+ function isEntityError(error) {
57
+ return typeof error === 'object' &&
58
+ error !== null &&
59
+ 'error' in error &&
60
+ typeof error.error === 'string';
61
+ }
62
+ function isPimsError(error) {
63
+ return typeof error === 'object' &&
64
+ error !== null &&
65
+ 'type' in error &&
66
+ 'title' in error &&
67
+ 'status' in error &&
68
+ typeof error.type === 'string' &&
69
+ typeof error.title === 'string' &&
70
+ typeof error.status === 'number';
71
+ }
72
+
73
+ /**
74
+ * HTTP status code constants for error handling
75
+ */
76
+ const HttpStatus = {
77
+ // Client errors (4xx)
78
+ BAD_REQUEST: 400,
79
+ UNAUTHORIZED: 401,
80
+ FORBIDDEN: 403,
81
+ NOT_FOUND: 404,
82
+ TOO_MANY_REQUESTS: 429,
83
+ // Server errors (5xx)
84
+ INTERNAL_SERVER_ERROR: 500,
85
+ BAD_GATEWAY: 502,
86
+ SERVICE_UNAVAILABLE: 503,
87
+ GATEWAY_TIMEOUT: 504
88
+ };
89
+ /**
90
+ * Error type constants for consistent error identification
91
+ */
92
+ const ErrorType = {
93
+ AUTHENTICATION: 'AuthenticationError',
94
+ AUTHORIZATION: 'AuthorizationError',
95
+ VALIDATION: 'ValidationError',
96
+ NOT_FOUND: 'NotFoundError',
97
+ RATE_LIMIT: 'RateLimitError',
98
+ SERVER: 'ServerError',
99
+ NETWORK: 'NetworkError'
100
+ };
101
+ /**
102
+ * HTTP header constants for error handling
103
+ */
104
+ const HttpHeaders = {
105
+ X_REQUEST_ID: 'x-request-id'
106
+ };
107
+ /**
108
+ * Standard error message constants
109
+ */
110
+ const ErrorMessages = {
111
+ // Authentication errors
112
+ AUTHENTICATION_FAILED: 'Authentication failed',
113
+ // Authorization errors
114
+ ACCESS_DENIED: 'Access denied',
115
+ // Validation errors
116
+ VALIDATION_FAILED: 'Validation failed',
117
+ // Not found errors
118
+ RESOURCE_NOT_FOUND: 'Resource not found',
119
+ // Rate limit errors
120
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
121
+ // Server errors
122
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
123
+ // Network errors
124
+ NETWORK_ERROR: 'Network error occurred',
125
+ REQUEST_TIMEOUT: 'Request timed out',
126
+ REQUEST_ABORTED: 'Request was aborted',
127
+ };
128
+ /**
129
+ * Error name constants for network error identification
130
+ */
131
+ const ErrorNames = {
132
+ ABORT_ERROR: 'AbortError'};
133
+
134
+ /**
135
+ * Parser for Orchestrator/Task error format
136
+ */
137
+ class OrchestratorErrorParser {
138
+ canParse(errorBody) {
139
+ return isOrchestratorError(errorBody);
140
+ }
141
+ parse(errorBody, response) {
142
+ const error = errorBody;
143
+ return {
144
+ message: error.message,
145
+ code: response?.status?.toString(),
146
+ details: {
147
+ errorCode: error.errorCode,
148
+ traceId: error.traceId,
149
+ originalResponse: error
150
+ },
151
+ requestId: error.traceId
152
+ };
153
+ }
154
+ }
155
+ /**
156
+ * Parser for Entity (Data Fabric) error format
157
+ */
158
+ class EntityErrorParser {
159
+ canParse(errorBody) {
160
+ return isEntityError(errorBody);
161
+ }
162
+ parse(errorBody, response) {
163
+ const error = errorBody;
164
+ return {
165
+ message: error.error,
166
+ code: response?.status?.toString(),
167
+ details: {
168
+ error: error.error,
169
+ traceId: error.traceId,
170
+ originalResponse: error
171
+ },
172
+ requestId: error.traceId
173
+ };
174
+ }
175
+ }
176
+ /**
177
+ * Parser for PIMS error format
178
+ */
179
+ class PimsErrorParser {
180
+ canParse(errorBody) {
181
+ return isPimsError(errorBody);
182
+ }
183
+ parse(errorBody, response) {
184
+ const error = errorBody;
185
+ let message = error.title;
186
+ // If there are validation errors, append them to the message for better visibility
187
+ if (error.errors && Object.keys(error.errors).length > 0) {
188
+ const errorMessages = Object.entries(error.errors)
189
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
190
+ .join('; ');
191
+ message += `. Validation errors: ${errorMessages}`;
192
+ }
193
+ return {
194
+ message,
195
+ code: response?.status?.toString(),
196
+ details: {
197
+ type: error.type,
198
+ title: error.title,
199
+ status: error.status,
200
+ errors: error.errors,
201
+ traceId: error.traceId,
202
+ originalResponse: error
203
+ },
204
+ requestId: error.traceId
205
+ };
206
+ }
207
+ }
208
+ /**
209
+ * Fallback parser for unrecognized formats
210
+ */
211
+ class GenericErrorParser {
212
+ canParse(_errorBody) {
213
+ return true; // Always can parse as last resort
214
+ }
215
+ parse(errorBody, response) {
216
+ // For unknown error formats, just pass through the raw error with fallback message
217
+ const message = response?.statusText || 'An error occurred';
218
+ return {
219
+ message,
220
+ code: response?.status?.toString(),
221
+ details: {
222
+ originalResponse: errorBody
223
+ },
224
+ };
225
+ }
226
+ }
227
+ /**
228
+ * Main error response parser using Chain of Responsibility pattern
229
+ *
230
+ * This parser standardizes error responses from different UiPath services into a
231
+ * consistent format, regardless of the original error structure.
232
+ *
233
+ * Supported formats:
234
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
235
+ * 2. Entity (Data Fabric): { error, traceId }
236
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
237
+ * 4. Generic: Fallback for any other format
238
+ *
239
+ * @example
240
+ * const parser = new ErrorResponseParser();
241
+ * const errorInfo = await parser.parse(response);
242
+ * // errorInfo will have consistent structure regardless of service
243
+ */
244
+ class ErrorResponseParser {
245
+ constructor() {
246
+ this.strategies = [
247
+ new OrchestratorErrorParser(),
248
+ new EntityErrorParser(),
249
+ new PimsErrorParser(),
250
+ new GenericErrorParser() // Must be last
251
+ ];
252
+ }
253
+ /**
254
+ * Parses error response body into standardized format
255
+ * @param response - The HTTP response object
256
+ * @returns Standardized error information
257
+ */
258
+ async parse(response) {
259
+ try {
260
+ const errorBody = await response.json();
261
+ // Find the first strategy that can parse this error format
262
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
263
+ // GenericErrorParser always returns true, so this will never be null
264
+ return strategy.parse(errorBody, response);
265
+ }
266
+ catch {
267
+ // Handle non-JSON responses
268
+ const responseText = await response.text().catch(() => '');
269
+ return {
270
+ message: response.statusText,
271
+ code: response.status.toString(),
272
+ details: {
273
+ parseError: 'Failed to parse error response as JSON',
274
+ responseText
275
+ },
276
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
277
+ };
278
+ }
279
+ }
280
+ }
281
+ // Export singleton instance
282
+ const errorResponseParser = new ErrorResponseParser();
283
+
284
+ /**
285
+ * Base error class for all UiPath SDK errors
286
+ * Extends Error for standard error handling compatibility
287
+ */
288
+ class UiPathError extends Error {
289
+ constructor(type, params) {
290
+ super(params.message);
291
+ this.name = type;
292
+ this.type = type;
293
+ this.statusCode = params.statusCode;
294
+ this.requestId = params.requestId;
295
+ this.timestamp = new Date();
296
+ // Maintains proper stack trace for where our error was thrown
297
+ if (Error.captureStackTrace) {
298
+ Error.captureStackTrace(this, this.constructor);
299
+ }
300
+ }
301
+ /**
302
+ * Returns a clean JSON representation of the error
303
+ */
304
+ toJSON() {
305
+ return {
306
+ type: this.type,
307
+ message: this.message,
308
+ statusCode: this.statusCode,
309
+ requestId: this.requestId,
310
+ timestamp: this.timestamp
311
+ };
312
+ }
313
+ /**
314
+ * Returns detailed debug information including stack trace
315
+ */
316
+ getDebugInfo() {
317
+ return {
318
+ ...this.toJSON(),
319
+ stack: this.stack
320
+ };
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Error thrown when authentication fails (401 errors)
326
+ * Common scenarios:
327
+ * - Invalid credentials
328
+ * - Expired token
329
+ * - Missing authentication
330
+ */
331
+ class AuthenticationError extends UiPathError {
332
+ constructor(params = {}) {
333
+ super(ErrorType.AUTHENTICATION, {
334
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
335
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
336
+ requestId: params.requestId
337
+ });
338
+ }
339
+ }
340
+
341
+ /**
342
+ * Error thrown when authorization fails (403 errors)
343
+ * Common scenarios:
344
+ * - Insufficient permissions
345
+ * - Access denied to resource
346
+ * - Invalid scope
347
+ */
348
+ class AuthorizationError extends UiPathError {
349
+ constructor(params = {}) {
350
+ super(ErrorType.AUTHORIZATION, {
351
+ message: params.message || ErrorMessages.ACCESS_DENIED,
352
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
353
+ requestId: params.requestId
354
+ });
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Error thrown when validation fails (400 errors or client-side validation)
360
+ * Common scenarios:
361
+ * - Invalid input parameters
362
+ * - Missing required fields
363
+ * - Invalid data format
364
+ */
365
+ class ValidationError extends UiPathError {
366
+ constructor(params = {}) {
367
+ super(ErrorType.VALIDATION, {
368
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
369
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
370
+ requestId: params.requestId
371
+ });
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Error thrown when a resource is not found (404 errors)
377
+ * Common scenarios:
378
+ * - Resource doesn't exist
379
+ * - Invalid ID provided
380
+ * - Resource deleted
381
+ */
382
+ class NotFoundError extends UiPathError {
383
+ constructor(params = {}) {
384
+ super(ErrorType.NOT_FOUND, {
385
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
386
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
387
+ requestId: params.requestId
388
+ });
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Error thrown when rate limit is exceeded (429 errors)
394
+ * Common scenarios:
395
+ * - Too many requests in a time window
396
+ * - API throttling
397
+ */
398
+ class RateLimitError extends UiPathError {
399
+ constructor(params = {}) {
400
+ super(ErrorType.RATE_LIMIT, {
401
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
402
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
403
+ requestId: params.requestId
404
+ });
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Error thrown when server encounters an error (5xx errors)
410
+ * Common scenarios:
411
+ * - Internal server error
412
+ * - Service unavailable
413
+ * - Gateway timeout
414
+ */
415
+ class ServerError extends UiPathError {
416
+ constructor(params = {}) {
417
+ super(ErrorType.SERVER, {
418
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
419
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
420
+ requestId: params.requestId
421
+ });
422
+ }
423
+ /**
424
+ * Checks if this is a temporary error that might succeed on retry
425
+ */
426
+ get isRetryable() {
427
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
428
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
429
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Error thrown when network/connection issues occur
435
+ * Common scenarios:
436
+ * - Connection timeout
437
+ * - DNS resolution failure
438
+ * - Network unreachable
439
+ * - Request aborted
440
+ */
441
+ class NetworkError extends UiPathError {
442
+ constructor(params = {}) {
443
+ super(ErrorType.NETWORK, {
444
+ message: params.message || ErrorMessages.NETWORK_ERROR,
445
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
446
+ requestId: params.requestId
447
+ });
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Factory for creating typed errors based on HTTP status codes
453
+ * Follows the Factory pattern for clean error instantiation
454
+ */
455
+ class ErrorFactory {
456
+ /**
457
+ * Creates appropriate error instance based on HTTP status code
458
+ */
459
+ static createFromHttpStatus(statusCode, errorInfo) {
460
+ const { message, requestId } = errorInfo;
461
+ // Map status codes to error types
462
+ switch (statusCode) {
463
+ case HttpStatus.BAD_REQUEST:
464
+ return new ValidationError({ message, statusCode, requestId });
465
+ case HttpStatus.UNAUTHORIZED:
466
+ return new AuthenticationError({ message, statusCode, requestId });
467
+ case HttpStatus.FORBIDDEN:
468
+ return new AuthorizationError({ message, statusCode, requestId });
469
+ case HttpStatus.NOT_FOUND:
470
+ return new NotFoundError({ message, statusCode, requestId });
471
+ case HttpStatus.TOO_MANY_REQUESTS:
472
+ return new RateLimitError({ message, statusCode, requestId });
473
+ default:
474
+ // For 5xx errors or any other status code
475
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
476
+ return new ServerError({ message, statusCode, requestId });
477
+ }
478
+ // For unknown client errors, treat as validation error
479
+ return new ValidationError({
480
+ message: `${message} (HTTP ${statusCode})`,
481
+ statusCode,
482
+ requestId
483
+ });
484
+ }
485
+ }
486
+ /**
487
+ * Creates a NetworkError from a fetch/network error
488
+ */
489
+ static createNetworkError(error) {
490
+ let message = ErrorMessages.NETWORK_ERROR;
491
+ if (error instanceof Error) {
492
+ if (error.name === ErrorNames.ABORT_ERROR) {
493
+ message = ErrorMessages.REQUEST_ABORTED;
494
+ }
495
+ else if (error.message.includes('timeout')) {
496
+ message = ErrorMessages.REQUEST_TIMEOUT;
497
+ }
498
+ else {
499
+ message = error.message;
500
+ }
501
+ }
502
+ return new NetworkError({ message });
503
+ }
504
+ }
505
+
506
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
507
+ /**
508
+ * Content type constants for HTTP requests/responses
509
+ */
510
+ const CONTENT_TYPES = {
511
+ JSON: 'application/json',
512
+ XML: 'application/xml',
513
+ OCTET_STREAM: 'application/octet-stream'
514
+ };
515
+ /**
516
+ * Response type constants for HTTP requests
517
+ */
518
+ const RESPONSE_TYPES = {
519
+ JSON: 'json',
520
+ TEXT: 'text',
521
+ BLOB: 'blob',
522
+ ARRAYBUFFER: 'arraybuffer'
523
+ };
524
+
525
+ class ApiClient {
526
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
527
+ this.defaultHeaders = {};
528
+ this.config = config;
529
+ this.executionContext = executionContext;
530
+ this.clientConfig = clientConfig;
531
+ this.tokenManager = tokenManager;
532
+ }
533
+ setDefaultHeaders(headers) {
534
+ this.defaultHeaders = { ...this.defaultHeaders, ...headers };
535
+ }
536
+ /**
537
+ * Gets a valid authentication token, refreshing if necessary.
538
+ * Used internally for API requests and exposed for services that need manual auth headers.
539
+ *
540
+ * @returns The valid token
541
+ * @throws AuthenticationError if no token available or refresh fails
542
+ */
543
+ async getValidToken() {
544
+ return this.tokenManager.getValidToken();
545
+ }
546
+ async getDefaultHeaders() {
547
+ // Get headers from execution context first
548
+ const contextHeaders = this.executionContext.getHeaders();
549
+ // If Authorization header is already set in context, use that
550
+ if (contextHeaders['Authorization']) {
551
+ return {
552
+ ...contextHeaders,
553
+ 'Content-Type': CONTENT_TYPES.JSON,
554
+ ...this.defaultHeaders,
555
+ ...this.clientConfig.headers
556
+ };
557
+ }
558
+ const token = await this.getValidToken();
559
+ return {
560
+ ...contextHeaders,
561
+ 'Authorization': `Bearer ${token}`,
562
+ 'Content-Type': CONTENT_TYPES.JSON,
563
+ ...this.defaultHeaders,
564
+ ...this.clientConfig.headers
565
+ };
566
+ }
567
+ async request(method, path, options = {}) {
568
+ // Ensure path starts with a forward slash
569
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
570
+ // Construct URL with org and tenant names
571
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
572
+ const headers = {
573
+ ...await this.getDefaultHeaders(),
574
+ ...options.headers
575
+ };
576
+ // Convert params to URLSearchParams
577
+ const searchParams = new URLSearchParams();
578
+ if (options.params) {
579
+ Object.entries(options.params).forEach(([key, value]) => {
580
+ searchParams.append(key, value.toString());
581
+ });
582
+ }
583
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
584
+ try {
585
+ const response = await fetch(fullUrl, {
586
+ method,
587
+ headers,
588
+ body: options.body ? JSON.stringify(options.body) : undefined,
589
+ signal: options.signal
590
+ });
591
+ if (!response.ok) {
592
+ const errorInfo = await errorResponseParser.parse(response);
593
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
594
+ }
595
+ if (response.status === 204) {
596
+ return undefined;
597
+ }
598
+ // Handle blob response type for binary data (e.g., file downloads)
599
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
600
+ const blob = await response.blob();
601
+ return blob;
602
+ }
603
+ // Check if we're expecting XML
604
+ const acceptHeader = headers['Accept'] || headers['accept'];
605
+ if (acceptHeader === CONTENT_TYPES.XML) {
606
+ const text = await response.text();
607
+ return text;
608
+ }
609
+ return response.json();
610
+ }
611
+ catch (error) {
612
+ // If it's already one of our errors, re-throw it
613
+ if (error.type && error.type.includes('Error')) {
614
+ throw error;
615
+ }
616
+ // Otherwise, it's likely a network error
617
+ throw ErrorFactory.createNetworkError(error);
618
+ }
619
+ }
620
+ async get(path, options = {}) {
621
+ return this.request('GET', path, options);
622
+ }
623
+ async post(path, data, options = {}) {
624
+ return this.request('POST', path, { ...options, body: data });
625
+ }
626
+ async put(path, data, options = {}) {
627
+ return this.request('PUT', path, { ...options, body: data });
628
+ }
629
+ async patch(path, data, options = {}) {
630
+ return this.request('PATCH', path, { ...options, body: data });
631
+ }
632
+ async delete(path, options = {}) {
633
+ return this.request('DELETE', path, options);
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Pagination types supported by the SDK
639
+ */
640
+ var PaginationType;
641
+ (function (PaginationType) {
642
+ PaginationType["OFFSET"] = "offset";
643
+ PaginationType["TOKEN"] = "token";
644
+ })(PaginationType || (PaginationType = {}));
645
+
646
+ /**
647
+ * Collection of utility functions for working with objects
648
+ */
649
+ /**
650
+ * Filters out undefined values from an object
651
+ * @param obj The source object
652
+ * @returns A new object without undefined values
653
+ *
654
+ * @example
655
+ * ```typescript
656
+ * // Object with undefined values
657
+ * const options = {
658
+ * name: 'test',
659
+ * count: 5,
660
+ * prefix: undefined,
661
+ * suffix: null
662
+ * };
663
+ * const result = filterUndefined(options);
664
+ * // result = { name: 'test', count: 5, suffix: null }
665
+ * ```
666
+ */
667
+ function filterUndefined(obj) {
668
+ const result = {};
669
+ for (const [key, value] of Object.entries(obj)) {
670
+ if (value !== undefined) {
671
+ result[key] = value;
672
+ }
673
+ }
674
+ return result;
675
+ }
676
+
677
+ /**
678
+ * Utility functions for platform detection
679
+ */
680
+ /**
681
+ * Checks if code is running in a browser environment
682
+ */
683
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
684
+
685
+ /**
686
+ * Base64 encoding/decoding
687
+ */
688
+ /**
689
+ * Encodes a string to base64
690
+ * @param str - The string to encode
691
+ * @returns Base64 encoded string
692
+ */
693
+ function encodeBase64(str) {
694
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
695
+ const encoder = new TextEncoder();
696
+ const data = encoder.encode(str);
697
+ // Convert Uint8Array to base64
698
+ if (isBrowser) {
699
+ // Browser environment
700
+ // Convert Uint8Array to binary string then to base64
701
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
702
+ return btoa(binaryString);
703
+ }
704
+ else {
705
+ // Node.js environment
706
+ return Buffer.from(data).toString('base64');
707
+ }
708
+ }
709
+ /**
710
+ * Decodes a base64 string
711
+ * @param base64 - The base64 string to decode
712
+ * @returns Decoded string
713
+ */
714
+ function decodeBase64(base64) {
715
+ let bytes;
716
+ if (isBrowser) {
717
+ // Browser environment
718
+ const binaryString = atob(base64);
719
+ bytes = new Uint8Array(binaryString.length);
720
+ for (let i = 0; i < binaryString.length; i++) {
721
+ bytes[i] = binaryString.charCodeAt(i);
722
+ }
723
+ }
724
+ else {
725
+ // Node.js environment
726
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
727
+ }
728
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
729
+ const decoder = new TextDecoder();
730
+ return decoder.decode(bytes);
731
+ }
732
+
733
+ /**
734
+ * PaginationManager handles the conversion between uniform cursor-based pagination
735
+ * and the specific pagination type for each service
736
+ */
737
+ class PaginationManager {
738
+ /**
739
+ * Create a pagination cursor for subsequent page requests
740
+ */
741
+ static createCursor({ pageInfo, type }) {
742
+ if (!pageInfo.hasMore) {
743
+ return undefined;
744
+ }
745
+ const cursorData = {
746
+ type,
747
+ pageSize: pageInfo.pageSize,
748
+ };
749
+ switch (type) {
750
+ case PaginationType.OFFSET:
751
+ if (pageInfo.currentPage) {
752
+ cursorData.pageNumber = pageInfo.currentPage + 1;
753
+ }
754
+ break;
755
+ case PaginationType.TOKEN:
756
+ if (pageInfo.continuationToken) {
757
+ cursorData.continuationToken = pageInfo.continuationToken;
758
+ }
759
+ else {
760
+ return undefined; // No continuation token, can't continue
761
+ }
762
+ break;
763
+ }
764
+ return {
765
+ value: encodeBase64(JSON.stringify(cursorData))
766
+ };
767
+ }
768
+ /**
769
+ * Create a paginated response with navigation cursors
770
+ */
771
+ static createPaginatedResponse({ pageInfo, type }, items) {
772
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
773
+ // Create previous page cursor if applicable
774
+ let previousCursor = undefined;
775
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
776
+ const prevCursorData = {
777
+ type,
778
+ pageNumber: pageInfo.currentPage - 1,
779
+ pageSize: pageInfo.pageSize,
780
+ };
781
+ previousCursor = {
782
+ value: encodeBase64(JSON.stringify(prevCursorData))
783
+ };
784
+ }
785
+ // Calculate total pages if we have totalCount and pageSize
786
+ let totalPages = undefined;
787
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
788
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
789
+ }
790
+ // Determine if this pagination type supports page jumping
791
+ const supportsPageJump = type === PaginationType.OFFSET;
792
+ // Create the result object with all fields, then filter out undefined values
793
+ const result = filterUndefined({
794
+ items,
795
+ totalCount: pageInfo.totalCount,
796
+ hasNextPage: pageInfo.hasMore,
797
+ nextCursor: nextCursor,
798
+ previousCursor: previousCursor,
799
+ currentPage: pageInfo.currentPage,
800
+ totalPages,
801
+ supportsPageJump
802
+ });
803
+ return result;
804
+ }
805
+ }
806
+
807
+ /**
808
+ * Creates headers object from key-value pairs
809
+ * @param headersObj - Object containing header key-value pairs
810
+ * @returns Headers object with all values converted to strings
811
+ *
812
+ * @example
813
+ * ```typescript
814
+ * // Single header
815
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
816
+ *
817
+ * // Multiple headers
818
+ * const headers = createHeaders({
819
+ * 'X-UIPATH-FolderKey': '1234567890',
820
+ * 'X-UIPATH-OrganizationUnitId': 123,
821
+ * 'Accept': 'application/json'
822
+ * });
823
+ *
824
+ * // Using constants
825
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
826
+ * const headers = createHeaders({
827
+ * [FOLDER_KEY]: 'abc-123',
828
+ * [FOLDER_ID]: 456
829
+ * });
830
+ *
831
+ * // Empty headers
832
+ * const headers = createHeaders();
833
+ * ```
834
+ */
835
+ function createHeaders(headersObj) {
836
+ const headers = {};
837
+ for (const [key, value] of Object.entries(headersObj)) {
838
+ if (value !== undefined && value !== null) {
839
+ headers[key] = value.toString();
840
+ }
841
+ }
842
+ return headers;
843
+ }
844
+
845
+ /**
846
+ * Common constants used across the SDK
847
+ */
848
+ /**
849
+ * Prefix used for OData query parameters
850
+ */
851
+ const ODATA_PREFIX = '$';
852
+ /**
853
+ * HTTP methods
854
+ */
855
+ const HTTP_METHODS = {
856
+ GET: 'GET',
857
+ POST: 'POST'};
858
+ /**
859
+ * Entity pagination constants for Data Fabric entities
860
+ */
861
+ const ENTITY_PAGINATION = {
862
+ /** Field name for items in entity response */
863
+ ITEMS_FIELD: 'value',
864
+ /** Field name for total count in entity response */
865
+ TOTAL_COUNT_FIELD: 'totalRecordCount'
866
+ };
867
+ /**
868
+ * Choice Set values endpoint pagination constants
869
+ * Note: The API returns items as a JSON string in 'jsonValue' field
870
+ */
871
+ const CHOICESET_VALUES_PAGINATION = {
872
+ /** Field name for items in choice set values response (contains JSON string) */
873
+ ITEMS_FIELD: 'jsonValue',
874
+ /** Field name for total count in choice set values response */
875
+ TOTAL_COUNT_FIELD: 'totalRecordCount'
876
+ };
877
+ /**
878
+ * OData OFFSET pagination parameter names (ODATA-style)
879
+ */
880
+ const ODATA_OFFSET_PARAMS = {
881
+ /** OData page size parameter name */
882
+ PAGE_SIZE_PARAM: '$top',
883
+ /** OData offset parameter name */
884
+ OFFSET_PARAM: '$skip',
885
+ /** OData count parameter name */
886
+ COUNT_PARAM: '$count'
887
+ };
888
+ /**
889
+ * Entity OFFSET pagination parameter names (limit/start style)
890
+ */
891
+ const ENTITY_OFFSET_PARAMS = {
892
+ /** Entity page size parameter name */
893
+ PAGE_SIZE_PARAM: 'limit',
894
+ /** Entity offset parameter name */
895
+ OFFSET_PARAM: 'start',
896
+ /** Entity count parameter (not used) */
897
+ COUNT_PARAM: undefined
898
+ };
899
+ /**
900
+ * Bucket TOKEN pagination parameter names
901
+ */
902
+ const BUCKET_TOKEN_PARAMS = {
903
+ /** Bucket page size parameter name */
904
+ PAGE_SIZE_PARAM: 'takeHint',
905
+ /** Bucket token parameter name */
906
+ TOKEN_PARAM: 'continuationToken'
907
+ };
908
+
909
+ /**
910
+ * Transforms data by mapping fields according to the provided field mapping
911
+ * @param data The source data to transform
912
+ * @param fieldMapping Object mapping source field names to target field names
913
+ * @returns Transformed data with mapped field names
914
+ *
915
+ * @example
916
+ * ```typescript
917
+ * // Single object transformation
918
+ * const data = { id: '123', userName: 'john' };
919
+ * const mapping = { id: 'userId', userName: 'name' };
920
+ * const result = transformData(data, mapping);
921
+ * // result = { userId: '123', name: 'john' }
922
+ *
923
+ * // Array transformation
924
+ * const dataArray = [
925
+ * { id: '123', userName: 'john' },
926
+ * { id: '456', userName: 'jane' }
927
+ * ];
928
+ * const result = transformData(dataArray, mapping);
929
+ * // result = [
930
+ * // { userId: '123', name: 'john' },
931
+ * // { userId: '456', name: 'jane' }
932
+ * // ]
933
+ * ```
934
+ */
935
+ function transformData(data, fieldMapping) {
936
+ // Handle array of objects
937
+ if (Array.isArray(data)) {
938
+ return data.map(item => transformData(item, fieldMapping));
939
+ }
940
+ // Handle single object
941
+ const result = { ...data };
942
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
943
+ if (sourceField in result) {
944
+ const value = result[sourceField];
945
+ delete result[sourceField];
946
+ result[targetField] = value;
947
+ }
948
+ }
949
+ return result;
950
+ }
951
+ /**
952
+ * Converts a string from PascalCase to camelCase
953
+ * @param str The PascalCase string to convert
954
+ * @returns The camelCase version of the string
955
+ *
956
+ * @example
957
+ * ```typescript
958
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
959
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
960
+ * ```
961
+ */
962
+ function pascalToCamelCase(str) {
963
+ if (!str)
964
+ return str;
965
+ return str.charAt(0).toLowerCase() + str.slice(1);
966
+ }
967
+ /**
968
+ * Generic function to transform object keys using a provided case conversion function
969
+ * @param data The object to transform
970
+ * @param convertCase The function to convert each key
971
+ * @returns A new object with transformed keys
972
+ */
973
+ function transformCaseKeys(data, convertCase) {
974
+ // Handle array of objects
975
+ if (Array.isArray(data)) {
976
+ return data.map(item => {
977
+ // If the array element is a primitive (string, number, etc.), return it as is
978
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
979
+ return item;
980
+ }
981
+ // Only recursively transform if it's actually an object
982
+ return transformCaseKeys(item, convertCase);
983
+ });
984
+ }
985
+ const result = {};
986
+ for (const [key, value] of Object.entries(data)) {
987
+ const transformedKey = convertCase(key);
988
+ // Recursively transform nested objects and arrays
989
+ if (value !== null && typeof value === 'object') {
990
+ result[transformedKey] = transformCaseKeys(value, convertCase);
991
+ }
992
+ else {
993
+ result[transformedKey] = value;
994
+ }
995
+ }
996
+ return result;
997
+ }
998
+ /**
999
+ * Transforms an object's keys from PascalCase to camelCase
1000
+ * @param data The object with PascalCase keys
1001
+ * @returns A new object with all keys converted to camelCase
1002
+ *
1003
+ * @example
1004
+ * ```typescript
1005
+ * // Simple object
1006
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
1007
+ * // Result: { id: "123", taskName: "Invoice" }
1008
+ *
1009
+ * // Nested object
1010
+ * pascalToCamelCaseKeys({
1011
+ * TaskId: "456",
1012
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
1013
+ * });
1014
+ * // Result: {
1015
+ * // taskId: "456",
1016
+ * // taskDetails: { assignedUser: "John", priority: "High" }
1017
+ * // }
1018
+ *
1019
+ * // Array of objects
1020
+ * pascalToCamelCaseKeys([
1021
+ * { Id: "1", IsComplete: false },
1022
+ * { Id: "2", IsComplete: true }
1023
+ * ]);
1024
+ * // Result: [
1025
+ * // { id: "1", isComplete: false },
1026
+ * // { id: "2", isComplete: true }
1027
+ * // ]
1028
+ * ```
1029
+ */
1030
+ function pascalToCamelCaseKeys(data) {
1031
+ return transformCaseKeys(data, pascalToCamelCase);
1032
+ }
1033
+ /**
1034
+ * Adds a prefix to specified keys in an object, returning a new object.
1035
+ * Only the provided keys are prefixed; all others are left unchanged.
1036
+ *
1037
+ * @param obj The source object
1038
+ * @param prefix The prefix to add (e.g., '$')
1039
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1040
+ * @returns A new object with specified keys prefixed
1041
+ *
1042
+ * @example
1043
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1044
+ */
1045
+ function addPrefixToKeys(obj, prefix, keys) {
1046
+ const result = {};
1047
+ for (const [key, value] of Object.entries(obj)) {
1048
+ if (keys.includes(key)) {
1049
+ result[`${prefix}${key}`] = value;
1050
+ }
1051
+ else {
1052
+ result[key] = value;
1053
+ }
1054
+ }
1055
+ return result;
1056
+ }
1057
+
1058
+ /**
1059
+ * Constants used throughout the pagination system
1060
+ */
1061
+ /** Maximum number of items that can be requested in a single page */
1062
+ const MAX_PAGE_SIZE = 1000;
1063
+ /** Default page size when jumpToPage is used without specifying pageSize */
1064
+ const DEFAULT_PAGE_SIZE = 50;
1065
+ /** Default field name for items in a paginated response */
1066
+ const DEFAULT_ITEMS_FIELD = 'value';
1067
+ /** Default field name for total count in a paginated response */
1068
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1069
+ /**
1070
+ * Limits the page size to the maximum allowed value
1071
+ * @param pageSize - Requested page size
1072
+ * @returns Limited page size value
1073
+ */
1074
+ function getLimitedPageSize(pageSize) {
1075
+ if (pageSize === undefined || pageSize === null) {
1076
+ return DEFAULT_PAGE_SIZE;
1077
+ }
1078
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1079
+ }
1080
+
1081
+ /**
1082
+ * Helper functions for pagination that can be used across services
1083
+ */
1084
+ class PaginationHelpers {
1085
+ /**
1086
+ * Checks if any pagination parameters are provided
1087
+ *
1088
+ * @param options - The options object to check
1089
+ * @returns True if any pagination parameter is defined, false otherwise
1090
+ */
1091
+ static hasPaginationParameters(options = {}) {
1092
+ const { cursor, pageSize, jumpToPage } = options;
1093
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1094
+ }
1095
+ /**
1096
+ * Parse a pagination cursor string into cursor data
1097
+ */
1098
+ static parseCursor(cursorString) {
1099
+ try {
1100
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1101
+ return cursorData;
1102
+ }
1103
+ catch {
1104
+ throw new Error('Invalid pagination cursor');
1105
+ }
1106
+ }
1107
+ /**
1108
+ * Validates cursor format and structure
1109
+ *
1110
+ * @param paginationOptions - The pagination options containing the cursor
1111
+ * @param paginationType - Optional pagination type to validate against
1112
+ */
1113
+ static validateCursor(paginationOptions, paginationType) {
1114
+ if (paginationOptions.cursor !== undefined) {
1115
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1116
+ throw new Error('cursor must contain a valid cursor string');
1117
+ }
1118
+ try {
1119
+ // Try to parse the cursor to validate it
1120
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1121
+ // If type is provided, validate cursor contains expected type information
1122
+ if (paginationType) {
1123
+ if (!cursorData.type) {
1124
+ throw new Error('Invalid cursor: missing pagination type');
1125
+ }
1126
+ // Check pagination type compatibility
1127
+ if (cursorData.type !== paginationType) {
1128
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1129
+ }
1130
+ }
1131
+ }
1132
+ catch (error) {
1133
+ if (error instanceof Error) {
1134
+ // If it's already our error with specific message, pass it through
1135
+ if (error.message.startsWith('Invalid cursor') ||
1136
+ error.message.startsWith('Pagination type mismatch')) {
1137
+ throw error;
1138
+ }
1139
+ }
1140
+ throw new Error('Invalid pagination cursor format');
1141
+ }
1142
+ }
1143
+ }
1144
+ /**
1145
+ * Comprehensive validation for pagination options
1146
+ *
1147
+ * @param options - The pagination options to validate
1148
+ * @param paginationType - The pagination type these options will be used with
1149
+ * @returns Processed pagination parameters ready for use
1150
+ */
1151
+ static validatePaginationOptions(options, paginationType) {
1152
+ // Validate pageSize
1153
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1154
+ throw new Error('pageSize must be a positive number');
1155
+ }
1156
+ // Validate jumpToPage
1157
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1158
+ throw new Error('jumpToPage must be a positive number');
1159
+ }
1160
+ // Validate cursor
1161
+ PaginationHelpers.validateCursor(options, paginationType);
1162
+ // Validate service compatibility
1163
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1164
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1165
+ }
1166
+ // Get processed parameters
1167
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1168
+ }
1169
+ /**
1170
+ * Convert a unified pagination options to service-specific parameters
1171
+ */
1172
+ static getRequestParameters(options, paginationType) {
1173
+ // Handle jumpToPage
1174
+ if (options.jumpToPage !== undefined) {
1175
+ const jumpToPageOptions = {
1176
+ pageSize: options.pageSize,
1177
+ pageNumber: options.jumpToPage
1178
+ };
1179
+ return filterUndefined(jumpToPageOptions);
1180
+ }
1181
+ // If no cursor is provided, it's a first page request
1182
+ if (!options.cursor) {
1183
+ const firstPageOptions = {
1184
+ pageSize: options.pageSize,
1185
+ // Only set pageNumber for OFFSET pagination
1186
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1187
+ };
1188
+ return filterUndefined(firstPageOptions);
1189
+ }
1190
+ // Parse the cursor
1191
+ try {
1192
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1193
+ const cursorBasedOptions = {
1194
+ pageSize: cursorData.pageSize || options.pageSize,
1195
+ pageNumber: cursorData.pageNumber,
1196
+ continuationToken: cursorData.continuationToken,
1197
+ type: cursorData.type,
1198
+ };
1199
+ return filterUndefined(cursorBasedOptions);
1200
+ }
1201
+ catch {
1202
+ throw new Error('Invalid pagination cursor');
1203
+ }
1204
+ }
1205
+ /**
1206
+ * Helper method for paginated resource retrieval
1207
+ *
1208
+ * @param params - Parameters for pagination
1209
+ * @returns Promise resolving to a paginated result
1210
+ */
1211
+ static async getAllPaginated(params) {
1212
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1213
+ const endpoint = getEndpoint(folderId);
1214
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1215
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1216
+ headers,
1217
+ params: additionalParams,
1218
+ pagination: {
1219
+ paginationType: options.paginationType || PaginationType.OFFSET,
1220
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1221
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1222
+ continuationTokenField: options.continuationTokenField,
1223
+ paginationParams: options.paginationParams
1224
+ }
1225
+ });
1226
+ // Parse items - automatically handle JSON string responses
1227
+ const rawItems = paginatedResponse.items;
1228
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1229
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1230
+ return {
1231
+ ...paginatedResponse,
1232
+ items: transformedItems
1233
+ };
1234
+ }
1235
+ /**
1236
+ * Helper method for non-paginated resource retrieval
1237
+ *
1238
+ * @param params - Parameters for non-paginated resource retrieval
1239
+ * @returns Promise resolving to an object with data and totalCount
1240
+ */
1241
+ static async getAllNonPaginated(params) {
1242
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1243
+ // Set default field names
1244
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1245
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1246
+ // Determine endpoint and headers based on folderId
1247
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1248
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1249
+ // Make the API call based on method
1250
+ let response;
1251
+ if (method === HTTP_METHODS.POST) {
1252
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1253
+ }
1254
+ else {
1255
+ response = await serviceAccess.get(endpoint, {
1256
+ params: additionalParams,
1257
+ headers
1258
+ });
1259
+ }
1260
+ // Extract and transform items from response
1261
+ const rawItems = response.data?.[itemsField];
1262
+ const totalCount = response.data?.[totalCountField];
1263
+ // Parse items - automatically handle JSON string responses
1264
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1265
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1266
+ return {
1267
+ items,
1268
+ totalCount
1269
+ };
1270
+ }
1271
+ /**
1272
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1273
+ *
1274
+ * @param config - Configuration for the getAll operation
1275
+ * @param options - Request options including pagination parameters
1276
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1277
+ */
1278
+ static async getAll(config, options) {
1279
+ const optionsWithDefaults = options || {};
1280
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1281
+ // Determine if pagination is requested
1282
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1283
+ // Process parameters (custom processing if provided, otherwise default)
1284
+ let processedOptions = restOptions;
1285
+ if (config.processParametersFn) {
1286
+ processedOptions = config.processParametersFn(restOptions, folderId);
1287
+ }
1288
+ // Apply ODATA prefix to keys (excluding specified keys)
1289
+ const excludeKeys = config.excludeFromPrefix || [];
1290
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1291
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1292
+ // Default pagination options
1293
+ const paginationOptions = {
1294
+ paginationType: PaginationType.OFFSET,
1295
+ itemsField: DEFAULT_ITEMS_FIELD,
1296
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1297
+ ...config.pagination
1298
+ };
1299
+ // Paginated flow
1300
+ if (isPaginationRequested) {
1301
+ return PaginationHelpers.getAllPaginated({
1302
+ serviceAccess: config.serviceAccess,
1303
+ getEndpoint: config.getEndpoint,
1304
+ folderId,
1305
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1306
+ additionalParams: prefixedOptions,
1307
+ transformFn: config.transformFn,
1308
+ method: config.method,
1309
+ options: {
1310
+ ...paginationOptions,
1311
+ paginationParams: config.pagination?.paginationParams
1312
+ }
1313
+ }); // Type assertion needed due to conditional return
1314
+ }
1315
+ // Non-paginated flow
1316
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1317
+ return PaginationHelpers.getAllNonPaginated({
1318
+ serviceAccess: config.serviceAccess,
1319
+ getAllEndpoint: config.getEndpoint(),
1320
+ getByFolderEndpoint: byFolderEndpoint,
1321
+ folderId,
1322
+ additionalParams: prefixedOptions,
1323
+ transformFn: config.transformFn,
1324
+ method: config.method,
1325
+ options: {
1326
+ itemsField: paginationOptions.itemsField,
1327
+ totalCountField: paginationOptions.totalCountField
1328
+ }
1329
+ });
1330
+ }
1331
+ }
1332
+
1333
+ /**
1334
+ * SDK Internals Registry - Internal registry for SDK instances
1335
+ *
1336
+ * This class is NOT exported in the public API.
1337
+ * It provides a secure way to share SDK internals between
1338
+ * the UiPath class and service classes without exposing them publicly.
1339
+ *
1340
+ * @internal
1341
+ */
1342
+ // Global symbol key to ensure WeakMap is shared across module instances
1343
+ // This prevents issues when core and service modules are bundled separately
1344
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1345
+ // Get or create the global WeakMap store
1346
+ const getGlobalStore = () => {
1347
+ const globalObj = globalThis;
1348
+ if (!globalObj[REGISTRY_KEY]) {
1349
+ globalObj[REGISTRY_KEY] = new WeakMap();
1350
+ }
1351
+ return globalObj[REGISTRY_KEY];
1352
+ };
1353
+ /**
1354
+ * Internal registry for SDK private components.
1355
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1356
+ * garbage collected when the SDK instance is no longer referenced.
1357
+ *
1358
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1359
+ * across separately bundled modules (core, entities, tasks, etc.).
1360
+ *
1361
+ * @internal - Not exported in public API
1362
+ */
1363
+ class SDKInternalsRegistry {
1364
+ // Use global store to ensure sharing across module bundles
1365
+ static get store() {
1366
+ return getGlobalStore();
1367
+ }
1368
+ /**
1369
+ * Register SDK instance internals
1370
+ * Called by UiPath constructor
1371
+ */
1372
+ static set(instance, internals) {
1373
+ this.store.set(instance, internals);
1374
+ }
1375
+ /**
1376
+ * Retrieve SDK instance internals
1377
+ * Called by BaseService constructor
1378
+ */
1379
+ static get(instance) {
1380
+ const internals = this.store.get(instance);
1381
+ if (!internals) {
1382
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1383
+ }
1384
+ return internals;
1385
+ }
1386
+ }
1387
+
1388
+ var _BaseService_apiClient;
1389
+ /**
1390
+ * Base class for all UiPath SDK services.
1391
+ *
1392
+ * Provides common functionality for authentication, configuration, and API communication.
1393
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1394
+ *
1395
+ * This class implements the dependency injection pattern where services receive a configured
1396
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1397
+ * including authentication token management.
1398
+ *
1399
+ * @remarks
1400
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1401
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1402
+ *
1403
+ */
1404
+ class BaseService {
1405
+ /**
1406
+ * Creates a base service instance with dependency injection.
1407
+ *
1408
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1409
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1410
+ * and token management internally.
1411
+ *
1412
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1413
+ * Services receive this via dependency injection in the modular pattern.
1414
+ *
1415
+ * @example
1416
+ * ```typescript
1417
+ * // Services automatically call this via super()
1418
+ * export class EntityService extends BaseService {
1419
+ * constructor(instance: IUiPath) {
1420
+ * super(instance); // Initializes the internal ApiClient
1421
+ * }
1422
+ * }
1423
+ *
1424
+ * // Usage in modular pattern
1425
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1426
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1427
+ *
1428
+ * const sdk = new UiPath(config);
1429
+ * await sdk.initialize();
1430
+ * const entities = new Entities(sdk);
1431
+ * ```
1432
+ */
1433
+ constructor(instance) {
1434
+ // Private field - not visible via Object.keys() or any reflection
1435
+ _BaseService_apiClient.set(this, void 0);
1436
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1437
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1438
+ }
1439
+ /**
1440
+ * Gets a valid authentication token, refreshing if necessary.
1441
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1442
+ *
1443
+ * @returns Promise resolving to a valid access token string
1444
+ * @throws AuthenticationError if no token is available or refresh fails
1445
+ */
1446
+ async getValidAuthToken() {
1447
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1448
+ }
1449
+ /**
1450
+ * Creates a service accessor for pagination helpers
1451
+ * This allows pagination helpers to access protected methods without making them public
1452
+ */
1453
+ createPaginationServiceAccess() {
1454
+ return {
1455
+ get: (path, options) => this.get(path, options || {}),
1456
+ post: (path, body, options) => this.post(path, body, options || {}),
1457
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1458
+ };
1459
+ }
1460
+ async request(method, path, options = {}) {
1461
+ switch (method.toUpperCase()) {
1462
+ case 'GET':
1463
+ return this.get(path, options);
1464
+ case 'POST':
1465
+ return this.post(path, options.body, options);
1466
+ case 'PUT':
1467
+ return this.put(path, options.body, options);
1468
+ case 'PATCH':
1469
+ return this.patch(path, options.body, options);
1470
+ case 'DELETE':
1471
+ return this.delete(path, options);
1472
+ default:
1473
+ throw new Error(`Unsupported HTTP method: ${method}`);
1474
+ }
1475
+ }
1476
+ async requestWithSpec(spec) {
1477
+ if (!spec.method || !spec.url) {
1478
+ throw new Error('Request spec must include method and url');
1479
+ }
1480
+ return this.request(spec.method, spec.url, spec);
1481
+ }
1482
+ async get(path, options = {}) {
1483
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1484
+ return { data: response };
1485
+ }
1486
+ async post(path, data, options = {}) {
1487
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1488
+ return { data: response };
1489
+ }
1490
+ async put(path, data, options = {}) {
1491
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1492
+ return { data: response };
1493
+ }
1494
+ async patch(path, data, options = {}) {
1495
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1496
+ return { data: response };
1497
+ }
1498
+ async delete(path, options = {}) {
1499
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1500
+ return { data: response };
1501
+ }
1502
+ /**
1503
+ * Execute a request with cursor-based pagination
1504
+ */
1505
+ async requestWithPagination(method, path, paginationOptions, options) {
1506
+ const paginationType = options.pagination.paginationType;
1507
+ // Validate and prepare pagination parameters
1508
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1509
+ // Prepare request parameters based on pagination type
1510
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1511
+ // For POST requests, merge pagination params into body; for GET, use query params
1512
+ if (method.toUpperCase() === 'POST') {
1513
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1514
+ options.body = {
1515
+ ...existingBody,
1516
+ ...options.params,
1517
+ ...requestParams
1518
+ };
1519
+ }
1520
+ else {
1521
+ // Merge pagination parameters with existing parameters
1522
+ options.params = {
1523
+ ...options.params,
1524
+ ...requestParams
1525
+ };
1526
+ }
1527
+ // Make the request
1528
+ const response = await this.request(method, path, options);
1529
+ // Extract data from the response and create page result
1530
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1531
+ itemsField: options.pagination.itemsField,
1532
+ totalCountField: options.pagination.totalCountField,
1533
+ continuationTokenField: options.pagination.continuationTokenField
1534
+ });
1535
+ }
1536
+ /**
1537
+ * Validates and prepares pagination parameters from options
1538
+ */
1539
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1540
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1541
+ }
1542
+ /**
1543
+ * Prepares request parameters for pagination based on pagination type
1544
+ */
1545
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1546
+ const requestParams = {};
1547
+ let limitedPageSize;
1548
+ const paginationParams = paginationConfig?.paginationParams;
1549
+ switch (paginationType) {
1550
+ case PaginationType.OFFSET:
1551
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1552
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1553
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1554
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1555
+ requestParams[pageSizeParam] = limitedPageSize;
1556
+ if (params.pageNumber && params.pageNumber > 1) {
1557
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1558
+ }
1559
+ // Include total count for ODATA APIs
1560
+ {
1561
+ requestParams[countParam] = true;
1562
+ }
1563
+ break;
1564
+ case PaginationType.TOKEN:
1565
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1566
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1567
+ if (params.pageSize) {
1568
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1569
+ }
1570
+ if (params.continuationToken) {
1571
+ requestParams[tokenParam] = params.continuationToken;
1572
+ }
1573
+ break;
1574
+ }
1575
+ return requestParams;
1576
+ }
1577
+ /**
1578
+ * Creates a paginated response from API response
1579
+ */
1580
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1581
+ // Extract fields from response
1582
+ const itemsField = fields.itemsField ||
1583
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1584
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1585
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1586
+ // Extract items and metadata
1587
+ const items = response.data[itemsField] || [];
1588
+ const totalCount = response.data[totalCountField];
1589
+ const continuationToken = response.data[continuationTokenField];
1590
+ // Determine if there are more pages
1591
+ const hasMore = this.determineHasMorePages(paginationType, {
1592
+ totalCount,
1593
+ pageSize: params.pageSize,
1594
+ currentPage: params.pageNumber || 1,
1595
+ itemsCount: items.length,
1596
+ continuationToken
1597
+ });
1598
+ // Create and return the page result
1599
+ return PaginationManager.createPaginatedResponse({
1600
+ pageInfo: {
1601
+ hasMore,
1602
+ totalCount,
1603
+ currentPage: params.pageNumber,
1604
+ pageSize: params.pageSize,
1605
+ continuationToken
1606
+ },
1607
+ type: paginationType,
1608
+ }, items);
1609
+ }
1610
+ /**
1611
+ * Determines if there are more pages based on pagination type and metadata
1612
+ */
1613
+ determineHasMorePages(paginationType, info) {
1614
+ switch (paginationType) {
1615
+ case PaginationType.OFFSET:
1616
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1617
+ // If totalCount is available, use it for precise calculation
1618
+ if (info.totalCount !== undefined) {
1619
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1620
+ }
1621
+ // Fallback when totalCount is not available
1622
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1623
+ return info.itemsCount === effectivePageSize;
1624
+ case PaginationType.TOKEN:
1625
+ return !!info.continuationToken;
1626
+ default:
1627
+ return false;
1628
+ }
1629
+ }
1630
+ }
1631
+ _BaseService_apiClient = new WeakMap();
1632
+
1633
+ /**
1634
+ * Creates entity methods that can be attached to entity data
1635
+ *
1636
+ * @param entityData - The entity metadata
1637
+ * @param service - The entity service instance
1638
+ * @returns Object containing entity methods
1639
+ */
1640
+ function createEntityMethods(entityData, service) {
1641
+ return {
1642
+ async insertRecord(data, options) {
1643
+ if (!entityData.id)
1644
+ throw new Error('Entity ID is undefined');
1645
+ return service.insertRecordById(entityData.id, data, options);
1646
+ },
1647
+ async insertRecords(data, options) {
1648
+ if (!entityData.id)
1649
+ throw new Error('Entity ID is undefined');
1650
+ return service.insertRecordsById(entityData.id, data, options);
1651
+ },
1652
+ async updateRecords(data, options) {
1653
+ if (!entityData.id)
1654
+ throw new Error('Entity ID is undefined');
1655
+ return service.updateRecordsById(entityData.id, data, options);
1656
+ },
1657
+ async deleteRecords(recordIds, options) {
1658
+ if (!entityData.id)
1659
+ throw new Error('Entity ID is undefined');
1660
+ return service.deleteRecordsById(entityData.id, recordIds, options);
1661
+ },
1662
+ async getAllRecords(options) {
1663
+ if (!entityData.id)
1664
+ throw new Error('Entity ID is undefined');
1665
+ return service.getAllRecords(entityData.id, options);
1666
+ },
1667
+ async getRecord(recordId, options) {
1668
+ if (!entityData.id)
1669
+ throw new Error('Entity ID is undefined');
1670
+ if (!recordId)
1671
+ throw new Error('Record ID is undefined');
1672
+ return service.getRecordById(entityData.id, recordId, options);
1673
+ },
1674
+ async downloadAttachment(recordId, fieldName) {
1675
+ if (!entityData.name)
1676
+ throw new Error('Entity name is undefined');
1677
+ return service.downloadAttachment({
1678
+ entityName: entityData.name,
1679
+ recordId,
1680
+ fieldName
1681
+ });
1682
+ },
1683
+ async insert(data, options) {
1684
+ return this.insertRecord(data, options);
1685
+ },
1686
+ async batchInsert(data, options) {
1687
+ return this.insertRecords(data, options);
1688
+ },
1689
+ async update(data, options) {
1690
+ return this.updateRecords(data, options);
1691
+ },
1692
+ async delete(recordIds, options) {
1693
+ return this.deleteRecords(recordIds, options);
1694
+ },
1695
+ async getRecords(options) {
1696
+ return this.getAllRecords(options);
1697
+ }
1698
+ };
1699
+ }
1700
+ /**
1701
+ * Creates an actionable entity metadata by combining entity with operational methods
1702
+ *
1703
+ * @param entityData - Entity metadata
1704
+ * @param service - The entity service instance
1705
+ * @returns Entity metadata with added methods
1706
+ */
1707
+ function createEntityWithMethods(entityData, service) {
1708
+ const methods = createEntityMethods(entityData, service);
1709
+ return Object.assign({}, entityData, methods);
1710
+ }
1711
+
1712
+ /**
1713
+ * Base path constants for different services
1714
+ */
1715
+ const DATAFABRIC_BASE = 'datafabric_';
1716
+
1717
+ /**
1718
+ * Data Fabric Service Endpoints
1719
+ */
1720
+ /**
1721
+ * Data Fabric Entity Service Endpoints
1722
+ */
1723
+ const DATA_FABRIC_ENDPOINTS = {
1724
+ ENTITY: {
1725
+ GET_ALL: `${DATAFABRIC_BASE}/api/Entity`,
1726
+ GET_ENTITY_RECORDS: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/read`,
1727
+ GET_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/Entity/${entityId}`,
1728
+ GET_RECORD_BY_ID: (entityId, recordId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/read/${recordId}`,
1729
+ INSERT_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/insert`,
1730
+ BATCH_INSERT_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/insert-batch`,
1731
+ UPDATE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/update-batch`,
1732
+ DELETE_BY_ID: (entityId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${entityId}/delete-batch`,
1733
+ DOWNLOAD_ATTACHMENT: (entityName, recordId, fieldName) => `${DATAFABRIC_BASE}/api/Attachment/${entityName}/${recordId}/${fieldName}`,
1734
+ },
1735
+ CHOICESETS: {
1736
+ GET_ALL: `${DATAFABRIC_BASE}/api/Entity/choiceset`,
1737
+ GET_BY_ID: (choiceSetId) => `${DATAFABRIC_BASE}/api/EntityService/entity/${choiceSetId}/query_expansion`,
1738
+ },
1739
+ };
1740
+
1741
+ /**
1742
+ * Creates query parameters object from key-value pairs, filtering out undefined values
1743
+ * @param paramsObj - Object containing parameter key-value pairs
1744
+ * @returns Parameters object with undefined values filtered out
1745
+ *
1746
+ * @example
1747
+ * ```typescript
1748
+ * // Entity service parameters
1749
+ * const params = createParams({
1750
+ * start: 0,
1751
+ * limit: 10,
1752
+ * expansionLevel: 1
1753
+ * });
1754
+ *
1755
+ * // With optional/undefined values (automatically filtered)
1756
+ * const params = createParams({
1757
+ * start: options.start, // Could be undefined
1758
+ * limit: options.limit, // Could be undefined
1759
+ * expansionLevel: options.expansionLevel // Could be undefined
1760
+ * });
1761
+ *
1762
+ * // Empty params
1763
+ * const params = createParams();
1764
+ * ```
1765
+ */
1766
+ function createParams(paramsObj = {}) {
1767
+ const params = {};
1768
+ for (const [key, value] of Object.entries(paramsObj)) {
1769
+ if (value !== undefined && value !== null) {
1770
+ params[key] = value;
1771
+ }
1772
+ }
1773
+ return params;
1774
+ }
1775
+
1776
+ /**
1777
+ * Entity field type names
1778
+ */
1779
+ var EntityFieldDataType;
1780
+ (function (EntityFieldDataType) {
1781
+ EntityFieldDataType["UUID"] = "UUID";
1782
+ EntityFieldDataType["STRING"] = "STRING";
1783
+ EntityFieldDataType["INTEGER"] = "INTEGER";
1784
+ EntityFieldDataType["DATETIME"] = "DATETIME";
1785
+ EntityFieldDataType["DATETIME_WITH_TZ"] = "DATETIME_WITH_TZ";
1786
+ EntityFieldDataType["DECIMAL"] = "DECIMAL";
1787
+ EntityFieldDataType["FLOAT"] = "FLOAT";
1788
+ EntityFieldDataType["DOUBLE"] = "DOUBLE";
1789
+ EntityFieldDataType["DATE"] = "DATE";
1790
+ EntityFieldDataType["BOOLEAN"] = "BOOLEAN";
1791
+ EntityFieldDataType["BIG_INTEGER"] = "BIG_INTEGER";
1792
+ EntityFieldDataType["MULTILINE_TEXT"] = "MULTILINE_TEXT";
1793
+ })(EntityFieldDataType || (EntityFieldDataType = {}));
1794
+ /**
1795
+ * Entity type enum
1796
+ */
1797
+ var EntityType;
1798
+ (function (EntityType) {
1799
+ EntityType["Entity"] = "Entity";
1800
+ EntityType["ChoiceSet"] = "ChoiceSet";
1801
+ EntityType["InternalEntity"] = "InternalEntity";
1802
+ EntityType["SystemEntity"] = "SystemEntity";
1803
+ })(EntityType || (EntityType = {}));
1804
+ /**
1805
+ * Reference types for fields
1806
+ */
1807
+ var ReferenceType;
1808
+ (function (ReferenceType) {
1809
+ ReferenceType["ManyToOne"] = "ManyToOne";
1810
+ })(ReferenceType || (ReferenceType = {}));
1811
+ /**
1812
+ * Field display types
1813
+ */
1814
+ var FieldDisplayType;
1815
+ (function (FieldDisplayType) {
1816
+ FieldDisplayType["Basic"] = "Basic";
1817
+ FieldDisplayType["Relationship"] = "Relationship";
1818
+ FieldDisplayType["File"] = "File";
1819
+ FieldDisplayType["ChoiceSetSingle"] = "ChoiceSetSingle";
1820
+ FieldDisplayType["ChoiceSetMultiple"] = "ChoiceSetMultiple";
1821
+ FieldDisplayType["AutoNumber"] = "AutoNumber";
1822
+ })(FieldDisplayType || (FieldDisplayType = {}));
1823
+ /**
1824
+ * Data direction type for external fields
1825
+ */
1826
+ var DataDirectionType;
1827
+ (function (DataDirectionType) {
1828
+ DataDirectionType["ReadOnly"] = "ReadOnly";
1829
+ DataDirectionType["ReadAndWrite"] = "ReadAndWrite";
1830
+ })(DataDirectionType || (DataDirectionType = {}));
1831
+ /**
1832
+ * Join type for source join criteria
1833
+ */
1834
+ var JoinType;
1835
+ (function (JoinType) {
1836
+ JoinType["LeftJoin"] = "LeftJoin";
1837
+ })(JoinType || (JoinType = {}));
1838
+
1839
+ /**
1840
+ * Entity field data types (SQL types from API)
1841
+ */
1842
+ var SqlFieldType;
1843
+ (function (SqlFieldType) {
1844
+ SqlFieldType["UNIQUEIDENTIFIER"] = "UNIQUEIDENTIFIER";
1845
+ SqlFieldType["NVARCHAR"] = "NVARCHAR";
1846
+ SqlFieldType["INT"] = "INT";
1847
+ SqlFieldType["DATETIME2"] = "DATETIME2";
1848
+ SqlFieldType["DATETIMEOFFSET"] = "DATETIMEOFFSET";
1849
+ SqlFieldType["FLOAT"] = "FLOAT";
1850
+ SqlFieldType["REAL"] = "REAL";
1851
+ SqlFieldType["BIGINT"] = "BIGINT";
1852
+ SqlFieldType["DATE"] = "DATE";
1853
+ SqlFieldType["BIT"] = "BIT";
1854
+ SqlFieldType["DECIMAL"] = "DECIMAL";
1855
+ SqlFieldType["MULTILINE"] = "MULTILINE";
1856
+ })(SqlFieldType || (SqlFieldType = {}));
1857
+ /**
1858
+ * Maps fields for Entities
1859
+ */
1860
+ const EntityMap = {
1861
+ createTime: 'createdTime',
1862
+ updateTime: 'updatedTime',
1863
+ sqlType: 'fieldDataType',
1864
+ fieldDefinition: 'fieldMetaData'
1865
+ };
1866
+ /**
1867
+ * Maps SQL field types to friendly display names
1868
+ */
1869
+ const EntityFieldTypeMap = {
1870
+ [SqlFieldType.UNIQUEIDENTIFIER]: EntityFieldDataType.UUID,
1871
+ [SqlFieldType.NVARCHAR]: EntityFieldDataType.STRING,
1872
+ [SqlFieldType.INT]: EntityFieldDataType.INTEGER,
1873
+ [SqlFieldType.DATETIME2]: EntityFieldDataType.DATETIME,
1874
+ [SqlFieldType.DATETIMEOFFSET]: EntityFieldDataType.DATETIME_WITH_TZ,
1875
+ [SqlFieldType.FLOAT]: EntityFieldDataType.FLOAT,
1876
+ [SqlFieldType.REAL]: EntityFieldDataType.DOUBLE,
1877
+ [SqlFieldType.BIGINT]: EntityFieldDataType.BIG_INTEGER,
1878
+ [SqlFieldType.DATE]: EntityFieldDataType.DATE,
1879
+ [SqlFieldType.BIT]: EntityFieldDataType.BOOLEAN,
1880
+ [SqlFieldType.DECIMAL]: EntityFieldDataType.DECIMAL,
1881
+ [SqlFieldType.MULTILINE]: EntityFieldDataType.MULTILINE_TEXT
1882
+ };
1883
+
1884
+ /**
1885
+ * SDK Telemetry constants
1886
+ */
1887
+ // Connection string placeholder that will be replaced during build
1888
+ 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";
1889
+ // SDK Version placeholder
1890
+ const SDK_VERSION = "1.1.0";
1891
+ const VERSION = "Version";
1892
+ const SERVICE = "Service";
1893
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1894
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1895
+ const CLOUD_URL = "CloudUrl";
1896
+ const CLOUD_CLIENT_ID = "CloudClientId";
1897
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1898
+ const APP_NAME = "ApplicationName";
1899
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1900
+ // Service and logger names
1901
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1902
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1903
+ // Event names
1904
+ const SDK_RUN_EVENT = "Sdk.Run";
1905
+ // Default value for unknown/empty attributes
1906
+ const UNKNOWN = "";
1907
+
1908
+ /**
1909
+ * Log exporter that sends ALL logs as Application Insights custom events
1910
+ */
1911
+ class ApplicationInsightsEventExporter {
1912
+ constructor(connectionString) {
1913
+ this.connectionString = connectionString;
1914
+ }
1915
+ export(logs, resultCallback) {
1916
+ try {
1917
+ logs.forEach(logRecord => {
1918
+ this.sendAsCustomEvent(logRecord);
1919
+ });
1920
+ resultCallback({ code: 0 });
1921
+ }
1922
+ catch (error) {
1923
+ console.debug('Failed to export logs to Application Insights:', error);
1924
+ resultCallback({ code: 2, error });
1925
+ }
1926
+ }
1927
+ shutdown() {
1928
+ return Promise.resolve();
1929
+ }
1930
+ sendAsCustomEvent(logRecord) {
1931
+ // Get event name from body or attributes
1932
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1933
+ const payload = {
1934
+ name: 'Microsoft.ApplicationInsights.Event',
1935
+ time: new Date().toISOString(),
1936
+ iKey: this.extractInstrumentationKey(),
1937
+ data: {
1938
+ baseType: 'EventData',
1939
+ baseData: {
1940
+ ver: 2,
1941
+ name: eventName,
1942
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1943
+ }
1944
+ },
1945
+ tags: {
1946
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1947
+ 'ai.cloud.roleInstance': SDK_VERSION
1948
+ }
1949
+ };
1950
+ this.sendToApplicationInsights(payload);
1951
+ }
1952
+ extractInstrumentationKey() {
1953
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1954
+ return match ? match[1] : '';
1955
+ }
1956
+ convertAttributesToProperties(attributes) {
1957
+ const properties = {};
1958
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1959
+ properties[key] = String(value);
1960
+ });
1961
+ return properties;
1962
+ }
1963
+ async sendToApplicationInsights(payload) {
1964
+ try {
1965
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1966
+ if (!ingestionEndpoint) {
1967
+ console.debug('No ingestion endpoint found in connection string');
1968
+ return;
1969
+ }
1970
+ const url = `${ingestionEndpoint}/v2/track`;
1971
+ const response = await fetch(url, {
1972
+ method: 'POST',
1973
+ headers: {
1974
+ 'Content-Type': 'application/json',
1975
+ },
1976
+ body: JSON.stringify(payload)
1977
+ });
1978
+ if (!response.ok) {
1979
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1980
+ }
1981
+ }
1982
+ catch (error) {
1983
+ console.debug('Error sending event telemetry to Application Insights:', error);
1984
+ }
1985
+ }
1986
+ extractIngestionEndpoint() {
1987
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1988
+ return match ? match[1] : '';
1989
+ }
1990
+ }
1991
+ /**
1992
+ * Singleton telemetry client
1993
+ */
1994
+ class TelemetryClient {
1995
+ constructor() {
1996
+ this.isInitialized = false;
1997
+ }
1998
+ static getInstance() {
1999
+ if (!TelemetryClient.instance) {
2000
+ TelemetryClient.instance = new TelemetryClient();
2001
+ }
2002
+ return TelemetryClient.instance;
2003
+ }
2004
+ /**
2005
+ * Initialize telemetry
2006
+ */
2007
+ initialize(config) {
2008
+ if (this.isInitialized) {
2009
+ return;
2010
+ }
2011
+ this.isInitialized = true;
2012
+ if (config) {
2013
+ this.telemetryContext = config;
2014
+ }
2015
+ try {
2016
+ const connectionString = this.getConnectionString();
2017
+ if (!connectionString) {
2018
+ return;
2019
+ }
2020
+ this.setupTelemetryProvider(connectionString);
2021
+ }
2022
+ catch (error) {
2023
+ // Silent failure - telemetry errors shouldn't break functionality
2024
+ console.debug('Failed to initialize OpenTelemetry:', error);
2025
+ }
2026
+ }
2027
+ getConnectionString() {
2028
+ const connectionString = CONNECTION_STRING;
2029
+ return connectionString;
2030
+ }
2031
+ setupTelemetryProvider(connectionString) {
2032
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
2033
+ const processor = new BatchLogRecordProcessor(exporter);
2034
+ this.logProvider = new LoggerProvider({
2035
+ processors: [processor]
2036
+ });
2037
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
2038
+ }
2039
+ /**
2040
+ * Track a telemetry event
2041
+ */
2042
+ track(eventName, name, extraAttributes = {}) {
2043
+ try {
2044
+ // Skip if logger not initialized
2045
+ if (!this.logger) {
2046
+ return;
2047
+ }
2048
+ const finalDisplayName = name || eventName;
2049
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
2050
+ // Emit as log
2051
+ this.logger.emit({
2052
+ body: finalDisplayName,
2053
+ attributes: attributes,
2054
+ timestamp: Date.now(),
2055
+ });
2056
+ }
2057
+ catch (error) {
2058
+ // Silent failure
2059
+ console.debug('Failed to track telemetry event:', error);
2060
+ }
2061
+ }
2062
+ /**
2063
+ * Get enriched attributes for telemetry events
2064
+ */
2065
+ getEnrichedAttributes(extraAttributes, eventName) {
2066
+ const attributes = {
2067
+ [APP_NAME]: SDK_SERVICE_NAME,
2068
+ [VERSION]: SDK_VERSION,
2069
+ [SERVICE]: eventName,
2070
+ [CLOUD_URL]: this.createCloudUrl(),
2071
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
2072
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
2073
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
2074
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
2075
+ ...extraAttributes,
2076
+ };
2077
+ return attributes;
2078
+ }
2079
+ /**
2080
+ * Create cloud URL from base URL, organization ID, and tenant ID
2081
+ */
2082
+ createCloudUrl() {
2083
+ const baseUrl = this.telemetryContext?.baseUrl;
2084
+ const orgId = this.telemetryContext?.orgName;
2085
+ const tenantId = this.telemetryContext?.tenantName;
2086
+ if (!baseUrl || !orgId || !tenantId) {
2087
+ return UNKNOWN;
2088
+ }
2089
+ return `${baseUrl}/${orgId}/${tenantId}`;
2090
+ }
2091
+ }
2092
+ // Export singleton instance
2093
+ const telemetryClient = TelemetryClient.getInstance();
2094
+
2095
+ /**
2096
+ * SDK Track decorator and function for telemetry
2097
+ */
2098
+ /**
2099
+ * Common tracking logic shared between method and function decorators
2100
+ */
2101
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
2102
+ return function (...args) {
2103
+ // Determine if we should track this call
2104
+ let shouldTrack = true;
2105
+ if (opts.condition !== undefined) {
2106
+ if (typeof opts.condition === 'function') {
2107
+ shouldTrack = opts.condition.apply(this, args);
2108
+ }
2109
+ else {
2110
+ shouldTrack = opts.condition;
2111
+ }
2112
+ }
2113
+ // Track the event if enabled
2114
+ if (shouldTrack) {
2115
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
2116
+ const serviceMethod = typeof nameOrOptions === 'string'
2117
+ ? nameOrOptions
2118
+ : fallbackName;
2119
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
2120
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
2121
+ }
2122
+ // Execute the original function
2123
+ return originalFunction.apply(this, args);
2124
+ };
2125
+ }
2126
+ /**
2127
+ * Track decorator that can be used to automatically track function calls
2128
+ *
2129
+ * Usage:
2130
+ * @track("Service.Method")
2131
+ * function myFunction() { ... }
2132
+ *
2133
+ * @track("Queue.GetAll")
2134
+ * async getAll() { ... }
2135
+ *
2136
+ * @track("Tasks.Create")
2137
+ * async create() { ... }
2138
+ *
2139
+ * @track("Assets.Update", { condition: false })
2140
+ * function myFunction() { ... }
2141
+ *
2142
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
2143
+ * function myFunction() { ... }
2144
+ */
2145
+ function track(nameOrOptions, options) {
2146
+ return function decorator(_target, propertyKey, descriptor) {
2147
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2148
+ if (descriptor && typeof descriptor.value === 'function') {
2149
+ // Method decorator
2150
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2151
+ return descriptor;
2152
+ }
2153
+ // Function decorator
2154
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2155
+ };
2156
+ }
2157
+
2158
+ /**
2159
+ * Service for interacting with the Data Fabric Entity API
2160
+ */
2161
+ class EntityService extends BaseService {
2162
+ /**
2163
+ * Gets entity metadata by entity ID with attached operation methods
2164
+ *
2165
+ * @param id - UUID of the entity
2166
+ * @returns Promise resolving to entity metadata with schema information and operation methods
2167
+ *
2168
+ * @example
2169
+ * ```typescript
2170
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2171
+ *
2172
+ * const entities = new Entities(sdk);
2173
+ * const entity = await entities.getById("<entityId>");
2174
+ *
2175
+ * // Call operations directly on the entity
2176
+ * const records = await entity.getAllRecords();
2177
+ *
2178
+ * // Insert a single record
2179
+ * const insertResult = await entity.insertRecord({ name: "John", age: 30 });
2180
+ *
2181
+ * // Or batch insert multiple records
2182
+ * const batchResult = await entity.insertRecords([
2183
+ * { name: "Jane", age: 25 },
2184
+ * { name: "Bob", age: 35 }
2185
+ * ]);
2186
+ * ```
2187
+ */
2188
+ async getById(id) {
2189
+ // Get entity metadata
2190
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_BY_ID(id));
2191
+ // Apply EntityMap transformations
2192
+ const metadata = transformData(response.data, EntityMap);
2193
+ // Transform metadata with field mappers
2194
+ this.applyFieldMappings(metadata);
2195
+ // Return the entity metadata with methods attached
2196
+ return createEntityWithMethods(metadata, this);
2197
+ }
2198
+ /**
2199
+ * Gets entity records by entity ID
2200
+ *
2201
+ * @param entityId - UUID of the entity
2202
+ * @param options - Query options including expansionLevel and pagination options
2203
+ * @returns Promise resolving to an array of entity records or paginated response
2204
+ *
2205
+ * @example
2206
+ * ```typescript
2207
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2208
+ *
2209
+ * const entities = new Entities(sdk);
2210
+ *
2211
+ * // Basic usage (non-paginated)
2212
+ * const records = await entities.getAllRecords("<entityId>");
2213
+ *
2214
+ * // With expansion level
2215
+ * const records = await entities.getAllRecords("<entityId>", {
2216
+ * expansionLevel: 1
2217
+ * });
2218
+ *
2219
+ * // With pagination
2220
+ * const paginatedResponse = await entities.getAllRecords("<entityId>", {
2221
+ * pageSize: 50,
2222
+ * expansionLevel: 1
2223
+ * });
2224
+ *
2225
+ * // Navigate to next page
2226
+ * const nextPage = await entities.getAllRecords("<entityId>", {
2227
+ * cursor: paginatedResponse.nextCursor,
2228
+ * expansionLevel: 1
2229
+ * });
2230
+ * ```
2231
+ */
2232
+ async getAllRecords(entityId, options) {
2233
+ return PaginationHelpers.getAll({
2234
+ serviceAccess: this.createPaginationServiceAccess(),
2235
+ getEndpoint: () => DATA_FABRIC_ENDPOINTS.ENTITY.GET_ENTITY_RECORDS(entityId),
2236
+ pagination: {
2237
+ paginationType: PaginationType.OFFSET,
2238
+ itemsField: ENTITY_PAGINATION.ITEMS_FIELD,
2239
+ totalCountField: ENTITY_PAGINATION.TOTAL_COUNT_FIELD,
2240
+ paginationParams: {
2241
+ pageSizeParam: ENTITY_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2242
+ offsetParam: ENTITY_OFFSET_PARAMS.OFFSET_PARAM,
2243
+ countParam: ENTITY_OFFSET_PARAMS.COUNT_PARAM
2244
+ }
2245
+ },
2246
+ excludeFromPrefix: ['expansionLevel'] // Don't add ODATA prefix to expansionLevel
2247
+ }, options);
2248
+ }
2249
+ /**
2250
+ * Gets a single entity record by entity ID and record ID
2251
+ *
2252
+ * @param entityId - UUID of the entity
2253
+ * @param recordId - UUID of the record
2254
+ * @param options - Query options including expansionLevel
2255
+ * @returns Promise resolving to the entity record
2256
+ *
2257
+ * @example
2258
+ * ```typescript
2259
+ * // Basic usage
2260
+ * const record = await sdk.entities.getRecordById(<entityId>, <recordId>);
2261
+ *
2262
+ * // With expansion level
2263
+ * const record = await sdk.entities.getRecordById(<entityId>, <recordId>, {
2264
+ * expansionLevel: 1
2265
+ * });
2266
+ * ```
2267
+ */
2268
+ async getRecordById(entityId, recordId, options = {}) {
2269
+ const params = createParams({
2270
+ expansionLevel: options.expansionLevel
2271
+ });
2272
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_RECORD_BY_ID(entityId, recordId), { params });
2273
+ // Convert PascalCase response to camelCase
2274
+ const camelResponse = pascalToCamelCaseKeys(response.data);
2275
+ // Apply EntityMap transformations
2276
+ const transformedResponse = transformData(camelResponse, EntityMap);
2277
+ return transformedResponse;
2278
+ }
2279
+ /**
2280
+ * Inserts a single record into an entity by entity ID
2281
+ *
2282
+ * @param entityId - UUID of the entity
2283
+ * @param data - Record to insert
2284
+ * @param options - Insert options
2285
+ * @returns Promise resolving to the inserted record with generated record ID
2286
+ *
2287
+ * @example
2288
+ * ```typescript
2289
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2290
+ *
2291
+ * const entities = new Entities(sdk);
2292
+ *
2293
+ * // Basic usage
2294
+ * const result = await entities.insertRecordById("<entityId>", { name: "John", age: 30 });
2295
+ *
2296
+ * // With options
2297
+ * const result = await entities.insertRecordById("<entityId>", { name: "John", age: 30 }, {
2298
+ * expansionLevel: 1
2299
+ * });
2300
+ * ```
2301
+ */
2302
+ async insertRecordById(id, data, options = {}) {
2303
+ const params = createParams({
2304
+ expansionLevel: options.expansionLevel
2305
+ });
2306
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.INSERT_BY_ID(id), data, {
2307
+ params,
2308
+ ...options
2309
+ });
2310
+ // Convert PascalCase response to camelCase
2311
+ const camelResponse = pascalToCamelCaseKeys(response.data);
2312
+ return camelResponse;
2313
+ }
2314
+ /**
2315
+ * Inserts data into an entity by entity ID using batch insert
2316
+ *
2317
+ * @param entityId - UUID of the entity
2318
+ * @param data - Array of records to insert
2319
+ * @param options - Insert options
2320
+ * @returns Promise resolving to insert response
2321
+ *
2322
+ * @example
2323
+ * ```typescript
2324
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2325
+ *
2326
+ * const entities = new Entities(sdk);
2327
+ *
2328
+ * // Basic usage
2329
+ * const result = await entities.insertRecordsById("<entityId>", [
2330
+ * { name: "John", age: 30 },
2331
+ * { name: "Jane", age: 25 }
2332
+ * ]);
2333
+ *
2334
+ * // With options
2335
+ * const result = await entities.insertRecordsById("<entityId>", [
2336
+ * { name: "John", age: 30 },
2337
+ * { name: "Jane", age: 25 }
2338
+ * ], {
2339
+ * expansionLevel: 1,
2340
+ * failOnFirst: true
2341
+ * });
2342
+ * ```
2343
+ */
2344
+ async insertRecordsById(id, data, options = {}) {
2345
+ const params = createParams({
2346
+ expansionLevel: options.expansionLevel,
2347
+ failOnFirst: options.failOnFirst
2348
+ });
2349
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.BATCH_INSERT_BY_ID(id), data, {
2350
+ params,
2351
+ ...options
2352
+ });
2353
+ // Convert PascalCase response to camelCase
2354
+ const camelResponse = pascalToCamelCaseKeys(response.data);
2355
+ return camelResponse;
2356
+ }
2357
+ /**
2358
+ * Updates data in an entity by entity ID
2359
+ *
2360
+ * @param entityId - UUID of the entity
2361
+ * @param data - Array of records to update. Each record MUST contain the record Id,
2362
+ * otherwise the update will fail.
2363
+ * @param options - Update options
2364
+ * @returns Promise resolving to update response
2365
+ *
2366
+ * @example
2367
+ * ```typescript
2368
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2369
+ *
2370
+ * const entities = new Entities(sdk);
2371
+ *
2372
+ * // Basic usage
2373
+ * const result = await entities.updateRecordsById("<entityId>", [
2374
+ * { Id: "123", name: "John Updated", age: 31 },
2375
+ * { Id: "456", name: "Jane Updated", age: 26 }
2376
+ * ]);
2377
+ *
2378
+ * // With options
2379
+ * const result = await entities.updateRecordsById("<entityId>", [
2380
+ * { Id: "123", name: "John Updated", age: 31 },
2381
+ * { Id: "456", name: "Jane Updated", age: 26 }
2382
+ * ], {
2383
+ * expansionLevel: 1,
2384
+ * failOnFirst: true
2385
+ * });
2386
+ * ```
2387
+ */
2388
+ async updateRecordsById(id, data, options = {}) {
2389
+ const params = createParams({
2390
+ expansionLevel: options.expansionLevel,
2391
+ failOnFirst: options.failOnFirst
2392
+ });
2393
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPDATE_BY_ID(id), data, {
2394
+ params,
2395
+ ...options
2396
+ });
2397
+ // Convert PascalCase response to camelCase
2398
+ const camelResponse = pascalToCamelCaseKeys(response.data);
2399
+ return camelResponse;
2400
+ }
2401
+ /**
2402
+ * Deletes data from an entity by entity ID
2403
+ *
2404
+ * @param entityId - UUID of the entity
2405
+ * @param recordIds - Array of record UUIDs to delete
2406
+ * @param options - Delete options
2407
+ * @returns Promise resolving to delete response
2408
+ *
2409
+ * @example
2410
+ * ```typescript
2411
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2412
+ *
2413
+ * const entities = new Entities(sdk);
2414
+ *
2415
+ * // Basic usage
2416
+ * const result = await entities.deleteRecordsById("<entityId>", [
2417
+ * "<recordId-1>", "<recordId-2>"
2418
+ * ]);
2419
+ * ```
2420
+ */
2421
+ async deleteRecordsById(id, recordIds, options = {}) {
2422
+ const params = createParams({
2423
+ failOnFirst: options.failOnFirst
2424
+ });
2425
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_BY_ID(id), recordIds, {
2426
+ params,
2427
+ ...options
2428
+ });
2429
+ // Convert PascalCase response to camelCase
2430
+ const camelResponse = pascalToCamelCaseKeys(response.data);
2431
+ return camelResponse;
2432
+ }
2433
+ /**
2434
+ * Gets all entities in the system
2435
+ *
2436
+ * @returns Promise resolving to an array of entity metadata
2437
+ *
2438
+ * @example
2439
+ * ```typescript
2440
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2441
+ *
2442
+ * const entities = new Entities(sdk);
2443
+ *
2444
+ * // Get all entities
2445
+ * const allEntities = await entities.getAll();
2446
+ *
2447
+ * // Call operations on an entity
2448
+ * const records = await allEntities[0].getAllRecords();
2449
+ * ```
2450
+ */
2451
+ async getAll() {
2452
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_ALL);
2453
+ // Apply transformations
2454
+ const entities = response.data.map(entity => {
2455
+ // Transform each entity
2456
+ const metadata = transformData(entity, EntityMap);
2457
+ this.applyFieldMappings(metadata);
2458
+ // Attach entity methods
2459
+ return createEntityWithMethods(metadata, this);
2460
+ });
2461
+ return entities;
2462
+ }
2463
+ /**
2464
+ * Downloads an attachment from an entity record field
2465
+ *
2466
+ * @param options - Options containing entityName, recordId, and fieldName
2467
+ * @returns Promise resolving to Blob containing the file content
2468
+ *
2469
+ * @example
2470
+ * ```typescript
2471
+ * import { Entities } from '@uipath/uipath-typescript/entities';
2472
+ *
2473
+ * const entities = new Entities(sdk);
2474
+ *
2475
+ * // Download attachment for a specific record and field
2476
+ * const blob = await entities.downloadAttachment({
2477
+ * entityName: 'Invoice',
2478
+ * recordId: '<record-uuid>',
2479
+ * fieldName: 'Documents'
2480
+ * });
2481
+ */
2482
+ async downloadAttachment(options) {
2483
+ const { entityName, recordId, fieldName } = options;
2484
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.DOWNLOAD_ATTACHMENT(entityName, recordId, fieldName), {
2485
+ responseType: RESPONSE_TYPES.BLOB
2486
+ });
2487
+ return response.data;
2488
+ }
2489
+ /**
2490
+ * @hidden
2491
+ * @deprecated Use {@link getAllRecords} instead.
2492
+ */
2493
+ async getRecordsById(entityId, options) {
2494
+ return this.getAllRecords(entityId, options);
2495
+ }
2496
+ /**
2497
+ * @hidden
2498
+ * @deprecated Use {@link insertRecordById} instead.
2499
+ */
2500
+ async insertById(id, data, options = {}) {
2501
+ return this.insertRecordById(id, data, options);
2502
+ }
2503
+ /**
2504
+ * @hidden
2505
+ * @deprecated Use {@link insertRecordsById} instead.
2506
+ */
2507
+ async batchInsertById(id, data, options = {}) {
2508
+ return this.insertRecordsById(id, data, options);
2509
+ }
2510
+ /**
2511
+ * @hidden
2512
+ * @deprecated Use {@link updateRecordsById} instead.
2513
+ */
2514
+ async updateById(id, data, options = {}) {
2515
+ return this.updateRecordsById(id, data, options);
2516
+ }
2517
+ /**
2518
+ * @hidden
2519
+ * @deprecated Use {@link deleteRecordsById} instead.
2520
+ */
2521
+ async deleteById(id, recordIds, options = {}) {
2522
+ return this.deleteRecordsById(id, recordIds, options);
2523
+ }
2524
+ /**
2525
+ * Orchestrates all field mapping transformations
2526
+ *
2527
+ * @param metadata - Entity metadata to transform
2528
+ * @private
2529
+ */
2530
+ applyFieldMappings(metadata) {
2531
+ this.mapFieldTypes(metadata);
2532
+ this.mapExternalFields(metadata);
2533
+ }
2534
+ /**
2535
+ * Maps SQL field types to friendly EntityFieldTypes
2536
+ *
2537
+ * @param metadata - Entity metadata with fields
2538
+ * @private
2539
+ */
2540
+ mapFieldTypes(metadata) {
2541
+ if (!metadata.fields?.length)
2542
+ return;
2543
+ metadata.fields = metadata.fields.map(field => {
2544
+ // Rename sqlType to fieldDataType
2545
+ let transformedField = transformData(field, EntityMap);
2546
+ // Map SQL field type to friendly name
2547
+ if (transformedField.fieldDataType?.name) {
2548
+ const sqlTypeName = transformedField.fieldDataType.name;
2549
+ if (EntityFieldTypeMap[sqlTypeName]) {
2550
+ transformedField.fieldDataType.name = EntityFieldTypeMap[sqlTypeName];
2551
+ }
2552
+ }
2553
+ this.transformNestedReferences(transformedField);
2554
+ return transformedField;
2555
+ });
2556
+ }
2557
+ /**
2558
+ * Transforms nested reference objects in field metadata
2559
+ */
2560
+ transformNestedReferences(field) {
2561
+ if (field.referenceEntity) {
2562
+ field.referenceEntity = transformData(field.referenceEntity, EntityMap);
2563
+ }
2564
+ if (field.referenceChoiceSet) {
2565
+ field.referenceChoiceSet = transformData(field.referenceChoiceSet, EntityMap);
2566
+ }
2567
+ if (field.referenceField?.definition) {
2568
+ field.referenceField.definition = transformData(field.referenceField.definition, EntityMap);
2569
+ }
2570
+ }
2571
+ /**
2572
+ * Maps external field names to consistent naming
2573
+ *
2574
+ * @param metadata - Entity metadata with externalFields
2575
+ * @private
2576
+ */
2577
+ mapExternalFields(metadata) {
2578
+ if (!metadata.externalFields?.length)
2579
+ return;
2580
+ metadata.externalFields = metadata.externalFields.map(externalSource => {
2581
+ if (externalSource.fields?.length) {
2582
+ externalSource.fields = externalSource.fields.map(field => {
2583
+ const transformedField = transformData(field, EntityMap);
2584
+ if (transformedField.fieldMetaData) {
2585
+ transformedField.fieldMetaData = transformData(transformedField.fieldMetaData, EntityMap);
2586
+ this.transformNestedReferences(transformedField.fieldMetaData);
2587
+ }
2588
+ return transformedField;
2589
+ });
2590
+ }
2591
+ return externalSource;
2592
+ });
2593
+ }
2594
+ }
2595
+ __decorate([
2596
+ track('Entities.GetById')
2597
+ ], EntityService.prototype, "getById", null);
2598
+ __decorate([
2599
+ track('Entities.GetAllRecords')
2600
+ ], EntityService.prototype, "getAllRecords", null);
2601
+ __decorate([
2602
+ track('Entities.GetRecordById')
2603
+ ], EntityService.prototype, "getRecordById", null);
2604
+ __decorate([
2605
+ track('Entities.InsertRecordById')
2606
+ ], EntityService.prototype, "insertRecordById", null);
2607
+ __decorate([
2608
+ track('Entities.InsertRecordsById')
2609
+ ], EntityService.prototype, "insertRecordsById", null);
2610
+ __decorate([
2611
+ track('Entities.UpdateRecordsById')
2612
+ ], EntityService.prototype, "updateRecordsById", null);
2613
+ __decorate([
2614
+ track('Entities.DeleteRecordsById')
2615
+ ], EntityService.prototype, "deleteRecordsById", null);
2616
+ __decorate([
2617
+ track('Entities.GetAll')
2618
+ ], EntityService.prototype, "getAll", null);
2619
+ __decorate([
2620
+ track('Entities.DownloadAttachment')
2621
+ ], EntityService.prototype, "downloadAttachment", null);
2622
+
2623
+ class ChoiceSetService extends BaseService {
2624
+ /**
2625
+ * Gets all choice sets in the system
2626
+ *
2627
+ * @returns Promise resolving to an array of choice set metadata
2628
+ *
2629
+ * @example
2630
+ * ```typescript
2631
+ * import { ChoiceSets } from '@uipath/uipath-typescript/entities';
2632
+ *
2633
+ * const choiceSets = new ChoiceSets(sdk);
2634
+ *
2635
+ * // Get all choice sets
2636
+ * const allChoiceSets = await choiceSets.getAll();
2637
+ *
2638
+ * // Iterate through choice sets
2639
+ * allChoiceSets.forEach(choiceSet => {
2640
+ * console.log(`ChoiceSet: ${choiceSet.displayName} (${choiceSet.name})`);
2641
+ * console.log(`Description: ${choiceSet.description}`);
2642
+ * });
2643
+ * ```
2644
+ */
2645
+ async getAll() {
2646
+ const rawResponse = await this.get(DATA_FABRIC_ENDPOINTS.CHOICESETS.GET_ALL);
2647
+ // Transform field names
2648
+ const data = rawResponse.data || [];
2649
+ return data.map(choiceSet => transformData(choiceSet, EntityMap));
2650
+ }
2651
+ /**
2652
+ * Gets choice set values by choice set ID with optional pagination
2653
+ *
2654
+ * The method returns either:
2655
+ * - A NonPaginatedResponse with items array (when no pagination parameters are provided)
2656
+ * - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
2657
+ *
2658
+ * @param choiceSetId - UUID of the choice set
2659
+ * @param options - Pagination options
2660
+ * @returns Promise resolving to choice set values or paginated result
2661
+ *
2662
+ * @example
2663
+ * ```typescript
2664
+ * import { ChoiceSets } from '@uipath/uipath-typescript/choicesets';
2665
+ *
2666
+ * const choiceSets = new ChoiceSets(sdk);
2667
+ *
2668
+ * // First, get the choice set ID using getAll()
2669
+ * const allChoiceSets = await choiceSets.getAll();
2670
+ * const expenseTypes = allChoiceSets.find(cs => cs.name === 'ExpenseTypes');
2671
+ * const choiceSetId = expenseTypes.id;
2672
+ *
2673
+ * // Get all values (non-paginated)
2674
+ * const values = await choiceSets.getById(choiceSetId);
2675
+ *
2676
+ * // Iterate through choice set values
2677
+ * for (const value of values.items) {
2678
+ * console.log(`Value: ${value.displayName} (${value.name})`);
2679
+ * }
2680
+ *
2681
+ * // First page with pagination
2682
+ * const page1 = await choiceSets.getById(choiceSetId, { pageSize: 10 });
2683
+ *
2684
+ * // Navigate using cursor
2685
+ * if (page1.hasNextPage) {
2686
+ * const page2 = await choiceSets.getById(choiceSetId, { cursor: page1.nextCursor });
2687
+ * }
2688
+ * ```
2689
+ */
2690
+ async getById(choiceSetId, options) {
2691
+ // Transform a single item from PascalCase to camelCase
2692
+ const transformFn = (item) => {
2693
+ const camelCased = pascalToCamelCaseKeys(item);
2694
+ return transformData(camelCased, EntityMap);
2695
+ };
2696
+ return PaginationHelpers.getAll({
2697
+ serviceAccess: this.createPaginationServiceAccess(),
2698
+ getEndpoint: () => DATA_FABRIC_ENDPOINTS.CHOICESETS.GET_BY_ID(choiceSetId),
2699
+ transformFn,
2700
+ method: HTTP_METHODS.POST,
2701
+ pagination: {
2702
+ paginationType: PaginationType.OFFSET,
2703
+ itemsField: CHOICESET_VALUES_PAGINATION.ITEMS_FIELD,
2704
+ totalCountField: CHOICESET_VALUES_PAGINATION.TOTAL_COUNT_FIELD,
2705
+ paginationParams: {
2706
+ pageSizeParam: ENTITY_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2707
+ offsetParam: ENTITY_OFFSET_PARAMS.OFFSET_PARAM,
2708
+ countParam: ENTITY_OFFSET_PARAMS.COUNT_PARAM
2709
+ }
2710
+ }
2711
+ }, options);
2712
+ }
2713
+ }
2714
+ __decorate([
2715
+ track('Choicesets.GetAll')
2716
+ ], ChoiceSetService.prototype, "getAll", null);
2717
+ __decorate([
2718
+ track('Choicesets.GetById')
2719
+ ], ChoiceSetService.prototype, "getById", null);
2720
+
2721
+ export { ChoiceSetService, ChoiceSetService as ChoiceSets, DataDirectionType, EntityService as Entities, EntityFieldDataType, EntityService, EntityType, FieldDisplayType, JoinType, ReferenceType, createEntityWithMethods };