@uipath/uipath-typescript 1.5.0 → 1.5.1

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