@uipath/uipath-typescript 1.3.8 → 1.3.10

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 (41) hide show
  1. package/dist/assets/index.cjs +44 -276
  2. package/dist/assets/index.mjs +44 -276
  3. package/dist/attachments/index.cjs +42 -273
  4. package/dist/attachments/index.mjs +42 -273
  5. package/dist/buckets/index.cjs +195 -276
  6. package/dist/buckets/index.d.ts +213 -1
  7. package/dist/buckets/index.mjs +195 -276
  8. package/dist/cases/index.cjs +427 -343
  9. package/dist/cases/index.d.ts +534 -2
  10. package/dist/cases/index.mjs +428 -344
  11. package/dist/conversational-agent/index.cjs +90 -287
  12. package/dist/conversational-agent/index.d.ts +62 -12
  13. package/dist/conversational-agent/index.mjs +90 -288
  14. package/dist/core/index.cjs +39 -289
  15. package/dist/core/index.d.ts +9 -98
  16. package/dist/core/index.mjs +40 -275
  17. package/dist/document-understanding/index.cjs +18 -1
  18. package/dist/document-understanding/index.d.ts +636 -610
  19. package/dist/document-understanding/index.mjs +18 -1
  20. package/dist/entities/index.cjs +251 -277
  21. package/dist/entities/index.d.ts +305 -2
  22. package/dist/entities/index.mjs +251 -277
  23. package/dist/feedback/index.cjs +42 -274
  24. package/dist/feedback/index.mjs +42 -274
  25. package/dist/index.cjs +998 -351
  26. package/dist/index.d.ts +2159 -762
  27. package/dist/index.mjs +998 -337
  28. package/dist/index.umd.js +1208 -237
  29. package/dist/jobs/index.cjs +44 -276
  30. package/dist/jobs/index.mjs +44 -276
  31. package/dist/maestro-processes/index.cjs +1761 -1717
  32. package/dist/maestro-processes/index.d.ts +430 -2
  33. package/dist/maestro-processes/index.mjs +1762 -1718
  34. package/dist/processes/index.cjs +72 -305
  35. package/dist/processes/index.d.ts +76 -26
  36. package/dist/processes/index.mjs +72 -305
  37. package/dist/queues/index.cjs +44 -276
  38. package/dist/queues/index.mjs +44 -276
  39. package/dist/tasks/index.cjs +44 -276
  40. package/dist/tasks/index.mjs +44 -276
  41. package/package.json +8 -10
@@ -1,4 +1,4 @@
1
- import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
1
+ import { getOrCreateClient, createTrack, createTrackEvent } from '@uipath/core-telemetry';
2
2
 
3
3
  /******************************************************************************
4
4
  Copyright (c) Microsoft Corporation.
@@ -43,466 +43,405 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
43
43
  };
44
44
 
45
45
  /**
46
- * Type guards for error response types
46
+ * Base path constants for different services
47
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
- }
48
+ const PIMS_BASE = 'pims_';
49
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
72
50
 
73
51
  /**
74
- * HTTP status code constants for error handling
52
+ * Maestro Service Endpoints
75
53
  */
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
54
  /**
90
- * Error type constants for consistent error identification
55
+ * Maestro Process Service Endpoints
91
56
  */
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'
57
+ const MAESTRO_ENDPOINTS = {
58
+ PROCESSES: {
59
+ GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`},
60
+ INSTANCES: {
61
+ GET_ALL: `${PIMS_BASE}/api/v1/instances`,
62
+ GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
63
+ GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
64
+ GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
65
+ GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
66
+ CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
67
+ PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
68
+ RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
69
+ },
70
+ INCIDENTS: {
71
+ GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
72
+ GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
73
+ GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
74
+ },
75
+ INSIGHTS: {
76
+ /** Top processes ranked by run count */
77
+ TOP_PROCESSES_BY_RUN_COUNT: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcessesByRunCount`,
78
+ /** Top processes ranked by failure count */
79
+ TOP_PROCESSES_WITH_FAILURE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcesseswithFailure`,
80
+ /** Instance status aggregated by date for time-series charts */
81
+ INSTANCE_STATUS_BY_DATE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/InstanceStatusByDate`,
82
+ /** Top processes ranked by total duration */
83
+ TOP_PROCESSES_BY_DURATION: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcessesByDuration`,
84
+ },
100
85
  };
86
+
101
87
  /**
102
- * HTTP header constants for error handling
88
+ * Maestro Process Models
89
+ * Model classes for Maestro processes
103
90
  */
104
- const HttpHeaders = {
105
- X_REQUEST_ID: 'x-request-id'
106
- };
107
91
  /**
108
- * Standard error message constants
92
+ * Creates methods for a process object
93
+ *
94
+ * @param processData - The process data (response from API)
95
+ * @param service - The process service instance
96
+ * @returns Object containing process methods
109
97
  */
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
- };
98
+ function createProcessMethods(processData, service) {
99
+ return {
100
+ async getIncidents() {
101
+ if (!processData.processKey)
102
+ throw new Error('Process key is undefined');
103
+ if (!processData.folderKey)
104
+ throw new Error('Folder key is undefined');
105
+ return service.getIncidents(processData.processKey, processData.folderKey);
106
+ }
107
+ };
108
+ }
128
109
  /**
129
- * Error name constants for network error identification
110
+ * Creates an actionable process by combining API process data with operational methods.
111
+ *
112
+ * @param processData - The process data from API
113
+ * @param service - The process service instance
114
+ * @returns A process object with added methods
130
115
  */
131
- const ErrorNames = {
132
- ABORT_ERROR: 'AbortError'};
116
+ function createProcessWithMethods(processData, service) {
117
+ const methods = createProcessMethods(processData, service);
118
+ return Object.assign({}, processData, methods);
119
+ }
133
120
 
134
121
  /**
135
- * Parser for Orchestrator/Task error format
122
+ * Builds the request body for Insights RTM "top" endpoints.
123
+ *
124
+ * @param startTime - Start of the time range to query
125
+ * @param endTime - End of the time range to query
126
+ * @param isCaseManagement - Whether to filter for case management processes
127
+ * @param options - Optional filters (packageId, processKey, version)
128
+ * @returns Request body for the Insights RTM endpoint
129
+ * @internal
136
130
  */
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
- }
131
+ function buildInsightsTopBody(startTime, endTime, isCaseManagement, options) {
132
+ return {
133
+ commonParams: {
134
+ startTime: startTime.getTime(),
135
+ endTime: endTime.getTime(),
136
+ isCaseManagement,
137
+ ...(options?.packageId ? { packageId: options.packageId } : {}),
138
+ ...(options?.processKey ? { processKey: options.processKey } : {}),
139
+ ...(options?.version ? { version: options.version } : {}),
140
+ }
141
+ };
154
142
  }
155
143
  /**
156
- * Parser for Entity (Data Fabric) error format
144
+ * Fetches instance status timeline from the Insights API.
145
+ * Shared implementation used by both MaestroProcessesService and CasesService.
146
+ *
147
+ * @param postFn - Bound post method from a BaseService subclass
148
+ * @param startTime - Start of the time range to query
149
+ * @param endTime - End of the time range to query
150
+ * @param isCaseManagement - Whether to filter for case management processes
151
+ * @param options - Optional settings for time bucketing granularity
152
+ * @returns Promise resolving to an array of instance status timeline entries
153
+ * @internal
157
154
  */
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
- }
155
+ async function fetchInstanceStatusTimeline(postFn, startTime, endTime, isCaseManagement, options) {
156
+ const response = await postFn(MAESTRO_ENDPOINTS.INSIGHTS.INSTANCE_STATUS_BY_DATE, {
157
+ commonParams: {
158
+ startTime: startTime.getTime(),
159
+ endTime: endTime.getTime(),
160
+ isCaseManagement,
161
+ },
162
+ timeSliceUnit: options?.groupBy,
163
+ timezoneOffset: new Date().getTimezoneOffset() * -1,
164
+ });
165
+ return response.data ?? [];
175
166
  }
167
+
176
168
  /**
177
- * Parser for PIMS error format
169
+ * Common constants used across the SDK
178
170
  */
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
171
  /**
209
- * Fallback parser for unrecognized formats
172
+ * Prefix used for OData query parameters
210
173
  */
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
- }
174
+ const ODATA_PREFIX = '$';
175
+ const UNKNOWN = 'Unknown';
176
+ const NO_INSTANCE = 'no-instance';
227
177
  /**
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
178
+ * HTTP methods
243
179
  */
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
-
180
+ const HTTP_METHODS = {
181
+ GET: 'GET',
182
+ POST: 'POST'};
284
183
  /**
285
- * Base error class for all UiPath SDK errors
286
- * Extends Error for standard error handling compatibility
184
+ * Process Instance pagination constants for token-based pagination
287
185
  */
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
-
186
+ const PROCESS_INSTANCE_PAGINATION = {
187
+ /** Field name for items in process instance response */
188
+ ITEMS_FIELD: 'instances',
189
+ /** Field name for continuation token in process instance response */
190
+ CONTINUATION_TOKEN_FIELD: 'nextPage'
191
+ };
324
192
  /**
325
- * Error thrown when authentication fails (401 errors)
326
- * Common scenarios:
327
- * - Invalid credentials
328
- * - Expired token
329
- * - Missing authentication
193
+ * OData OFFSET pagination parameter names (ODATA-style)
330
194
  */
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
-
195
+ const ODATA_OFFSET_PARAMS = {
196
+ /** OData page size parameter name */
197
+ PAGE_SIZE_PARAM: '$top',
198
+ /** OData offset parameter name */
199
+ OFFSET_PARAM: '$skip',
200
+ /** OData count parameter name */
201
+ COUNT_PARAM: '$count'
202
+ };
341
203
  /**
342
- * Error thrown when authorization fails (403 errors)
343
- * Common scenarios:
344
- * - Insufficient permissions
345
- * - Access denied to resource
346
- * - Invalid scope
204
+ * Bucket TOKEN pagination parameter names
347
205
  */
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
-
206
+ const BUCKET_TOKEN_PARAMS = {
207
+ /** Bucket page size parameter name */
208
+ PAGE_SIZE_PARAM: 'takeHint',
209
+ /** Bucket token parameter name */
210
+ TOKEN_PARAM: 'continuationToken'
211
+ };
358
212
  /**
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
213
+ * Process Instance TOKEN pagination parameter names
364
214
  */
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
- }
215
+ const PROCESS_INSTANCE_TOKEN_PARAMS = {
216
+ /** Process instance page size parameter name */
217
+ PAGE_SIZE_PARAM: 'pageSize',
218
+ /** Process instance token parameter name */
219
+ TOKEN_PARAM: 'nextPage'
220
+ };
374
221
 
375
222
  /**
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
223
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
224
+ * Returns the original value if parsing fails.
381
225
  */
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
226
  /**
393
- * Error thrown when rate limit is exceeded (429 errors)
394
- * Common scenarios:
395
- * - Too many requests in a time window
396
- * - API throttling
227
+ * Transforms data by mapping fields according to the provided field mapping
228
+ * @param data The source data to transform
229
+ * @param fieldMapping Object mapping source field names to target field names
230
+ * @returns Transformed data with mapped field names
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * // Single object transformation
235
+ * const data = { id: '123', userName: 'john' };
236
+ * const mapping = { id: 'userId', userName: 'name' };
237
+ * const result = transformData(data, mapping);
238
+ * // result = { userId: '123', name: 'john' }
239
+ *
240
+ * // Array transformation
241
+ * const dataArray = [
242
+ * { id: '123', userName: 'john' },
243
+ * { id: '456', userName: 'jane' }
244
+ * ];
245
+ * const result = transformData(dataArray, mapping);
246
+ * // result = [
247
+ * // { userId: '123', name: 'john' },
248
+ * // { userId: '456', name: 'jane' }
249
+ * // ]
250
+ * ```
397
251
  */
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
- });
252
+ function transformData(data, fieldMapping) {
253
+ // Handle array of objects
254
+ if (Array.isArray(data)) {
255
+ return data.map(item => transformData(item, fieldMapping));
405
256
  }
257
+ // Handle single object
258
+ const result = { ...data };
259
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
260
+ if (sourceField in result) {
261
+ const value = result[sourceField];
262
+ delete result[sourceField];
263
+ result[targetField] = value;
264
+ }
265
+ }
266
+ return result;
406
267
  }
407
-
408
268
  /**
409
- * Error thrown when server encounters an error (5xx errors)
410
- * Common scenarios:
411
- * - Internal server error
412
- * - Service unavailable
413
- * - Gateway timeout
269
+ * Adds a prefix to specified keys in an object, returning a new object.
270
+ * Only the provided keys are prefixed; all others are left unchanged.
271
+ *
272
+ * @param obj The source object
273
+ * @param prefix The prefix to add (e.g., '$')
274
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
275
+ * @returns A new object with specified keys prefixed
276
+ *
277
+ * @example
278
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
414
279
  */
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;
280
+ function addPrefixToKeys(obj, prefix, keys) {
281
+ const result = {};
282
+ for (const [key, value] of Object.entries(obj)) {
283
+ if (keys.includes(key)) {
284
+ result[`${prefix}${key}`] = value;
285
+ }
286
+ else {
287
+ result[key] = value;
288
+ }
430
289
  }
290
+ return result;
431
291
  }
432
292
 
433
293
  /**
434
- * Error thrown when network/connection issues occur
435
- * Common scenarios:
436
- * - Connection timeout
437
- * - DNS resolution failure
438
- * - Network unreachable
439
- * - Request aborted
294
+ * Maps fields for Incident entities
440
295
  */
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
-
296
+ const ProcessIncidentMap = {
297
+ errorTimeUtc: 'errorTime'
298
+ };
451
299
  /**
452
- * Factory for creating typed errors based on HTTP status codes
453
- * Follows the Factory pattern for clean error instantiation
300
+ * Maps fields for Incident Summary entities
454
301
  */
455
- class ErrorFactory {
302
+ const ProcessIncidentSummaryMap = {
303
+ firstTimeUtc: 'firstOccuranceTime'
304
+ };
305
+
306
+ /**
307
+ * Helpers for fetching BPMN XML and extracting element details used to annotate responses
308
+ */
309
+ class BpmnHelpers {
456
310
  /**
457
- * Creates appropriate error instance based on HTTP status code
311
+ * Parse BPMN XML and extract element id {name,type} used for incidents
458
312
  */
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 });
313
+ static parseBpmnElementsForIncidents(bpmnXml) {
314
+ const elementInfo = {};
315
+ try {
316
+ // Find <bpmn:...> start tags and capture the element type.
317
+ // Then read 'id' and 'name' attributes from each tag.
318
+ const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
319
+ for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
320
+ const [fullTag, elementType] = tagMatch;
321
+ // Extract attributes from the current tag text.
322
+ const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
323
+ if (!idMatch) {
324
+ continue;
477
325
  }
478
- // For unknown client errors, treat as validation error
479
- return new ValidationError({
480
- message: `${message} (HTTP ${statusCode})`,
481
- statusCode,
482
- requestId
483
- });
326
+ const elementId = idMatch[1];
327
+ const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
328
+ const name = nameMatch ? nameMatch[1] : '';
329
+ // Convert BPMN element type to human-readable format
330
+ const activityType = this.formatActivityTypeForIncidents(elementType);
331
+ const activityName = name || elementId;
332
+ elementInfo[elementId] = {
333
+ type: activityType,
334
+ name: activityName
335
+ };
336
+ }
484
337
  }
338
+ catch (error) {
339
+ console.warn('Failed to parse BPMN XML for incidents:', error);
340
+ }
341
+ return elementInfo;
485
342
  }
