@uipath/uipath-typescript
Version:
UiPath TypeScript SDK
1,603 lines (1,582 loc) • 170 kB
TypeScript
import { z } from 'zod';
declare const ConfigSchema: z.ZodObject<{
baseUrl: z.ZodDefault<z.ZodString>;
orgName: z.ZodString;
tenantName: z.ZodString;
secret: z.ZodOptional<z.ZodString>;
clientId: z.ZodOptional<z.ZodString>;
redirectUri: z.ZodOptional<z.ZodString>;
scope: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
baseUrl: string;
orgName: string;
tenantName: string;
secret?: string | undefined;
clientId?: string | undefined;
redirectUri?: string | undefined;
scope?: string | undefined;
}, {
orgName: string;
tenantName: string;
baseUrl?: string | undefined;
secret?: string | undefined;
clientId?: string | undefined;
redirectUri?: string | undefined;
scope?: string | undefined;
}>;
type Config = z.infer<typeof ConfigSchema>;
/**
* Simplified universal pagination cursor
* Used to fetch next/previous pages
*/
interface PaginationCursor {
/** Opaque string containing all information needed to fetch next page */
value: string;
}
/**
* Discriminated union for pagination methods - ensures cursor and jumpToPage are mutually exclusive
*/
type PaginationMethodUnion = {
cursor?: PaginationCursor;
jumpToPage?: never;
} | {
cursor?: never;
jumpToPage?: number;
} | {
cursor?: never;
jumpToPage?: never;
};
/**
* Pagination options. Users cannot specify both cursor and jumpToPage.
*/
type PaginationOptions = {
/** Size of the page to fetch (items per page) */
pageSize?: number;
} & PaginationMethodUnion;
/**
* Paginated response containing items and navigation information
*/
interface PaginatedResponse<T> {
/** The items in the current page */
items: T[];
/** Total count of items across all pages (if available) */
totalCount?: number;
/** Whether more pages are available */
hasNextPage: boolean;
/** Cursor to fetch the next page (if available) */
nextCursor?: PaginationCursor;
/** Cursor to fetch the previous page (if available) */
previousCursor?: PaginationCursor;
/** Current page number (1-based, if available) */
currentPage?: number;
/** Total number of pages (if available) */
totalPages?: number;
/** Whether this pagination type supports jumping to arbitrary pages */
supportsPageJump: boolean;
}
/**
* Response for non-paginated calls that includes both data and total count
*/
interface NonPaginatedResponse<T> {
items: T[];
totalCount?: number;
}
/**
* Helper type for defining paginated method overloads
* Creates a union type of all ways pagination can be triggered
*/
type HasPaginationOptions<T> = (T & {
pageSize: number;
}) | (T & {
cursor: PaginationCursor;
}) | (T & {
jumpToPage: number;
});
/**
* Pagination types supported by the SDK
*/
declare enum PaginationType {
OFFSET = "offset",
TOKEN = "token"
}
/**
* Interface for service access methods needed by pagination helpers
*/
interface PaginationServiceAccess {
get<T>(path: string, options?: any): Promise<{
data: T;
}>;
requestWithPagination<T>(method: string, path: string, paginationOptions: PaginationOptions, options: RequestWithPaginationOptions): Promise<PaginatedResponse<T>>;
}
/**
* Field names for extracting data from paginated responses.
*/
interface PaginationFieldNames {
itemsField?: string;
totalCountField?: string;
continuationTokenField?: string;
}
/**
* Options for the requestWithPagination method in BaseService.
*/
interface RequestWithPaginationOptions extends RequestSpec {
pagination: PaginationFieldNames & {
paginationType: PaginationType;
paginationParams?: {
pageSizeParam?: string;
offsetParam?: string;
tokenParam?: string;
countParam?: string;
};
};
}
/**
* HTTP methods supported by the API client
*/
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
/**
* Supported response types for API requests
*/
type ResponseType = 'json' | 'text' | 'blob' | 'arraybuffer' | 'stream';
/**
* Query parameters type with support for arrays and nested objects
*/
type QueryParams = Record<string, string | number | boolean | Array<string | number | boolean> | null | undefined>;
/**
* Standard HTTP headers type
*/
type Headers = Record<string, string>;
/**
* Options for request retries
*/
interface RetryOptions {
/** Maximum number of retry attempts */
maxRetries?: number;
/** Base delay between retries in milliseconds */
retryDelay?: number;
/** Whether to use exponential backoff */
useExponentialBackoff?: boolean;
/** Status codes that should trigger a retry */
retryableStatusCodes?: number[];
}
/**
* Options for request timeouts
*/
interface TimeoutOptions {
/** Request timeout in milliseconds */
timeout?: number;
/** Whether to abort the request on timeout */
abortOnTimeout?: boolean;
}
/**
* Options for request body transformation
*/
interface BodyOptions {
/** Whether to stringify the body */
stringify?: boolean;
/** Content type override */
contentType?: string;
}
/**
* Pagination metadata for API requests
*/
interface PaginationMetadata {
/** Type of pagination used by the API endpoint */
paginationType: PaginationType;
/** Response field containing items array (defaults to 'value') */
itemsField?: string;
/** Response field containing total count (defaults to '@odata.count') */
totalCountField?: string;
/** Response field containing continuation token (defaults to 'continuationToken') */
continuationTokenField?: string;
}
/**
* Base interface for all API requests
*/
interface RequestSpec {
/** HTTP method for the request */
method?: HttpMethod;
/** URL endpoint for the request */
url?: string;
/** Query parameters to be appended to the URL */
params?: QueryParams;
/** HTTP headers to include with the request */
headers?: Headers;
/** Raw body content (takes precedence over data) */
body?: unknown;
/** Expected response type */
responseType?: ResponseType;
/** Request timeout options */
timeoutOptions?: TimeoutOptions;
/** Retry behavior options */
retryOptions?: RetryOptions;
/** Body transformation options */
bodyOptions?: BodyOptions;
/** AbortSignal for cancelling the request */
signal?: AbortSignal;
/** Pagination metadata for the request */
pagination?: PaginationMetadata;
}
/**
* ExecutionContext manages the state and context of API operations.
* It provides a way to share context across service calls and maintain
* execution state throughout the lifecycle of operations.
*/
declare class ExecutionContext {
private context;
private headers;
/**
* Set a context value that will be available throughout the execution
*/
set<T>(key: string, value: T): void;
/**
* Get a previously set context value
*/
get<T>(key: string): T | undefined;
/**
* Set custom headers that will be included in all API requests
*/
setHeaders(headers: Record<string, string>): void;
/**
* Get all custom headers
*/
getHeaders(): Record<string, string>;
/**
* Clear all context and headers
*/
clear(): void;
/**
* Create a request spec for an API call
*/
createRequestSpec(spec?: Partial<RequestSpec>): RequestSpec;
}
/**
* Authentication token information
*/
interface TokenInfo {
token: string;
type: 'secret' | 'oauth';
expiresAt?: Date;
refreshToken?: string;
}
/**
* OAuth token response
*/
interface AuthToken {
access_token: string;
token_type: string;
expires_in: number;
scope: string;
refresh_token?: string;
}
/**
* TokenManager is responsible for managing authentication tokens.
* It provides token operations for a specific client ID.
* - For OAuth tokens: Uses session storage with client ID-based keys
* - For Secret tokens: Stores only in memory, allowing multiple instances
*/
declare class TokenManager {
private executionContext;
private config;
private isOAuth;
private currentToken?;
private readonly STORAGE_KEY_PREFIX;
private refreshPromise;
/**
* Creates a new TokenManager instance
* @param executionContext The execution context
* @param config The SDK configuration
* @param isOAuth Whether this is an OAuth-based authentication
*/
constructor(executionContext: ExecutionContext, config: Config, isOAuth?: boolean);
/**
* Checks if a token is expired
* @param tokenInfo The token info to check
* @returns true if the token is expired, false otherwise
*/
isTokenExpired(tokenInfo?: TokenInfo): boolean;
/**
* Gets the storage key for this TokenManager instance
*/
private _getStorageKey;
/**
* Loads token from session storage if available
* @returns true if a valid token was loaded, false otherwise
*/
loadFromStorage(): boolean;
/**
* Parse and validate token info from storage
* @param storedToken JSON string from storage
* @returns Valid TokenInfo or undefined if invalid
*/
private _parseTokenInfo;
/**
* Sets a new token and updates all necessary contexts
*/
setToken(tokenInfo: TokenInfo): void;
/**
* Gets the current token information
*/
getTokenInfo(): TokenInfo | undefined;
/**
* Gets just the token string
*/
getToken(): string | undefined;
/**
* Checks if we have a valid token
*/
hasValidToken(): boolean;
/**
* Clears the current token
*/
clearToken(): void;
/**
* Updates execution context with token information
*/
private _updateExecutionContext;
/**
* Refreshes the access token using the stored refresh token.
* This method only works for OAuth flow.
* Uses a lock mechanism to prevent multiple simultaneous refreshes.
* @returns A promise that resolves to the new AuthToken
* @throws Error if not in OAuth flow, refresh token is missing, or the request fails
*/
refreshAccessToken(): Promise<AuthToken>;
/**
* Internal method to perform the actual token refresh
*/
private _doRefreshToken;
}
interface ApiClientConfig {
headers?: Record<string, string>;
}
declare class ApiClient {
private readonly config;
private readonly executionContext;
private readonly clientConfig;
private defaultHeaders;
private tokenManager;
constructor(config: Config, executionContext: ExecutionContext, tokenManager: TokenManager, clientConfig?: ApiClientConfig);
setDefaultHeaders(headers: Record<string, string>): void;
/**
* Checks if the current token needs refresh and refreshes it if necessary
* @returns The valid token
* @throws Error if token refresh fails
*/
private ensureValidToken;
private getDefaultHeaders;
private request;
get<T>(path: string, options?: RequestSpec): Promise<T>;
post<T>(path: string, data?: unknown, options?: RequestSpec): Promise<T>;
put<T>(path: string, data?: unknown, options?: RequestSpec): Promise<T>;
patch<T>(path: string, data?: unknown, options?: RequestSpec): Promise<T>;
delete<T>(path: string, options?: RequestSpec): Promise<T>;
}
interface ApiResponse<T> {
data: T;
}
declare class BaseService {
protected readonly config: Config;
protected readonly executionContext: ExecutionContext;
protected readonly apiClient: ApiClient;
constructor(config: Config, executionContext: ExecutionContext, tokenManager: TokenManager);
/**
* Creates a service accessor for pagination helpers
* This allows pagination helpers to access protected methods without making them public
*/
protected createPaginationServiceAccess(): PaginationServiceAccess;
protected request<T>(method: string, path: string, options?: RequestSpec): Promise<ApiResponse<T>>;
protected requestWithSpec<T>(spec: RequestSpec): Promise<ApiResponse<T>>;
protected get<T>(path: string, options?: RequestSpec): Promise<ApiResponse<T>>;
protected post<T>(path: string, data?: unknown, options?: RequestSpec): Promise<ApiResponse<T>>;
protected put<T>(path: string, data?: unknown, options?: RequestSpec): Promise<ApiResponse<T>>;
protected patch<T>(path: string, data?: unknown, options?: RequestSpec): Promise<ApiResponse<T>>;
protected delete<T>(path: string, options?: RequestSpec): Promise<ApiResponse<T>>;
/**
* Execute a request with cursor-based pagination
*/
protected requestWithPagination<T>(method: string, path: string, paginationOptions: PaginationOptions, options: RequestWithPaginationOptions): Promise<PaginatedResponse<T>>;
/**
* Validates and prepares pagination parameters from options
*/
private validateAndPreparePaginationParams;
/**
* Prepares request parameters for pagination based on pagination type
*/
private preparePaginationRequestParams;
/**
* Creates a paginated response from API response
*/
private createPaginatedResponseFromResponse;
/**
* Determines if there are more pages based on pagination type and metadata
*/
private determineHasMorePages;
}
/**
* Entity field type names
*/
declare enum EntityFieldDataType {
UUID = "UUID",
STRING = "STRING",
INTEGER = "INTEGER",
DATETIME = "DATETIME",
DATETIME_WITH_TZ = "DATETIME_WITH_TZ",
DECIMAL = "DECIMAL",
FLOAT = "FLOAT",
DOUBLE = "DOUBLE",
DATE = "DATE",
BOOLEAN = "BOOLEAN",
BIG_INTEGER = "BIG_INTEGER",
MULTILINE_TEXT = "MULTILINE_TEXT"
}
/**
* Represents a single entity record
*/
interface EntityRecord {
/**
* Unique identifier for the record
*/
id: string;
/**
* Additional dynamic fields for the entity
*/
[key: string]: any;
}
/**
* Options for getting an entity by Id
*/
type EntityGetRecordsByIdOptions = {
/** Level of entity expansion (default: 0) */
expansionLevel?: number;
} & PaginationOptions;
/**
* Common options for entity operations that modify multiple records
*/
interface EntityOperationOptions {
/** Level of entity expansion (default: 0) */
expansionLevel?: number;
/** Whether to fail on first error (default: false) */
failOnFirst?: boolean;
}
/**
* Options for inserting data into an entity
*/
type EntityInsertOptions = EntityOperationOptions;
/**
* Options for updating data in an entity
*/
type EntityUpdateOptions = EntityOperationOptions;
/**
* Options for deleting data from an entity
*/
interface EntityDeleteOptions {
/** Whether to fail on first error (default: false) */
failOnFirst?: boolean;
}
/**
* Represents a failure record in an entity operation
*/
interface FailureRecord {
/** Error message */
error?: string;
/** Original record that failed */
record?: Record<string, any>;
}
/**
* Response from an entity operation that modifies multiple records
*/
interface EntityOperationResponse {
/** Records that were successfully processed */
successRecords: Record<string, any>[];
/** Records that failed processing */
failureRecords: FailureRecord[];
}
/**
* Response from inserting data into an entity
*/
type EntityInsertResponse = EntityOperationResponse;
/**
* Response from updating data in an entity
*/
type EntityUpdateResponse = EntityOperationResponse;
/**
* Response from deleting data from an entity
*/
type EntityDeleteResponse = EntityOperationResponse;
/**
* Entity type enum
*/
declare enum EntityType {
Entity = "Entity",
ChoiceSet = "ChoiceSet",
InternalEntity = "InternalEntity",
SystemEntity = "SystemEntity"
}
/**
* Field type metadata
*/
interface FieldDataType {
name: EntityFieldDataType;
lengthLimit?: number;
maxValue?: number;
minValue?: number;
decimalPrecision?: number;
}
/**
* Reference types for fields
*/
declare enum ReferenceType {
ManyToOne = "ManyToOne"
}
/**
* Field display types
*/
declare enum FieldDisplayType {
Basic = "Basic",
Relationship = "Relationship",
File = "File",
ChoiceSetSingle = "ChoiceSetSingle",
ChoiceSetMultiple = "ChoiceSetMultiple",
AutoNumber = "AutoNumber"
}
/**
* Data direction type for external fields
*/
declare enum DataDirectionType {
ReadOnly = "ReadOnly",
ReadAndWrite = "ReadAndWrite"
}
/**
* Join type for source join criteria
*/
declare enum JoinType {
LeftJoin = "LeftJoin"
}
/**
* Field reference with ID
*/
interface Field {
id: string;
definition?: FieldMetaData;
}
/**
* Detailed field definition
*/
interface FieldMetaData {
id: string;
name: string;
isPrimaryKey: boolean;
isForeignKey: boolean;
isExternalField: boolean;
isHiddenField: boolean;
isUnique: boolean;
referenceName?: string;
referenceEntity?: RawEntityGetResponse;
referenceChoiceSet?: RawEntityGetResponse;
referenceField?: Field;
referenceType: ReferenceType;
fieldDataType: FieldDataType;
isRequired: boolean;
displayName: string;
description: string;
createdTime: string;
createdBy: string;
updatedTime: string;
updatedBy?: string;
isSystemField: boolean;
fieldDisplayType?: FieldDisplayType;
choiceSetId?: string;
defaultValue?: string;
isAttachment: boolean;
isRbacEnabled: boolean;
}
/**
* External object details
*/
interface ExternalObject {
id: string;
externalObjectName?: string;
externalObjectDisplayName?: string;
primaryKey?: string;
externalConnectionId: string;
entityId?: string;
isPrimarySource: boolean;
}
/**
* External connection details
*/
interface ExternalConnection {
id: string;
connectionId: string;
elementInstanceId: number;
folderKey: string;
connectorKey?: string;
connectorName?: string;
connectionName?: string;
}
/**
* External field mapping
*/
interface ExternalFieldMapping {
id: string;
externalFieldName?: string;
externalFieldDisplayName?: string;
externalObjectId: string;
externalFieldType?: string;
internalFieldId: string;
directionType: DataDirectionType;
}
/**
* External field
*/
interface ExternalField {
fieldMetaData: FieldMetaData;
externalFieldMappingDetail: ExternalFieldMapping;
}
/**
* External source fields
*/
interface ExternalSourceFields {
fields?: ExternalField[];
externalObjectDetail?: ExternalObject;
externalConnectionDetail?: ExternalConnection;
}
/**
* Source join criteria
*/
interface SourceJoinCriteria {
id: string;
entityId: string;
joinFieldName?: string;
joinType: JoinType;
relatedSourceObjectId?: string;
relatedSourceFieldName?: string;
}
/**
* Entity metadata returned by getById
*/
interface RawEntityGetResponse {
name: string;
displayName: string;
entityType: EntityType;
description: string;
fields: FieldMetaData[];
externalFields?: ExternalSourceFields[];
sourceJoinCriterias?: SourceJoinCriteria[];
recordCount?: number;
storageSizeInMB?: number;
usedStorageSizeInMB?: number;
attachmentSizeInByte?: number;
isRbacEnabled: boolean;
id: string;
createdBy: string;
createdTime: string;
updatedTime?: string;
updatedBy?: string;
}
/**
* Service for managing UiPath Data Fabric Entities.
*
* Entities are collections of records that can be used to store and manage data in the Data Fabric. [UiPath Data Fabric Guide](https://docs.uipath.com/data-service/automation-cloud/latest/user-guide/introduction)
*
*/
interface EntityServiceModel {
/**
* Gets all entities in the system
*
* @returns Promise resolving to either an array of entities NonPaginatedResponse<EntityGetResponse> or a PaginatedResponse<EntityGetResponse> when pagination options are used.
* {@link EntityGetResponse}
* @example
* ```typescript
* // Get all entities
* const entities = await sdk.entities.getAll();
*
* // Iterate through entities
* entities.forEach(entity => {
* console.log(`Entity: ${entity.displayName} (${entity.name})`);
* console.log(`Type: ${entity.entityType}`);
* });
*
* // Find a specific entity by name
* const customerEntity = entities.find(e => e.name === 'Customer');
*
* // Use entity methods directly
* if (customerEntity) {
* const records = await customerEntity.getRecords();
* console.log(`Customer records: ${records.items.length}`);
*
* const insertResult = await customerEntity.insert([
* { name: "John", age: 30 }
* ]);
* }
* ```
*/
getAll(): Promise<EntityGetResponse[]>;
/**
* Gets entity metadata by entity ID with attached operation methods
*
* @param id - UUID of the entity
* @returns Promise resolving to entity metadata with operation methods
* {@link EntityGetResponse}
* @example
* ```typescript
* // Get entity metadata with methods
* const entity = await sdk.entities.getById(<entityId>);
*
* // Call operations directly on the entity
* const records = await entity.getRecords();
*
* const insertResult = await entity.insert([
* { name: "John", age: 30 }
* ]);
* ```
*/
getById(id: string): Promise<EntityGetResponse>;
/**
* Gets entity records by entity ID
*
* @param entityId - UUID of the entity
* @param options - Query options
* @returns Promise resolving to either an array of entity records NonPaginatedResponse<EntityRecord> or a PaginatedResponse<EntityRecord> when pagination options are used.
* {@link EntityRecord}
* @example
* ```typescript
* // Basic usage (non-paginated)
* const records = await sdk.entities.getRecordsById(<entityId>);
*
* // With expansion level
* const records = await sdk.entities.getRecordsById(<entityId>, {
* expansionLevel: 1
* });
*
* // With pagination
* const paginatedResponse = await sdk.entities.getRecordsById(<entityId>, {
* pageSize: 50,
* expansionLevel: 1
* });
*
* // Navigate to next page
* const nextPage = await sdk.entities.getRecordsById(<entityId>, {
* cursor: paginatedResponse.nextCursor,
* expansionLevel: 1
* });
* ```
*/
getRecordsById<T extends EntityGetRecordsByIdOptions = EntityGetRecordsByIdOptions>(entityId: string, options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<EntityRecord> : NonPaginatedResponse<EntityRecord>>;
/**
* Inserts data into an entity by entity ID
*
* @param id - UUID of the entity
* @param data - Array of records to insert
* @param options - Insert options
* @returns Promise resolving to insert response
* {@link EntityInsertResponse}
* @example
* ```typescript
* // Basic usage
* const result = await sdk.entities.insertById(<entityId>, [
* { name: "John", age: 30 },
* { name: "Jane", age: 25 }
* ]);
*
* // With options
* const result = await sdk.entities.insertById(<entityId>, [
* { name: "John", age: 30 },
* { name: "Jane", age: 25 }
* ], {
* expansionLevel: 1,
* failOnFirst: true
* });
* ```
*/
insertById(id: string, data: Record<string, any>[], options?: EntityInsertOptions): Promise<EntityInsertResponse>;
/**
* Updates data in an entity by entity ID
*
* @param id - UUID of the entity
* @param data - Array of records to update. Each record MUST contain the record Id.
* @param options - Update options
* @returns Promise resolving to update response
* {@link EntityUpdateResponse}
* @example
* ```typescript
* // Basic usage
* const result = await sdk.entities.updateById(<entityId>, [
* { Id: "123", name: "John Updated", age: 31 },
* { Id: "456", name: "Jane Updated", age: 26 }
* ]);
*
* // With options
* const result = await sdk.entities.updateById(<entityId>, [
* { Id: "123", name: "John Updated", age: 31 },
* { Id: "456", name: "Jane Updated", age: 26 }
* ], {
* expansionLevel: 1,
* failOnFirst: true
* });
* ```
*/
updateById(id: string, data: EntityRecord[], options?: EntityUpdateOptions): Promise<EntityUpdateResponse>;
/**
* Deletes data from an entity by entity ID
*
* @param id - UUID of the entity
* @param recordIds - Array of record UUIDs to delete
* @param options - Delete options
* @returns Promise resolving to delete response
* {@link EntityDeleteResponse}
* @example
* ```typescript
* // Basic usage
* const result = await sdk.entities.deleteById(<entityId>, [
* <recordId-1>, <recordId-2>
* ]);
* ```
*/
deleteById(id: string, recordIds: string[], options?: EntityDeleteOptions): Promise<EntityDeleteResponse>;
}
/**
* Entity methods interface - defines operations that can be performed on an entity
*/
interface EntityMethods {
/**
* Insert data into this entity
*
* @param data - Array of records to insert
* @param options - Insert options
* @returns Promise resolving to insert response
*/
insert(data: Record<string, any>[], options?: EntityInsertOptions): Promise<EntityInsertResponse>;
/**
* Update data in this entity
*
* @param data - Array of records to update. Each record MUST contain the record Id,
* otherwise the update will fail.
* @param options - Update options
* @returns Promise resolving to update response
*/
update(data: EntityRecord[], options?: EntityUpdateOptions): Promise<EntityUpdateResponse>;
/**
* Delete data from this entity
*
* @param recordIds - Array of record UUIDs to delete
* @param options - Delete options
* @returns Promise resolving to delete response
*/
delete(recordIds: string[], options?: EntityDeleteOptions): Promise<EntityDeleteResponse>;
/**
* Get records from this entity
*
* @param options - Query options
* @returns Promise resolving to query response
*/
getRecords<T extends EntityGetRecordsByIdOptions = EntityGetRecordsByIdOptions>(options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<EntityRecord> : NonPaginatedResponse<EntityRecord>>;
}
/**
* Entity with methods combining metadata with operation methods
*/
type EntityGetResponse = RawEntityGetResponse & EntityMethods;
/**
* Creates an actionable entity metadata by combining entity with operational methods
*
* @param entityData - Entity metadata
* @param service - The entity service instance
* @returns Entity metadata with added methods
*/
declare function createEntityWithMethods(entityData: RawEntityGetResponse, service: EntityServiceModel): EntityGetResponse;
/**
* Service for interacting with the Data Fabric Entity API
*/
declare class EntityService extends BaseService implements EntityServiceModel {
/**
* @hideconstructor
*/
constructor(config: Config, executionContext: ExecutionContext, tokenManager: TokenManager);
/**
* Gets entity metadata by entity ID with attached operation methods
*
* @param id - UUID of the entity
* @returns Promise resolving to entity metadata with schema information and operation methods
*
* @example
* ```typescript
* // Get entity metadata with methods
* const entity = await sdk.entities.getById("<entityId>");
*
* // Call operations directly on the entity
* const records = await entity.getRecords();
*
* const insertResult = await entity.insert([
* { name: "John", age: 30 }
* ]);
* ```
*/
getById(id: string): Promise<EntityGetResponse>;
/**
* Gets entity records by entity ID
*
* @param entityId - UUID of the entity
* @param options - Query options including expansionLevel and pagination options
* @returns Promise resolving to an array of entity records or paginated response
*
* @example
* ```typescript
* // Basic usage (non-paginated)
* const records = await sdk.entities.getRecordsById(<entityId>);
*
* // With expansion level
* const records = await sdk.entities.getRecordsById(<entityId>, {
* expansionLevel: 1
* });
*
* // With pagination
* const paginatedResponse = await sdk.entities.getRecordsById(<entityId>, {
* pageSize: 50,
* expansionLevel: 1
* });
*
* // Navigate to next page
* const nextPage = await sdk.entities.getRecordsById(<entityId>, {
* cursor: paginatedResponse.nextCursor,
* expansionLevel: 1
* });
* ```
*/
getRecordsById<T extends EntityGetRecordsByIdOptions = EntityGetRecordsByIdOptions>(entityId: string, options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<EntityRecord> : NonPaginatedResponse<EntityRecord>>;
/**
* Inserts data into an entity by entity ID
*
* @param entityId - UUID of the entity
* @param data - Array of records to insert
* @param options - Insert options
* @returns Promise resolving to insert response
*
* @example
* ```typescript
* // Basic usage
* const result = await sdk.entities.insertById(<entityId>, [
* { name: "John", age: 30 },
* { name: "Jane", age: 25 }
* ]);
*
* // With options
* const result = await sdk.entities.insertById(<entityId>, [
* { name: "John", age: 30 },
* { name: "Jane", age: 25 }
* ], {
* expansionLevel: 1,
* failOnFirst: true
* });
* ```
*/
insertById(id: string, data: Record<string, any>[], options?: EntityInsertOptions): Promise<EntityInsertResponse>;
/**
* Updates data in an entity by entity ID
*
* @param entityId - UUID of the entity
* @param data - Array of records to update. Each record MUST contain the record Id,
* otherwise the update will fail.
* @param options - Update options
* @returns Promise resolving to update response
*
* @example
* ```typescript
* // Basic usage
* const result = await sdk.entities.updateById(<entityId>, [
* { Id: "123", name: "John Updated", age: 31 },
* { Id: "456", name: "Jane Updated", age: 26 }
* ]);
*
* // With options
* const result = await sdk.entities.updateById(<entityId>, [
* { Id: "123", name: "John Updated", age: 31 },
* { Id: "456", name: "Jane Updated", age: 26 }
* ], {
* expansionLevel: 1,
* failOnFirst: true
* });
* ```
*/
updateById(id: string, data: EntityRecord[], options?: EntityUpdateOptions): Promise<EntityUpdateResponse>;
/**
* Deletes data from an entity by entity ID
*
* @param entityId - UUID of the entity
* @param recordIds - Array of record UUIDs to delete
* @param options - Delete options
* @returns Promise resolving to delete response
*
* @example
* ```typescript
* // Basic usage
* const result = await sdk.entities.deleteById(<entityId>, [
* <recordId-1>, <recordId-2>
* ]);
* ```
*/
deleteById(id: string, recordIds: string[], options?: EntityDeleteOptions): Promise<EntityDeleteResponse>;
/**
* Gets all entities in the system
*
* @returns Promise resolving to an array of entity metadata
*
* @example
* ```typescript
* // Get all entities
* const entities = await sdk.entities.getAll();
*
* // Call operations on an entity
* const records = await entities[0].getRecords();
* ```
*/
getAll(): Promise<EntityGetResponse[]>;
/**
* Orchestrates all field mapping transformations
*
* @param metadata - Entity metadata to transform
* @private
*/
private applyFieldMappings;
/**
* Maps SQL field types to friendly EntityFieldTypes
*
* @param metadata - Entity metadata with fields
* @private
*/
private mapFieldTypes;
/**
* Transforms nested reference objects in field metadata
*/
private transformNestedReferences;
/**
* Maps external field names to consistent naming
*
* @param metadata - Entity metadata with externalFields
* @private
*/
private mapExternalFields;
}
/**
* Maestro Process Types
* Types and interfaces for Maestro process management
*/
/**
* Process information with instance statistics
*/
interface RawMaestroProcessGetAllResponse {
/** Unique key identifying the process */
processKey: string;
/** Package identifier */
packageId: string;
/** Process name */
name: string;
/** Folder key where process is located */
folderKey: string;
/** Folder name */
folderName: string;
/** Available package versions */
packageVersions: string[];
/** Total number of versions */
versionCount: number;
/** Process instance count - pending */
pendingCount: number;
/** Process instance count - running */
runningCount: number;
/** Process instance count - completed */
completedCount: number;
/** Process instance count - paused */
pausedCount: number;
/** Process instance count - cancelled */
cancelledCount: number;
/** Process instance count - faulted */
faultedCount: number;
/** Process instance count - retrying */
retryingCount: number;
/** Process instance count - resuming */
resumingCount: number;
/** Process instance count - pausing */
pausingCount: number;
/** Process instance count - canceling */
cancelingCount: number;
}
/**
* Process Incident Status
*/
declare enum ProcessIncidentStatus {
Open = "Open",
Closed = "Closed"
}
/**
* Process Incident Type
*/
declare enum ProcessIncidentType {
System = "System",
User = "User",
Deployment = "Deployment"
}
/**
* Process Incident Severity
*/
declare enum ProcessIncidentSeverity {
Error = "Error",
Warning = "Warning"
}
/**
* Process Incident Debug Mode
*/
declare enum DebugMode {
None = "None",
Default = "Default",
StepByStep = "StepByStep",
SingleStep = "SingleStep"
}
/**
* Process Incident Get Response
*/
interface ProcessIncidentGetResponse {
instanceId: string;
elementId: string;
folderKey: string;
processKey: string;
incidentId: string;
incidentStatus: ProcessIncidentStatus;
incidentType: ProcessIncidentType | null;
errorCode: string;
errorMessage: string;
errorTime: string;
errorDetails: string;
debugMode: DebugMode;
incidentSeverity: ProcessIncidentSeverity | null;
incidentElementActivityType: string;
incidentElementActivityName: string;
}
/**
* Process Incident Summary Get Response
*/
interface ProcessIncidentGetAllResponse {
count: number;
errorMessage: string;
errorCode: string;
firstOccuranceTime: string;
processKey: string;
}
/**
* Maestro Process Models
* Model classes for Maestro processes
*/
/**
* Service for managing UiPath Maestro Processes
*
* UiPath Maestro is a cloud-native orchestration layer that coordinates bots, AI agents, and humans for seamless, intelligent automation of complex workflows. [UiPath Maestro Guide](https://docs.uipath.com/maestro/automation-cloud/latest/user-guide/introduction-to-maestro)
*/
interface MaestroProcessesServiceModel {
/**
* @returns Promise resolving to array of MaestroProcess objects with methods
* {@link MaestroProcessGetAllResponse}
* @example
* ```typescript
* // Get all processes
* const processes = await sdk.maestro.processes.getAll();
*
* // Access process information and incidents
* for (const process of processes) {
* console.log(`Process: ${process.processKey}`);
* console.log(`Running instances: ${process.runningCount}`);
* console.log(`Faulted instances: ${process.faultedCount}`);
*
* // Get incidents for this process
* const incidents = await process.getIncidents();
* console.log(`Incidents: ${incidents.length}`);
* }
*
* ```
*/
getAll(): Promise<MaestroProcessGetAllResponse[]>;
/**
* Get incidents for a specific process
*
* @param processKey The key of the process to get incidents for
* @param folderKey The folder key for authorization
* @returns Promise resolving to array of incidents for the process
* {@link ProcessIncidentGetResponse}
* @example
* ```typescript
* // Get incidents for a specific process
* const incidents = await sdk.maestro.processes.getIncidents('<processKey>', '<folderKey>');
*
* // Access incident details
* for (const incident of incidents) {
* console.log(`Element: ${incident.incidentElementActivityName} (${incident.incidentElementActivityType})`);
* console.log(`Status: ${incident.incidentStatus}`);
* console.log(`Error: ${incident.errorMessage}`);
* }
* ```
*/
getIncidents(processKey: string, folderKey: string): Promise<ProcessIncidentGetResponse[]>;
}
interface ProcessMethods {
/**
* Gets incidents for this process
*
* @returns Promise resolving to array of process incidents
*/
getIncidents(): Promise<ProcessIncidentGetResponse[]>;
}
type MaestroProcessGetAllResponse = RawMaestroProcessGetAllResponse & ProcessMethods;
/**
* Creates an actionable process by combining API process data with operational methods.
*
* @param processData - The process data from API
* @param service - The process service instance
* @returns A process object with added methods
*/
declare function createProcessWithMethods(processData: MaestroProcessGetAllResponse, service: MaestroProcessesServiceModel): MaestroProcessGetAllResponse;
/**
* Constants used throughout the pagination system
*/
/** Maximum number of items that can be requested in a single page */
declare const MAX_PAGE_SIZE = 1000;
/** Default page size when jumpToPage is used without specifying pageSize */
declare const DEFAULT_PAGE_SIZE = 50;
/** Default field name for items in a paginated response */
declare const DEFAULT_ITEMS_FIELD = "value";
/** Default field name for total count in a paginated response */
declare const DEFAULT_TOTAL_COUNT_FIELD = "@odata.count";
/**
* Limits the page size to the maximum allowed value
* @param pageSize - Requested page size
* @returns Limited page size value
*/
declare function getLimitedPageSize(pageSize?: number): number;
/**
* Process Instance Types
* Types and interfaces for Maestro process instance management
*/
/**
* Response for getting a single process instance
*/
interface RawProcessInstanceGetResponse {
instanceId: string;
packageKey: string;
packageId: string;
packageVersion: string;
latestRunId: string;
latestRunStatus: string;
processKey: string;
folderKey: string;
userId: number;
instanceDisplayName: string;
startedByUser: string;
source: string;
creatorUserKey: string;
startedTime: string;
completedTime: string | null;
instanceRuns: ProcessInstanceRun[];
}
/**
* Query options for getting process instances
*/
interface ProcessInstanceGetAllOptions {
packageId?: string;
packageVersion?: string;
processKey?: string;
errorCode?: string;
}
/**
* Query options for getting process instances with pagination support
*/
type ProcessInstanceGetAllWithPaginationOptions = ProcessInstanceGetAllOptions & PaginationOptions;
/**
* Request for process instance operations (cancel, pause, resume)
*/
interface ProcessInstanceOperationOptions {
comment?: string;
}
/**
* Response from PIMS operations (cancel, pause, resume)
*/
interface ProcessInstanceOperationResponse {
instanceId: string;
status: string;
}
/**
* Response for process instance execution history
*/
interface ProcessInstanceExecutionHistoryResponse {
id: string;
traceId: string;
parentId: string | null;
name: string;
startedTime: string;
endTime: string | null;
attributes: string | null;
createdTime: string;
updatedTime?: string;
expiredTime: string | null;
}
/**
* Process Instance run
*/
interface ProcessInstanceRun {
runId: string;
status: string;
startedTime: string;
completedTime: string;
}
type BpmnXmlString = string;
/**
* Process Instance element metadata
*/
interface ElementMetaData {
elementId: string;
elementRunId: string;
isMarker: boolean;
inputs: Record<string, any>;
inputDefinitions: Record<string, any>;
outputs: Record<string, any>;
}
/**
* Process Instance global variable metadata
*/
interface GlobalVariableMetaData {
id: string;
name: string;
/**
* Common values: "integer", "string", "boolean"
* May also contain custom types or "any" when type cannot be determined
*/
type: string;
elementId: string;
/** Name of the BPMN node/element */
source: string;
value: any;
}
/**
* Response for getting global variables for process instance
*/
interface ProcessInstanceGetVariablesResponse {
elements: ElementMetaData[];
globalVariables: GlobalVariableMetaData[];
instanceId: string;
parentElementId: string | null;
}
/**
* Options for getting global variables
*/
interface ProcessInstanceGetVariablesOptions {
parentElementId?: string;
}
interface CollectionResponse<T> {
value: T[];
}
/**
* Standardized result interface for all operation methods (pause, cancel, complete, update, upload, etc.)
* Success responses include data from the request context or API response
*/
interface OperationResponse<TData> {
/**
* Whether the operation was successful
*/
success: boolean;
/**
* Response data (can contain error details in case of failure)
*/
data: TData;
}
/**
* Common enum for job state used across services
*/
declare enum JobState {
Pending = "Pending",
Running = "Running",
Stopping = "Stopping",
Terminating = "Terminating",
Faulted = "Faulted",
Successful = "Successful",
Stopped = "Stopped",
Suspended = "Suspended",
Resumed = "Resumed"
}
interface BaseOptions {
expand?: string;
select?: string;
}
/**
* Common request options interface used across services for querying data
*/
interface RequestOptions extends BaseOptions {
filter?: string;
orderby?: string;
}
/**
* Service for managing UiPath Maestro Process instances
*
* Maestro process instances are the running instances of Maestro processes. [UiPath Maestro Process Instances Guide](https://docs.uipath.com/maestro/automation-cloud/latest/user-guide/all-instances-view)
*/
interface ProcessInstancesServiceModel {
/**
* Get all process instances with optional filtering and pagination
*
* The method returns either:
* - A NonPaginatedResponse with items array (when no pagination parameters are provided)
* - A PaginatedResponse with navigation cursors (when any pagination parameter is provided)
*
* @param options Query parameters for filtering instances and pagination
* @returns Promise resolving to either an array of process instances NonPaginatedResponse<ProcessInstanceGetResponse> or a PaginatedResponse<ProcessInstanceGetResponse> when pagination options are used.
* {@link ProcessInstanceGetResponse}
* @example
* ```typescript
* // Get all instances (non-paginated)
* const instances = await sdk.maestro.processes.instances.getAll();
*
* // Cancel faulted instances using methods directly on instances
* for (const instance of instances.items) {
* if (instance.latestRunStatus === 'Faulted') {
* await instance.cancel({ comment: 'Cancelling faulted instance' });
* }
* }
*
* // With filtering
* const instances = await sdk.maestro.processes.instances.getAll({
* processKey: 'MyProcess'
* });
*
* // First page with pagination
* const page1 = await sdk.maestro.processes.instances.getAll({ pageSize: 10 });
*
* // Navigate using cursor
* if (page1.hasNextPage) {
* const page2 = await sdk.maestro.processes.instances.getAll({ cursor: page1.nextCursor });
* }
* ```
*/
getAll<T extends ProcessInstanceGetAllWithPaginationOptions = ProcessInstanceGetAllWithPaginationOptions>(options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<ProcessInstanceGetResponse> : NonPaginatedResponse<ProcessInstanceGetResponse>>;
/**
* Get a process instance by ID with operation methods (cancel, pause, resume)
* @param id The ID of the instance to retrieve
* @param folderKey The folder key for authorization
* @returns Promise resolving to a process instance
* {@link ProcessInstanceGetResponse}
* @example
* ```typescript
* // Get a specific process instance
* const instance = await sdk.maestro.processes.instances.getById(
* <instanceId>,
* <folderKey>
* );
*
* // Access instance properties
* console.log(`Status: ${instance.latestRunStatus}`);
*
* ```
*/
getById(id: string, folderKey: string): Promise<ProcessInstanceGetResponse>;
/**
* Get execution history (spans) for a process instance
* @param instanceId The ID of the instance to get history for
* @returns Promise resolving to execution history
* {@link ProcessInstanceExecutionHistoryResponse}
* @example
* ```typescript
* // Get execution history for a process instance
* const history = await sdk.maestro.processes.instances.getExecutionHistory(
* <instanceId>
* );
*
* // Analyze execution timeline
* history.forEach(span => {
* console.log(`Activity: ${span.name}`);
* console.log(`Start: ${span.startTime}`);
* console.log(`Duration: ${span.duration}ms`);
* });
*
* ```
*/
getExecutionHistory(instanceId: string): Promise<ProcessInstanceExecutionHistoryResponse[]>;
/**
* Get BPMN XML file for a process instance
* @param instanceId The ID of the instance to get BPMN for
* @param folderKey The folder key for authorization
* @returns Promise resolving to BPMN XML file
* {@link BpmnXmlString}
* @example
* ```typescript
* // Get BPMN XML for a process instance
* const bpmnXml = await sdk.maestro.processes.instances.getBpmn(
* <instanceId>,
* <folderKey>
* );
*
* // Render BPMN diagram in frontend using bpmn-js
* import BpmnViewer from 'bpmn-js/lib/Viewer';
*
* const viewer = new BpmnViewer({
* container: '#bpmn-diagram'
* });
*
* await viewer.importXML(bpmnXml);
*
* // Zoom to fit the diagram
* viewer.get('canvas').zoom('fit-viewport');
* ```
*/
getBpmn(instanceId: string, folderKey: string): Promise<BpmnXmlString>;
/**
* Cancel a process instance
* @param instanceId The ID of the instance to cancel
* @param folderKey The folder key for authorization
* @param options Optional cancellation options with comment
* @returns Promise resolving to operation result with instance data
* @example
* ```typescript
* // Cancel a process instance
* const result = await sdk.maestro.processes.instances.cancel(
* <instanceId>,
* <folderKey>
* );
*
* or
*
* const instance = await sdk.maestro.processes.instances.getById(
* <instanceId>,
* <folderKey>
* );
* const result = await instance.cancel();
*
* console.log(`Cancelled: ${result.success}`);
*
* // Cancel with a comment
* const result = await instance.cancel({
* comment: 'Cancelling due to invalid input data'
* });
*
* if (result.success) {
* console.log(`Instance ${result.data.instanceId} status: ${result.data.status}`);
* }
* ```
*/
cancel(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise<OperationResponse<ProcessInstanceOperationResponse>>;
/**
* Pause a process instance
* @param instanceId The ID of the instance to pause
* @param folderKey The folder key for authorization
* @param options Optional pause options with comment
* @returns Promise resolving to operation result with instance data
*/
pause(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise<OperationResponse<ProcessInstanceOperationResponse>>;
/**
* Resume a process instance
* @param instanceId The ID of the instance to resume
* @param folderKey The folder key for authorization
* @param options Optional resume options with comment
* @returns Promise resolving to operation result with instance data
*/
resume(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise<OperationResponse<ProcessInstanceOperationResponse>>;
/**
* Get global variables for a process instance
*
* @param instanceId The ID of the instance to get variables for
* @param folderKey The folder key for authorization
* @param options Optional options including parentElementId to filter by parent element
* @returns Promise resolving to