import type { AutotaskQueryOptions, AutotaskClientConfig, // Added for SDK pagination SdkProgressData, // Restored SdkClientPagedResponse } from "./types/index.js"; import type { AllAutotaskEntityNames, AutotaskEntityTypeMap } from "./autotask-types/index.js"; import { LogLevel } from "./types/logger.js"; import type { ProcessedFieldDetailedInfo, CompactFieldInfo } from "./types/fields.js"; /** * Primary client for interacting with the Autotask API. * * This client provides a high-level interface for querying Autotask entities with features including: * - **Automatic pagination**: Handle large result sets transparently * - **Rate limiting**: Built-in respect for API rate limits with configurable strategies * - **Relationship embedding**: Automatically fetch and embed related entities * - **Robust error handling**: Comprehensive retry logic with exponential backoff * - **Structured logging**: Configurable logging levels for debugging and monitoring * * @example * ```typescript * const client = new AutotaskClient({ * credentials: { * username: 'api@company.com', * secret: 'your-secret-key' * }, * zoneInfo: { baseUrl: 'https://webservices5.autotask.net' } * }); * * // Query entities with automatic pagination * const companies = await client.queryAllEntities('Companies', { * filter: [{ field: 'isActive', op: 'eq', value: true }], * include: [{ path: 'primaryContact', select: ['firstName', 'lastName'] }] * }); * * // Manual pagination for large datasets * const firstPage = await client.queryEntities('Tickets', { * sdkPageSize: 50, * includeTotalCount: true * }); * ``` */ export declare class AutotaskClient { private clientConfig; private finalApiBaseUrl; private rateLimitManager?; private retryConfig; private logger; private currentLogLevel; private clientLogger; private apiWrapper; /** * Relationship configurations for all supported entities. * Used for automatic relationship embedding when include clauses are specified. */ private readonly relationshipConfigs; /** * Creates a new AutotaskClient instance. * * The constructor handles comprehensive configuration processing including: * - Credential validation and formatting * - API endpoint construction and validation * - Rate limiting strategy initialization * - Retry policy configuration * - Logger setup with appropriate levels * * @param config - Client configuration including credentials, endpoints, and behavior options * @throws {AutotaskClientError} When configuration is invalid or incomplete */ constructor(config: AutotaskClientConfig); private _logDebug; private _logInfo; private _logWarn; private _logError; /** * Core HTTP request method with comprehensive error handling and retry logic. * * This method implements the following reliability patterns: * - **Proactive rate limiting**: Waits for rate limit windows before making requests * - **Request timeout handling**: Configurable timeouts with proper abort signal usage * - **Exponential backoff**: Intelligent retry delays for transient failures * - **Error categorization**: Maps various failure types to appropriate error classes * * @param method - HTTP method (GET, POST, PUT, PATCH, DELETE) * @param entityPath - API endpoint path (relative or absolute URL) * @param payload - Request body for POST/PUT requests * @param rateLimitIdentifier - Unique identifier for rate limit tracking per entity/operation * @returns Promise resolving to the parsed response data * @throws {TimeoutError} When request exceeds configured timeout * @throws {RateLimitError} When rate limits are exceeded and retries exhausted * @throws {NetworkError} For network-related failures * @throws {AutotaskApiError} For API-specific errors from Autotask */ private request; /** * Executes paginated API queries with entity-specific rate limiting. * * This method handles the Autotask API's pagination format and provides * entity-specific rate limiting for optimal performance across different * entity types which may have different rate limit characteristics. * * @param entityNameForRateLimit - Entity name for rate limit bucket identification * @param targetApiUrl - Complete API endpoint URL for the query * @param queryBody - Query parameters including filters and field selection * @param rateLimitIdSuffix - Additional identifier for rate limit categorization * @returns Promise resolving to paginated API response */ private _executeApiPageQuery; private _parseAutotaskApiErrorResponse; private _buildFinalApiBaseUrl; private _buildRequestUrl; private _getDefaultHeaders; private _calculateRetryDelayMs; private _handleRequestErrorAndRetry; private _handleProactiveRateLimiting; /** * Fetches and embeds related entities based on include clauses. * * This method implements automatic relationship resolution by: * 1. **Extracting foreign keys** from primary entities * 2. **Bulk fetching** related entities to minimize API calls * 3. **Mapping relationships** back to primary entities * 4. **Handling missing relationships** gracefully with error accumulation * * The relationship embedding supports both to-one and to-many relationships * as defined in the relationship configuration. Foreign key validation * ensures data integrity while providing detailed error reporting. * * @param primaryEntityName - Name of the primary entity type * @param items - Array of primary entities to augment with relationships * @param includeClauses - Relationship paths and field selections to embed * @param accumulatedErrors - Error collection for non-fatal relationship issues * @returns Promise resolving to augmented entities with embedded relationships */ private _fetchAndEmbedRelationships; /** * Queries entities with support for pagination, filtering, and relationship embedding. * * This method provides the core querying functionality with support for: * - **Manual pagination** using continuation tokens * - **Automatic relationship embedding** via include clauses * - **Total count fetching** for pagination UI components * - **Comprehensive error handling** with detailed error accumulation * * The pagination system uses continuation tokens that encode both API pagination * state and SDK-level page numbering, allowing for flexible navigation through * large result sets while maintaining consistency with the Autotask API's * pagination model. * * @example * ```typescript * // Basic query with filtering * const result = await client.queryEntities('Companies', { * filter: [{ field: 'isActive', op: 'eq', value: true }], * fields: ['id', 'companyName', 'city'], * sdkPageSize: 25 * }); * * // Query with relationship embedding * const companiesWithContacts = await client.queryEntities('Companies', { * include: [{ * path: 'primaryContact', * select: ['firstName', 'lastName', 'emailAddress'] * }], * includeTotalCount: true * }); * * // Navigate to next page * if (result.hasNextPage && result.continuationToken) { * const nextPage = await client.queryEntities('Companies', { * continuationToken: result.continuationToken * }); * } * ``` * * @param entityName - Name of the Autotask entity to query * @param options - Query configuration including filters, pagination, and relationships * @returns Promise resolving to paginated response with items and navigation metadata * @throws {AutotaskClientError} For invalid continuation tokens or configuration errors * @throws {AutotaskApiError} For API-specific errors from Autotask */ queryEntities(entityName: E, options: AutotaskQueryOptions): Promise>; /** * Queries all entities of a specified type, automatically handling pagination. * * This convenience method abstracts away pagination complexity by automatically * fetching all pages and combining results. It's ideal for: * - **Data export operations** where you need complete datasets * - **Relationship lookups** where you need to resolve all related entities * - **Analytics and reporting** where partial data would be problematic * * The method provides optional progress reporting for long-running operations * and can pre-fetch total counts for accurate progress calculation. * * **Performance Considerations:** * - Use with caution for entities with very large datasets (>10K records) * - Consider using `queryEntities` with manual pagination for better memory management * - Monitor API rate limits when fetching large datasets * * @example * ```typescript * // Simple usage - fetch all active companies * const allCompanies = await client.queryAllEntities('Companies', { * filter: [{ field: 'isActive', op: 'eq', value: true }] * }); * * // With progress reporting for large datasets * const allTickets = await client.queryAllEntities( * 'Tickets', * { * filter: [{ field: 'status', op: 'in', value: [1, 5, 8] }], * include: [{ path: 'assignedResource', select: ['firstName', 'lastName'] }] * }, * (progress) => { * console.log(`Fetched ${progress.totalItemsFetchedSoFar} tickets...`); * if (progress.totalKnownItems) { * const percent = (progress.totalItemsFetchedSoFar / progress.totalKnownItems) * 100; * console.log(`Progress: ${percent.toFixed(1)}%`); * } * }, * { fetchTotalCountForProgress: true } * ); * ``` * * @param entityName - Name of the Autotask entity to query * @param initialQueryOptions - Query configuration (filters, includes, etc.) * @param onProgress - Optional callback for progress reporting during long operations * @param progressOptions - Configuration for progress reporting behavior * @returns Promise resolving to array of all matching entities * @throws {AutotaskApiError} For API-specific errors from Autotask * @throws {AutotaskClientError} For client configuration or network errors */ queryAllEntities(entityName: E, initialQueryOptions?: AutotaskQueryOptions, onProgress?: (progressData: SdkProgressData) => void, progressOptions?: { fetchTotalCountForProgress?: boolean; }): Promise; /** * Retrieves detailed field information for a given Autotask entity from the * `/entityInformation/fields` endpoint. * * By default (`compact: true`, since v0.13.0) returns a slim, LLM-friendly * shape: picklists are collapsed to `picklistMap` / `picklistMapByParent` * maps with the raw `picklistValues[]` array dropped, and noisy metadata * (`isUserDefinedField`, `isActive`, `isSystem`, `sortOrder`, …) is omitted. * * Pass `{ compact: false }` to get the legacy verbose shape that preserves * every key the Autotask API returned. * * @param entityName The name of the Autotask entity (e.g., "Tickets", "Contacts"). * Case-sensitive and should match Autotask's entity names. * @param requestedFieldNames Optional array of specific field names to retrieve. * If omitted or empty, all fields are returned. * @param options Shape control. `{ compact: true }` (default) returns * `CompactFieldInfo[]`. `{ compact: false }` returns the * legacy `ProcessedFieldDetailedInfo[]` shape. * @throws {AutotaskClientError} if `entityName` is not provided. * @throws {AutotaskApiError} if the API call fails or returns an unexpected response. */ getEntityFieldsDetailed(entityName: string, requestedFieldNames?: string[], options?: { compact?: true; }): Promise; getEntityFieldsDetailed(entityName: string, requestedFieldNames: string[] | undefined, options: { compact: false; }): Promise; /** * Creates a new entity in Autotask. * * This method provides comprehensive entity creation with: * - **Automatic validation** of required fields * - **Rate limiting** specific to create operations * - **Error handling** with detailed error reporting * - **Type safety** with entity-specific types * * @example * ```typescript * // Create a new company * const newCompany = await client.createEntity('Companies', { * companyName: 'New Company', * companyType: 1, * phone: '555-1234' * }); * * // Create a new contact * const newContact = await client.createEntity('Contacts', { * firstName: 'John', * lastName: 'Doe', * companyID: 123, * emailAddress: 'john.doe@example.com' * }); * ``` * * @param entityName - Name of the Autotask entity to create * @param entityData - Entity data to create (without id field) * @returns Promise resolving to the created entity with assigned ID * @throws {AutotaskApiError} For API-specific validation or creation errors * @throws {AutotaskClientError} For client configuration or network errors */ createEntity(entityName: E, entityData: Omit): Promise; /** * Updates an existing entity in Autotask. * * This method provides comprehensive entity updating with: * - **Partial updates** - only specified fields are updated * - **Rate limiting** specific to update operations * - **Error handling** with detailed error reporting * - **Type safety** with entity-specific types * * @example * ```typescript * // Update a company's phone number * const updatedCompany = await client.updateEntity('Companies', 123, { * phone: '555-9999' * }); * * // Update multiple fields on a contact * const updatedContact = await client.updateEntity('Contacts', 456, { * emailAddress: 'newemail@example.com', * title: 'Senior Manager' * }); * ``` * * @param entityName - Name of the Autotask entity to update * @param entityId - ID of the entity to update * @param entityData - Partial entity data to update * @returns Promise resolving to the updated entity * @throws {AutotaskApiError} For API-specific validation or update errors * @throws {AutotaskClientError} For client configuration or network errors */ updateEntity(entityName: E, entityId: number, entityData: Partial>): Promise; /** * Deletes an entity from Autotask. * * This method provides comprehensive entity deletion with: * - **Safety checks** to prevent accidental deletions * - **Rate limiting** specific to delete operations * - **Error handling** with detailed error reporting * - **Confirmation** of successful deletion * * @example * ```typescript * // Delete a company * await client.deleteEntity('Companies', 123); * * // Delete a contact * await client.deleteEntity('Contacts', 456); * ``` * * @param entityName - Name of the Autotask entity to delete * @param entityId - ID of the entity to delete * @returns Promise resolving when deletion is complete * @throws {AutotaskApiError} For API-specific deletion errors * @throws {AutotaskClientError} For client configuration or network errors */ deleteEntity(entityName: E, entityId: number): Promise; /** * Gets the current effective log level for this client instance. * * @returns The current log level setting */ getLogLevel(): LogLevel; private _encodeContinuationToken; private _decodeContinuationToken; /** * Internal method for direct API request execution. * Primarily used for testing and specialized use cases. * * @param method - HTTP method * @param url - Target URL * @param body - Request body * @param signal - Optional abort signal for request cancellation * @returns Promise resolving to response data */ private _executeApiRequest; } //# sourceMappingURL=client.d.ts.map