486
343
  /**
487
- * Creates a NetworkError from a fetch/network error
344
+ * Format BPMN element type to human-readable activity type for incidents
488
345
  */
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
- }
346
+ static formatActivityTypeForIncidents(elementType) {
347
+ // Convert camelCase BPMN element types to human-readable format
348
+ // e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
349
+ return elementType
350
+ .replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
351
+ .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
352
+ .trim(); // Remove any leading/trailing spaces
353
+ }
354
+ /**
355
+ * Fetch BPMN via getBpmn and add element name/type to each incident
356
+ */
357
+ static async enrichIncidentsWithBpmnData(incidents, folderKey, service) {
358
+ // Check if all incidents have the same instanceId
359
+ const uniqueInstanceIds = [...new Set(incidents.map(i => i.instanceId))];
360
+ if (uniqueInstanceIds.length === 1) {
361
+ // Single instance optimization (in case of process instance incidents)
362
+ const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
363
+ return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
501
364
  }
502
- return new NetworkError({ message });
365
+ else {
366
+ // Multiple instances optimization (in case of process incidents)
367
+ return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
368
+ }
369
+ }
370
+ /**
371
+ * When incidents span multiple instances, fetch BPMN per instance and annotate
372
+ */
373
+ static async enrichMultipleInstanceIncidents(incidents, folderKey, service) {
374
+ const groups = incidents.reduce((acc, incident) => {
375
+ const id = incident.instanceId || NO_INSTANCE;
376
+ (acc[id] = acc[id] || []).push(incident);
377
+ return acc;
378
+ }, {});
379
+ const results = await Promise.all(Object.entries(groups).map(async (entry) => {
380
+ const [instanceId, groupIncidents] = entry;
381
+ const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
382
+ return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
383
+ }));
384
+ return results.flat();
385
+ }
386
+ /**
387
+ * Retrieve BPMN XML for an instance and derive element id → {name,type}
388
+ */
389
+ static async getBpmnElementInfo(instanceId, folderKey, service) {
390
+ if (!instanceId || instanceId === NO_INSTANCE) {
391
+ return {};
392
+ }
393
+ try {
394
+ const bpmnXml = await service.getBpmn(instanceId, folderKey);
395
+ return this.parseBpmnElementsForIncidents(bpmnXml);
396
+ }
397
+ catch (error) {
398
+ console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
399
+ return {};
400
+ }
401
+ }
402
+ /**
403
+ * Transform a raw incident by attaching element name/type from BPMN
404
+ */
405
+ static transformIncidentWithBpmn(incident, elementInfo) {
406
+ const element = elementInfo[incident.elementId];
407
+ const transformed = transformData(incident, ProcessIncidentMap);
408
+ return {
409
+ ...transformed,
410
+ incidentElementActivityType: element?.type || UNKNOWN,
411
+ incidentElementActivityName: element?.name || UNKNOWN
412
+ };
503
413
  }
504
414
  }
505
415
 
416
+ /**
417
+ * SDK Telemetry constants.
418
+ *
419
+ * Only the SDK's identity (version, service name, role name, …) lives
420
+ * here. The Application Insights connection string is injected into
421
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
422
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
423
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
424
+ * SDK's public API.
425
+ */
426
+ /** SDK version placeholder — patched by the SDK publish workflow. */
427
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
428
+
429
+ /**
430
+ * UiPath TypeScript SDK Telemetry
431
+ *
432
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
433
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
434
+ * does this independently, so events carry their own consumer's identity
435
+ * and tenant context.
436
+ */
437
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
438
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
439
+ // from the `UiPath` constructor therefore wires up `@track` decorators
440
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
441
+ const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
442
+ const track = createTrack(sdkClient);
443
+ createTrackEvent(sdkClient);
444
+
506
445
  const FOLDER_KEY = 'X-UIPATH-FolderKey';
507
446
  const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
508
447
  const TRACEPARENT = 'traceparent';
@@ -525,1524 +464,1412 @@ const RESPONSE_TYPES = {
525
464
  ARRAYBUFFER: 'arraybuffer'
526
465
  };
527
466
 
