UNPKG

@iota-big3/sdk-gateway

Version:

Universal API Gateway with protocol translation, intelligent routing, rate limiting, health checking, and caching

583 lines 16.3 kB
/** * Enhanced Type Definitions for SDK * Following Phase 2g: Test-driven, incremental, backward-compatible enhancements * These types eliminate common 'any' and 'unknown' usage patterns * * @module enhanced-types * @description Provides type-safe alternatives to common JavaScript patterns, * reducing ESLint errors and improving IntelliSense across the monorepo. */ import type { AnyFunction, AuthUser, JsonValue } from './common'; /** * Type-safe event handler function * * @template TEvent - The type of event object * @param event - The event object passed to the handler * @returns void or Promise<void> for async handlers * * @example * ```typescript * // Instead of: (...args: any[]) => void * const handler: EventHandler<ClickEvent> = (event) => { * // Process click coordinates * processClick(event.x, event.y); * }; * ``` */ export type EventHandler<TEvent = unknown> = (event: TEvent) => void | Promise<void>; /** * Type-safe event handler with multiple arguments * * @template TArgs - Tuple type of arguments * @param args - Arguments passed to the handler * @returns void or Promise<void> for async handlers * * @example * ```typescript * // Instead of: (...args: any[]) => void * const handler: MultiArgEventHandler<[string, number, boolean]> = (name, age, active) => { * // Process user data * updateUserProfile(name, age, active); * }; * ``` */ export type MultiArgEventHandler<TArgs extends readonly unknown[] = readonly unknown[]> = (...args: TArgs) => void | Promise<void>; /** * Type-safe callback function following Node.js convention * * @template TResult - The type of successful result * @template TError - The type of error (defaults to Error) * @param error - Error object if operation failed, null otherwise * @param result - Result of the operation if successful * * @example * ```typescript * // Instead of: (err: any, result?: any) => void * const callback: Callback<User> = (error, user) => { * if (error) { * handleError(error); * } else { * processUser(user); * } * }; * ``` */ export type Callback<TResult = unknown, TError = Error> = (error: TError | null, result?: TResult) => void; /** * Type-safe middleware function for request processing pipelines * * @template TContext - The context object passed through middleware * @param context - Request/application context * @param next - Function to call the next middleware * @returns void or Promise<void> for async middleware * * @example * ```typescript * // Instead of: (req: any, res: any, next: any) => void * const authMiddleware: MiddlewareFunction<AppContext> = async (context, next) => { * if (!context.user) { * throw new Error('Unauthorized'); * } * await next(); * }; * ``` */ export type MiddlewareFunction<TContext = unknown> = (context: TContext, next: () => Promise<void>) => void | Promise<void>; /** * Type-safe reducer function for state management * * @template TState - The type of state object * @template TAction - The type of action object * @param state - Current state * @param action - Action to process * @returns New state (immutable update) * * @example * ```typescript * // Instead of: (state: any, action: any) => any * const reducer: Reducer<AppState, AppAction> = (state, action) => { * switch (action.type) { * case 'INCREMENT': * return { ...state, count: state.count + 1 }; * default: * return state; * } * }; * ``` */ export type Reducer<TState, TAction> = (state: TState, action: TAction) => TState; /** * Type-safe predicate function for filtering and validation * * @template T - The type being tested * @param value - Value to test * @returns true if value passes the predicate test * * @example * ```typescript * // Instead of: (value: any) => boolean * const isAdult: Predicate<Person> = (person) => person.age >= 18; * const adults = people.filter(isAdult); * ``` */ export type Predicate<T> = (value: T) => boolean; /** * Type-safe comparator function for sorting * * @template T - The type being compared * @param a - First value to compare * @param b - Second value to compare * @returns Negative if a < b, positive if a > b, zero if equal * * @example * ```typescript * // Instead of: (a: any, b: any) => number * const byAge: Comparator<Person> = (a, b) => a.age - b.age; * people.sort(byAge); * ``` */ export type Comparator<T> = (a: T, b: T) => number; /** * Type-safe mapper function for transformations * * @template TInput - Input type * @template TOutput - Output type * @param value - Value to transform * @returns Transformed value * * @example * ```typescript * // Instead of: (value: any) => any * const getName: Mapper<User, string> = (user) => user.name; * const names = users.map(getName); * ``` */ export type Mapper<TInput, TOutput> = (value: TInput) => TOutput; /** * Type-safe async mapper function * * @template TInput - Input type * @template TOutput - Output type * @param value - Value to transform * @returns Promise of transformed value * * @example * ```typescript * // Instead of: async (value: any) => any * const fetchProfile: AsyncMapper<string, UserProfile> = async (userId) => { * const response = await fetch(`/api/users/${userId}`); * return response.json(); * }; * ``` */ export type AsyncMapper<TInput, TOutput> = (value: TInput) => Promise<TOutput>; /** * Type-safe configuration object * * @template T - Configuration shape * * @example * ```typescript * // Instead of: Record<string, any> * interface DatabaseConfig { * host: string; * port: number; * ssl: boolean; * } * const config: ConfigObject<DatabaseConfig> = { * host: 'localhost', * port: 5432, * ssl: true * }; * ``` */ export type ConfigObject<T extends Record<string, unknown> = Record<string, unknown>> = { [K in keyof T]: T[K]; }; /** * Type-safe metadata object with known and unknown keys * * @template TKnownKeys - Known metadata properties * * @example * ```typescript * // Instead of: Record<string, any> * interface KnownMeta { * version: string; * timestamp: number; * } * const metadata: Metadata<KnownMeta> = { * version: '1.0.0', * timestamp: Date.now(), * // Additional unknown keys are JSON-safe * custom: 'value', * tags: ['production', 'v1'] * }; * ``` */ export type Metadata<TKnownKeys extends Record<string, unknown> = Record<string, never>> = TKnownKeys & Record<string, JsonValue>; /** * Type-safe options object with partial known properties * * @template T - Options shape * * @example * ```typescript * // Instead of: Record<string, any> * interface RequestOptions { * timeout: number; * retries: number; * } * const options: Options<RequestOptions> = { * timeout: 5000, * // Can include additional unknown options * custom: true * }; * ``` */ export type Options<T extends Record<string, unknown> = Record<string, unknown>> = Partial<T> & Record<string, unknown>; /** * Type-safe context object for request/operation scoping * * @template TKnown - Known context properties * * @example * ```typescript * // Instead of: Record<string, any> * interface RequestContext { * apiVersion: string; * feature: string; * } * const context: Context<RequestContext> = { * user: { id: '123', email: 'user@example.com' }, * correlationId: 'abc-123', * metadata: { * apiVersion: 'v2', * feature: 'user-profile' * } * }; * ``` */ export interface Context<TKnown extends Record<string, unknown> = Record<string, never>> { user?: AuthUser; correlationId?: string; requestId?: string; timestamp?: number; metadata?: Metadata<TKnown>; } /** * Type-safe map structure with specific key and value types * * @template K - Key type (string, number, or symbol) * @template V - Value type * * @example * ```typescript * // Instead of: Record<string, any> * type UserMap = TypedMap<string, User>; * const users: UserMap = { * 'user-123': { id: 'user-123', name: 'John' }, * 'user-456': { id: 'user-456', name: 'Jane' } * }; * ``` */ export type TypedMap<K extends string | number | symbol, V> = { [key in K]: V; }; /** * Type-safe enum map ensuring all enum values are present * * @template TEnum - String enum type * @template TValue - Value type for each enum key * * @example * ```typescript * // Instead of: Record<string, any> * enum Status { * Active = 'active', * Inactive = 'inactive', * Pending = 'pending' * } * const statusMessages: EnumMap<Status, string> = { * [Status.Active]: 'User is active', * [Status.Inactive]: 'User is inactive', * [Status.Pending]: 'User activation pending' * }; * ``` */ export type EnumMap<TEnum extends string, TValue> = { [K in TEnum]: TValue; }; /** * Type-safe indexed collection * * @template TKey - Index key type (string or number) * @template TValue - Value type * * @example * ```typescript * // Instead of: { [key: string]: any } * type UserById = IndexedCollection<number, User>; * const usersById: UserById = { * 1: { id: 1, name: 'Alice' }, * 2: { id: 2, name: 'Bob' } * }; * ``` */ export type IndexedCollection<TKey extends string | number, TValue> = { [K in TKey]: TValue; }; /** * Type-safe error with typed cause and additional metadata * * @template TCause - Type of the error cause * * @example * ```typescript * // Instead of: Error with any cause * interface NetworkCause { * endpoint: string; * timeout: number; * } * * const error: TypedError<NetworkCause> = { * name: 'RequestError', * message: 'API request failed', * code: 'NETWORK_ERROR', * statusCode: 500, * cause: { * endpoint: '/api/users', * timeout: 5000 * } * }; * ``` */ export interface TypedError<TCause = unknown> extends Error { cause?: TCause; code?: string; statusCode?: number; details?: Record<string, JsonValue>; } /** * Type-safe validation error with field-level information * * @example * ```typescript * const error: ValidationError = { * name: 'ValidationError', * message: 'Email format is invalid', * field: 'email', * value: 'not-an-email', * constraint: 'email-format', * code: 'INVALID_EMAIL' * }; * ``` */ export interface ValidationError extends TypedError { field: string; value: unknown; constraint: string; message: string; } /** * Type-safe aggregate error for collecting multiple errors * * @template TError - Type of collected errors * * @example * ```typescript * const errors: ValidationError[] = validateForm(data); * if (errors.length > 0) { * const aggregateError: AggregateError<ValidationError> = { * name: 'AggregateError', * message: 'Multiple validation errors occurred', * code: 'VALIDATION_FAILED', * errors: errors * }; * throw aggregateError; * } * ``` */ export interface AggregateError<TError = TypedError> extends TypedError { errors: TError[]; } /** * Type-safe promise that can be resolved externally */ export interface DeferredPromise<T> { promise: Promise<T>; resolve: (value: T) => void; reject: (reason?: unknown) => void; } /** * Type-safe result type (similar to Result<T, E> in Rust) */ export type Result<TSuccess, TError = Error> = { success: true; value: TSuccess; } | { success: false; error: TError; }; /** * Type-safe option type (similar to Option<T> in Rust) */ export type Option<T> = { some: true; value: T; } | { some: false; }; /** * Extract promise type recursively * Better than UnwrapPromise for nested promises */ export type DeepUnwrapPromise<T> = T extends Promise<infer U> ? DeepUnwrapPromise<U> : T; /** * Make specific keys required */ export type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>; /** * Make specific keys optional */ export type OptionalKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; /** * Exclude null and undefined from type */ export type NonNullable<T> = T extends null | undefined ? never : T; /** * Extract function arguments as tuple */ export type FunctionArgs<T extends AnyFunction> = T extends (...args: infer A) => unknown ? A : never; /** * Extract function return type */ export type FunctionReturn<T extends AnyFunction> = T extends (...args: unknown[]) => infer R ? R : never; /** * Create branded type for additional type safety */ export type Brand<T, TBrand> = T & { __brand: TBrand; }; /** * Create opaque type (nominal typing) */ export type Opaque<T, TToken> = T & { __opaque: TToken; }; /** * Education-specific user type with FERPA/COPPA compliance support * * @extends AuthUser * * @property userType - Role within the education system * @property schoolId - Optional identifier for the user's school * @property districtId - Optional identifier for the school district * @property gradeLevel - Grade level (1-12) for students * @property subjects - Subjects taught (teachers) or enrolled in (students) * * @example * ```typescript * // Teacher example * const teacher: EducationUser = { * id: 'teacher-123', * email: 'jsmith@school.edu', * name: 'Jane Smith', * userType: 'teacher', * schoolId: 'school-456', * subjects: ['Mathematics', 'Physics'], * roles: ['teacher', 'department-head'] * }; * * // Student example (COPPA compliance for age < 13) * const student: EducationUser = { * id: 'student-789', * name: 'John Doe', * userType: 'student', * gradeLevel: 7, * schoolId: 'school-456', * metadata: { * parentalConsent: true, * coppaVerified: true * } * }; * ``` */ export interface EducationUser extends AuthUser { userType: 'student' | 'teacher' | 'parent' | 'administrator'; schoolId?: string; districtId?: string; gradeLevel?: number; subjects?: string[]; } /** * Healthcare-specific user type with HIPAA compliance support * * @extends AuthUser * * @property userType - Role within the healthcare system * @property facilityId - Healthcare facility identifier * @property departmentId - Department within the facility * @property specialties - Medical specialties for providers * @property npi - National Provider Identifier for billing * * @example * ```typescript * const provider: HealthcareUser = { * id: 'doc-123', * email: 'dr.jones@hospital.com', * name: 'Dr. Sarah Jones', * userType: 'provider', * facilityId: 'hospital-789', * departmentId: 'cardiology', * specialties: ['Cardiology', 'Internal Medicine'], * npi: '1234567890' * }; * ``` */ export interface HealthcareUser extends AuthUser { userType: 'patient' | 'provider' | 'staff' | 'administrator'; facilityId?: string; departmentId?: string; specialties?: string[]; npi?: string; } /** * Type-safe permission checker */ export type PermissionChecker<TResource = string, TAction = string> = (user: AuthUser, resource: TResource, action: TAction) => boolean | Promise<boolean>; /** * Type-safe audit logger */ export interface AuditLogger<TAction = string, TResource = unknown> { log(action: TAction, resource: TResource, user: AuthUser, metadata?: Metadata): Promise<void>; } /** * Type guard function type */ export type TypeGuard<T> = (value: unknown) => value is T; /** * Async type guard function type */ export type AsyncTypeGuard<_T> = (value: unknown) => Promise<boolean>; /** * Type assertion function type */ export type TypeAssertion<T> = (value: unknown) => asserts value is T; /** * Create a typed event emitter interface */ export interface TypedEventEmitter<TEvents extends Record<string, unknown[]>> { on<K extends keyof TEvents>(event: K, handler: (...args: TEvents[K]) => void): this; off<K extends keyof TEvents>(event: K, handler: (...args: TEvents[K]) => void): this; emit<K extends keyof TEvents>(event: K, ...args: TEvents[K]): boolean; once<K extends keyof TEvents>(event: K, handler: (...args: TEvents[K]) => void): this; } /** * Create a typed observable interface */ export interface TypedObservable<T> { subscribe(observer: (value: T) => void): () => void; next(value: T): void; } //# sourceMappingURL=enhanced-types.d.ts.map