UNPKG

@simpleapps-com/augur-api

Version:

TypeScript client library for Augur microservices API endpoints

457 lines 18.5 kB
import { HTTPClient } from './client'; import { z } from 'zod'; /** * Interface for discovery metadata that AI agents can use to navigate services */ export interface DiscoveryEndpoint { /** Complete API path (e.g., api.joomla.users.list) */ fullPath: string; /** Service name (e.g., joomla, nexus, items) */ service: string; /** Business domain (e.g., user-management, content-management) */ domain: string; /** HTTP method (GET, POST, PUT, DELETE) */ method: string; /** Endpoint URL path */ path: string; /** Description of what this endpoint does */ description: string; /** Array of search terms for AI navigation */ searchTerms: string[]; /** Related endpoints across services */ relatedEndpoints: string[]; /** Common usage patterns in natural language */ commonPatterns: string[]; /** Reference to data-only method alternative */ dataMethod?: string; /** Whether this endpoint is discoverable by AI agents */ discoverable: boolean; } /** * Interface for service discovery metadata */ export interface ServiceDiscoveryMetadata { /** Service name */ serviceName: string; /** Service description */ description: string; /** Base URL for the service */ baseUrl: string; /** Array of discoverable endpoints */ endpoints: DiscoveryEndpoint[]; } /** * HTTP method types for API operations */ export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'; /** * Configuration for API endpoint operations */ export interface EndpointConfig<TParams = unknown, TResponse = unknown> { /** HTTP method for the request */ method: HTTPMethod; /** Endpoint path (will be prefixed with baseUrl) */ path: string; /** Zod schema for validating request parameters */ paramsSchema?: z.ZodSchema<TParams>; /** Zod schema for validating response data */ responseSchema: z.ZodSchema<TResponse>; /** Whether this endpoint requires authentication (default: true) */ requiresAuth?: boolean; } /** * Standard pagination parameters with better type constraints */ export interface PaginationParams { /** Number of items to return (1-1000) */ limit?: number; /** Starting offset for pagination (>= 0) */ offset?: number; /** Sort ordering in format: 'field|ASC' or 'field|DESC' */ orderBy?: string; } /** * Standard search parameters extending pagination */ export interface SearchParams extends PaginationParams { /** Search query string */ q?: string; } /** * Edge caching parameters for Cloudflare integration */ export interface CacheParams { /** Cache duration in hours (1, 2, 3, 4, 5, 8) - accepts numbers or string representations for HTTP compatibility */ edgeCache?: 1 | 2 | 3 | 4 | 5 | 8 | '1' | '2' | '3' | '4' | '5' | '8'; } /** * Standard GET request parameters combining pagination, search, and caching */ export interface StandardGetParams extends SearchParams, CacheParams { } /** * Standard API response structure - REQUIRED for all services (8-field format) * This is the ONLY acceptable response format for all APIs */ export interface BaseResponse<T> { /** Number of items in current response */ count: number; /** Response data of type T */ data: T; /** Response message */ message: string; /** Additional options for the response */ options: unknown[] | Record<string, unknown>; /** Parameters used in the request */ params: unknown[] | Record<string, unknown>; /** HTTP status code */ status: number; /** Total items in dataset */ total: number; /** Total results available */ totalResults: number; } /** * Result of a successful API operation */ export interface OperationResult<T> { data: T; status: number; headers?: Record<string, string>; } /** * Abstract base class for all service clients * * Provides standardized error handling, validation, and request processing * to eliminate boilerplate code across service implementations. * * @example * ```typescript * class MyServiceClient extends BaseServiceClient { * constructor(http: HTTPClient, baseUrl?: string) { * super('myservice', http, baseUrl || 'https://myservice.augur-api.com'); * } * * // Simple method using executeRequest * async getUser(id: number) { * return this.executeRequest({ * method: 'GET', * path: `/users/${id}`, * responseSchema: UserResponseSchema * }); * } * * // Method with parameters * async listUsers(params?: UserListParams) { * return this.executeRequest({ * method: 'GET', * path: '/users', * paramsSchema: UserListParamsSchema, * responseSchema: UserListResponseSchema * }, params); * } * } * ``` */ export declare abstract class BaseServiceClient { protected readonly serviceName: string; protected readonly http: HTTPClient; protected readonly baseUrl: string; /** * Create a new service client instance * @param serviceName Name of the service (used for error reporting) * @param http Configured HTTPClient instance * @param baseUrl Base URL for the service API */ constructor(serviceName: string, http: HTTPClient, baseUrl: string); /** * Execute a standardized API request with automatic validation and error handling * * This method handles all the common patterns: * - Parameter validation with Zod schemas * - HTTP request execution * - Response validation * - Consistent error handling and reporting * * @param config Endpoint configuration including method, path, and schemas * @param params Optional request parameters (query params for GET, body for POST/PUT) * @param pathParams Optional path parameters for URL substitution * @returns Promise resolving to the validated response data * @throws ValidationError When parameters or response validation fails * @throws AugurError For HTTP errors (handled by HTTPClient interceptors) */ protected executeRequest<TParams = unknown, TResponse = unknown>(config: EndpointConfig<TParams, TResponse>, params?: TParams, pathParams?: Record<string, string | number>): Promise<TResponse>; /** * Validate request parameters using the provided schema */ private validateParameters; /** * Execute HTTP request based on the configured method */ private executeHttpRequest; /** * Create a detailed validation error with context information */ private createValidationError; /** * Create a standardized list method factory * * Generates a function that follows the standard list pattern with optional parameters, * pagination support, and consistent error handling. * * @param endpoint The API endpoint path * @param paramsSchema Zod schema for validating query parameters * @param responseSchema Zod schema for validating the response * @returns A function that executes the list operation */ protected createListMethod<TParams = StandardGetParams, TItem = unknown, TResponse extends BaseResponse<TItem[]> = BaseResponse<TItem[]>>(endpoint: string, paramsSchema: z.ZodSchema<TParams>, responseSchema: z.ZodSchema<TResponse>): (params?: TParams) => Promise<TResponse>; /** * Create a standardized get method factory * * Generates a function that retrieves a single item by ID with optional parameters. * * @param endpointTemplate The API endpoint template with parameter placeholders * @param responseSchema Zod schema for validating the response * @param paramsSchema Optional Zod schema for query parameters * @returns A function that executes the get operation */ protected createGetMethod<TParams = CacheParams, TItem = unknown, TResponse extends BaseResponse<TItem> = BaseResponse<TItem>>(endpointTemplate: string, responseSchema: z.ZodSchema<TResponse>, paramsSchema?: z.ZodSchema<TParams>): (id: string | number, params?: TParams) => Promise<TResponse>; /** * Create a standardized create method factory * * Generates a function that creates a new resource via POST request. * * @param endpoint The API endpoint path * @param requestSchema Zod schema for validating request data * @param responseSchema Zod schema for validating the response * @returns A function that executes the create operation */ protected createCreateMethod<TRequest, TResponse>(endpoint: string, requestSchema: z.ZodSchema<TRequest>, responseSchema: z.ZodSchema<TResponse>): (data: TRequest) => Promise<TResponse>; /** * Create a standardized update method factory * * Generates a function that updates an existing resource via PUT request. * * @param endpointTemplate The API endpoint template with parameter placeholders * @param requestSchema Zod schema for validating request data * @param responseSchema Zod schema for validating the response * @returns A function that executes the update operation */ protected createUpdateMethod<TRequest, TResponse>(endpointTemplate: string, requestSchema: z.ZodSchema<TRequest>, responseSchema: z.ZodSchema<TResponse>): (id: string | number, data: TRequest) => Promise<TResponse>; /** * Create a standardized delete method factory * * Generates a function that deletes a resource via DELETE request. * * @param endpointTemplate The API endpoint template with parameter placeholders * @param responseSchema Zod schema for validating the response * @returns A function that executes the delete operation */ protected createDeleteMethod<TResponse>(endpointTemplate: string, responseSchema: z.ZodSchema<TResponse>): (id: string | number) => Promise<TResponse>; /** * Create a health check method that follows the standard pattern * * @param responseSchema Zod schema for the health check response * @returns A function that executes the health check */ protected createHealthCheckMethod<TResponse>(responseSchema: z.ZodSchema<TResponse>): () => Promise<TResponse>; /** * Create a delete method that returns a boolean success indicator * * Common pattern for delete operations that don't return the deleted entity. * The method always returns true if the request succeeds (no error thrown). * * @param endpointTemplate The API endpoint template with parameter placeholders * @returns A function that executes the delete operation and returns true on success */ protected createDeleteBooleanMethod(endpointTemplate: string): (id: string | number) => Promise<boolean>; /** * Create a search method with required query parameter * * Enforces that a search query is provided and handles the common search pattern. * * @param endpoint The API endpoint path * @param paramsSchema Zod schema for validating search parameters (must include 'q') * @param responseSchema Zod schema for validating the response * @returns A function that executes the search operation */ protected createSearchMethod<TParams extends SearchParams, TResponse>(endpoint: string, paramsSchema: z.ZodSchema<TParams>, responseSchema: z.ZodSchema<TResponse>): (params: TParams) => Promise<TResponse>; /** * Create a method that returns the first item from an array response * * Common pattern for endpoints that return an array but we only need the first item. * * @param endpoint The API endpoint path * @param paramsSchema Zod schema for validating request parameters * @param itemSchema Zod schema for validating individual items in the array * @returns A function that executes the request and returns the first item or undefined */ protected createSingleItemMethod<TParams, TItem>(endpoint: string, paramsSchema: z.ZodSchema<TParams>, itemSchema: z.ZodSchema<TItem>): (params: TParams) => Promise<TItem | undefined>; /** * Create an action method for operations like enable/disable * * Common pattern for POST/PUT endpoints that perform actions on resources. * * @param endpointTemplate The API endpoint template with placeholders * @param method HTTP method (POST or PUT) * @param responseSchema Zod schema for validating the response * @param pathParams Additional path parameters beyond the id * @returns A function that executes the action */ protected createActionMethod<TResponse>(endpointTemplate: string, method: 'POST' | 'PUT', responseSchema: z.ZodSchema<TResponse>, pathParams?: Record<string, string>): (id: string | number) => Promise<TResponse>; /** * Create a void method that doesn't return meaningful data * * Common pattern for operations that succeed with empty or undefined responses. * * @param endpointTemplate The API endpoint template * @param method HTTP method * @returns A function that executes the operation */ protected createVoidMethod(endpointTemplate: string, method: HTTPMethod): (id?: string | number) => Promise<void>; /** * Helper to create a standard array response schema */ private createArrayResponseSchema; /** * Create a standardized document method for endpoints that return enhanced documentation * * Common pattern across services for endpoints like /content/{id}/doc, /users/{id}/doc, etc. * * @param endpointTemplate The API endpoint template with parameter placeholders * @param responseSchema Zod schema for validating the document response * @param paramsSchema Optional Zod schema for query parameters * @returns A function that executes the document retrieval operation */ protected createDocMethod<TParams, TResponse>(endpointTemplate: string, responseSchema: z.ZodSchema<TResponse>, paramsSchema?: z.ZodSchema<TParams>): (id: string | number, params?: TParams) => Promise<TResponse>; /** * Create a standardized ping method for service availability testing * * @param responseSchema Zod schema for the ping response (typically string or literal) * @returns A function that executes the ping operation */ protected createPingMethod<TResponse>(responseSchema: z.ZodSchema<TResponse>): () => Promise<TResponse>; /** * Build endpoint path with optional path parameter substitution * * @param pathTemplate Path template with {param} placeholders * @param pathParams Object containing parameter values * @returns Processed endpoint path * * @example * ```typescript * buildEndpointPath('/users/{id}', { id: '123' }) // returns '/users/123' * buildEndpointPath('/health-check') // returns '/health-check' * ``` */ private buildEndpointPath; /** * Create a debugging helper for troubleshooting validation errors * * @param config Endpoint configuration * @param params Parameters being validated * @returns Debug information object */ protected createDebugInfo<TParams>(config: EndpointConfig<TParams>, params?: TParams): { endpoint: string; method: string; hasParamSchema: boolean; providedParams: TParams | undefined; expectedSchema?: string; }; /** * Validate parameters and provide detailed error information for debugging * * @param schema Zod schema to validate against * @param params Parameters to validate * @param context Context information for error messages * @returns Validation result with detailed error information */ protected validateWithDebugInfo<T>(schema: z.ZodSchema<T>, params: unknown, context: string): { success: true; data: T; } | { success: false; errors: string[]; rawErrors: z.ZodError; }; /** * Extract parameter name from endpoint template * * @param endpointTemplate The endpoint template (e.g., '/bin-transfer/{binTransferHdrUid}') * @returns The parameter name (e.g., 'binTransferHdrUid') or null if no parameter found * * @example * ```typescript * extractParameterName('/bin-transfer/{binTransferHdrUid}') // returns 'binTransferHdrUid' * extractParameterName('/users/{id}') // returns 'id' * extractParameterName('/health-check') // returns null * ``` */ private extractParameterName; /** * Get discovery metadata for this service client * * This method extracts semantic JSDoc metadata from all methods in the service client * to enable AI agents to understand the service topology and navigate endpoints. * * @returns ServiceDiscoveryMetadata containing service info and endpoint metadata */ getDiscoveryMetadata(): ServiceDiscoveryMetadata; /** * Get all method names from the service client instance */ private getAllMethods; /** * Recursively walk prototype chain to collect methods */ private walkPrototypeChain; /** * Check if a property is a valid method to include in discovery */ private isValidMethod; /** * Extract semantic metadata from a method's JSDoc comments * * This method parses JSDoc comments to extract the semantic tags required * for AI agent discovery and navigation. */ private extractMethodMetadata; /** * Get method function from instance */ private getMethodFunction; /** * Extract JSDoc content from method source */ private extractJSDocContent; /** * Parse all semantic tags from JSDoc content */ private parseSemanticTags; /** * Check if required semantic tags are present */ private hasRequiredTags; /** * Extract description from JSDoc content */ private extractDescription; /** * Extract a single JSDoc tag value */ private extractJSDocTag; /** * Extract an array JSDoc tag value (e.g., @searchTerms ["term1", "term2"]) */ private extractJSDocArrayTag; /** * Infer HTTP method and path from method implementation */ private inferMethodDetails; /** * Get service description - can be overridden by subclasses */ protected getServiceDescription(): string; } //# sourceMappingURL=base-client.d.ts.map