@uipath/uipath-typescript 1.4.0 → 1.4.2

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 (51) hide show
  1. package/dist/agent-memory/index.cjs +16 -9
  2. package/dist/agent-memory/index.mjs +16 -9
  3. package/dist/agents/index.cjs +278 -9
  4. package/dist/agents/index.d.ts +465 -6
  5. package/dist/agents/index.mjs +279 -10
  6. package/dist/assets/index.cjs +16 -9
  7. package/dist/assets/index.mjs +16 -9
  8. package/dist/attachments/index.cjs +16 -9
  9. package/dist/attachments/index.mjs +16 -9
  10. package/dist/buckets/index.cjs +114 -124
  11. package/dist/buckets/index.d.ts +197 -84
  12. package/dist/buckets/index.mjs +114 -124
  13. package/dist/cases/index.cjs +79 -13
  14. package/dist/cases/index.d.ts +30 -3
  15. package/dist/cases/index.mjs +79 -13
  16. package/dist/conversational-agent/index.cjs +16 -9
  17. package/dist/conversational-agent/index.mjs +16 -9
  18. package/dist/core/index.cjs +35 -6
  19. package/dist/core/index.mjs +35 -6
  20. package/dist/document-understanding/index.cjs +84 -84
  21. package/dist/document-understanding/index.d.ts +2 -1
  22. package/dist/document-understanding/index.mjs +1 -1
  23. package/dist/entities/index.cjs +253 -69
  24. package/dist/entities/index.d.ts +343 -116
  25. package/dist/entities/index.mjs +253 -69
  26. package/dist/feedback/index.cjs +16 -9
  27. package/dist/feedback/index.mjs +16 -9
  28. package/dist/governance/index.cjs +16 -9
  29. package/dist/governance/index.mjs +16 -9
  30. package/dist/index.cjs +529 -193
  31. package/dist/index.d.ts +2141 -750
  32. package/dist/index.mjs +529 -194
  33. package/dist/index.umd.js +529 -193
  34. package/dist/jobs/index.cjs +16 -9
  35. package/dist/jobs/index.mjs +16 -9
  36. package/dist/maestro-processes/index.cjs +16 -9
  37. package/dist/maestro-processes/index.mjs +16 -9
  38. package/dist/orchestrator-du-module/index.cjs +1788 -0
  39. package/dist/orchestrator-du-module/index.d.ts +757 -0
  40. package/dist/orchestrator-du-module/index.mjs +1785 -0
  41. package/dist/processes/index.cjs +16 -9
  42. package/dist/processes/index.mjs +16 -9
  43. package/dist/queues/index.cjs +16 -9
  44. package/dist/queues/index.mjs +16 -9
  45. package/dist/tasks/index.cjs +79 -13
  46. package/dist/tasks/index.d.ts +109 -4
  47. package/dist/tasks/index.mjs +80 -14
  48. package/dist/traces/index.cjs +303 -9
  49. package/dist/traces/index.d.ts +482 -2
  50. package/dist/traces/index.mjs +302 -10
  51. package/package.json +11 -1