528
- class ApiClient {
529
- constructor(config, executionContext, tokenManager, clientConfig = {}) {
530
- this.config = config;
531
- this.executionContext = executionContext;
532
- this.clientConfig = clientConfig;
533
- this.tokenManager = tokenManager;
534
- }
535
- /**
536
- * Gets a valid authentication token, refreshing if necessary.
537
- * Used internally for API requests and exposed for services that need manual auth headers.
538
- *
539
- * @returns The valid token
540
- * @throws AuthenticationError if no token available or refresh fails
541
- */
542
- async getValidToken() {
543
- return this.tokenManager.getValidToken();
544
- }
545
- async getDefaultHeaders() {
546
- const token = await this.getValidToken();
547
- return {
548
- 'Authorization': `Bearer ${token}`,
549
- 'Content-Type': CONTENT_TYPES.JSON,
550
- ...this.clientConfig.headers
551
- };
552
- }
553
- async request(method, path, options = {}) {
554
- // Ensure path starts with a forward slash
555
- const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
556
- // Construct URL with org and tenant names
557
- const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
558
- const isFormData = options.body instanceof FormData;
559
- const defaultHeaders = await this.getDefaultHeaders();
560
- if (isFormData) {
561
- delete defaultHeaders['Content-Type'];
562
- }
563
- const traceId = crypto.randomUUID().replace(/-/g, '');
564
- const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
565
- const traceparentValue = `00-${traceId}-${spanId}-01`;
566
- const headers = {
567
- ...defaultHeaders,
568
- [TRACEPARENT]: traceparentValue,
569
- [UIPATH_TRACEPARENT_ID]: traceparentValue,
570
- ...options.headers
571
- };
572
- // Convert params to URLSearchParams
573
- const searchParams = new URLSearchParams();
574
- if (options.params) {
575
- Object.entries(options.params).forEach(([key, value]) => {
576
- searchParams.append(key, value.toString());
577
- });
578
- }
579
- const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
580
- let body = undefined;
581
- if (options.body) {
582
- body = isFormData ? options.body : JSON.stringify(options.body);
467
+ /**
468
+ * Creates headers object from key-value pairs
469
+ * @param headersObj - Object containing header key-value pairs
470
+ * @returns Headers object with all values converted to strings
471
+ *
472
+ * @example
473
+ * ```typescript
474
+ * // Single header
475
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
476
+ *
477
+ * // Multiple headers
478
+ * const headers = createHeaders({
479
+ * 'X-UIPATH-FolderKey': '1234567890',
480
+ * 'X-UIPATH-OrganizationUnitId': 123,
481
+ * 'Accept': 'application/json'
482
+ * });
483
+ *
484
+ * // Using constants
485
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
486
+ * const headers = createHeaders({
487
+ * [FOLDER_KEY]: 'abc-123',
488
+ * [FOLDER_ID]: 456
489
+ * });
490
+ *
491
+ * // Empty headers
492
+ * const headers = createHeaders();
493
+ * ```
494
+ */
495
+ function createHeaders(headersObj) {
496
+ const headers = {};
497
+ for (const [key, value] of Object.entries(headersObj)) {
498
+ if (value !== undefined && value !== null) {
499
+ headers[key] = value.toString();
583
500
  }
584
- try {
585
- const response = await fetch(fullUrl, {
586
- method,
587
- headers,
588
- body,
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
- const text = await response.text();
610
- if (!text) {
611
- return undefined;
612
- }
613
- return JSON.parse(text);
614
- }
615
- catch (error) {
616
- // If it's already one of our errors, re-throw it
617
- if (error.type && error.type.includes('Error')) {
618
- throw error;
619
- }
620
- // Otherwise, it's likely a network error
621
- throw ErrorFactory.createNetworkError(error);
622
- }
623
- }
624
- async get(path, options = {}) {
625
- return this.request('GET', path, options);
626
- }
627
- async post(path, data, options = {}) {
628
- return this.request('POST', path, { ...options, body: data });
629
- }
630
- async put(path, data, options = {}) {
631
- return this.request('PUT', path, { ...options, body: data });
632
- }
633
- async patch(path, data, options = {}) {
634
- return this.request('PATCH', path, { ...options, body: data });
635
- }
636
- async delete(path, options = {}) {
637
- return this.request('DELETE', path, options);
638
501
  }
502
+ return headers;
639
503
  }
640
504
 
641
505
  /**
642
- * Pagination types supported by the SDK
506
+ * Type guards for error response types
643
507
  */
644
- var PaginationType;
645
- (function (PaginationType) {
646
- PaginationType["OFFSET"] = "offset";
647
- PaginationType["TOKEN"] = "token";
648
- })(PaginationType || (PaginationType = {}));
508
+ function isOrchestratorError(error) {
509
+ return typeof error === 'object' &&
510
+ error !== null &&
511
+ 'message' in error &&
512
+ 'errorCode' in error &&
513
+ typeof error.message === 'string' &&
514
+ typeof error.errorCode === 'number';
515
+ }
516
+ function isEntityError(error) {
517
+ return typeof error === 'object' &&
518
+ error !== null &&
519
+ 'error' in error &&
520
+ typeof error.error === 'string';
521
+ }
522
+ function isPimsError(error) {
523
+ return typeof error === 'object' &&
524
+ error !== null &&
525
+ 'type' in error &&
526
+ 'title' in error &&
527
+ 'status' in error &&
528
+ typeof error.type === 'string' &&
529
+ typeof error.title === 'string' &&
530
+ typeof error.status === 'number';
531
+ }
649
532
 
650
533
  /**
651
- * Collection of utility functions for working with objects
534
+ * HTTP status code constants for error handling
652
535
  */
536
+ const HttpStatus = {
537
+ // Client errors (4xx)
538
+ BAD_REQUEST: 400,
539
+ UNAUTHORIZED: 401,
540
+ FORBIDDEN: 403,
541
+ NOT_FOUND: 404,
542
+ TOO_MANY_REQUESTS: 429,
543
+ // Server errors (5xx)
544
+ INTERNAL_SERVER_ERROR: 500,
545
+ BAD_GATEWAY: 502,
546
+ SERVICE_UNAVAILABLE: 503,
547
+ GATEWAY_TIMEOUT: 504
548
+ };
653
549
  /**
654
- * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
655
- * and dot-separated nested paths (e.g., 'pagination.totalCount').
656
- * Direct key match takes priority over nested traversal.
550
+ * Error type constants for consistent error identification
657
551
  */
658
- function resolveNestedField(data, fieldPath) {
659
- if (!data) {
660
- return undefined;
661
- }
662
- if (fieldPath in data) {
663
- return data[fieldPath];
664
- }
665
- if (!fieldPath.includes('.')) {
666
- return undefined;
667
- }
668
- let value = data;
669
- for (const part of fieldPath.split('.')) {
670
- value = value?.[part];
671
- }
672
- return value;
673
- }
552
+ const ErrorType = {
553
+ AUTHENTICATION: 'AuthenticationError',
554
+ AUTHORIZATION: 'AuthorizationError',
555
+ VALIDATION: 'ValidationError',
556
+ NOT_FOUND: 'NotFoundError',
557
+ RATE_LIMIT: 'RateLimitError',
558
+ SERVER: 'ServerError',
559
+ NETWORK: 'NetworkError'
560
+ };
674
561
  /**
675
- * Filters out undefined values from an object
676
- * @param obj The source object
677
- * @returns A new object without undefined values
678
- *
679
- * @example
680
- * ```typescript
681
- * // Object with undefined values
682
- * const options = {
683
- * name: 'test',
684
- * count: 5,
685
- * prefix: undefined,
686
- * suffix: null
687
- * };
688
- * const result = filterUndefined(options);
689
- * // result = { name: 'test', count: 5, suffix: null }
690
- * ```
562
+ * HTTP header constants for error handling
691
563
  */
692
- function filterUndefined(obj) {
693
- const result = {};
694
- for (const [key, value] of Object.entries(obj)) {
695
- if (value !== undefined) {
696
- result[key] = value;
697
- }
698
- }
699
- return result;
700
- }
701
-
564
+ const HttpHeaders = {
565
+ X_REQUEST_ID: 'x-request-id'
566
+ };
702
567
  /**
703
- * Utility functions for platform detection
568
+ * Standard error message constants
704
569
  */
570
+ const ErrorMessages = {
571
+ // Authentication errors
572
+ AUTHENTICATION_FAILED: 'Authentication failed',
573
+ // Authorization errors
574
+ ACCESS_DENIED: 'Access denied',
575
+ // Validation errors
576
+ VALIDATION_FAILED: 'Validation failed',
577
+ // Not found errors
578
+ RESOURCE_NOT_FOUND: 'Resource not found',
579
+ // Rate limit errors
580
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
581
+ // Server errors
582
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
583
+ // Network errors
584
+ NETWORK_ERROR: 'Network error occurred',
585
+ REQUEST_TIMEOUT: 'Request timed out',
586
+ REQUEST_ABORTED: 'Request was aborted',
587
+ };
705
588
  /**
706
- * Checks if code is running in a browser environment
589
+ * Error name constants for network error identification
707
590
  */
708
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
709
- isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
591
+ const ErrorNames = {
592
+ ABORT_ERROR: 'AbortError'};
710
593
 
711
594
  /**
712
- * Base64 encoding/decoding
713
- */
714
- /**
715
- * Encodes a string to base64
716
- * @param str - The string to encode
717
- * @returns Base64 encoded string
595
+ * Parser for Orchestrator/Task error format
718
596
  */
719
- function encodeBase64(str) {
720
- // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
721
- const encoder = new TextEncoder();
722
- const data = encoder.encode(str);
723
- // Convert Uint8Array to base64
724
- if (isBrowser) {
725
- // Browser environment
726
- // Convert Uint8Array to binary string then to base64
727
- const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
728
- return btoa(binaryString);
597
+ class OrchestratorErrorParser {
598
+ canParse(errorBody) {
599
+ return isOrchestratorError(errorBody);
729
600
  }
730
- else {
731
- // Node.js environment
732
- return Buffer.from(data).toString('base64');
601
+ parse(errorBody, response) {
602
+ const error = errorBody;
603
+ return {
604
+ message: error.message,
605
+ code: response?.status?.toString(),
606
+ details: {
607
+ errorCode: error.errorCode,
608
+ traceId: error.traceId,
609
+ originalResponse: error
610
+ },
611
+ requestId: error.traceId
612
+ };
733
613
  }
734
614
  }
735
615
  /**
736
- * Decodes a base64 string
737
- * @param base64 - The base64 string to decode
738
- * @returns Decoded string
616
+ * Parser for Entity (Data Fabric) error format
739
617
  */
740
- function decodeBase64(base64) {
741
- let bytes;
742
- if (isBrowser) {
743
- // Browser environment
744
- const binaryString = atob(base64);
745
- bytes = new Uint8Array(binaryString.length);
746
- for (let i = 0; i < binaryString.length; i++) {
747
- bytes[i] = binaryString.charCodeAt(i);
748
- }
618
+ class EntityErrorParser {
619
+ canParse(errorBody) {
620
+ return isEntityError(errorBody);
749
621
  }
750
- else {
751
- // Node.js environment
752
- bytes = new Uint8Array(Buffer.from(base64, 'base64'));
622
+ parse(errorBody, response) {
623
+ const error = errorBody;
624
+ return {
625
+ message: error.error,
626
+ code: response?.status?.toString(),
627
+ details: {
628
+ error: error.error,
629
+ traceId: error.traceId,
630
+ originalResponse: error
631
+ },
632
+ requestId: error.traceId
633
+ };
753
634
  }
754
- // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
755
- const decoder = new TextDecoder();
756
- return decoder.decode(bytes);
757
635
  }
758
-
759
636
  /**
760
- * PaginationManager handles the conversion between uniform cursor-based pagination
761
- * and the specific pagination type for each service
637
+ * Parser for PIMS error format
762
638
  */
763
- class PaginationManager {
764
- /**
765
- * Create a pagination cursor for subsequent page requests
766
- */
767
- static createCursor({ pageInfo, type }) {
768
- if (!pageInfo.hasMore) {
769
- return undefined;
770
- }
771
- const cursorData = {
772
- type,
773
- pageSize: pageInfo.pageSize,
774
- };
775
- switch (type) {
776
- case PaginationType.OFFSET:
777
- if (pageInfo.currentPage) {
778
- cursorData.pageNumber = pageInfo.currentPage + 1;
779
- }
780
- break;
781
- case PaginationType.TOKEN:
782
- if (pageInfo.continuationToken) {
783
- cursorData.continuationToken = pageInfo.continuationToken;
784
- }
785
- else {
786
- return undefined; // No continuation token, can't continue
787
- }
788
- break;
639
+ class PimsErrorParser {
640
+ canParse(errorBody) {
641
+ return isPimsError(errorBody);
642
+ }
643
+ parse(errorBody, response) {
644
+ const error = errorBody;
645
+ let message = error.title;
646
+ // If there are validation errors, append them to the message for better visibility
647
+ if (error.errors && Object.keys(error.errors).length > 0) {
648
+ const errorMessages = Object.entries(error.errors)
649
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
650
+ .join('; ');
651
+ message += `. Validation errors: ${errorMessages}`;
789
652
  }
790
653
  return {
791
- value: encodeBase64(JSON.stringify(cursorData))
654
+ message,
655
+ code: response?.status?.toString(),
656
+ details: {
657
+ type: error.type,
658
+ title: error.title,
659
+ status: error.status,
660
+ errors: error.errors,
661
+ traceId: error.traceId,
662
+ originalResponse: error
663
+ },
664
+ requestId: error.traceId
792
665
  };
793
666
  }
794
- /**
795
- * Create a paginated response with navigation cursors
796
- */
797
- static createPaginatedResponse({ pageInfo, type }, items) {
798
- const nextCursor = PaginationManager.createCursor({ pageInfo, type });
799
- // Create previous page cursor if applicable
800
- let previousCursor = undefined;
801
- if (pageInfo.currentPage && pageInfo.currentPage > 1) {
802
- const prevCursorData = {
803
- type,
804
- pageNumber: pageInfo.currentPage - 1,
805
- pageSize: pageInfo.pageSize,
806
- };
807
- previousCursor = {
808
- value: encodeBase64(JSON.stringify(prevCursorData))
809
- };
810
- }
811
- // Calculate total pages if we have totalCount and pageSize
812
- let totalPages = undefined;
813
- if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
814
- totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
815
- }
816
- // Determine if this pagination type supports page jumping
817
- const supportsPageJump = type === PaginationType.OFFSET;
818
- // Create the result object with all fields, then filter out undefined values
819
- const result = filterUndefined({
820
- items,
821
- totalCount: pageInfo.totalCount,
822
- hasNextPage: pageInfo.hasMore,
823
- nextCursor: nextCursor,
824
- previousCursor: previousCursor,
825
- currentPage: pageInfo.currentPage,
826
- totalPages,
827
- supportsPageJump
828
- });
829
- return result;
667
+ }
668
+ /**
669
+ * Fallback parser for unrecognized formats
670
+ */
671
+ class GenericErrorParser {
672
+ canParse(_errorBody) {
673
+ return true; // Always can parse as last resort
674
+ }
675
+ parse(errorBody, response) {
676
+ // For unknown error formats, just pass through the raw error with fallback message
677
+ const message = response?.statusText || 'An error occurred';
678
+ return {
679
+ message,
680
+ code: response?.status?.toString(),
681
+ details: {
682
+ originalResponse: errorBody
683
+ },
684
+ };
830
685
  }
831
686
  }
832
-
833
687
  /**
834
- * Creates headers object from key-value pairs
835
- * @param headersObj - Object containing header key-value pairs
836
- * @returns Headers object with all values converted to strings
837
- *
838
- * @example
839
- * ```typescript
840
- * // Single header
841
- * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
688
+ * Main error response parser using Chain of Responsibility pattern
842
689
  *
843
- * // Multiple headers
844
- * const headers = createHeaders({
845
- * 'X-UIPATH-FolderKey': '1234567890',
846
- * 'X-UIPATH-OrganizationUnitId': 123,
847
- * 'Accept': 'application/json'
848
- * });
690
+ * This parser standardizes error responses from different UiPath services into a
691
+ * consistent format, regardless of the original error structure.
849
692
  *
850
- * // Using constants
851
- * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
852
- * const headers = createHeaders({
853
- * [FOLDER_KEY]: 'abc-123',
854
- * [FOLDER_ID]: 456
855
- * });
693
+ * Supported formats:
694
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
695
+ * 2. Entity (Data Fabric): { error, traceId }
696
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
697
+ * 4. Generic: Fallback for any other format
856
698
  *
857
- * // Empty headers
858
- * const headers = createHeaders();
859
- * ```
699
+ * @example
700
+ * const parser = new ErrorResponseParser();
701
+ * const errorInfo = await parser.parse(response);
702
+ * // errorInfo will have consistent structure regardless of service
860
703
  */
861
- function createHeaders(headersObj) {
862
- const headers = {};
863
- for (const [key, value] of Object.entries(headersObj)) {
864
- if (value !== undefined && value !== null) {
865
- headers[key] = value.toString();
704
+ class ErrorResponseParser {
705
+ constructor() {
706
+ this.strategies = [
707
+ new OrchestratorErrorParser(),
708
+ new EntityErrorParser(),
709
+ new PimsErrorParser(),
710
+ new GenericErrorParser() // Must be last
711
+ ];
712
+ }
713
+ /**
714
+ * Parses error response body into standardized format
715
+ * @param response - The HTTP response object
716
+ * @returns Standardized error information
717
+ */
718
+ async parse(response) {
719
+ try {
720
+ const errorBody = await response.json();
721
+ // Find the first strategy that can parse this error format
722
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
723
+ // GenericErrorParser always returns true, so this will never be null
724
+ return strategy.parse(errorBody, response);
725
+ }
726
+ catch {
727
+ // Handle non-JSON responses
728
+ const responseText = await response.text().catch(() => '');
729
+ return {
730
+ message: response.statusText,
731
+ code: response.status.toString(),
732
+ details: {
733
+ parseError: 'Failed to parse error response as JSON',
734
+ responseText
735
+ },
736
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
737
+ };
866
738
  }
867
739
  }
868
- return headers;
869
740
  }
741
+ // Export singleton instance
742
+ const errorResponseParser = new ErrorResponseParser();
870
743
 
871
744
  /**
872
- * Common constants used across the SDK
745
+ * Base error class for all UiPath SDK errors
746
+ * Extends Error for standard error handling compatibility
873
747
  */
748
+ class UiPathError extends Error {
749
+ constructor(type, params) {
750
+ super(params.message);
751
+ this.name = type;
752
+ this.type = type;
753
+ this.statusCode = params.statusCode;
754
+ this.requestId = params.requestId;
755
+ this.timestamp = new Date();
756
+ // Maintains proper stack trace for where our error was thrown
757
+ if (Error.captureStackTrace) {
758
+ Error.captureStackTrace(this, this.constructor);
759
+ }
760
+ }
761
+ /**
762
+ * Returns a clean JSON representation of the error
763
+ */
764
+ toJSON() {
765
+ return {
766
+ type: this.type,
767
+ message: this.message,
768
+ statusCode: this.statusCode,
769
+ requestId: this.requestId,
770
+ timestamp: this.timestamp
771
+ };
772
+ }
773
+ /**
774
+ * Returns detailed debug information including stack trace
775
+ */
776
+ getDebugInfo() {
777
+ return {
778
+ ...this.toJSON(),
779
+ stack: this.stack
780
+ };
781
+ }
782
+ }
783
+
874
784
  /**
875
- * Prefix used for OData query parameters
785
+ * Error thrown when authentication fails (401 errors)
786
+ * Common scenarios:
787
+ * - Invalid credentials
788
+ * - Expired token
789
+ * - Missing authentication
876
790
  */
877
- const ODATA_PREFIX = '$';
878
- const UNKNOWN$1 = 'Unknown';
879
- const NO_INSTANCE = 'no-instance';
791
+ class AuthenticationError extends UiPathError {
792
+ constructor(params = {}) {
793
+ super(ErrorType.AUTHENTICATION, {
794
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
795
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
796
+ requestId: params.requestId
797
+ });
798
+ }
799
+ }
800
+
880
801
  /**
881
- * HTTP methods
802
+ * Error thrown when authorization fails (403 errors)
803
+ * Common scenarios:
804
+ * - Insufficient permissions
805
+ * - Access denied to resource
806
+ * - Invalid scope
882
807
  */
883
- const HTTP_METHODS = {
884
- GET: 'GET',
885
- POST: 'POST'};
808
+ class AuthorizationError extends UiPathError {
809
+ constructor(params = {}) {
810
+ super(ErrorType.AUTHORIZATION, {
811
+ message: params.message || ErrorMessages.ACCESS_DENIED,
812
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
813
+ requestId: params.requestId
814
+ });
815
+ }
816
+ }
817
+
886
818
  /**
887
- * Process Instance pagination constants for token-based pagination
819
+ * Error thrown when validation fails (400 errors or client-side validation)
820
+ * Common scenarios:
821
+ * - Invalid input parameters
822
+ * - Missing required fields
823
+ * - Invalid data format
888
824
  */
889
- const PROCESS_INSTANCE_PAGINATION = {
890
- /** Field name for items in process instance response */
891
- ITEMS_FIELD: 'instances',
892
- /** Field name for continuation token in process instance response */
893
- CONTINUATION_TOKEN_FIELD: 'nextPage'
894
- };
895
- /**
896
- * OData OFFSET pagination parameter names (ODATA-style)
897
- */
898
- const ODATA_OFFSET_PARAMS = {
899
- /** OData page size parameter name */
900
- PAGE_SIZE_PARAM: '$top',
901
- /** OData offset parameter name */
902
- OFFSET_PARAM: '$skip',
903
- /** OData count parameter name */
904
- COUNT_PARAM: '$count'
905
- };
906
- /**
907
- * Bucket TOKEN pagination parameter names
908
- */
909
- const BUCKET_TOKEN_PARAMS = {
910
- /** Bucket page size parameter name */
911
- PAGE_SIZE_PARAM: 'takeHint',
912
- /** Bucket token parameter name */
913
- TOKEN_PARAM: 'continuationToken'
914
- };
915
- /**
916
- * Process Instance TOKEN pagination parameter names
917
- */
918
- const PROCESS_INSTANCE_TOKEN_PARAMS = {
919
- /** Process instance page size parameter name */
920
- PAGE_SIZE_PARAM: 'pageSize',
921
- /** Process instance token parameter name */
922
- TOKEN_PARAM: 'nextPage'
923
- };
825
+ class ValidationError extends UiPathError {
826
+ constructor(params = {}) {
827
+ super(ErrorType.VALIDATION, {
828
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
829
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
830
+ requestId: params.requestId
831
+ });
832
+ }
833
+ }
924
834
 
925
835
  /**
926
- * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
927
- * Returns the original value if parsing fails.
928
- */
929
- /**
930
- * Transforms data by mapping fields according to the provided field mapping
931
- * @param data The source data to transform
932
- * @param fieldMapping Object mapping source field names to target field names
933
- * @returns Transformed data with mapped field names
934
- *
935
- * @example
936
- * ```typescript
937
- * // Single object transformation
938
- * const data = { id: '123', userName: 'john' };
939
- * const mapping = { id: 'userId', userName: 'name' };
940
- * const result = transformData(data, mapping);
941
- * // result = { userId: '123', name: 'john' }
942
- *
943
- * // Array transformation
944
- * const dataArray = [
945
- * { id: '123', userName: 'john' },
946
- * { id: '456', userName: 'jane' }
947
- * ];
948
- * const result = transformData(dataArray, mapping);
949
- * // result = [
950
- * // { userId: '123', name: 'john' },
951
- * // { userId: '456', name: 'jane' }
952
- * // ]
953
- * ```
836
+ * Error thrown when a resource is not found (404 errors)
837
+ * Common scenarios:
838
+ * - Resource doesn't exist
839
+ * - Invalid ID provided
840
+ * - Resource deleted
954
841
  */
955
- function transformData(data, fieldMapping) {
956
- // Handle array of objects
957
- if (Array.isArray(data)) {
958
- return data.map(item => transformData(item, fieldMapping));
959
- }
960
- // Handle single object
961
- const result = { ...data };
962
- for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
963
- if (sourceField in result) {
964
- const value = result[sourceField];
965
- delete result[sourceField];
966
- result[targetField] = value;
967
- }
842
+ class NotFoundError extends UiPathError {
843
+ constructor(params = {}) {
844
+ super(ErrorType.NOT_FOUND, {
845
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
846
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
847
+ requestId: params.requestId
848
+ });
968
849
  }
969
- return result;
970
850
  }
851
+
971
852
  /**
972
- * Adds a prefix to specified keys in an object, returning a new object.
973
- * Only the provided keys are prefixed; all others are left unchanged.
974
- *
975
- * @param obj The source object
976
- * @param prefix The prefix to add (e.g., '$')
977
- * @param keys The keys to prefix (e.g., ['expand', 'filter'])
978
- * @returns A new object with specified keys prefixed
979
- *
980
- * @example
981
- * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
853
+ * Error thrown when rate limit is exceeded (429 errors)
854
+ * Common scenarios:
855
+ * - Too many requests in a time window
856
+ * - API throttling
982
857
  */
983
- function addPrefixToKeys(obj, prefix, keys) {
984
- const result = {};
985
- for (const [key, value] of Object.entries(obj)) {
986
- if (keys.includes(key)) {
987
- result[`${prefix}${key}`] = value;
988
- }
989
- else {
990
- result[key] = value;
991
- }
858
+ class RateLimitError extends UiPathError {
859
+ constructor(params = {}) {
860
+ super(ErrorType.RATE_LIMIT, {
861
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
862
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
863
+ requestId: params.requestId
864
+ });
992
865
  }
993
- return result;
994
866
  }
995
867
 
996
868
  /**
997
- * Constants used throughout the pagination system
869
+ * Error thrown when server encounters an error (5xx errors)
870
+ * Common scenarios:
871
+ * - Internal server error
872
+ * - Service unavailable
873
+ * - Gateway timeout
998
874
  */
999
- /** Maximum number of items that can be requested in a single page */
1000
- const MAX_PAGE_SIZE = 1000;
1001
- /** Default page size when jumpToPage is used without specifying pageSize */
1002
- const DEFAULT_PAGE_SIZE = 50;
1003
- /** Default field name for items in a paginated response */
1004
- const DEFAULT_ITEMS_FIELD = 'value';
1005
- /** Default field name for total count in a paginated response */
1006
- const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
875
+ class ServerError extends UiPathError {
876
+ constructor(params = {}) {
877
+ super(ErrorType.SERVER, {
878
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
879
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
880
+ requestId: params.requestId
881
+ });
882
+ }
883
+ /**
884
+ * Checks if this is a temporary error that might succeed on retry
885
+ */
886
+ get isRetryable() {
887
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
888
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
889
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
890
+ }
891
+ }
892
+
1007
893
  /**
1008
- * Limits the page size to the maximum allowed value
1009
- * @param pageSize - Requested page size
1010
- * @returns Limited page size value
894
+ * Error thrown when network/connection issues occur
895
+ * Common scenarios:
896
+ * - Connection timeout
897
+ * - DNS resolution failure
898
+ * - Network unreachable
899
+ * - Request aborted
1011
900
  */
1012
- function getLimitedPageSize(pageSize) {
1013
- if (pageSize === undefined || pageSize === null) {
1014
- return DEFAULT_PAGE_SIZE;
901
+ class NetworkError extends UiPathError {
902
+ constructor(params = {}) {
903
+ super(ErrorType.NETWORK, {
904
+ message: params.message || ErrorMessages.NETWORK_ERROR,
905
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
906
+ requestId: params.requestId
907
+ });
1015
908
  }
1016
- return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1017
909
  }
1018
910
 
1019
911
  /**
1020
- * Helper functions for pagination that can be used across services
912
+ * Factory for creating typed errors based on HTTP status codes
913
+ * Follows the Factory pattern for clean error instantiation
1021
914
  */
1022
- class PaginationHelpers {
915
+ class ErrorFactory {
1023
916
  /**
1024
- * Checks if any pagination parameters are provided
1025
- *
1026
- * @param options - The options object to check
1027
- * @returns True if any pagination parameter is defined, false otherwise
917
+ * Creates appropriate error instance based on HTTP status code
1028
918
  */
1029
- static hasPaginationParameters(options = {}) {
1030
- const { cursor, pageSize, jumpToPage } = options;
1031
- return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
919
+ static createFromHttpStatus(statusCode, errorInfo) {
920
+ const { message, requestId } = errorInfo;
921
+ // Map status codes to error types
922
+ switch (statusCode) {
923
+ case HttpStatus.BAD_REQUEST:
924
+ return new ValidationError({ message, statusCode, requestId });
925
+ case HttpStatus.UNAUTHORIZED:
926
+ return new AuthenticationError({ message, statusCode, requestId });
927
+ case HttpStatus.FORBIDDEN:
928
+ return new AuthorizationError({ message, statusCode, requestId });
929
+ case HttpStatus.NOT_FOUND:
930
+ return new NotFoundError({ message, statusCode, requestId });
931
+ case HttpStatus.TOO_MANY_REQUESTS:
932
+ return new RateLimitError({ message, statusCode, requestId });
933
+ default:
934
+ // For 5xx errors or any other status code
935
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
936
+ return new ServerError({ message, statusCode, requestId });
937
+ }
938
+ // For unknown client errors, treat as validation error
939
+ return new ValidationError({
940
+ message: `${message} (HTTP ${statusCode})`,
941
+ statusCode,
942
+ requestId
943
+ });
944
+ }
1032
945
  }
1033
946
  /**
1034
- * Parse a pagination cursor string into cursor data
947
+ * Creates a NetworkError from a fetch/network error
1035
948
  */
1036
- static parseCursor(cursorString) {
1037
- try {
1038
- const cursorData = JSON.parse(decodeBase64(cursorString));
1039
- return cursorData;
1040
- }
1041
- catch {
1042
- throw new Error('Invalid pagination cursor');
949
+ static createNetworkError(error) {
950
+ let message = ErrorMessages.NETWORK_ERROR;
951
+ if (error instanceof Error) {
952
+ if (error.name === ErrorNames.ABORT_ERROR) {
953
+ message = ErrorMessages.REQUEST_ABORTED;
954
+ }
955
+ else if (error.message.includes('timeout')) {
956
+ message = ErrorMessages.REQUEST_TIMEOUT;
957
+ }
958
+ else {
959
+ message = error.message;
960
+ }
1043
961
  }
962
+ return new NetworkError({ message });
963
+ }
964
+ }
965
+
966
+ class ApiClient {
967
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
968
+ this.config = config;
969
+ this.executionContext = executionContext;
970
+ this.clientConfig = clientConfig;
971
+ this.tokenManager = tokenManager;
1044
972
  }
1045
973
  /**
1046
- * Validates cursor format and structure
974
+ * Gets a valid authentication token, refreshing if necessary.
975
+ * Used internally for API requests and exposed for services that need manual auth headers.
1047
976
  *
1048
- * @param paginationOptions - The pagination options containing the cursor
1049
- * @param paginationType - Optional pagination type to validate against
977
+ * @returns The valid token
978
+ * @throws AuthenticationError if no token available or refresh fails
1050
979
  */
1051
- static validateCursor(paginationOptions, paginationType) {
1052
- if (paginationOptions.cursor !== undefined) {
1053
- if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1054
- throw new Error('cursor must contain a valid cursor string');
980
+ async getValidToken() {
981
+ return this.tokenManager.getValidToken();
982
+ }
983
+ async getDefaultHeaders() {
984
+ const token = await this.getValidToken();
985
+ return {
986
+ 'Authorization': `Bearer ${token}`,
987
+ 'Content-Type': CONTENT_TYPES.JSON,
988
+ ...this.clientConfig.headers
989
+ };
990
+ }
991
+ async request(method, path, options = {}) {
992
+ // Ensure path starts with a forward slash
993
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
994
+ // Construct URL with org and tenant names
995
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
996
+ const isFormData = options.body instanceof FormData;
997
+ const defaultHeaders = await this.getDefaultHeaders();
998
+ if (isFormData) {
999
+ delete defaultHeaders['Content-Type'];
1000
+ }
1001
+ const traceId = crypto.randomUUID().replace(/-/g, '');
1002
+ const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
1003
+ const traceparentValue = `00-${traceId}-${spanId}-01`;
1004
+ const headers = {
1005
+ ...defaultHeaders,
1006
+ [TRACEPARENT]: traceparentValue,
1007
+ [UIPATH_TRACEPARENT_ID]: traceparentValue,
1008
+ ...options.headers
1009
+ };
1010
+ // Convert params to URLSearchParams
1011
+ const searchParams = new URLSearchParams();
1012
+ if (options.params) {
1013
+ Object.entries(options.params).forEach(([key, value]) => {
1014
+ searchParams.append(key, value.toString());
1015
+ });
1016
+ }
1017
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
1018
+ let body = undefined;
1019
+ if (options.body) {
1020
+ body = isFormData ? options.body : JSON.stringify(options.body);
1021
+ }
1022
+ try {
1023
+ const response = await fetch(fullUrl, {
1024
+ method,
1025
+ headers,
1026
+ body,
1027
+ signal: options.signal
1028
+ });
1029
+ if (!response.ok) {
1030
+ const errorInfo = await errorResponseParser.parse(response);
1031
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
1032
+ }
1033
+ if (response.status === 204) {
1034
+ return undefined;
1035
+ }
1036
+ // Handle blob response type for binary data (e.g., file downloads)
1037
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
1038
+ const blob = await response.blob();
1039
+ return blob;
1040
+ }
1041
+ // Check if we're expecting XML
1042
+ const acceptHeader = headers['Accept'] || headers['accept'];
1043
+ if (acceptHeader === CONTENT_TYPES.XML) {
1044
+ const text = await response.text();
1045
+ return text;
1046
+ }
1047
+ const text = await response.text();
1048
+ if (!text) {
1049
+ return undefined;
1055
1050
  }
1056
1051
  try {
1057
- // Try to parse the cursor to validate it
1058
- const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1059
- // If type is provided, validate cursor contains expected type information
1060
- if (paginationType) {
1061
- if (!cursorData.type) {
1062
- throw new Error('Invalid cursor: missing pagination type');
1063
- }
1064
- // Check pagination type compatibility
1065
- if (cursorData.type !== paginationType) {
1066
- throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1067
- }
1068
- }
1052
+ return JSON.parse(text);
1069
1053
  }
1070
1054
  catch (error) {
1071
- if (error instanceof Error) {
1072
- // If it's already our error with specific message, pass it through
1073
- if (error.message.startsWith('Invalid cursor') ||
1074
- error.message.startsWith('Pagination type mismatch')) {
1075
- throw error;
1076
- }
1055
+ if (error instanceof SyntaxError) {
1056
+ throw new ServerError({
1057
+ message: `Server returned non-JSON response (${response.status} ${response.url}): ${error.message}`,
1058
+ statusCode: response.status,
1059
+ });
1077
1060
  }
1078
- throw new Error('Invalid pagination cursor format');
1061
+ throw error;
1079
1062
  }
1080
1063
  }
1081
- }
1082
- /**
1083
- * Comprehensive validation for pagination options
1084
- *
1085
- * @param options - The pagination options to validate
1086
- * @param paginationType - The pagination type these options will be used with
1087
- * @returns Processed pagination parameters ready for use
1088
- */
1089
- static validatePaginationOptions(options, paginationType) {
1090
- // Validate pageSize
1091
- if (options.pageSize !== undefined && options.pageSize <= 0) {
1092
- throw new Error('pageSize must be a positive number');
1093
- }
1094
- // Validate jumpToPage
1095
- if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1096
- throw new Error('jumpToPage must be a positive number');
1097
- }
1098
- // Validate cursor
1099
- PaginationHelpers.validateCursor(options, paginationType);
1100
- // Validate service compatibility
1101
- if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1102
- throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1064
+ catch (error) {
1065
+ // If it's already one of our errors, re-throw it
1066
+ if (error.type && error.type.includes('Error')) {
1067
+ throw error;
1068
+ }
1069
+ // Otherwise, it's a genuine network/fetch failure
1070
+ throw ErrorFactory.createNetworkError(error);
1103
1071
  }
1104
- // Get processed parameters
1105
- return PaginationHelpers.getRequestParameters(options, paginationType);
1106
1072
  }
1107
- /**
1108
- * Convert a unified pagination options to service-specific parameters
1109
- */
1110
- static getRequestParameters(options, paginationType) {
1111
- // Handle jumpToPage
1112
- if (options.jumpToPage !== undefined) {
1113
- const jumpToPageOptions = {
1114
- pageSize: options.pageSize,
1115
- pageNumber: options.jumpToPage
1116
- };
1117
- return filterUndefined(jumpToPageOptions);
1118
- }
1119
- // If no cursor is provided, it's a first page request
1120
- if (!options.cursor) {
1121
- const firstPageOptions = {
1122
- pageSize: options.pageSize,
1123
- // Only set pageNumber for OFFSET pagination
1124
- pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1125
- };
1126
- return filterUndefined(firstPageOptions);
1127
- }
1128
- // Parse the cursor
1129
- try {
1130
- const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1131
- const cursorBasedOptions = {
1132
- pageSize: cursorData.pageSize || options.pageSize,
1133
- pageNumber: cursorData.pageNumber,
1134
- continuationToken: cursorData.continuationToken,
1135
- type: cursorData.type,
1136
- };
1137
- return filterUndefined(cursorBasedOptions);
1073
+ async get(path, options = {}) {
1074
+ return this.request('GET', path, options);
1075
+ }
1076
+ async post(path, data, options = {}) {
1077
+ return this.request('POST', path, { ...options, body: data });
1078
+ }
1079
+ async put(path, data, options = {}) {
1080
+ return this.request('PUT', path, { ...options, body: data });
1081
+ }
1082
+ async patch(path, data, options = {}) {
1083
+ return this.request('PATCH', path, { ...options, body: data });
1084
+ }
1085
+ async delete(path, options = {}) {
1086
+ return this.request('DELETE', path, options);
1087
+ }
1088
+ }
1089
+
1090
+ /**
1091
+ * Pagination types supported by the SDK
1092
+ */
1093
+ var PaginationType;
1094
+ (function (PaginationType) {
1095
+ PaginationType["OFFSET"] = "offset";
1096
+ PaginationType["TOKEN"] = "token";
1097
+ })(PaginationType || (PaginationType = {}));
1098
+
1099
+ /**
1100
+ * Collection of utility functions for working with objects
1101
+ */
1102
+ /**
1103
+ * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
1104
+ * and dot-separated nested paths (e.g., 'pagination.totalCount').
1105
+ * Direct key match takes priority over nested traversal.
1106
+ */
1107
+ function resolveNestedField(data, fieldPath) {
1108
+ if (!data) {
1109
+ return undefined;
1110
+ }
1111
+ if (fieldPath in data) {
1112
+ return data[fieldPath];
1113
+ }
1114
+ if (!fieldPath.includes('.')) {
1115
+ return undefined;
1116
+ }
1117
+ let value = data;
1118
+ for (const part of fieldPath.split('.')) {
1119
+ value = value?.[part];
1120
+ }
1121
+ return value;
1122
+ }
1123
+ /**
1124
+ * Filters out undefined values from an object
1125
+ * @param obj The source object
1126
+ * @returns A new object without undefined values
1127
+ *
1128
+ * @example
1129
+ * ```typescript
1130
+ * // Object with undefined values
1131
+ * const options = {
1132
+ * name: 'test',
1133
+ * count: 5,
1134
+ * prefix: undefined,
1135
+ * suffix: null
1136
+ * };
1137
+ * const result = filterUndefined(options);
1138
+ * // result = { name: 'test', count: 5, suffix: null }
1139
+ * ```
1140
+ */
1141
+ function filterUndefined(obj) {
1142
+ const result = {};
1143
+ for (const [key, value] of Object.entries(obj)) {
1144
+ if (value !== undefined) {
1145
+ result[key] = value;
1138
1146
  }
1139
- catch {
1140
- throw new Error('Invalid pagination cursor');
1147
+ }
1148
+ return result;
1149
+ }
1150
+
1151
+ /**
1152
+ * Utility functions for platform detection
1153
+ */
1154
+ /**
1155
+ * Checks if code is running in a browser environment
1156
+ */
1157
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
1158
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
1159
+
1160
+ /**
1161
+ * Base64 encoding/decoding
1162
+ */
1163
+ /**
1164
+ * Encodes a string to base64
1165
+ * @param str - The string to encode
1166
+ * @returns Base64 encoded string
1167
+ */
1168
+ function encodeBase64(str) {
1169
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
1170
+ const encoder = new TextEncoder();
1171
+ const data = encoder.encode(str);
1172
+ // Convert Uint8Array to base64
1173
+ if (isBrowser) {
1174
+ // Browser environment
1175
+ // Convert Uint8Array to binary string then to base64
1176
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
1177
+ return btoa(binaryString);
1178
+ }
1179
+ else {
1180
+ // Node.js environment
1181
+ return Buffer.from(data).toString('base64');
1182
+ }
1183
+ }
1184
+ /**
1185
+ * Decodes a base64 string
1186
+ * @param base64 - The base64 string to decode
1187
+ * @returns Decoded string
1188
+ */
1189
+ function decodeBase64(base64) {
1190
+ let bytes;
1191
+ if (isBrowser) {
1192
+ // Browser environment
1193
+ const binaryString = atob(base64);
1194
+ bytes = new Uint8Array(binaryString.length);
1195
+ for (let i = 0; i < binaryString.length; i++) {
1196
+ bytes[i] = binaryString.charCodeAt(i);
1141
1197
  }
1142
1198
  }
1143
- /**
1144
- * Helper method for paginated resource retrieval
1145
- *
1146
- * @param params - Parameters for pagination
1147
- * @returns Promise resolving to a paginated result
1148
- */
1149
- static async getAllPaginated(params) {
1150
- const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1151
- const endpoint = getEndpoint(folderId);
1152
- const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1153
- const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1154
- headers,
1155
- params: additionalParams,
1156
- pagination: {
1157
- paginationType: options.paginationType || PaginationType.OFFSET,
1158
- itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1159
- totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1160
- continuationTokenField: options.continuationTokenField,
1161
- paginationParams: options.paginationParams
1162
- }
1163
- });
1164
- // Parse items - automatically handle JSON string responses
1165
- const rawItems = paginatedResponse.items;
1166
- const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1167
- const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1168
- return {
1169
- ...paginatedResponse,
1170
- items: transformedItems
1171
- };
1199
+ else {
1200
+ // Node.js environment
1201
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
1172
1202
  }
1203
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
1204
+ const decoder = new TextDecoder();
1205
+ return decoder.decode(bytes);
1206
+ }
1207
+
1208
+ /**
1209
+ * PaginationManager handles the conversion between uniform cursor-based pagination
1210
+ * and the specific pagination type for each service
1211
+ */
1212
+ class PaginationManager {
1173
1213
  /**
1174
- * Helper method for non-paginated resource retrieval
1175
- *
1176
- * @param params - Parameters for non-paginated resource retrieval
1177
- * @returns Promise resolving to an object with data and totalCount
1214
+ * Create a pagination cursor for subsequent page requests
1178
1215
  */
1179
- static async getAllNonPaginated(params) {
1180
- const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1181
- // Set default field names
1182
- const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1183
- const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1184
- // Determine endpoint and headers based on folderId
1185
- const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1186
- const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1187
- // Make the API call based on method
1188
- let response;
1189
- if (method === HTTP_METHODS.POST) {
1190
- response = await serviceAccess.post(endpoint, additionalParams, { headers });
1216
+ static createCursor({ pageInfo, type }) {
1217
+ if (!pageInfo.hasMore) {
1218
+ return undefined;
1191
1219
  }
1192
- else {
1193
- response = await serviceAccess.get(endpoint, {
1194
- params: additionalParams,
1195
- headers
1196
- });
1220
+ const cursorData = {
1221
+ type,
1222
+ pageSize: pageInfo.pageSize,
1223
+ };
1224
+ switch (type) {
1225
+ case PaginationType.OFFSET:
1226
+ if (pageInfo.currentPage) {
1227
+ cursorData.pageNumber = pageInfo.currentPage + 1;
1228
+ }
1229
+ break;
1230
+ case PaginationType.TOKEN:
1231
+ if (pageInfo.continuationToken) {
1232
+ cursorData.continuationToken = pageInfo.continuationToken;
1233
+ }
1234
+ else {
1235
+ return undefined; // No continuation token, can't continue
1236
+ }
1237
+ break;
1197
1238
  }
1198
- // Extract and transform items from response
1199
- // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1200
- const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
1201
- const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1202
- const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1203
- // Parse items - automatically handle JSON string responses
1204
- const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1205
- const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1206
1239
  return {
1207
- items,
1208
- totalCount
1240
+ value: encodeBase64(JSON.stringify(cursorData))
1209
1241
  };
1210
1242
  }
1211
1243
  /**
1212
- * Centralized getAll implementation that handles both paginated and non-paginated requests
1213
- *
1214
- * @param config - Configuration for the getAll operation
1215
- * @param options - Request options including pagination parameters
1216
- * @returns Promise resolving to either paginated or non-paginated response based on options
1244
+ * Create a paginated response with navigation cursors
1217
1245
  */
1218
- static async getAll(config, options) {
1219
- const optionsWithDefaults = options || {};
1220
- const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1221
- // Determine if pagination is requested
1222
- const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1223
- // Process parameters (custom processing if provided, otherwise default)
1224
- let processedOptions = restOptions;
1225
- if (config.processParametersFn) {
1226
- processedOptions = config.processParametersFn(restOptions, folderId);
1246
+ static createPaginatedResponse({ pageInfo, type }, items) {
1247
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
1248
+ // Create previous page cursor if applicable
1249
+ let previousCursor = undefined;
1250
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
1251
+ const prevCursorData = {
1252
+ type,
1253
+ pageNumber: pageInfo.currentPage - 1,
1254
+ pageSize: pageInfo.pageSize,
1255
+ };
1256
+ previousCursor = {
1257
+ value: encodeBase64(JSON.stringify(prevCursorData))
1258
+ };
1227
1259
  }
1228
- // Apply ODATA prefix to keys (excluding specified keys)
1229
- const excludeKeys = config.excludeFromPrefix || [];
1230
- const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1231
- const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1232
- // Default pagination options
1233
- const paginationOptions = {
1234
- paginationType: PaginationType.OFFSET,
1235
- itemsField: DEFAULT_ITEMS_FIELD,
1236
- totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1237
- ...config.pagination
1238
- };
1239
- // Paginated flow
1240
- if (isPaginationRequested) {
1241
- return PaginationHelpers.getAllPaginated({
1242
- serviceAccess: config.serviceAccess,
1243
- getEndpoint: config.getEndpoint,
1244
- folderId,
1245
- paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1246
- additionalParams: prefixedOptions,
1247
- transformFn: config.transformFn,
1248
- method: config.method,
1249
- options: {
1250
- ...paginationOptions,
1251
- paginationParams: config.pagination?.paginationParams
1252
- }
1253
- }); // Type assertion needed due to conditional return
1260
+ // Calculate total pages if we have totalCount and pageSize
1261
+ let totalPages = undefined;
1262
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
1263
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
1254
1264
  }
1255
- // Non-paginated flow
1256
- const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1257
- return PaginationHelpers.getAllNonPaginated({
1258
- serviceAccess: config.serviceAccess,
1259
- getAllEndpoint: config.getEndpoint(),
1260
- getByFolderEndpoint: byFolderEndpoint,
1261
- folderId,
1262
- additionalParams: prefixedOptions,
1263
- transformFn: config.transformFn,
1264
- method: config.method,
1265
- options: {
1266
- itemsField: paginationOptions.itemsField,
1267
- totalCountField: paginationOptions.totalCountField
1268
- }
1265
+ // Determine if this pagination type supports page jumping
1266
+ const supportsPageJump = type === PaginationType.OFFSET;
1267
+ // Create the result object with all fields, then filter out undefined values
1268
+ const result = filterUndefined({
1269
+ items,
1270
+ totalCount: pageInfo.totalCount,
1271
+ hasNextPage: pageInfo.hasMore,
1272
+ nextCursor: nextCursor,
1273
+ previousCursor: previousCursor,
1274
+ currentPage: pageInfo.currentPage,
1275
+ totalPages,
1276
+ supportsPageJump
1269
1277
  });
1278
+ return result;
1270
1279
  }
1271
1280
  }
1272
1281
 
1273
1282
  /**
1274
- * SDK Internals Registry - Internal registry for SDK instances
1275
- *
1276
- * This class is NOT exported in the public API.
1277
- * It provides a secure way to share SDK internals between
1278
- * the UiPath class and service classes without exposing them publicly.
1279
- *
1280
- * @internal
1281
- */
1282
- // Global symbol key to ensure WeakMap is shared across module instances
1283
- // This prevents issues when core and service modules are bundled separately
1284
- const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1285
- // Get or create the global WeakMap store
1286
- const getGlobalStore = () => {
1287
- const globalObj = globalThis;
1288
- if (!globalObj[REGISTRY_KEY]) {
1289
- globalObj[REGISTRY_KEY] = new WeakMap();
1290
- }
1291
- return globalObj[REGISTRY_KEY];
1292
- };
1293
- /**
1294
- * Internal registry for SDK private components.
1295
- * Uses WeakMap to prevent memory leaks - entries are automatically
1296
- * garbage collected when the SDK instance is no longer referenced.
1297
- *
1298
- * Uses a global singleton pattern to ensure the same WeakMap is shared
1299
- * across separately bundled modules (core, entities, tasks, etc.).
1300
- *
1301
- * @internal - Not exported in public API
1302
- */
1303
- class SDKInternalsRegistry {
1304
- // Use global store to ensure sharing across module bundles
1305
- static get store() {
1306
- return getGlobalStore();
1307
- }
1308
- /**
1309
- * Register SDK instance internals
1310
- * Called by UiPath constructor
1311
- */
1312
- static set(instance, internals) {
1313
- this.store.set(instance, internals);
1314
- }
1315
- /**
1316
- * Retrieve SDK instance internals
1317
- * Called by BaseService constructor
1318
- */
1319
- static get(instance) {
1320
- const internals = this.store.get(instance);
1321
- if (!internals) {
1322
- throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1323
- }
1324
- return internals;
1283
+ * Constants used throughout the pagination system
1284
+ */
1285
+ /** Maximum number of items that can be requested in a single page */
1286
+ const MAX_PAGE_SIZE = 1000;
1287
+ /** Default page size when jumpToPage is used without specifying pageSize */
1288
+ const DEFAULT_PAGE_SIZE = 50;
1289
+ /** Default field name for items in a paginated response */
1290
+ const DEFAULT_ITEMS_FIELD = 'value';
1291
+ /** Default field name for total count in a paginated response */
1292
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1293
+ /**
1294
+ * Limits the page size to the maximum allowed value
1295
+ * @param pageSize - Requested page size
1296
+ * @returns Limited page size value
1297
+ */
1298
+ function getLimitedPageSize(pageSize) {
1299
+ if (pageSize === undefined || pageSize === null) {
1300
+ return DEFAULT_PAGE_SIZE;
1325
1301
  }
1302
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1326
1303
  }
1327
1304
 
1328
- var _BaseService_apiClient;
1329
1305
  /**
1330
- * Base class for all UiPath SDK services.
1331
- *
1332
- * Provides common functionality for authentication, configuration, and API communication.
1333
- * All service classes extend this base to inherit dependency injection and HTTP client access.
1334
- *
1335
- * This class implements the dependency injection pattern where services receive a configured
1336
- * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1337
- * including authentication token management.
1338
- *
1339
- * @remarks
1340
- * Service classes should extend this base and call `super(uiPath)` in their constructor.
1341
- * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1342
- *
1306
+ * Helper functions for pagination that can be used across services
1343
1307
  */
1344
- class BaseService {
1308
+ class PaginationHelpers {
1345
1309
  /**
1346
- * Creates a base service instance with dependency injection.
1347
- *
1348
- * Extracts configuration, execution context, and token manager from the UiPath instance
1349
- * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1350
- * and token management internally.
1351
- *
1352
- * @param instance - UiPath SDK instance providing authentication and configuration.
1353
- * Services receive this via dependency injection in the modular pattern.
1354
- * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1355
- * CAS external-app auth)
1356
- *
1357
- * @example
1358
- * ```typescript
1359
- * // Services automatically call this via super()
1360
- * export class EntityService extends BaseService {
1361
- * constructor(instance: IUiPath) {
1362
- * super(instance); // Initializes the internal ApiClient
1363
- * }
1364
- * }
1365
- *
1366
- * // Usage in modular pattern
1367
- * import { UiPath } from '@uipath/uipath-typescript/core';
1368
- * import { Entities } from '@uipath/uipath-typescript/entities';
1310
+ * Checks if any pagination parameters are provided
1369
1311
  *
1370
- * const sdk = new UiPath(config);
1371
- * await sdk.initialize();
1372
- * const entities = new Entities(sdk);
1373
- * ```
1312
+ * @param options - The options object to check
1313
+ * @returns True if any pagination parameter is defined, false otherwise
1374
1314
  */
1375
- constructor(instance, headers) {
1376
- // Private field - not visible via Object.keys() or any reflection
1377
- _BaseService_apiClient.set(this, void 0);
1378
- const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1379
- __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1380
- this.config = { folderKey };
1315
+ static hasPaginationParameters(options = {}) {
1316
+ const { cursor, pageSize, jumpToPage } = options;
1317
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1381
1318
  }
1382
1319
  /**
1383
- * Gets a valid authentication token, refreshing if necessary.
1384
- * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1385
- *
1386
- * @returns Promise resolving to a valid access token string
1387
- * @throws AuthenticationError if no token is available or refresh fails
1320
+ * Parse a pagination cursor string into cursor data
1388
1321
  */
1389
- async getValidAuthToken() {
1390
- return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1322
+ static parseCursor(cursorString) {
1323
+ try {
1324
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1325
+ return cursorData;
1326
+ }
1327
+ catch {
1328
+ throw new Error('Invalid pagination cursor');
1329
+ }
1391
1330
  }
1392
1331
  /**
1393
- * Creates a service accessor for pagination helpers
1394
- * This allows pagination helpers to access protected methods without making them public
1332
+ * Validates cursor format and structure
1333
+ *
1334
+ * @param paginationOptions - The pagination options containing the cursor
1335
+ * @param paginationType - Optional pagination type to validate against
1395
1336
  */
1396
- createPaginationServiceAccess() {
1397
- return {
1398
- get: (path, options) => this.get(path, options || {}),
1399
- post: (path, body, options) => this.post(path, body, options || {}),
1400
- requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1401
- };
1402
- }
1403
- async request(method, path, options = {}) {
1404
- switch (method.toUpperCase()) {
1405
- case 'GET':
1406
- return this.get(path, options);
1407
- case 'POST':
1408
- return this.post(path, options.body, options);
1409
- case 'PUT':
1410
- return this.put(path, options.body, options);
1411
- case 'PATCH':
1412
- return this.patch(path, options.body, options);
1413
- case 'DELETE':
1414
- return this.delete(path, options);
1415
- default:
1416
- throw new Error(`Unsupported HTTP method: ${method}`);
1337
+ static validateCursor(paginationOptions, paginationType) {
1338
+ if (paginationOptions.cursor !== undefined) {
1339
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1340
+ throw new Error('cursor must contain a valid cursor string');
1341
+ }
1342
+ try {
1343
+ // Try to parse the cursor to validate it
1344
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1345
+ // If type is provided, validate cursor contains expected type information
1346
+ if (paginationType) {
1347
+ if (!cursorData.type) {
1348
+ throw new Error('Invalid cursor: missing pagination type');
1349
+ }
1350
+ // Check pagination type compatibility
1351
+ if (cursorData.type !== paginationType) {
1352
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1353
+ }
1354
+ }
1355
+ }
1356
+ catch (error) {
1357
+ if (error instanceof Error) {
1358
+ // If it's already our error with specific message, pass it through
1359
+ if (error.message.startsWith('Invalid cursor') ||
1360
+ error.message.startsWith('Pagination type mismatch')) {
1361
+ throw error;
1362
+ }
1363
+ }
1364
+ throw new Error('Invalid pagination cursor format');
1365
+ }
1417
1366
  }
1418
1367
  }
1419
- async requestWithSpec(spec) {
1420
- if (!spec.method || !spec.url) {
1421
- throw new Error('Request spec must include method and url');
1368
+ /**
1369
+ * Comprehensive validation for pagination options
1370
+ *
1371
+ * @param options - The pagination options to validate
1372
+ * @param paginationType - The pagination type these options will be used with
1373
+ * @returns Processed pagination parameters ready for use
1374
+ */
1375
+ static validatePaginationOptions(options, paginationType) {
1376
+ // Validate pageSize
1377
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1378
+ throw new Error('pageSize must be a positive number');
1422
1379
  }
1423
- return this.request(spec.method, spec.url, spec);
1424
- }
1425
- async get(path, options = {}) {
1426
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1427
- return { data: response };
1428
- }
1429
- async post(path, data, options = {}) {
1430
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1431
- return { data: response };
1432
- }
1433
- async put(path, data, options = {}) {
1434
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1435
- return { data: response };
1436
- }
1437
- async patch(path, data, options = {}) {
1438
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1439
- return { data: response };
1440
- }
1441
- async delete(path, options = {}) {
1442
- const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1443
- return { data: response };
1380
+ // Validate jumpToPage
1381
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1382
+ throw new Error('jumpToPage must be a positive number');
1383
+ }
1384
+ // Validate cursor
1385
+ PaginationHelpers.validateCursor(options, paginationType);
1386
+ // Validate service compatibility
1387
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1388
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1389
+ }
1390
+ // Get processed parameters
1391
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1444
1392
  }
1445
1393
  /**
1446
- * Execute a request with cursor-based pagination
1394
+ * Convert a unified pagination options to service-specific parameters
1447
1395
  */
1448
- async requestWithPagination(method, path, paginationOptions, options) {
1449
- const paginationType = options.pagination.paginationType;
1450
- // Validate and prepare pagination parameters
1451
- const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1452
- // Prepare request parameters based on pagination type
1453
- const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1454
- // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1455
- if (method.toUpperCase() === 'POST') {
1456
- const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1457
- options.body = {
1458
- ...existingBody,
1459
- ...options.params,
1460
- ...requestParams
1396
+ static getRequestParameters(options, paginationType) {
1397
+ // Handle jumpToPage
1398
+ if (options.jumpToPage !== undefined) {
1399
+ const jumpToPageOptions = {
1400
+ pageSize: options.pageSize,
1401
+ pageNumber: options.jumpToPage
1461
1402
  };
1462
- options.params = undefined;
1403
+ return filterUndefined(jumpToPageOptions);
1463
1404
  }
1464
- else {
1465
- // Merge pagination parameters with existing parameters
1466
- options.params = {
1467
- ...options.params,
1468
- ...requestParams
1405
+ // If no cursor is provided, it's a first page request
1406
+ if (!options.cursor) {
1407
+ const firstPageOptions = {
1408
+ pageSize: options.pageSize,
1409
+ // Only set pageNumber for OFFSET pagination
1410
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1469
1411
  };
1412
+ return filterUndefined(firstPageOptions);
1413
+ }
1414
+ // Parse the cursor
1415
+ try {
1416
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1417
+ const cursorBasedOptions = {
1418
+ pageSize: cursorData.pageSize || options.pageSize,
1419
+ pageNumber: cursorData.pageNumber,
1420
+ continuationToken: cursorData.continuationToken,
1421
+ type: cursorData.type,
1422
+ };
1423
+ return filterUndefined(cursorBasedOptions);
1424
+ }
1425
+ catch {
1426
+ throw new Error('Invalid pagination cursor');
1470
1427
  }
1471
- // Make the request
1472
- const response = await this.request(method, path, options);
1473
- // Extract data from the response and create page result
1474
- return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1475
- itemsField: options.pagination.itemsField,
1476
- totalCountField: options.pagination.totalCountField,
1477
- continuationTokenField: options.pagination.continuationTokenField
1478
- });
1479
- }
1480
- /**
1481
- * Validates and prepares pagination parameters from options
1482
- */
1483
- validateAndPreparePaginationParams(paginationType, paginationOptions) {
1484
- return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1485
1428
  }
1486
1429
  /**
1487
- * Prepares request parameters for pagination based on pagination type
1430
+ * Helper method for paginated resource retrieval
1431
+ *
1432
+ * @param params - Parameters for pagination
1433
+ * @returns Promise resolving to a paginated result
1488
1434
  */
1489
- preparePaginationRequestParams(paginationType, params, paginationConfig) {
1490
- const requestParams = {};
1491
- let limitedPageSize;
1492
- const paginationParams = paginationConfig?.paginationParams;
1493
- switch (paginationType) {
1494
- case PaginationType.OFFSET:
1495
- limitedPageSize = getLimitedPageSize(params.pageSize);
1496
- const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1497
- const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1498
- const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1499
- // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1500
- // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1501
- const convertToSkip = paginationParams?.convertToSkip ?? true;
1502
- requestParams[pageSizeParam] = limitedPageSize;
1503
- if (convertToSkip) {
1504
- if (params.pageNumber && params.pageNumber > 1) {
1505
- requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1506
- }
1507
- }
1508
- else {
1509
- requestParams[offsetParam] = params.pageNumber || 1;
1510
- }
1511
- {
1512
- requestParams[countParam] = true;
1513
- }
1514
- break;
1515
- case PaginationType.TOKEN:
1516
- const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1517
- const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1518
- if (params.pageSize) {
1519
- requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1520
- }
1521
- if (params.continuationToken) {
1522
- requestParams[tokenParam] = params.continuationToken;
1523
- }
1524
- break;
1525
- }
1526
- return requestParams;
1435
+ static async getAllPaginated(params) {
1436
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1437
+ const endpoint = getEndpoint(folderId);
1438
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1439
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1440
+ headers,
1441
+ params: additionalParams,
1442
+ pagination: {
1443
+ paginationType: options.paginationType || PaginationType.OFFSET,
1444
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1445
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1446
+ continuationTokenField: options.continuationTokenField,
1447
+ paginationParams: options.paginationParams
1448
+ }
1449
+ });
1450
+ // Parse items - automatically handle JSON string responses
1451
+ const rawItems = paginatedResponse.items;
1452
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1453
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1454
+ return {
1455
+ ...paginatedResponse,
1456
+ items: transformedItems
1457
+ };
1527
1458
  }
1528
1459
  /**
1529
- * Creates a paginated response from API response
1460
+ * Helper method for non-paginated resource retrieval
1461
+ *
1462
+ * @param params - Parameters for non-paginated resource retrieval
1463
+ * @returns Promise resolving to an object with data and totalCount
1530
1464
  */
1531
- createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1532
- // Extract fields from response
1533
- const itemsField = fields.itemsField ||
1534
- (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1535
- const totalCountField = fields.totalCountField || 'totalRecordCount';
1536
- const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1537
- // Extract items and metadata
1465
+ static async getAllNonPaginated(params) {
1466
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1467
+ // Set default field names
1468
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1469
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1470
+ // Determine endpoint and headers based on folderId
1471
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1472
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1473
+ // Make the API call based on method
1474
+ let response;
1475
+ if (method === HTTP_METHODS.POST) {
1476
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1477
+ }
1478
+ else {
1479
+ response = await serviceAccess.get(endpoint, {
1480
+ params: additionalParams,
1481
+ headers
1482
+ });
1483
+ }
1484
+ // Extract and transform items from response
1538
1485
  // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1539
- const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
1486
+ const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
1540
1487
  const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1541
1488
  const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1542
- const continuationToken = response.data[continuationTokenField];
1543
- // Determine if there are more pages
1544
- const hasMore = this.determineHasMorePages(paginationType, {
1545
- totalCount,
1546
- pageSize: params.pageSize,
1547
- currentPage: params.pageNumber || 1,
1548
- itemsCount: items.length,
1549
- continuationToken
1550
- });
1551
- // Create and return the page result
1552
- return PaginationManager.createPaginatedResponse({
1553
- pageInfo: {
1554
- hasMore,
1555
- totalCount,
1556
- currentPage: params.pageNumber,
1557
- pageSize: params.pageSize,
1558
- continuationToken
1559
- },
1560
- type: paginationType,
1561
- }, items);
1489
+ // Parse items - automatically handle JSON string responses
1490
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1491
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1492
+ return {
1493
+ items,
1494
+ totalCount
1495
+ };
1562
1496
  }
1563
1497
  /**
1564
- * Determines if there are more pages based on pagination type and metadata
1498
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1499
+ *
1500
+ * @param config - Configuration for the getAll operation
1501
+ * @param options - Request options including pagination parameters
1502
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1565
1503
  */
1566
- determineHasMorePages(paginationType, info) {
1567
- switch (paginationType) {
1568
- case PaginationType.OFFSET:
1569
- const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1570
- // If totalCount is available, use it for precise calculation
1571
- if (info.totalCount !== undefined) {
1572
- return (info.currentPage * effectivePageSize) < info.totalCount;
1573
- }
1574
- // Fallback when totalCount is not available
1575
- // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1576
- return info.itemsCount === effectivePageSize;
1577
- case PaginationType.TOKEN:
1578
- return !!info.continuationToken;
1579
- default:
1580
- return false;
1504
+ static async getAll(config, options) {
1505
+ const optionsWithDefaults = options || {};
1506
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1507
+ // Determine if pagination is requested
1508
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1509
+ // Process parameters (custom processing if provided, otherwise default)
1510
+ let processedOptions = restOptions;
1511
+ if (config.processParametersFn) {
1512
+ processedOptions = config.processParametersFn(restOptions, folderId);
1581
1513
  }
1582
- }
1583
- }
1584
- _BaseService_apiClient = new WeakMap();
1585
-
1586
- /**
1587
- * Base path constants for different services
1588
- */
1589
- const PIMS_BASE = 'pims_';
1590
-
1591
- /**
1592
- * Maestro Service Endpoints
1593
- */
1594
- /**
1595
- * Maestro Process Service Endpoints
1596
- */
1597
- const MAESTRO_ENDPOINTS = {
1598
- PROCESSES: {
1599
- GET_ALL: `${PIMS_BASE}/api/v1/processes/summary`},
1600
- INSTANCES: {
1601
- GET_ALL: `${PIMS_BASE}/api/v1/instances`,
1602
- GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
1603
- GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
1604
- GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
1605
- GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
1606
- CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
1607
- PAUSE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/pause`,
1608
- RESUME: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/resume`,
1609
- },
1610
- INCIDENTS: {
1611
- GET_ALL: `${PIMS_BASE}/api/v1/incidents/summary`,
1612
- GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
1613
- GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
1614
- }};
1615
-
1616
- /**
1617
- * Maestro Process Models
1618
- * Model classes for Maestro processes
1619
- */
1620
- /**
1621
- * Creates methods for a process object
1622
- *
1623
- * @param processData - The process data (response from API)
1624
- * @param service - The process service instance
1625
- * @returns Object containing process methods
1626
- */
1627
- function createProcessMethods(processData, service) {
1628
- return {
1629
- async getIncidents() {
1630
- if (!processData.processKey)
1631
- throw new Error('Process key is undefined');
1632
- if (!processData.folderKey)
1633
- throw new Error('Folder key is undefined');
1634
- return service.getIncidents(processData.processKey, processData.folderKey);
1514
+ // Apply ODATA prefix to keys (excluding specified keys)
1515
+ const excludeKeys = config.excludeFromPrefix || [];
1516
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1517
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1518
+ // Default pagination options
1519
+ const paginationOptions = {
1520
+ paginationType: PaginationType.OFFSET,
1521
+ itemsField: DEFAULT_ITEMS_FIELD,
1522
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1523
+ ...config.pagination
1524
+ };
1525
+ // Paginated flow
1526
+ if (isPaginationRequested) {
1527
+ return PaginationHelpers.getAllPaginated({
1528
+ serviceAccess: config.serviceAccess,
1529
+ getEndpoint: config.getEndpoint,
1530
+ folderId,
1531
+ headers: config.headers,
1532
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1533
+ additionalParams: prefixedOptions,
1534
+ transformFn: config.transformFn,
1535
+ method: config.method,
1536
+ options: {
1537
+ ...paginationOptions,
1538
+ paginationParams: config.pagination?.paginationParams
1539
+ }
1540
+ }); // Type assertion needed due to conditional return
1635
1541
  }
1636
- };
1637
- }
1638
- /**
1639
- * Creates an actionable process by combining API process data with operational methods.
1640
- *
1641
- * @param processData - The process data from API
1642
- * @param service - The process service instance
1643
- * @returns A process object with added methods
1644
- */
1645
- function createProcessWithMethods(processData, service) {
1646
- const methods = createProcessMethods(processData, service);
1647
- return Object.assign({}, processData, methods);
1542
+ // Non-paginated flow
1543
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1544
+ return PaginationHelpers.getAllNonPaginated({
1545
+ serviceAccess: config.serviceAccess,
1546
+ getAllEndpoint: config.getEndpoint(),
1547
+ getByFolderEndpoint: byFolderEndpoint,
1548
+ folderId,
1549
+ headers: config.headers,
1550
+ additionalParams: prefixedOptions,
1551
+ transformFn: config.transformFn,
1552
+ method: config.method,
1553
+ options: {
1554
+ itemsField: paginationOptions.itemsField,
1555
+ totalCountField: paginationOptions.totalCountField
1556
+ }
1557
+ });
1558
+ }
1648
1559
  }
1649
1560
 
1650
1561
  /**
1651
- * Maps fields for Incident entities
1562
+ * SDK Internals Registry - Internal registry for SDK instances
1563
+ *
1564
+ * This class is NOT exported in the public API.
1565
+ * It provides a secure way to share SDK internals between
1566
+ * the UiPath class and service classes without exposing them publicly.
1567
+ *
1568
+ * @internal
1652
1569
  */
1653
- const ProcessIncidentMap = {
1654
- errorTimeUtc: 'errorTime'
1570
+ // Global symbol key to ensure WeakMap is shared across module instances
1571
+ // This prevents issues when core and service modules are bundled separately
1572
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1573
+ // Get or create the global WeakMap store
1574
+ const getGlobalStore = () => {
1575
+ const globalObj = globalThis;
1576
+ if (!globalObj[REGISTRY_KEY]) {
1577
+ globalObj[REGISTRY_KEY] = new WeakMap();
1578
+ }
1579
+ return globalObj[REGISTRY_KEY];
1655
1580
  };
1656
1581
  /**
1657
- * Maps fields for Incident Summary entities
1582
+ * Internal registry for SDK private components.
1583
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1584
+ * garbage collected when the SDK instance is no longer referenced.
1585
+ *
1586
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1587
+ * across separately bundled modules (core, entities, tasks, etc.).
1588
+ *
1589
+ * @internal - Not exported in public API
1658
1590
  */
1659
- const ProcessIncidentSummaryMap = {
1660
- firstTimeUtc: 'firstOccuranceTime'
1661
- };
1662
-
1663
- /**
1664
- * Helpers for fetching BPMN XML and extracting element details used to annotate responses
1665
- */
1666
- class BpmnHelpers {
1667
- /**
1668
- * Parse BPMN XML and extract element id → {name,type} used for incidents
1669
- */
1670
- static parseBpmnElementsForIncidents(bpmnXml) {
1671
- const elementInfo = {};
1672
- try {
1673
- // Find <bpmn:...> start tags and capture the element type.
1674
- // Then read 'id' and 'name' attributes from each tag.
1675
- const bpmnOpenTagRegex = /<bpmn:([A-Za-z][\w.-]*)\b[^>]*>/g;
1676
- for (const tagMatch of bpmnXml.matchAll(bpmnOpenTagRegex)) {
1677
- const [fullTag, elementType] = tagMatch;
1678
- // Extract attributes from the current tag text.
1679
- const idMatch = /\bid\s*=\s*"([^"]*)"/.exec(fullTag);
1680
- if (!idMatch) {
1681
- continue;
1682
- }
1683
- const elementId = idMatch[1];
1684
- const nameMatch = /\bname\s*=\s*"([^"]*)"/.exec(fullTag);
1685
- const name = nameMatch ? nameMatch[1] : '';
1686
- // Convert BPMN element type to human-readable format
1687
- const activityType = this.formatActivityTypeForIncidents(elementType);
1688
- const activityName = name || elementId;
1689
- elementInfo[elementId] = {
1690
- type: activityType,
1691
- name: activityName
1692
- };
1693
- }
1694
- }
1695
- catch (error) {
1696
- console.warn('Failed to parse BPMN XML for incidents:', error);
1697
- }
1698
- return elementInfo;
1591
+ class SDKInternalsRegistry {
1592
+ // Use global store to ensure sharing across module bundles
1593
+ static get store() {
1594
+ return getGlobalStore();
1699
1595
  }
1700
1596
  /**
1701
- * Format BPMN element type to human-readable activity type for incidents
1597
+ * Register SDK instance internals
1598
+ * Called by UiPath constructor
1702
1599
  */
1703
- static formatActivityTypeForIncidents(elementType) {
1704
- // Convert camelCase BPMN element types to human-readable format
1705
- // e.g., "serviceTask" -> "Service Task", "exclusiveGateway" -> "Exclusive Gateway"
1706
- return elementType
1707
- .replace(/([A-Z])/g, ' $1') // Add space before uppercase letters
1708
- .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
1709
- .trim(); // Remove any leading/trailing spaces
1600
+ static set(instance, internals) {
1601
+ this.store.set(instance, internals);
1710
1602
  }
1711
1603
  /**
1712
- * Fetch BPMN via getBpmn and add element name/type to each incident
1604
+ * Retrieve SDK instance internals
1605
+ * Called by BaseService constructor
1713
1606
  */
1714
- static async enrichIncidentsWithBpmnData(incidents, folderKey, service) {
1715
- // Check if all incidents have the same instanceId
1716
- const uniqueInstanceIds = [...new Set(incidents.map(i => i.instanceId))];
1717
- if (uniqueInstanceIds.length === 1) {
1718
- // Single instance optimization (in case of process instance incidents)
1719
- const elementInfo = await this.getBpmnElementInfo(uniqueInstanceIds[0], folderKey, service);
1720
- return incidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
1721
- }
1722
- else {
1723
- // Multiple instances optimization (in case of process incidents)
1724
- return this.enrichMultipleInstanceIncidents(incidents, folderKey, service);
1607
+ static get(instance) {
1608
+ const internals = this.store.get(instance);
1609
+ if (!internals) {
1610
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1725
1611
  }
1612
+ return internals;
1726
1613
  }
1614
+ }
1615
+
1616
+ var _BaseService_apiClient;
1617
+ /**
1618
+ * Base class for all UiPath SDK services.
1619
+ *
1620
+ * Provides common functionality for authentication, configuration, and API communication.
1621
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1622
+ *
1623
+ * This class implements the dependency injection pattern where services receive a configured
1624
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1625
+ * including authentication token management.
1626
+ *
1627
+ * @remarks
1628
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1629
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1630
+ *
1631
+ */
1632
+ class BaseService {
1727
1633
  /**
1728
- * When incidents span multiple instances, fetch BPMN per instance and annotate
1634
+ * Creates a base service instance with dependency injection.
1635
+ *
1636
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1637
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1638
+ * and token management internally.
1639
+ *
1640
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1641
+ * Services receive this via dependency injection in the modular pattern.
1642
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1643
+ * CAS external-app auth)
1644
+ *
1645
+ * @example
1646
+ * ```typescript
1647
+ * // Services automatically call this via super()
1648
+ * export class EntityService extends BaseService {
1649
+ * constructor(instance: IUiPath) {
1650
+ * super(instance); // Initializes the internal ApiClient
1651
+ * }
1652
+ * }
1653
+ *
1654
+ * // Usage in modular pattern
1655
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1656
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1657
+ *
1658
+ * const sdk = new UiPath(config);
1659
+ * await sdk.initialize();
1660
+ * const entities = new Entities(sdk);
1661
+ * ```
1729
1662
  */
1730
- static async enrichMultipleInstanceIncidents(incidents, folderKey, service) {
1731
- const groups = incidents.reduce((acc, incident) => {
1732
- const id = incident.instanceId || NO_INSTANCE;
1733
- (acc[id] = acc[id] || []).push(incident);
1734
- return acc;
1735
- }, {});
1736
- const results = await Promise.all(Object.entries(groups).map(async (entry) => {
1737
- const [instanceId, groupIncidents] = entry;
1738
- const elementInfo = await this.getBpmnElementInfo(instanceId, folderKey, service);
1739
- return groupIncidents.map((incident) => this.transformIncidentWithBpmn(incident, elementInfo));
1740
- }));
1741
- return results.flat();
1663
+ constructor(instance, headers) {
1664
+ // Private field - not visible via Object.keys() or any reflection
1665
+ _BaseService_apiClient.set(this, void 0);
1666
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1667
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1668
+ this.config = { folderKey };
1742
1669
  }
1743
1670
  /**
1744
- * Retrieve BPMN XML for an instance and derive element id → {name,type}
1671
+ * Gets a valid authentication token, refreshing if necessary.
1672
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1673
+ *
1674
+ * @returns Promise resolving to a valid access token string
1675
+ * @throws AuthenticationError if no token is available or refresh fails
1745
1676
  */
1746
- static async getBpmnElementInfo(instanceId, folderKey, service) {
1747
- if (!instanceId || instanceId === NO_INSTANCE) {
1748
- return {};
1749
- }
1750
- try {
1751
- const bpmnXml = await service.getBpmn(instanceId, folderKey);
1752
- return this.parseBpmnElementsForIncidents(bpmnXml);
1753
- }
1754
- catch (error) {
1755
- console.warn(`Failed to get BPMN for instance ${instanceId}:`, error);
1756
- return {};
1757
- }
1677
+ async getValidAuthToken() {
1678
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1758
1679
  }
1759
1680
  /**
1760
- * Transform a raw incident by attaching element name/type from BPMN
1681
+ * Creates a service accessor for pagination helpers
1682
+ * This allows pagination helpers to access protected methods without making them public
1761
1683
  */
1762
- static transformIncidentWithBpmn(incident, elementInfo) {
1763
- const element = elementInfo[incident.elementId];
1764
- const transformed = transformData(incident, ProcessIncidentMap);
1684
+ createPaginationServiceAccess() {
1765
1685
  return {
1766
- ...transformed,
1767
- incidentElementActivityType: element?.type || UNKNOWN$1,
1768
- incidentElementActivityName: element?.name || UNKNOWN$1
1686
+ get: (path, options) => this.get(path, options || {}),
1687
+ post: (path, body, options) => this.post(path, body, options || {}),
1688
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1769
1689
  };
1770
1690
  }
1771
- }
1772
-
1773
- /**
1774
- * SDK Telemetry constants
1775
- */
1776
- // Connection string placeholder that will be replaced during build
1777
- 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";
1778
- // SDK Version placeholder
1779
- const SDK_VERSION = "1.3.8";
1780
- const VERSION = "Version";
1781
- const SERVICE = "Service";
1782
- const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1783
- const CLOUD_TENANT_NAME = "CloudTenantName";
1784
- const CLOUD_URL = "CloudUrl";
1785
- const CLOUD_CLIENT_ID = "CloudClientId";
1786
- const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1787
- const APP_NAME = "ApplicationName";
1788
- const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1789
- // Service and logger names
1790
- const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1791
- const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1792
- // Event names
1793
- const SDK_RUN_EVENT = "Sdk.Run";
1794
- // Default value for unknown/empty attributes
1795
- const UNKNOWN = "";
1796
-
1797
- /**
1798
- * Log exporter that sends ALL logs as Application Insights custom events
1799
- */
1800
- class ApplicationInsightsEventExporter {
1801
- constructor(connectionString) {
1802
- this.connectionString = connectionString;
1803
- }
1804
- export(logs, resultCallback) {
1805
- try {
1806
- logs.forEach(logRecord => {
1807
- this.sendAsCustomEvent(logRecord);
1808
- });
1809
- resultCallback({ code: 0 });
1810
- }
1811
- catch (error) {
1812
- console.debug('Failed to export logs to Application Insights:', error);
1813
- resultCallback({ code: 2, error });
1691
+ async request(method, path, options = {}) {
1692
+ switch (method.toUpperCase()) {
1693
+ case 'GET':
1694
+ return this.get(path, options);
1695
+ case 'POST':
1696
+ return this.post(path, options.body, options);
1697
+ case 'PUT':
1698
+ return this.put(path, options.body, options);
1699
+ case 'PATCH':
1700
+ return this.patch(path, options.body, options);
1701
+ case 'DELETE':
1702
+ return this.delete(path, options);
1703
+ default:
1704
+ throw new Error(`Unsupported HTTP method: ${method}`);
1814
1705
  }
1815
1706
  }
1816
- shutdown() {
1817
- return Promise.resolve();
1818
- }
1819
- sendAsCustomEvent(logRecord) {
1820
- // Get event name from body or attributes
1821
- const eventName = logRecord.body || SDK_RUN_EVENT;
1822
- const payload = {
1823
- name: 'Microsoft.ApplicationInsights.Event',
1824
- time: new Date().toISOString(),
1825
- iKey: this.extractInstrumentationKey(),
1826
- data: {
1827
- baseType: 'EventData',
1828
- baseData: {
1829
- ver: 2,
1830
- name: eventName,
1831
- properties: this.convertAttributesToProperties(logRecord.attributes || {})
1832
- }
1833
- },
1834
- tags: {
1835
- 'ai.cloud.role': CLOUD_ROLE_NAME,
1836
- 'ai.cloud.roleInstance': SDK_VERSION
1837
- }
1838
- };
1839
- this.sendToApplicationInsights(payload);
1840
- }
1841
- extractInstrumentationKey() {
1842
- const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1843
- return match ? match[1] : '';
1707
+ async requestWithSpec(spec) {
1708
+ if (!spec.method || !spec.url) {
1709
+ throw new Error('Request spec must include method and url');
1710
+ }
1711
+ return this.request(spec.method, spec.url, spec);
1844
1712
  }
1845
- convertAttributesToProperties(attributes) {
1846
- const properties = {};
1847
- Object.entries(attributes || {}).forEach(([key, value]) => {
1848
- properties[key] = String(value);
1849
- });
1850
- return properties;
1713
+ async get(path, options = {}) {
1714
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1715
+ return { data: response };
1851
1716
  }
1852
- async sendToApplicationInsights(payload) {
1853
- try {
1854
- const ingestionEndpoint = this.extractIngestionEndpoint();
1855
- if (!ingestionEndpoint) {
1856
- console.debug('No ingestion endpoint found in connection string');
1857
- return;
1858
- }
1859
- const url = `${ingestionEndpoint}/v2/track`;
1860
- const response = await fetch(url, {
1861
- method: 'POST',
1862
- headers: {
1863
- 'Content-Type': 'application/json',
1864
- },
1865
- body: JSON.stringify(payload)
1866
- });
1867
- if (!response.ok) {
1868
- console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1869
- }
1870
- }
1871
- catch (error) {
1872
- console.debug('Error sending event telemetry to Application Insights:', error);
1873
- }
1717
+ async post(path, data, options = {}) {
1718
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1719
+ return { data: response };
1874
1720
  }
1875
- extractIngestionEndpoint() {
1876
- const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1877
- return match ? match[1] : '';
1721
+ async put(path, data, options = {}) {
1722
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1723
+ return { data: response };
1878
1724
  }
1879
- }
1880
- /**
1881
- * Singleton telemetry client
1882
- */
1883
- class TelemetryClient {
1884
- constructor() {
1885
- this.isInitialized = false;
1725
+ async patch(path, data, options = {}) {
1726
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1727
+ return { data: response };
1886
1728
  }
1887
- static getInstance() {
1888
- if (!TelemetryClient.instance) {
1889
- TelemetryClient.instance = new TelemetryClient();
1890
- }
1891
- return TelemetryClient.instance;
1729
+ async delete(path, options = {}) {
1730
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1731
+ return { data: response };
1892
1732
  }
1893
1733
  /**
1894
- * Initialize telemetry
1734
+ * Execute a request with cursor-based pagination
1895
1735
  */
1896
- initialize(config) {
1897
- if (this.isInitialized) {
1898
- return;
1899
- }
1900
- this.isInitialized = true;
1901
- if (config) {
1902
- this.telemetryContext = config;
1903
- }
1904
- try {
1905
- const connectionString = this.getConnectionString();
1906
- if (!connectionString) {
1907
- return;
1908
- }
1909
- this.setupTelemetryProvider(connectionString);
1736
+ async requestWithPagination(method, path, paginationOptions, options) {
1737
+ const paginationType = options.pagination.paginationType;
1738
+ // Validate and prepare pagination parameters
1739
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1740
+ // Prepare request parameters based on pagination type
1741
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1742
+ // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1743
+ if (method.toUpperCase() === 'POST') {
1744
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1745
+ options.body = {
1746
+ ...existingBody,
1747
+ ...options.params,
1748
+ ...requestParams
1749
+ };
1750
+ options.params = undefined;
1910
1751
  }
1911
- catch (error) {
1912
- // Silent failure - telemetry errors shouldn't break functionality
1913
- console.debug('Failed to initialize OpenTelemetry:', error);
1752
+ else {
1753
+ // Merge pagination parameters with existing parameters
1754
+ options.params = {
1755
+ ...options.params,
1756
+ ...requestParams
1757
+ };
1914
1758
  }
1915
- }
1916
- getConnectionString() {
1917
- const connectionString = CONNECTION_STRING;
1918
- return connectionString;
1919
- }
1920
- setupTelemetryProvider(connectionString) {
1921
- const exporter = new ApplicationInsightsEventExporter(connectionString);
1922
- const processor = new BatchLogRecordProcessor(exporter);
1923
- this.logProvider = new LoggerProvider({
1924
- processors: [processor]
1759
+ // Make the request
1760
+ const response = await this.request(method, path, options);
1761
+ // Extract data from the response and create page result
1762
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1763
+ itemsField: options.pagination.itemsField,
1764
+ totalCountField: options.pagination.totalCountField,
1765
+ continuationTokenField: options.pagination.continuationTokenField
1925
1766
  });
1926
- this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1927
1767
  }
1928
1768
  /**
1929
- * Track a telemetry event
1769
+ * Validates and prepares pagination parameters from options
1930
1770
  */
1931
- track(eventName, name, extraAttributes = {}) {
1932
- try {
1933
- // Skip if logger not initialized
1934
- if (!this.logger) {
1935
- return;
1936
- }
1937
- const finalDisplayName = name || eventName;
1938
- const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1939
- // Emit as log
1940
- this.logger.emit({
1941
- body: finalDisplayName,
1942
- attributes: attributes,
1943
- timestamp: Date.now(),
1944
- });
1945
- }
1946
- catch (error) {
1947
- // Silent failure
1948
- console.debug('Failed to track telemetry event:', error);
1771
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1772
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1773
+ }
1774
+ /**
1775
+ * Prepares request parameters for pagination based on pagination type
1776
+ */
1777
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1778
+ const requestParams = {};
1779
+ let limitedPageSize;
1780
+ const paginationParams = paginationConfig?.paginationParams;
1781
+ switch (paginationType) {
1782
+ case PaginationType.OFFSET:
1783
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1784
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1785
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1786
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1787
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1788
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1789
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1790
+ requestParams[pageSizeParam] = limitedPageSize;
1791
+ if (convertToSkip) {
1792
+ if (params.pageNumber && params.pageNumber > 1) {
1793
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1794
+ }
1795
+ }
1796
+ else {
1797
+ requestParams[offsetParam] = params.pageNumber || 1;
1798
+ }
1799
+ {
1800
+ requestParams[countParam] = true;
1801
+ }
1802
+ break;
1803
+ case PaginationType.TOKEN:
1804
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1805
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1806
+ if (params.pageSize) {
1807
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1808
+ }
1809
+ if (params.continuationToken) {
1810
+ requestParams[tokenParam] = params.continuationToken;
1811
+ }
1812
+ break;
1949
1813
  }
1814
+ return requestParams;
1950
1815
  }
1951
1816
  /**
1952
- * Get enriched attributes for telemetry events
1817
+ * Creates a paginated response from API response
1953
1818
  */
1954
- getEnrichedAttributes(extraAttributes, eventName) {
1955
- const attributes = {
1956
- [APP_NAME]: SDK_SERVICE_NAME,
1957
- [VERSION]: SDK_VERSION,
1958
- [SERVICE]: eventName,
1959
- [CLOUD_URL]: this.createCloudUrl(),
1960
- [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1961
- [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1962
- [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1963
- [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1964
- ...extraAttributes,
1965
- };
1966
- return attributes;
1819
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1820
+ // Extract fields from response
1821
+ const itemsField = fields.itemsField ||
1822
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1823
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1824
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1825
+ // Extract items and metadata
1826
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1827
+ const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
1828
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1829
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1830
+ const continuationToken = response.data[continuationTokenField];
1831
+ // Determine if there are more pages
1832
+ const hasMore = this.determineHasMorePages(paginationType, {
1833
+ totalCount,
1834
+ pageSize: params.pageSize,
1835
+ currentPage: params.pageNumber || 1,
1836
+ itemsCount: items.length,
1837
+ continuationToken
1838
+ });
1839
+ // Create and return the page result
1840
+ return PaginationManager.createPaginatedResponse({
1841
+ pageInfo: {
1842
+ hasMore,
1843
+ totalCount,
1844
+ currentPage: params.pageNumber,
1845
+ pageSize: params.pageSize,
1846
+ continuationToken
1847
+ },
1848
+ type: paginationType,
1849
+ }, items);
1967
1850
  }
1968
1851
  /**
1969
- * Create cloud URL from base URL, organization ID, and tenant ID
1852
+ * Determines if there are more pages based on pagination type and metadata
1970
1853
  */
1971
- createCloudUrl() {
1972
- const baseUrl = this.telemetryContext?.baseUrl;
1973
- const orgId = this.telemetryContext?.orgName;
1974
- const tenantId = this.telemetryContext?.tenantName;
1975
- if (!baseUrl || !orgId || !tenantId) {
1976
- return UNKNOWN;
1854
+ determineHasMorePages(paginationType, info) {
1855
+ switch (paginationType) {
1856
+ case PaginationType.OFFSET:
1857
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1858
+ // If totalCount is available, use it for precise calculation
1859
+ if (info.totalCount !== undefined) {
1860
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1861
+ }
1862
+ // Fallback when totalCount is not available
1863
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1864
+ return info.itemsCount === effectivePageSize;
1865
+ case PaginationType.TOKEN:
1866
+ return !!info.continuationToken;
1867
+ default:
1868
+ return false;
1977
1869
  }
1978
- return `${baseUrl}/${orgId}/${tenantId}`;
1979
1870
  }
1980
1871
  }
1981
- // Export singleton instance
1982
- const telemetryClient = TelemetryClient.getInstance();
1983
-
1984
- /**
1985
- * SDK Track decorator and function for telemetry
1986
- */
1987
- /**
1988
- * Common tracking logic shared between method and function decorators
1989
- */
1990
- function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1991
- return function (...args) {
1992
- // Determine if we should track this call
1993
- let shouldTrack = true;
1994
- if (opts.condition !== undefined) {
1995
- if (typeof opts.condition === 'function') {
1996
- shouldTrack = opts.condition.apply(this, args);
1997
- }
1998
- else {
1999
- shouldTrack = opts.condition;
2000
- }
2001
- }
2002
- // Track the event if enabled
2003
- if (shouldTrack) {
2004
- // Use the full name provided in the decorator (e.g., "Queue.GetAll")
2005
- const serviceMethod = typeof nameOrOptions === 'string'
2006
- ? nameOrOptions
2007
- : fallbackName;
2008
- // Use 'Sdk.Run' as the name and serviceMethod as the service
2009
- telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
2010
- }
2011
- // Execute the original function
2012
- return originalFunction.apply(this, args);
2013
- };
2014
- }
2015
- /**
2016
- * Track decorator that can be used to automatically track function calls
2017
- *
2018
- * Usage:
2019
- * @track("Service.Method")
2020
- * function myFunction() { ... }
2021
- *
2022
- * @track("Queue.GetAll")
2023
- * async getAll() { ... }
2024
- *
2025
- * @track("Tasks.Create")
2026
- * async create() { ... }
2027
- *
2028
- * @track("Assets.Update", { condition: false })
2029
- * function myFunction() { ... }
2030
- *
2031
- * @track("Processes.Start", { attributes: { customProp: "value" } })
2032
- * function myFunction() { ... }
2033
- */
2034
- function track(nameOrOptions, options) {
2035
- return function decorator(_target, propertyKey, descriptor) {
2036
- const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
2037
- if (descriptor && typeof descriptor.value === 'function') {
2038
- // Method decorator
2039
- descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
2040
- return descriptor;
2041
- }
2042
- // Function decorator
2043
- return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
2044
- };
2045
- }
1872
+ _BaseService_apiClient = new WeakMap();
2046
1873
 
2047
1874
  /**
2048
1875
  * Creates methods for a process instance
@@ -2237,6 +2064,40 @@ var SLADurationUnit;
2237
2064
  SLADurationUnit["MONTHS"] = "m";
2238
2065
  })(SLADurationUnit || (SLADurationUnit = {}));
2239
2066
 
2067
+ /**
2068
+ * Insights Types
2069
+ * Shared types for Maestro insights analytics endpoints
2070
+ */
2071
+ /**
2072
+ * Time bucketing granularity for insights time-series queries.
2073
+ *
2074
+ * Controls how data points are grouped on the time axis.
2075
+ */
2076
+ var TimeInterval;
2077
+ (function (TimeInterval) {
2078
+ /** Group data points by hour */
2079
+ TimeInterval["Hour"] = "HOUR";
2080
+ /** Group data points by day */
2081
+ TimeInterval["Day"] = "DAY";
2082
+ /** Group data points by week */
2083
+ TimeInterval["Week"] = "WEEK";
2084
+ })(TimeInterval || (TimeInterval = {}));
2085
+ /**
2086
+ * Final instance statuses returned by the instance status timeline endpoint.
2087
+ *
2088
+ * Only includes statuses where the instance has finished execution — Completed, Faulted, or Cancelled.
2089
+ * Active statuses like Running or Paused are not included.
2090
+ */
2091
+ var InstanceFinalStatus;
2092
+ (function (InstanceFinalStatus) {
2093
+ /** Instance completed successfully */
2094
+ InstanceFinalStatus["Completed"] = "Completed";
2095
+ /** Instance encountered an error */
2096
+ InstanceFinalStatus["Faulted"] = "Faulted";
2097
+ /** Instance was cancelled */
2098
+ InstanceFinalStatus["Cancelled"] = "Cancelled";
2099
+ })(InstanceFinalStatus || (InstanceFinalStatus = {}));
2100
+
2240
2101
  /**
2241
2102
  * Maps fields for Process Instance entities to ensure consistent naming
2242
2103
  */
@@ -2612,6 +2473,177 @@ class MaestroProcessesService extends BaseService {
2612
2473
  // Fetch BPMN XML and add element name/type to each incident
2613
2474
  return BpmnHelpers.enrichIncidentsWithBpmnData(rawResponse.data || [], folderKey, this.processInstancesService);
2614
2475
  }
2476
+ /**
2477
+ * Get the top 5 processes ranked by run count within a time range.
2478
+ *
2479
+ * Returns an array of up to 5 processes sorted by how many times they were executed,
2480
+ * useful for identifying the most active processes in a given period.
2481
+ *
2482
+ * @param startTime - Start of the time range to query
2483
+ * @param endTime - End of the time range to query
2484
+ * @param options - Optional filters (packageId, processKey, version)
2485
+ * @returns Promise resolving to an array of {@link ProcessGetTopRunCountResponse}
2486
+ * @example
2487
+ * ```typescript
2488
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2489
+ *
2490
+ * const maestroProcesses = new MaestroProcesses(sdk);
2491
+ *
2492
+ * // Get top processes by run count for the last 7 days
2493
+ * const topProcesses = await maestroProcesses.getTopRunCount(
2494
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2495
+ * new Date()
2496
+ * );
2497
+ *
2498
+ * for (const process of topProcesses) {
2499
+ * console.log(`${process.packageId}: ${process.runCount} runs`);
2500
+ * }
2501
+ * ```
2502
+ *
2503
+ * @example
2504
+ * ```typescript
2505
+ * // Get top processes by run count for a specific package
2506
+ * const filtered = await maestroProcesses.getTopRunCount(
2507
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2508
+ * new Date(),
2509
+ * { packageId: '<packageId>' }
2510
+ * );
2511
+ * ```
2512
+ */
2513
+ async getTopRunCount(startTime, endTime, options) {
2514
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_RUN_COUNT, buildInsightsTopBody(startTime, endTime, false, options));
2515
+ return (data ?? []).map(process => ({ ...process, name: process.packageId }));
2516
+ }
2517
+ /**
2518
+ * Get all instances status counts aggregated by date for maestro processes.
2519
+ *
2520
+ * Returns time-grouped counts of instances grouped by status (Completed, Faulted, Cancelled),
2521
+ * useful for rendering time-series charts. Use `groupBy` to control the time bucket size
2522
+ * (hour, day, or week) — defaults to day if not provided.
2523
+ *
2524
+ * @param startTime - Start of the time range to query
2525
+ * @param endTime - End of the time range to query
2526
+ * @param options - Optional settings for time bucketing granularity
2527
+ * @returns Promise resolving to an array of {@link InstanceStatusTimelineResponse}
2528
+ *
2529
+ * @example
2530
+ * ```typescript
2531
+ * // Get daily instance status for the last 7 days
2532
+ * const now = new Date();
2533
+ * const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
2534
+ * const statuses = await maestroProcesses.getInstanceStatusTimeline(sevenDaysAgo, now);
2535
+ *
2536
+ * for (const entry of statuses) {
2537
+ * console.log(`${entry.startTime} — ${entry.status}: ${entry.count}`);
2538
+ * }
2539
+ * ```
2540
+ *
2541
+ * @example
2542
+ * ```typescript
2543
+ * import { TimeInterval } from '@uipath/uipath-typescript/maestro-processes';
2544
+ *
2545
+ * // Get hourly breakdown
2546
+ * const statuses = await maestroProcesses.getInstanceStatusTimeline(startTime, endTime, {
2547
+ * groupBy: TimeInterval.Hour,
2548
+ * });
2549
+ * ```
2550
+ *
2551
+ * @example
2552
+ * ```typescript
2553
+ * // Get all-time data (from Unix epoch to now)
2554
+ * const allTime = await maestroProcesses.getInstanceStatusTimeline(new Date(0), new Date());
2555
+ * ```
2556
+ */
2557
+ async getInstanceStatusTimeline(startTime, endTime, options) {
2558
+ return fetchInstanceStatusTimeline(this.post.bind(this), startTime, endTime, false, options);
2559
+ }
2560
+ /**
2561
+ * Get the top 10 processes ranked by failure count within a time range.
2562
+ *
2563
+ * Returns an array of up to 10 processes sorted by how many instances faulted,
2564
+ * useful for identifying the most error-prone processes in a given period.
2565
+ *
2566
+ * @param startTime - Start of the time range to query
2567
+ * @param endTime - End of the time range to query
2568
+ * @param options - Optional filters (packageId, processKey, version)
2569
+ * @returns Promise resolving to an array of {@link ProcessGetTopFaultedCountResponse}
2570
+ * @example
2571
+ * ```typescript
2572
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2573
+ *
2574
+ * const maestroProcesses = new MaestroProcesses(sdk);
2575
+ *
2576
+ * // Get top processes by faulted count for the last 7 days
2577
+ * const topFailing = await maestroProcesses.getTopFaultedCount(
2578
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2579
+ * new Date()
2580
+ * );
2581
+ *
2582
+ * for (const process of topFailing) {
2583
+ * console.log(`${process.packageId}: ${process.faultedCount} failures`);
2584
+ * }
2585
+ * ```
2586
+ *
2587
+ * @example
2588
+ * ```typescript
2589
+ * // Get top processes by faulted count for a specific package
2590
+ * const filtered = await maestroProcesses.getTopFaultedCount(
2591
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2592
+ * new Date(),
2593
+ * { packageId: '<packageId>' }
2594
+ * );
2595
+ * ```
2596
+ */
2597
+ async getTopFaultedCount(startTime, endTime, options) {
2598
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_WITH_FAILURE, buildInsightsTopBody(startTime, endTime, false, options));
2599
+ return (data ?? []).map(item => ({
2600
+ packageId: item.packageId,
2601
+ processKey: item.processKey,
2602
+ faultedCount: item.runCount,
2603
+ name: item.packageId,
2604
+ }));
2605
+ }
2606
+ /**
2607
+ * Get the top 5 processes ranked by total duration within a time range.
2608
+ *
2609
+ * Returns an array of up to 5 processes sorted by their total execution time,
2610
+ * useful for identifying the longest-running processes in a given period.
2611
+ *
2612
+ * @param startTime - Start of the time range to query
2613
+ * @param endTime - End of the time range to query
2614
+ * @param options - Optional filters (packageId, processKey, version)
2615
+ * @returns Promise resolving to an array of {@link ProcessGetTopDurationResponse}
2616
+ * @example
2617
+ * ```typescript
2618
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
2619
+ *
2620
+ * const maestroProcesses = new MaestroProcesses(sdk);
2621
+ *
2622
+ * // Get top processes by duration for the last 7 days
2623
+ * const topProcesses = await maestroProcesses.getTopExecutionDuration(
2624
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2625
+ * new Date()
2626
+ * );
2627
+ *
2628
+ * for (const process of topProcesses) {
2629
+ * console.log(`${process.packageId}: ${process.duration}ms total`);
2630
+ * }
2631
+ * ```
2632
+ *
2633
+ * @example
2634
+ * ```typescript
2635
+ * // Get top processes by duration for a specific package
2636
+ * const filtered = await maestroProcesses.getTopExecutionDuration(
2637
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
2638
+ * new Date(),
2639
+ * { packageId: '<packageId>' }
2640
+ * );
2641
+ * ```
2642
+ */
2643
+ async getTopExecutionDuration(startTime, endTime, options) {
2644
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_DURATION, buildInsightsTopBody(startTime, endTime, false, options));
2645
+ return (data ?? []).map(process => ({ ...process, name: process.packageId }));
2646
+ }
2615
2647
  }
2616
2648
  __decorate([
2617
2649
  track('MaestroProcesses.GetAll')
@@ -2619,6 +2651,18 @@ __decorate([
2619
2651
  __decorate([
2620
2652
  track('MaestroProcesses.GetIncidents')
2621
2653
  ], MaestroProcessesService.prototype, "getIncidents", null);
2654
+ __decorate([
2655
+ track('MaestroProcesses.GetTopRunCount')
2656
+ ], MaestroProcessesService.prototype, "getTopRunCount", null);
2657
+ __decorate([
2658
+ track('MaestroProcesses.GetInstanceStatusTimeline')
2659
+ ], MaestroProcessesService.prototype, "getInstanceStatusTimeline", null);
2660
+ __decorate([
2661
+ track('MaestroProcesses.GetTopFaultedCount')
2662
+ ], MaestroProcessesService.prototype, "getTopFaultedCount", null);
2663
+ __decorate([
2664
+ track('MaestroProcesses.GetTopExecutionDuration')
2665
+ ], MaestroProcessesService.prototype, "getTopExecutionDuration", null);
2622
2666
 
2623
2667
  /**
2624
2668
  * Service class for Maestro Process Incidents
@@ -2656,4 +2700,4 @@ __decorate([
2656
2700
  track('ProcessIncidents.getAll')
2657
2701
  ], ProcessIncidentsService.prototype, "getAll", null);
2658
2702
 
2659
- export { DebugMode, MaestroProcessesService as MaestroProcesses, MaestroProcessesService, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, ProcessIncidentsService as ProcessIncidents, ProcessIncidentsService, ProcessInstancesService as ProcessInstances, ProcessInstancesService, createProcessInstanceWithMethods, createProcessWithMethods };
2703
+ export { DebugMode, InstanceFinalStatus, MaestroProcessesService as MaestroProcesses, MaestroProcessesService, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, ProcessIncidentsService as ProcessIncidents, ProcessIncidentsService, ProcessInstancesService as ProcessInstances, ProcessInstancesService, TimeInterval, createProcessInstanceWithMethods, createProcessWithMethods };