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