@@ -0,0 +1,1785 @@
1
+ import { getOrCreateClient, createTrack, createTrackEvent } from '@uipath/core-telemetry';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+
20
+ function __decorate(decorators, target, key, desc) {
21
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
23
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+
27
+ function __classPrivateFieldGet(receiver, state, kind, f) {
28
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
29
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
30
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
31
+ }
32
+
33
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
34
+ if (kind === "m") throw new TypeError("Private method is not writable");
35
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
36
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
37
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
38
+ }
39
+
40
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
41
+ var e = new Error(message);
42
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
43
+ };
44
+
45
+ /**
46
+ * SDK Telemetry constants.
47
+ *
48
+ * Only the SDK's identity (version, service name, role name, …) lives
49
+ * here. The Application Insights connection string is injected into
50
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
51
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
52
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
53
+ * SDK's public API.
54
+ */
55
+ /** SDK version placeholder — patched by the SDK publish workflow. */
56
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
57
+
58
+ /**
59
+ * UiPath TypeScript SDK Telemetry
60
+ *
61
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
62
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
63
+ * does this independently, so events carry their own consumer's identity
64
+ * and tenant context.
65
+ */
66
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
67
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
68
+ // from the `UiPath` constructor therefore wires up `@track` decorators
69
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
70
+ const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
71
+ const track = createTrack(sdkClient);
72
+ createTrackEvent(sdkClient);
73
+
74
+ /**
75
+ * Base path constants for different services
76
+ */
77
+ const ORCHESTRATOR_BASE = 'orchestrator_';
78
+
79
+ /**
80
+ * Orchestrator Service Endpoints
81
+ */
82
+ /**
83
+ * Orchestrator DU Module Endpoints (validation flows)
84
+ */
85
+ const ORCHESTRATOR_DU_MODULE_ENDPOINTS = {
86
+ SUBMIT_EXCEPTION_REPORT: `${ORCHESTRATOR_BASE}/doc-understanding/DocumentModule/SubmitExceptionReport`,
87
+ PROCESS_EXTRACTED_DATA: `${ORCHESTRATOR_BASE}/doc-understanding/DocumentModule/ProcessExtractedData`,
88
+ };
89
+
90
+ /**
91
+ * Base error class for all UiPath SDK errors
92
+ * Extends Error for standard error handling compatibility
93
+ */
94
+ class UiPathError extends Error {
95
+ constructor(type, params) {
96
+ super(params.message);
97
+ this.name = type;
98
+ this.type = type;
99
+ this.statusCode = params.statusCode;
100
+ this.requestId = params.requestId;
101
+ this.timestamp = new Date();
102
+ // Maintains proper stack trace for where our error was thrown
103
+ if (Error.captureStackTrace) {
104
+ Error.captureStackTrace(this, this.constructor);
105
+ }
106
+ }
107
+ /**
108
+ * Returns a clean JSON representation of the error
109
+ */
110
+ toJSON() {
111
+ return {
112
+ type: this.type,
113
+ message: this.message,
114
+ statusCode: this.statusCode,
115
+ requestId: this.requestId,
116
+ timestamp: this.timestamp
117
+ };
118
+ }
119
+ /**
120
+ * Returns detailed debug information including stack trace
121
+ */
122
+ getDebugInfo() {
123
+ return {
124
+ ...this.toJSON(),
125
+ stack: this.stack
126
+ };
127
+ }
128
+ }
129
+
130
+ /**
131
+ * HTTP status code constants for error handling
132
+ */
133
+ const HttpStatus = {
134
+ // Client errors (4xx)
135
+ BAD_REQUEST: 400,
136
+ UNAUTHORIZED: 401,
137
+ FORBIDDEN: 403,
138
+ NOT_FOUND: 404,
139
+ TOO_MANY_REQUESTS: 429,
140
+ // Server errors (5xx)
141
+ INTERNAL_SERVER_ERROR: 500,
142
+ BAD_GATEWAY: 502,
143
+ SERVICE_UNAVAILABLE: 503,
144
+ GATEWAY_TIMEOUT: 504
145
+ };
146
+ /**
147
+ * Error type constants for consistent error identification
148
+ */
149
+ const ErrorType = {
150
+ AUTHENTICATION: 'AuthenticationError',
151
+ AUTHORIZATION: 'AuthorizationError',
152
+ VALIDATION: 'ValidationError',
153
+ NOT_FOUND: 'NotFoundError',
154
+ RATE_LIMIT: 'RateLimitError',
155
+ SERVER: 'ServerError',
156
+ NETWORK: 'NetworkError'
157
+ };
158
+ /**
159
+ * HTTP header constants for error handling
160
+ */
161
+ const HttpHeaders = {
162
+ X_REQUEST_ID: 'x-request-id'
163
+ };
164
+ /**
165
+ * Standard error message constants
166
+ */
167
+ const ErrorMessages = {
168
+ // Authentication errors
169
+ AUTHENTICATION_FAILED: 'Authentication failed',
170
+ // Authorization errors
171
+ ACCESS_DENIED: 'Access denied',
172
+ // Validation errors
173
+ VALIDATION_FAILED: 'Validation failed',
174
+ // Not found errors
175
+ RESOURCE_NOT_FOUND: 'Resource not found',
176
+ // Rate limit errors
177
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
178
+ // Server errors
179
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
180
+ // Network errors
181
+ NETWORK_ERROR: 'Network error occurred',
182
+ REQUEST_TIMEOUT: 'Request timed out',
183
+ REQUEST_ABORTED: 'Request was aborted',
184
+ };
185
+ /**
186
+ * Error name constants for network error identification
187
+ */
188
+ const ErrorNames = {
189
+ ABORT_ERROR: 'AbortError'};
190
+
191
+ /**
192
+ * Error thrown when authentication fails (401 errors)
193
+ * Common scenarios:
194
+ * - Invalid credentials
195
+ * - Expired token
196
+ * - Missing authentication
197
+ */
198
+ class AuthenticationError extends UiPathError {
199
+ constructor(params = {}) {
200
+ super(ErrorType.AUTHENTICATION, {
201
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
202
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
203
+ requestId: params.requestId
204
+ });
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Error thrown when authorization fails (403 errors)
210
+ * Common scenarios:
211
+ * - Insufficient permissions
212
+ * - Access denied to resource
213
+ * - Invalid scope
214
+ */
215
+ class AuthorizationError extends UiPathError {
216
+ constructor(params = {}) {
217
+ super(ErrorType.AUTHORIZATION, {
218
+ message: params.message || ErrorMessages.ACCESS_DENIED,
219
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
220
+ requestId: params.requestId
221
+ });
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Error thrown when validation fails (400 errors or client-side validation)
227
+ * Common scenarios:
228
+ * - Invalid input parameters
229
+ * - Missing required fields
230
+ * - Invalid data format
231
+ */
232
+ class ValidationError extends UiPathError {
233
+ constructor(params = {}) {
234
+ super(ErrorType.VALIDATION, {
235
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
236
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
237
+ requestId: params.requestId
238
+ });
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Error thrown when a resource is not found (404 errors)
244
+ * Common scenarios:
245
+ * - Resource doesn't exist
246
+ * - Invalid ID provided
247
+ * - Resource deleted
248
+ */
249
+ class NotFoundError extends UiPathError {
250
+ constructor(params = {}) {
251
+ super(ErrorType.NOT_FOUND, {
252
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
253
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
254
+ requestId: params.requestId
255
+ });
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Error thrown when rate limit is exceeded (429 errors)
261
+ * Common scenarios:
262
+ * - Too many requests in a time window
263
+ * - API throttling
264
+ */
265
+ class RateLimitError extends UiPathError {
266
+ constructor(params = {}) {
267
+ super(ErrorType.RATE_LIMIT, {
268
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
269
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
270
+ requestId: params.requestId
271
+ });
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Error thrown when server encounters an error (5xx errors)
277
+ * Common scenarios:
278
+ * - Internal server error
279
+ * - Service unavailable
280
+ * - Gateway timeout
281
+ */
282
+ class ServerError extends UiPathError {
283
+ constructor(params = {}) {
284
+ super(ErrorType.SERVER, {
285
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
286
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
287
+ requestId: params.requestId
288
+ });
289
+ }
290
+ /**
291
+ * Checks if this is a temporary error that might succeed on retry
292
+ */
293
+ get isRetryable() {
294
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
295
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
296
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Error thrown when network/connection issues occur
302
+ * Common scenarios:
303
+ * - Connection timeout
304
+ * - DNS resolution failure
305
+ * - Network unreachable
306
+ * - Request aborted
307
+ */
308
+ class NetworkError extends UiPathError {
309
+ constructor(params = {}) {
310
+ super(ErrorType.NETWORK, {
311
+ message: params.message || ErrorMessages.NETWORK_ERROR,
312
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
313
+ requestId: params.requestId
314
+ });
315
+ }
316
+ }
317
+
318
+ const FOLDER_KEY = 'X-UIPATH-FolderKey';
319
+ const FOLDER_PATH_ENCODED = 'X-UIPATH-FolderPath-Encoded';
320
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
321
+ const TRACEPARENT = 'traceparent';
322
+ const UIPATH_TRACEPARENT_ID = 'x-uipath-traceparent-id';
323
+ /**
324
+ * Content type constants for HTTP requests/responses
325
+ */
326
+ const CONTENT_TYPES = {
327
+ JSON: 'application/json',
328
+ XML: 'application/xml',
329
+ OCTET_STREAM: 'application/octet-stream'
330
+ };
331
+ /**
332
+ * Response type constants for HTTP requests
333
+ */
334
+ const RESPONSE_TYPES = {
335
+ JSON: 'json',
336
+ TEXT: 'text',
337
+ BLOB: 'blob',
338
+ ARRAYBUFFER: 'arraybuffer'
339
+ };
340
+
341
+ /**
342
+ * Creates headers object from key-value pairs
343
+ * @param headersObj - Object containing header key-value pairs
344
+ * @returns Headers object with all values converted to strings
345
+ *
346
+ * @example
347
+ * ```typescript
348
+ * // Single header
349
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
350
+ *
351
+ * // Multiple headers
352
+ * const headers = createHeaders({
353
+ * 'X-UIPATH-FolderKey': '1234567890',
354
+ * 'X-UIPATH-OrganizationUnitId': 123,
355
+ * 'Accept': 'application/json'
356
+ * });
357
+ *
358
+ * // Using constants
359
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
360
+ * const headers = createHeaders({
361
+ * [FOLDER_KEY]: 'abc-123',
362
+ * [FOLDER_ID]: 456
363
+ * });
364
+ *
365
+ * // Empty headers
366
+ * const headers = createHeaders();
367
+ * ```
368
+ */
369
+ function createHeaders(headersObj) {
370
+ const headers = {};
371
+ for (const [key, value] of Object.entries(headersObj)) {
372
+ if (value !== undefined && value !== null) {
373
+ headers[key] = value.toString();
374
+ }
375
+ }
376
+ return headers;
377
+ }
378
+
379
+ /**
380
+ * Encodes a folder path for the `X-UIPATH-FolderPath-Encoded` header.
381
+ *
382
+ * Orchestrator decodes this header as **base64-encoded UTF-16 LE bytes**
383
+ * (see `HttpHeadersProviderExtensions.GetDecoded` + `OrganizationUnitProvider`
384
+ * in the Orchestrator repo, which call `Encoding.Unicode.GetString(...)`).
385
+ * URL-encoding is NOT what the server expects — it must be base64-of-UTF-16-LE
386
+ * bytes.
387
+ *
388
+ * @param folderPath - The folder path (e.g. 'Shared/Finance')
389
+ * @returns Base64 string suitable for the `X-UIPATH-FolderPath-Encoded` header
390
+ */
391
+ function encodeFolderPathHeader(folderPath) {
392
+ // Force little-endian regardless of host byte order. `Uint16Array` viewed
393
+ // as `Uint8Array` would use the host's native order — correct on LE hosts
394
+ // (x86/ARM-LE) but wrong on BE hosts. `DataView.setUint16(..., true)`
395
+ // pins LE.
396
+ const buf = new ArrayBuffer(folderPath.length * 2);
397
+ const view = new DataView(buf);
398
+ for (let i = 0; i < folderPath.length; i++) {
399
+ view.setUint16(i * 2, folderPath.charCodeAt(i), true);
400
+ }
401
+ const bytes = new Uint8Array(buf);
402
+ let binary = '';
403
+ for (let i = 0; i < bytes.byteLength; i++) {
404
+ binary += String.fromCharCode(bytes[i]);
405
+ }
406
+ // btoa is browser-native; Node 16+ also has it as a global
407
+ return btoa(binary);
408
+ }
409
+
410
+ /**
411
+ * Resolves folder context into the appropriate Orchestrator folder headers.
412
+ *
413
+ * Centralized so all folder-scoped methods (e.g. `assets.getByName`,
414
+ * `processes.getByName`, future Queues/Buckets/Jobs) share one implementation.
415
+ *
416
+ * Each input field maps directly to its header — no auto-detection or type
417
+ * coercion. When multiple fields are supplied, all corresponding headers
418
+ * are forwarded and the server resolves precedence.
419
+ *
420
+ * Routing:
421
+ * - `folderId` → `X-UIPATH-OrganizationUnitId`
422
+ * - `folderKey` → `X-UIPATH-FolderKey`
423
+ * - `folderPath` → `X-UIPATH-FolderPath-Encoded`
424
+ * - none set + `fallbackFolderKey` → fallback used as `X-UIPATH-FolderKey`
425
+ * - none set + no fallback → `ValidationError`
426
+ *
427
+ * @throws ValidationError when no folder context can be resolved.
428
+ */
429
+ function resolveFolderHeaders(input) {
430
+ const { folderId, folderKey, folderPath, resourceType, fallbackFolderKey } = input;
431
+ const trimmedKey = folderKey?.trim();
432
+ const trimmedPath = folderPath?.trim();
433
+ const headers = {};
434
+ if (folderId !== undefined) {
435
+ headers[FOLDER_ID] = folderId;
436
+ }
437
+ if (trimmedKey) {
438
+ headers[FOLDER_KEY] = trimmedKey;
439
+ }
440
+ if (trimmedPath) {
441
+ headers[FOLDER_PATH_ENCODED] = encodeFolderPathHeader(trimmedPath);
442
+ }
443
+ // No explicit folder context → meta-tag fallback or error.
444
+ if (Object.keys(headers).length === 0) {
445
+ if (!fallbackFolderKey) {
446
+ throw new ValidationError({
447
+ message: `${resourceType} requires folder context: pass \`folderId\`, \`folderKey\`, or \`folderPath\`, or initialize the SDK with a folder context.`,
448
+ });
449
+ }
450
+ headers[FOLDER_KEY] = fallbackFolderKey;
451
+ }
452
+ return createHeaders(headers);
453
+ }
454
+
455
+ /**
456
+ * Type guards for error response types
457
+ */
458
+ function isOrchestratorError(error) {
459
+ return typeof error === 'object' &&
460
+ error !== null &&
461
+ 'message' in error &&
462
+ 'errorCode' in error &&
463
+ typeof error.message === 'string' &&
464
+ typeof error.errorCode === 'number';
465
+ }
466
+ function isEntityError(error) {
467
+ return typeof error === 'object' &&
468
+ error !== null &&
469
+ 'error' in error &&
470
+ typeof error.error === 'string';
471
+ }
472
+ function isPimsError(error) {
473
+ return typeof error === 'object' &&
474
+ error !== null &&
475
+ 'type' in error &&
476
+ 'title' in error &&
477
+ 'status' in error &&
478
+ typeof error.type === 'string' &&
479
+ typeof error.title === 'string' &&
480
+ typeof error.status === 'number';
481
+ }
482
+
483
+ /**
484
+ * Parser for Orchestrator/Task error format
485
+ */
486
+ class OrchestratorErrorParser {
487
+ canParse(errorBody) {
488
+ return isOrchestratorError(errorBody);
489
+ }
490
+ parse(errorBody, response) {
491
+ const error = errorBody;
492
+ return {
493
+ message: error.message,
494
+ code: response?.status?.toString(),
495
+ details: {
496
+ errorCode: error.errorCode,
497
+ traceId: error.traceId,
498
+ originalResponse: error
499
+ },
500
+ requestId: error.traceId
501
+ };
502
+ }
503
+ }
504
+ /**
505
+ * Parser for Entity (Data Fabric) error format
506
+ */
507
+ class EntityErrorParser {
508
+ canParse(errorBody) {
509
+ return isEntityError(errorBody);
510
+ }
511
+ parse(errorBody, response) {
512
+ const error = errorBody;
513
+ return {
514
+ message: error.error,
515
+ code: response?.status?.toString(),
516
+ details: {
517
+ error: error.error,
518
+ traceId: error.traceId,
519
+ originalResponse: error
520
+ },
521
+ requestId: error.traceId
522
+ };
523
+ }
524
+ }
525
+ /**
526
+ * Parser for PIMS error format
527
+ */
528
+ class PimsErrorParser {
529
+ canParse(errorBody) {
530
+ return isPimsError(errorBody);
531
+ }
532
+ parse(errorBody, response) {
533
+ const error = errorBody;
534
+ let message = error.title;
535
+ // If there are validation errors, append them to the message for better visibility
536
+ if (error.errors && Object.keys(error.errors).length > 0) {
537
+ const errorMessages = Object.entries(error.errors)
538
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
539
+ .join('; ');
540
+ message += `. Validation errors: ${errorMessages}`;
541
+ }
542
+ return {
543
+ message,
544
+ code: response?.status?.toString(),
545
+ details: {
546
+ type: error.type,
547
+ title: error.title,
548
+ status: error.status,
549
+ errors: error.errors,
550
+ traceId: error.traceId,
551
+ originalResponse: error
552
+ },
553
+ requestId: error.traceId
554
+ };
555
+ }
556
+ }
557
+ /**
558
+ * Fallback parser for unrecognized formats
559
+ */
560
+ class GenericErrorParser {
561
+ canParse(_errorBody) {
562
+ return true; // Always can parse as last resort
563
+ }
564
+ parse(errorBody, response) {
565
+ // For unknown error formats, just pass through the raw error with fallback message
566
+ const message = response?.statusText || 'An error occurred';
567
+ return {
568
+ message,
569
+ code: response?.status?.toString(),
570
+ details: {
571
+ originalResponse: errorBody
572
+ },
573
+ };
574
+ }
575
+ }
576
+ /**
577
+ * Main error response parser using Chain of Responsibility pattern
578
+ *
579
+ * This parser standardizes error responses from different UiPath services into a
580
+ * consistent format, regardless of the original error structure.
581
+ *
582
+ * Supported formats:
583
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
584
+ * 2. Entity (Data Fabric): { error, traceId }
585
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
586
+ * 4. Generic: Fallback for any other format
587
+ *
588
+ * @example
589
+ * const parser = new ErrorResponseParser();
590
+ * const errorInfo = await parser.parse(response);
591
+ * // errorInfo will have consistent structure regardless of service
592
+ */
593
+ class ErrorResponseParser {
594
+ constructor() {
595
+ this.strategies = [
596
+ new OrchestratorErrorParser(),
597
+ new EntityErrorParser(),
598
+ new PimsErrorParser(),
599
+ new GenericErrorParser() // Must be last
600
+ ];
601
+ }
602
+ /**
603
+ * Parses error response body into standardized format
604
+ * @param response - The HTTP response object
605
+ * @returns Standardized error information
606
+ */
607
+ async parse(response) {
608
+ try {
609
+ const errorBody = await response.json();
610
+ // Find the first strategy that can parse this error format
611
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
612
+ // GenericErrorParser always returns true, so this will never be null
613
+ return strategy.parse(errorBody, response);
614
+ }
615
+ catch {
616
+ // Handle non-JSON responses
617
+ const responseText = await response.text().catch(() => '');
618
+ return {
619
+ message: response.statusText,
620
+ code: response.status.toString(),
621
+ details: {
622
+ parseError: 'Failed to parse error response as JSON',
623
+ responseText
624
+ },
625
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
626
+ };
627
+ }
628
+ }
629
+ }
630
+ // Export singleton instance
631
+ const errorResponseParser = new ErrorResponseParser();
632
+
633
+ /**
634
+ * Factory for creating typed errors based on HTTP status codes
635
+ * Follows the Factory pattern for clean error instantiation
636
+ */
637
+ class ErrorFactory {
638
+ /**
639
+ * Creates appropriate error instance based on HTTP status code
640
+ */
641
+ static createFromHttpStatus(statusCode, errorInfo) {
642
+ const { message, requestId } = errorInfo;
643
+ // Map status codes to error types
644
+ switch (statusCode) {
645
+ case HttpStatus.BAD_REQUEST:
646
+ return new ValidationError({ message, statusCode, requestId });
647
+ case HttpStatus.UNAUTHORIZED:
648
+ return new AuthenticationError({ message, statusCode, requestId });
649
+ case HttpStatus.FORBIDDEN:
650
+ return new AuthorizationError({ message, statusCode, requestId });
651
+ case HttpStatus.NOT_FOUND:
652
+ return new NotFoundError({ message, statusCode, requestId });
653
+ case HttpStatus.TOO_MANY_REQUESTS:
654
+ return new RateLimitError({ message, statusCode, requestId });
655
+ default:
656
+ // For 5xx errors or any other status code
657
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
658
+ return new ServerError({ message, statusCode, requestId });
659
+ }
660
+ // For unknown client errors, treat as validation error
661
+ return new ValidationError({
662
+ message: `${message} (HTTP ${statusCode})`,
663
+ statusCode,
664
+ requestId
665
+ });
666
+ }
667
+ }
668
+ /**
669
+ * Creates a NetworkError from a fetch/network error
670
+ */
671
+ static createNetworkError(error) {
672
+ let message = ErrorMessages.NETWORK_ERROR;
673
+ if (error instanceof Error) {
674
+ if (error.name === ErrorNames.ABORT_ERROR) {
675
+ message = ErrorMessages.REQUEST_ABORTED;
676
+ }
677
+ else if (error.message.includes('timeout')) {
678
+ message = ErrorMessages.REQUEST_TIMEOUT;
679
+ }
680
+ else {
681
+ message = error.message;
682
+ }
683
+ }
684
+ return new NetworkError({ message });
685
+ }
686
+ }
687
+
688
+ class ApiClient {
689
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
690
+ this.config = config;
691
+ this.executionContext = executionContext;
692
+ this.clientConfig = clientConfig;
693
+ this.tokenManager = tokenManager;
694
+ }
695
+ /**
696
+ * Gets a valid authentication token, refreshing if necessary.
697
+ * Used internally for API requests and exposed for services that need manual auth headers.
698
+ *
699
+ * @returns The valid token
700
+ * @throws AuthenticationError if no token available or refresh fails
701
+ */
702
+ async getValidToken() {
703
+ return this.tokenManager.getValidToken();
704
+ }
705
+ async getDefaultHeaders() {
706
+ const token = await this.getValidToken();
707
+ return {
708
+ 'Authorization': `Bearer ${token}`,
709
+ 'Content-Type': CONTENT_TYPES.JSON,
710
+ ...this.clientConfig.headers
711
+ };
712
+ }
713
+ async request(method, path, options = {}) {
714
+ // Ensure path starts with a forward slash
715
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
716
+ // Construct URL with org and tenant names
717
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
718
+ const isFormData = options.body instanceof FormData;
719
+ const defaultHeaders = await this.getDefaultHeaders();
720
+ if (isFormData) {
721
+ delete defaultHeaders['Content-Type'];
722
+ }
723
+ const traceId = crypto.randomUUID().replace(/-/g, '');
724
+ const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
725
+ const traceparentValue = `00-${traceId}-${spanId}-01`;
726
+ const headers = {
727
+ ...defaultHeaders,
728
+ [TRACEPARENT]: traceparentValue,
729
+ [UIPATH_TRACEPARENT_ID]: traceparentValue,
730
+ ...options.headers
731
+ };
732
+ // Convert params to URLSearchParams
733
+ const searchParams = new URLSearchParams();
734
+ if (options.params) {
735
+ Object.entries(options.params).forEach(([key, value]) => {
736
+ searchParams.append(key, value.toString());
737
+ });
738
+ }
739
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
740
+ let body = undefined;
741
+ if (options.body) {
742
+ body = isFormData ? options.body : JSON.stringify(options.body);
743
+ }
744
+ try {
745
+ const response = await fetch(fullUrl, {
746
+ method,
747
+ headers,
748
+ body,
749
+ signal: options.signal
750
+ });
751
+ if (!response.ok) {
752
+ const errorInfo = await errorResponseParser.parse(response);
753
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
754
+ }
755
+ if (response.status === 204) {
756
+ return undefined;
757
+ }
758
+ // Handle blob response type for binary data (e.g., file downloads)
759
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
760
+ const blob = await response.blob();
761
+ return blob;
762
+ }
763
+ // Check if we're expecting XML
764
+ const acceptHeader = headers['Accept'] || headers['accept'];
765
+ if (acceptHeader === CONTENT_TYPES.XML) {
766
+ const text = await response.text();
767
+ return text;
768
+ }
769
+ const text = await response.text();
770
+ if (!text) {
771
+ return undefined;
772
+ }
773
+ try {
774
+ return JSON.parse(text);
775
+ }
776
+ catch (error) {
777
+ if (error instanceof SyntaxError) {
778
+ throw new ServerError({
779
+ message: `Server returned non-JSON response (${response.status} ${response.url}): ${error.message}`,
780
+ statusCode: response.status,
781
+ });
782
+ }
783
+ throw error;
784
+ }
785
+ }
786
+ catch (error) {
787
+ // If it's already one of our errors, re-throw it
788
+ if (error.type && error.type.includes('Error')) {
789
+ throw error;
790
+ }
791
+ // Otherwise, it's a genuine network/fetch failure
792
+ throw ErrorFactory.createNetworkError(error);
793
+ }
794
+ }
795
+ async get(path, options = {}) {
796
+ return this.request('GET', path, options);
797
+ }
798
+ async post(path, data, options = {}) {
799
+ return this.request('POST', path, { ...options, body: data });
800
+ }
801
+ async put(path, data, options = {}) {
802
+ return this.request('PUT', path, { ...options, body: data });
803
+ }
804
+ async patch(path, data, options = {}) {
805
+ return this.request('PATCH', path, { ...options, body: data });
806
+ }
807
+ async delete(path, options = {}) {
808
+ return this.request('DELETE', path, options);
809
+ }
810
+ }
811
+
812
+ /**
813
+ * Pagination types supported by the SDK
814
+ */
815
+ var PaginationType;
816
+ (function (PaginationType) {
817
+ PaginationType["OFFSET"] = "offset";
818
+ PaginationType["TOKEN"] = "token";
819
+ })(PaginationType || (PaginationType = {}));
820
+
821
+ /**
822
+ * Collection of utility functions for working with objects
823
+ */
824
+ /**
825
+ * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
826
+ * and dot-separated nested paths (e.g., 'pagination.totalCount').
827
+ * Direct key match takes priority over nested traversal.
828
+ */
829
+ function resolveNestedField(data, fieldPath) {
830
+ if (!data) {
831
+ return undefined;
832
+ }
833
+ if (fieldPath in data) {
834
+ return data[fieldPath];
835
+ }
836
+ if (!fieldPath.includes('.')) {
837
+ return undefined;
838
+ }
839
+ let value = data;
840
+ for (const part of fieldPath.split('.')) {
841
+ value = value?.[part];
842
+ }
843
+ return value;
844
+ }
845
+ /**
846
+ * Filters out undefined values from an object
847
+ * @param obj The source object
848
+ * @returns A new object without undefined values
849
+ *
850
+ * @example
851
+ * ```typescript
852
+ * // Object with undefined values
853
+ * const options = {
854
+ * name: 'test',
855
+ * count: 5,
856
+ * prefix: undefined,
857
+ * suffix: null
858
+ * };
859
+ * const result = filterUndefined(options);
860
+ * // result = { name: 'test', count: 5, suffix: null }
861
+ * ```
862
+ */
863
+ function filterUndefined(obj) {
864
+ const result = {};
865
+ for (const [key, value] of Object.entries(obj)) {
866
+ if (value !== undefined) {
867
+ result[key] = value;
868
+ }
869
+ }
870
+ return result;
871
+ }
872
+
873
+ /**
874
+ * Utility functions for platform detection
875
+ */
876
+ /**
877
+ * Checks if code is running in a browser environment
878
+ */
879
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
880
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
881
+ const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
882
+ /**
883
+ * True when the coded app has been loaded inside a host frame that explicitly
884
+ * opted into token delegation by adding `?host=embed` to the iframe src URL.
885
+ */
886
+ const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
887
+ /**
888
+ * The validated parent origin, read from the `?basedomain=` query param set
889
+ * by the embedding host in the iframe src URL.
890
+ * Mirrors the same mechanism used by ActionCenterTokenManager.
891
+ * Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
892
+ */
893
+ (() => {
894
+ if (!isHostEmbedded)
895
+ return null;
896
+ const basedomain = _params?.get('basedomain');
897
+ if (!basedomain)
898
+ return null;
899
+ try {
900
+ return new URL(basedomain).origin;
901
+ }
902
+ catch {
903
+ console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
904
+ return null;
905
+ }
906
+ })();
907
+
908
+ /**
909
+ * Base64 encoding/decoding
910
+ */
911
+ /**
912
+ * Encodes a string to base64
913
+ * @param str - The string to encode
914
+ * @returns Base64 encoded string
915
+ */
916
+ function encodeBase64(str) {
917
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
918
+ const encoder = new TextEncoder();
919
+ const data = encoder.encode(str);
920
+ // Convert Uint8Array to base64
921
+ if (isBrowser) {
922
+ // Browser environment
923
+ // Convert Uint8Array to binary string then to base64
924
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
925
+ return btoa(binaryString);
926
+ }
927
+ else {
928
+ // Node.js environment
929
+ return Buffer.from(data).toString('base64');
930
+ }
931
+ }
932
+ /**
933
+ * Decodes a base64 string
934
+ * @param base64 - The base64 string to decode
935
+ * @returns Decoded string
936
+ */
937
+ function decodeBase64(base64) {
938
+ let bytes;
939
+ if (isBrowser) {
940
+ // Browser environment
941
+ const binaryString = atob(base64);
942
+ bytes = new Uint8Array(binaryString.length);
943
+ for (let i = 0; i < binaryString.length; i++) {
944
+ bytes[i] = binaryString.charCodeAt(i);
945
+ }
946
+ }
947
+ else {
948
+ // Node.js environment
949
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
950
+ }
951
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
952
+ const decoder = new TextDecoder();
953
+ return decoder.decode(bytes);
954
+ }
955
+
956
+ /**
957
+ * PaginationManager handles the conversion between uniform cursor-based pagination
958
+ * and the specific pagination type for each service
959
+ */
960
+ class PaginationManager {
961
+ /**
962
+ * Create a pagination cursor for subsequent page requests
963
+ */
964
+ static createCursor({ pageInfo, type }) {
965
+ if (!pageInfo.hasMore) {
966
+ return undefined;
967
+ }
968
+ const cursorData = {
969
+ type,
970
+ pageSize: pageInfo.pageSize,
971
+ };
972
+ switch (type) {
973
+ case PaginationType.OFFSET:
974
+ if (pageInfo.currentPage) {
975
+ cursorData.pageNumber = pageInfo.currentPage + 1;
976
+ }
977
+ break;
978
+ case PaginationType.TOKEN:
979
+ if (pageInfo.continuationToken) {
980
+ cursorData.continuationToken = pageInfo.continuationToken;
981
+ }
982
+ else {
983
+ return undefined; // No continuation token, can't continue
984
+ }
985
+ break;
986
+ }
987
+ return {
988
+ value: encodeBase64(JSON.stringify(cursorData))
989
+ };
990
+ }
991
+ /**
992
+ * Create a paginated response with navigation cursors
993
+ */
994
+ static createPaginatedResponse({ pageInfo, type }, items) {
995
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
996
+ // Create previous page cursor if applicable
997
+ let previousCursor = undefined;
998
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
999
+ const prevCursorData = {
1000
+ type,
1001
+ pageNumber: pageInfo.currentPage - 1,
1002
+ pageSize: pageInfo.pageSize,
1003
+ };
1004
+ previousCursor = {
1005
+ value: encodeBase64(JSON.stringify(prevCursorData))
1006
+ };
1007
+ }
1008
+ // Calculate total pages if we have totalCount and pageSize
1009
+ let totalPages = undefined;
1010
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
1011
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
1012
+ }
1013
+ // Determine if this pagination type supports page jumping
1014
+ const supportsPageJump = type === PaginationType.OFFSET;
1015
+ // Create the result object with all fields, then filter out undefined values
1016
+ const result = filterUndefined({
1017
+ items,
1018
+ totalCount: pageInfo.totalCount,
1019
+ hasNextPage: pageInfo.hasMore,
1020
+ nextCursor: nextCursor,
1021
+ previousCursor: previousCursor,
1022
+ currentPage: pageInfo.currentPage,
1023
+ totalPages,
1024
+ supportsPageJump
1025
+ });
1026
+ return result;
1027
+ }
1028
+ }
1029
+
1030
+ /**
1031
+ * Common constants used across the SDK
1032
+ */
1033
+ /**
1034
+ * Prefix used for OData query parameters
1035
+ */
1036
+ const ODATA_PREFIX = '$';
1037
+ /**
1038
+ * HTTP methods
1039
+ */
1040
+ const HTTP_METHODS = {
1041
+ GET: 'GET',
1042
+ POST: 'POST'};
1043
+ /**
1044
+ * OData OFFSET pagination parameter names (ODATA-style)
1045
+ */
1046
+ const ODATA_OFFSET_PARAMS = {
1047
+ /** OData page size parameter name */
1048
+ PAGE_SIZE_PARAM: '$top',
1049
+ /** OData offset parameter name */
1050
+ OFFSET_PARAM: '$skip',
1051
+ /** OData count parameter name */
1052
+ COUNT_PARAM: '$count'
1053
+ };
1054
+ /**
1055
+ * Bucket TOKEN pagination parameter names
1056
+ */
1057
+ const BUCKET_TOKEN_PARAMS = {
1058
+ /** Bucket page size parameter name */
1059
+ PAGE_SIZE_PARAM: 'takeHint',
1060
+ /** Bucket token parameter name */
1061
+ TOKEN_PARAM: 'continuationToken'
1062
+ };
1063
+
1064
+ /**
1065
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
1066
+ * Returns the original value if parsing fails.
1067
+ */
1068
+ /**
1069
+ * Adds a prefix to specified keys in an object, returning a new object.
1070
+ * Only the provided keys are prefixed; all others are left unchanged.
1071
+ *
1072
+ * @param obj The source object
1073
+ * @param prefix The prefix to add (e.g., '$')
1074
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1075
+ * @returns A new object with specified keys prefixed
1076
+ *
1077
+ * @example
1078
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1079
+ */
1080
+ function addPrefixToKeys(obj, prefix, keys) {
1081
+ const result = {};
1082
+ for (const [key, value] of Object.entries(obj)) {
1083
+ if (keys.includes(key)) {
1084
+ result[`${prefix}${key}`] = value;
1085
+ }
1086
+ else {
1087
+ result[key] = value;
1088
+ }
1089
+ }
1090
+ return result;
1091
+ }
1092
+
1093
+ /**
1094
+ * Constants used throughout the pagination system
1095
+ */
1096
+ /** Maximum number of items that can be requested in a single page */
1097
+ const MAX_PAGE_SIZE = 1000;
1098
+ /** Default page size when jumpToPage is used without specifying pageSize */
1099
+ const DEFAULT_PAGE_SIZE = 50;
1100
+ /** Default field name for items in a paginated response */
1101
+ const DEFAULT_ITEMS_FIELD = 'value';
1102
+ /** Default field name for total count in a paginated response */
1103
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1104
+ /**
1105
+ * Limits the page size to the maximum allowed value
1106
+ * @param pageSize - Requested page size
1107
+ * @returns Limited page size value
1108
+ */
1109
+ function getLimitedPageSize(pageSize) {
1110
+ if (pageSize === undefined || pageSize === null) {
1111
+ return DEFAULT_PAGE_SIZE;
1112
+ }
1113
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1114
+ }
1115
+
1116
+ /**
1117
+ * Helper functions for pagination that can be used across services
1118
+ */
1119
+ class PaginationHelpers {
1120
+ /**
1121
+ * Checks if any pagination parameters are provided
1122
+ *
1123
+ * @param options - The options object to check
1124
+ * @returns True if any pagination parameter is defined, false otherwise
1125
+ */
1126
+ static hasPaginationParameters(options = {}) {
1127
+ const { cursor, pageSize, jumpToPage } = options;
1128
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1129
+ }
1130
+ /**
1131
+ * Parse a pagination cursor string into cursor data
1132
+ */
1133
+ static parseCursor(cursorString) {
1134
+ try {
1135
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1136
+ return cursorData;
1137
+ }
1138
+ catch {
1139
+ throw new Error('Invalid pagination cursor');
1140
+ }
1141
+ }
1142
+ /**
1143
+ * Validates cursor format and structure
1144
+ *
1145
+ * @param paginationOptions - The pagination options containing the cursor
1146
+ * @param paginationType - Optional pagination type to validate against
1147
+ */
1148
+ static validateCursor(paginationOptions, paginationType) {
1149
+ if (paginationOptions.cursor !== undefined) {
1150
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1151
+ throw new Error('cursor must contain a valid cursor string');
1152
+ }
1153
+ try {
1154
+ // Try to parse the cursor to validate it
1155
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1156
+ // If type is provided, validate cursor contains expected type information
1157
+ if (paginationType) {
1158
+ if (!cursorData.type) {
1159
+ throw new Error('Invalid cursor: missing pagination type');
1160
+ }
1161
+ // Check pagination type compatibility
1162
+ if (cursorData.type !== paginationType) {
1163
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1164
+ }
1165
+ }
1166
+ }
1167
+ catch (error) {
1168
+ if (error instanceof Error) {
1169
+ // If it's already our error with specific message, pass it through
1170
+ if (error.message.startsWith('Invalid cursor') ||
1171
+ error.message.startsWith('Pagination type mismatch')) {
1172
+ throw error;
1173
+ }
1174
+ }
1175
+ throw new Error('Invalid pagination cursor format');
1176
+ }
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Comprehensive validation for pagination options
1181
+ *
1182
+ * @param options - The pagination options to validate
1183
+ * @param paginationType - The pagination type these options will be used with
1184
+ * @returns Processed pagination parameters ready for use
1185
+ */
1186
+ static validatePaginationOptions(options, paginationType) {
1187
+ // Validate pageSize
1188
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1189
+ throw new Error('pageSize must be a positive number');
1190
+ }
1191
+ // Validate jumpToPage
1192
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1193
+ throw new Error('jumpToPage must be a positive number');
1194
+ }
1195
+ // Validate cursor
1196
+ PaginationHelpers.validateCursor(options, paginationType);
1197
+ // Validate service compatibility
1198
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1199
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1200
+ }
1201
+ // Get processed parameters
1202
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1203
+ }
1204
+ /**
1205
+ * Convert a unified pagination options to service-specific parameters
1206
+ */
1207
+ static getRequestParameters(options, paginationType) {
1208
+ // Handle jumpToPage
1209
+ if (options.jumpToPage !== undefined) {
1210
+ const jumpToPageOptions = {
1211
+ pageSize: options.pageSize,
1212
+ pageNumber: options.jumpToPage
1213
+ };
1214
+ return filterUndefined(jumpToPageOptions);
1215
+ }
1216
+ // If no cursor is provided, it's a first page request
1217
+ if (!options.cursor) {
1218
+ const firstPageOptions = {
1219
+ pageSize: options.pageSize,
1220
+ // Only set pageNumber for OFFSET pagination
1221
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1222
+ };
1223
+ return filterUndefined(firstPageOptions);
1224
+ }
1225
+ // Parse the cursor
1226
+ try {
1227
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1228
+ const cursorBasedOptions = {
1229
+ pageSize: cursorData.pageSize || options.pageSize,
1230
+ pageNumber: cursorData.pageNumber,
1231
+ continuationToken: cursorData.continuationToken,
1232
+ type: cursorData.type,
1233
+ };
1234
+ return filterUndefined(cursorBasedOptions);
1235
+ }
1236
+ catch {
1237
+ throw new Error('Invalid pagination cursor');
1238
+ }
1239
+ }
1240
+ /**
1241
+ * Helper method for paginated resource retrieval
1242
+ *
1243
+ * @param params - Parameters for pagination
1244
+ * @returns Promise resolving to a paginated result
1245
+ */
1246
+ static async getAllPaginated(params) {
1247
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1248
+ const endpoint = getEndpoint(folderId);
1249
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1250
+ // On POST, the caller's options go in the body; queryParams stays in the URL.
1251
+ // On GET, everything is URL — queryParams merges with additionalParams.
1252
+ const isPost = method === HTTP_METHODS.POST;
1253
+ const requestSpec = isPost
1254
+ ? { body: additionalParams, params: queryParams }
1255
+ : { params: { ...additionalParams, ...queryParams } };
1256
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1257
+ headers,
1258
+ ...requestSpec,
1259
+ pagination: {
1260
+ paginationType: options.paginationType || PaginationType.OFFSET,
1261
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1262
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1263
+ continuationTokenField: options.continuationTokenField,
1264
+ paginationParams: options.paginationParams
1265
+ }
1266
+ });
1267
+ // Parse items - automatically handle JSON string responses
1268
+ const rawItems = paginatedResponse.items;
1269
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1270
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1271
+ return {
1272
+ ...paginatedResponse,
1273
+ items: transformedItems
1274
+ };
1275
+ }
1276
+ /**
1277
+ * Helper method for non-paginated resource retrieval
1278
+ *
1279
+ * @param params - Parameters for non-paginated resource retrieval
1280
+ * @returns Promise resolving to an object with data and totalCount
1281
+ */
1282
+ static async getAllNonPaginated(params) {
1283
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1284
+ // Set default field names
1285
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1286
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1287
+ // Determine endpoint and headers based on folderId
1288
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1289
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1290
+ // Make the API call based on method
1291
+ let response;
1292
+ if (method === HTTP_METHODS.POST) {
1293
+ response = await serviceAccess.post(endpoint, additionalParams, { headers, params: queryParams });
1294
+ }
1295
+ else {
1296
+ response = await serviceAccess.get(endpoint, {
1297
+ params: { ...additionalParams, ...queryParams },
1298
+ headers
1299
+ });
1300
+ }
1301
+ // Extract and transform items from response
1302
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1303
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1304
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1305
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1306
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1307
+ // Parse items - automatically handle JSON string responses
1308
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1309
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1310
+ return {
1311
+ items,
1312
+ totalCount
1313
+ };
1314
+ }
1315
+ /**
1316
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1317
+ *
1318
+ * @param config - Configuration for the getAll operation
1319
+ * @param options - Request options including pagination parameters
1320
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1321
+ */
1322
+ static async getAll(config, options) {
1323
+ const optionsWithDefaults = options || {};
1324
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1325
+ // Determine if pagination is requested
1326
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1327
+ // Process parameters (custom processing if provided, otherwise default)
1328
+ let processedOptions = restOptions;
1329
+ if (config.processParametersFn) {
1330
+ processedOptions = config.processParametersFn(restOptions, folderId);
1331
+ }
1332
+ // Apply ODATA prefix to keys (excluding specified keys)
1333
+ const excludeKeys = config.excludeFromPrefix || [];
1334
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1335
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1336
+ // Default pagination options
1337
+ const paginationOptions = {
1338
+ paginationType: PaginationType.OFFSET,
1339
+ itemsField: DEFAULT_ITEMS_FIELD,
1340
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1341
+ ...config.pagination
1342
+ };
1343
+ // Paginated flow
1344
+ if (isPaginationRequested) {
1345
+ return PaginationHelpers.getAllPaginated({
1346
+ serviceAccess: config.serviceAccess,
1347
+ getEndpoint: config.getEndpoint,
1348
+ folderId,
1349
+ headers: config.headers,
1350
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1351
+ additionalParams: prefixedOptions,
1352
+ queryParams: config.queryParams,
1353
+ transformFn: config.transformFn,
1354
+ method: config.method,
1355
+ options: {
1356
+ ...paginationOptions,
1357
+ paginationParams: config.pagination?.paginationParams
1358
+ }
1359
+ }); // Type assertion needed due to conditional return
1360
+ }
1361
+ // Non-paginated flow
1362
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1363
+ return PaginationHelpers.getAllNonPaginated({
1364
+ serviceAccess: config.serviceAccess,
1365
+ getAllEndpoint: config.getEndpoint(),
1366
+ getByFolderEndpoint: byFolderEndpoint,
1367
+ folderId,
1368
+ headers: config.headers,
1369
+ additionalParams: prefixedOptions,
1370
+ queryParams: config.queryParams,
1371
+ transformFn: config.transformFn,
1372
+ method: config.method,
1373
+ options: {
1374
+ itemsField: paginationOptions.itemsField,
1375
+ totalCountField: paginationOptions.totalCountField
1376
+ }
1377
+ });
1378
+ }
1379
+ }
1380
+
1381
+ /**
1382
+ * SDK Internals Registry - Internal registry for SDK instances
1383
+ *
1384
+ * This class is NOT exported in the public API.
1385
+ * It provides a secure way to share SDK internals between
1386
+ * the UiPath class and service classes without exposing them publicly.
1387
+ *
1388
+ * @internal
1389
+ */
1390
+ // Global symbol key to ensure WeakMap is shared across module instances
1391
+ // This prevents issues when core and service modules are bundled separately
1392
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1393
+ // Get or create the global WeakMap store
1394
+ const getGlobalStore = () => {
1395
+ const globalObj = globalThis;
1396
+ if (!globalObj[REGISTRY_KEY]) {
1397
+ globalObj[REGISTRY_KEY] = new WeakMap();
1398
+ }
1399
+ return globalObj[REGISTRY_KEY];
1400
+ };
1401
+ /**
1402
+ * Internal registry for SDK private components.
1403
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1404
+ * garbage collected when the SDK instance is no longer referenced.
1405
+ *
1406
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1407
+ * across separately bundled modules (core, entities, tasks, etc.).
1408
+ *
1409
+ * @internal - Not exported in public API
1410
+ */
1411
+ class SDKInternalsRegistry {
1412
+ // Use global store to ensure sharing across module bundles
1413
+ static get store() {
1414
+ return getGlobalStore();
1415
+ }
1416
+ /**
1417
+ * Register SDK instance internals
1418
+ * Called by UiPath constructor
1419
+ */
1420
+ static set(instance, internals) {
1421
+ this.store.set(instance, internals);
1422
+ }
1423
+ /**
1424
+ * Retrieve SDK instance internals
1425
+ * Called by BaseService constructor
1426
+ */
1427
+ static get(instance) {
1428
+ const internals = this.store.get(instance);
1429
+ if (!internals) {
1430
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1431
+ }
1432
+ return internals;
1433
+ }
1434
+ }
1435
+
1436
+ var _BaseService_apiClient;
1437
+ /**
1438
+ * Base class for all UiPath SDK services.
1439
+ *
1440
+ * Provides common functionality for authentication, configuration, and API communication.
1441
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1442
+ *
1443
+ * This class implements the dependency injection pattern where services receive a configured
1444
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1445
+ * including authentication token management.
1446
+ *
1447
+ * @remarks
1448
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1449
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1450
+ *
1451
+ */
1452
+ class BaseService {
1453
+ /**
1454
+ * Creates a base service instance with dependency injection.
1455
+ *
1456
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1457
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1458
+ * and token management internally.
1459
+ *
1460
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1461
+ * Services receive this via dependency injection in the modular pattern.
1462
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1463
+ * CAS external-app auth)
1464
+ *
1465
+ * @example
1466
+ * ```typescript
1467
+ * // Services automatically call this via super()
1468
+ * export class EntityService extends BaseService {
1469
+ * constructor(instance: IUiPath) {
1470
+ * super(instance); // Initializes the internal ApiClient
1471
+ * }
1472
+ * }
1473
+ *
1474
+ * // Usage in modular pattern
1475
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1476
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1477
+ *
1478
+ * const sdk = new UiPath(config);
1479
+ * await sdk.initialize();
1480
+ * const entities = new Entities(sdk);
1481
+ * ```
1482
+ */
1483
+ constructor(instance, headers) {
1484
+ // Private field - not visible via Object.keys() or any reflection
1485
+ _BaseService_apiClient.set(this, void 0);
1486
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1487
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1488
+ this.config = { folderKey };
1489
+ }
1490
+ /**
1491
+ * Gets a valid authentication token, refreshing if necessary.
1492
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1493
+ *
1494
+ * @returns Promise resolving to a valid access token string
1495
+ * @throws AuthenticationError if no token is available or refresh fails
1496
+ */
1497
+ async getValidAuthToken() {
1498
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1499
+ }
1500
+ /**
1501
+ * Creates a service accessor for pagination helpers
1502
+ * This allows pagination helpers to access protected methods without making them public
1503
+ */
1504
+ createPaginationServiceAccess() {
1505
+ return {
1506
+ get: (path, options) => this.get(path, options || {}),
1507
+ post: (path, body, options) => this.post(path, body, options || {}),
1508
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1509
+ };
1510
+ }
1511
+ async request(method, path, options = {}) {
1512
+ switch (method.toUpperCase()) {
1513
+ case 'GET':
1514
+ return this.get(path, options);
1515
+ case 'POST':
1516
+ return this.post(path, options.body, options);
1517
+ case 'PUT':
1518
+ return this.put(path, options.body, options);
1519
+ case 'PATCH':
1520
+ return this.patch(path, options.body, options);
1521
+ case 'DELETE':
1522
+ return this.delete(path, options);
1523
+ default:
1524
+ throw new Error(`Unsupported HTTP method: ${method}`);
1525
+ }
1526
+ }
1527
+ async requestWithSpec(spec) {
1528
+ if (!spec.method || !spec.url) {
1529
+ throw new Error('Request spec must include method and url');
1530
+ }
1531
+ return this.request(spec.method, spec.url, spec);
1532
+ }
1533
+ async get(path, options = {}) {
1534
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1535
+ return { data: response };
1536
+ }
1537
+ async post(path, data, options = {}) {
1538
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1539
+ return { data: response };
1540
+ }
1541
+ async put(path, data, options = {}) {
1542
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1543
+ return { data: response };
1544
+ }
1545
+ async patch(path, data, options = {}) {
1546
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1547
+ return { data: response };
1548
+ }
1549
+ async delete(path, options = {}) {
1550
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1551
+ return { data: response };
1552
+ }
1553
+ /**
1554
+ * Execute a request with cursor-based pagination
1555
+ */
1556
+ async requestWithPagination(method, path, paginationOptions, options) {
1557
+ const paginationType = options.pagination.paginationType;
1558
+ // Validate and prepare pagination parameters
1559
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1560
+ // Prepare request parameters based on pagination type
1561
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1562
+ // Route pagination state to wherever the API expects it (body for POST, URL for GET).
1563
+ // Caller-supplied options.body / options.params are respected as-is — the api-client
1564
+ // already handles params (URL) and body (request body) independently for every method.
1565
+ if (method.toUpperCase() === 'POST') {
1566
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1567
+ options.body = {
1568
+ ...existingBody,
1569
+ ...requestParams
1570
+ };
1571
+ }
1572
+ else {
1573
+ options.params = {
1574
+ ...options.params,
1575
+ ...requestParams
1576
+ };
1577
+ }
1578
+ // Make the request
1579
+ const response = await this.request(method, path, options);
1580
+ // Extract data from the response and create page result
1581
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1582
+ itemsField: options.pagination.itemsField,
1583
+ totalCountField: options.pagination.totalCountField,
1584
+ continuationTokenField: options.pagination.continuationTokenField
1585
+ });
1586
+ }
1587
+ /**
1588
+ * Validates and prepares pagination parameters from options
1589
+ */
1590
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1591
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1592
+ }
1593
+ /**
1594
+ * Prepares request parameters for pagination based on pagination type
1595
+ */
1596
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1597
+ const requestParams = {};
1598
+ let limitedPageSize;
1599
+ const paginationParams = paginationConfig?.paginationParams;
1600
+ switch (paginationType) {
1601
+ case PaginationType.OFFSET:
1602
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1603
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1604
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1605
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1606
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1607
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1608
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1609
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1610
+ const zeroBased = paginationParams?.zeroBased ?? false;
1611
+ requestParams[pageSizeParam] = limitedPageSize;
1612
+ if (convertToSkip) {
1613
+ if (params.pageNumber && params.pageNumber > 1) {
1614
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1615
+ }
1616
+ }
1617
+ else {
1618
+ const sdkPageNumber = params.pageNumber || 1;
1619
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1620
+ }
1621
+ {
1622
+ requestParams[countParam] = true;
1623
+ }
1624
+ break;
1625
+ case PaginationType.TOKEN:
1626
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1627
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1628
+ if (params.pageSize) {
1629
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1630
+ }
1631
+ if (params.continuationToken) {
1632
+ requestParams[tokenParam] = params.continuationToken;
1633
+ }
1634
+ break;
1635
+ }
1636
+ return requestParams;
1637
+ }
1638
+ /**
1639
+ * Creates a paginated response from API response
1640
+ */
1641
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1642
+ // Extract fields from response
1643
+ const itemsField = fields.itemsField ||
1644
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1645
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1646
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1647
+ // Extract items and metadata
1648
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1649
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1650
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1651
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1652
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1653
+ const continuationToken = response.data[continuationTokenField];
1654
+ // Determine if there are more pages
1655
+ const hasMore = this.determineHasMorePages(paginationType, {
1656
+ totalCount,
1657
+ pageSize: params.pageSize,
1658
+ currentPage: params.pageNumber || 1,
1659
+ itemsCount: items.length,
1660
+ continuationToken
1661
+ });
1662
+ // Create and return the page result
1663
+ return PaginationManager.createPaginatedResponse({
1664
+ pageInfo: {
1665
+ hasMore,
1666
+ totalCount,
1667
+ currentPage: params.pageNumber,
1668
+ pageSize: params.pageSize,
1669
+ continuationToken
1670
+ },
1671
+ type: paginationType,
1672
+ }, items);
1673
+ }
1674
+ /**
1675
+ * Determines if there are more pages based on pagination type and metadata
1676
+ */
1677
+ determineHasMorePages(paginationType, info) {
1678
+ switch (paginationType) {
1679
+ case PaginationType.OFFSET:
1680
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1681
+ // If totalCount is available, use it for precise calculation
1682
+ if (info.totalCount !== undefined) {
1683
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1684
+ }
1685
+ // Fallback when totalCount is not available
1686
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1687
+ return info.itemsCount === effectivePageSize;
1688
+ case PaginationType.TOKEN:
1689
+ return !!info.continuationToken;
1690
+ default:
1691
+ return false;
1692
+ }
1693
+ }
1694
+ }
1695
+ _BaseService_apiClient = new WeakMap();
1696
+
1697
+ /**
1698
+ * Service for the Orchestrator Document Understanding module.
1699
+ */
1700
+ class OrchestratorDuModuleService extends BaseService {
1701
+ /**
1702
+ * Submits an exception report for a Document Understanding validation task.
1703
+ *
1704
+ * Records that the document under validation cannot be processed normally and captures
1705
+ * a reason. The server echoes the submitted payload and signals acceptance via
1706
+ * {@link SubmitExceptionReportResponse.IsSuccessful}.
1707
+ *
1708
+ * @param taskId - Identifier of the validation task the exception applies to.
1709
+ * @param documentId - Identifier of the document the exception applies to.
1710
+ * @param reason - Free-text reason the document is being reported as an exception.
1711
+ * @returns Promise resolving to a {@link SubmitExceptionReportResponse} containing the echoed payload and success status.
1712
+ *
1713
+ * @example
1714
+ * ```typescript
1715
+ * import { Tasks, TaskType } from '@uipath/uipath-typescript/tasks';
1716
+ *
1717
+ * const tasks = new Tasks(sdk);
1718
+ *
1719
+ * // Fetch the Document Validation task to get its documentId
1720
+ * const dvTask = await tasks.getById(<taskId>, { taskType: TaskType.DocumentValidation }, <folderId>);
1721
+ * const documentId = dvTask.data?.documentId as string;
1722
+ *
1723
+ * // Submit an exception report for the validation task
1724
+ * const result = await orchestratorDuModule.submitExceptionReport(<taskId>, documentId, '<reason>');
1725
+ *
1726
+ * if (result.IsSuccessful) {
1727
+ * console.log('Exception recorded for', result.SubmitResult?.DocumentId);
1728
+ * }
1729
+ * ```
1730
+ * @internal
1731
+ */
1732
+ async submitExceptionReport(taskId, documentId, reason, options) {
1733
+ const headers = resolveFolderHeaders({
1734
+ folderId: options.folderId,
1735
+ folderKey: options.folderKey,
1736
+ folderPath: options.folderPath,
1737
+ resourceType: 'orchestratorDuModule.submitExceptionReport',
1738
+ fallbackFolderKey: this.config.folderKey,
1739
+ });
1740
+ const response = await this.post(ORCHESTRATOR_DU_MODULE_ENDPOINTS.SUBMIT_EXCEPTION_REPORT, { DocumentId: documentId, Reason: reason }, { params: { taskId }, headers });
1741
+ return response.data;
1742
+ }
1743
+ /**
1744
+ * Processes automatically extracted data against validator-edited data and a taxonomy.
1745
+ *
1746
+ * Sends the automatic extraction result, the validated extraction result, and the
1747
+ * document taxonomy to the server, which merges and normalizes the inputs and returns
1748
+ * the resulting {@link ExtractionResult}.
1749
+ *
1750
+ * @param request - Automatic and validated extraction results plus the document taxonomy.
1751
+ * @returns Promise resolving to the merged {@link ExtractionResult}.
1752
+ *
1753
+ * @example
1754
+ * ```typescript
1755
+ * // Merge automatic and validator-edited extraction results against a taxonomy
1756
+ * const result = await orchestratorDuModule.processExtractedData({
1757
+ * AutomaticExtractedResults: <automaticExtractionResult>,
1758
+ * ValidatedExtractedResults: <validatedData>,
1759
+ * Taxonomy: <taxonomy>,
1760
+ * });
1761
+ *
1762
+ * console.log(result.DocumentId, result.ResultsDocument?.DocumentTypeName);
1763
+ * ```
1764
+ * @internal
1765
+ */
1766
+ async processExtractedData(request, options) {
1767
+ const headers = resolveFolderHeaders({
1768
+ folderId: options.folderId,
1769
+ folderKey: options.folderKey,
1770
+ folderPath: options.folderPath,
1771
+ resourceType: 'orchestratorDuModule.processExtractedData',
1772
+ fallbackFolderKey: this.config.folderKey,
1773
+ });
1774
+ const response = await this.post(ORCHESTRATOR_DU_MODULE_ENDPOINTS.PROCESS_EXTRACTED_DATA, request, { headers });
1775
+ return response.data;
1776
+ }
1777
+ }
1778
+ __decorate([
1779
+ track('OrchestratorDuModule.SubmitExceptionReport')
1780
+ ], OrchestratorDuModuleService.prototype, "submitExceptionReport", null);
1781
+ __decorate([
1782
+ track('OrchestratorDuModule.ProcessExtractedData')
1783
+ ], OrchestratorDuModuleService.prototype, "processExtractedData", null);
1784
+
1785
+ export { OrchestratorDuModuleService as OrchestratorDuModule, OrchestratorDuModuleService };