{"version":3,"file":"type-safe-api-client.mjs","sources":["../../../src/lib/services/type-safe-api-client.ts"],"sourcesContent":["/**\n * @file Type-Safe API Client\n * @description Contract-first API client with Zod schema validation,\n * runtime type checking, and full type inference from endpoint definitions.\n * Designed for microservices plug-and-play integration.\n * @module @/lib/services/TypeSafeApiClient\n *\n * This module provides a fully type-safe API client that:\n * - Validates request parameters, query strings, and bodies at runtime using Zod schemas\n * - Infers TypeScript types from Zod schemas for full compile-time safety\n * - Supports path parameter interpolation with type-safe params\n * - Provides detailed validation error messages for debugging\n * - Integrates with React Query for caching and invalidation\n *\n * @example\n * ```typescript\n * // Define your API contract\n * const userContract = {\n *   getUser: defineGet('/users/:id', userSchema, {\n *     params: z.object({ id: z.string().uuid() })\n *   }),\n *   createUser: definePost('/users', userSchema, {\n *     body: createUserSchema\n *   })\n * } as const;\n *\n * // Create a typed client\n * const api = createTypedApiClient(userContract, { baseUrl: '/api' });\n *\n * // Use with full type safety\n * const user = await api.getUser({ params: { id: 'uuid-here' } });\n * ```\n *\n * @see {@link createTypedApiClient} for creating API clients\n * @see {@link defineEndpoint} for defining endpoints\n */\n\nimport { z, type ZodType, type ZodSchema, type ZodError } from 'zod';\nimport { apiClient, type ApiError, type RequestConfig } from '@/lib/api';\n\n/**\n * Re-export HttpError for backward compatibility\n * @deprecated Use ApiError from '@/lib/api/types' instead\n */\nexport type { ApiError as HttpError } from '@/lib/api/types';\n\n// =============================================================================\n// TYPE DEFINITIONS\n// =============================================================================\n\n/**\n * Supported HTTP methods\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * Endpoint definition with full type safety\n */\nexport interface EndpointDefinition<\n  TParams extends ZodType = ZodType,\n  TQuery extends ZodType = ZodType,\n  TBody extends ZodType = ZodType,\n  TResponse extends ZodType = ZodType,\n> {\n  /** HTTP method */\n  method: HttpMethod;\n  /** URL path with optional :param placeholders */\n  path: string;\n  /** Path parameters schema */\n  params?: TParams;\n  /** Query parameters schema */\n  query?: TQuery;\n  /** Request body schema */\n  body?: TBody;\n  /** Response data schema */\n  response: TResponse;\n  /** Additional headers */\n  headers?: Record<string, string>;\n  /** Request timeout (ms) */\n  timeout?: number;\n  /** Tags for categorization and cache invalidation */\n  tags?: string[];\n  /** Description for documentation */\n  description?: string;\n  /** Whether this endpoint requires authentication */\n  requiresAuth?: boolean;\n}\n\n/**\n * API contract - collection of endpoint definitions\n */\nexport type ApiContract = Record<string, EndpointDefinition>;\n\n/**\n * Infer request types from endpoint definition\n */\nexport type InferRequest<E extends EndpointDefinition> = {\n  params: E['params'] extends ZodType ? z.infer<E['params']> : never;\n  query: E['query'] extends ZodType ? z.infer<E['query']> : never;\n  body: E['body'] extends ZodType ? z.infer<E['body']> : never;\n};\n\n/**\n * Infer response type from endpoint definition\n */\nexport type InferResponse<E extends EndpointDefinition> = z.infer<E['response']>;\n\n/**\n * Build request options type based on endpoint requirements\n */\nexport type RequestOptions<E extends EndpointDefinition> = (E['params'] extends ZodType\n  ? { params: z.infer<E['params']> }\n  : object) &\n  (E['query'] extends ZodType ? { query: z.infer<E['query']> } : object) &\n  (E['body'] extends ZodType ? { body: z.infer<E['body']> } : object) & {\n    /** Abort signal for cancellation */\n    signal?: AbortSignal;\n    /** Skip request/response validation */\n    skipValidation?: boolean;\n    /** Additional headers for this request */\n    headers?: Record<string, string>;\n    /** Override timeout for this request */\n    timeout?: number;\n  };\n\n/**\n * Type-safe API client methods generated from contract\n */\nexport type TypedApiClient<T extends ApiContract> = {\n  [K in keyof T]: (options: RequestOptions<T[K]>) => Promise<InferResponse<T[K]>>;\n};\n\n/**\n * API client configuration\n */\nexport interface TypedApiClientConfig {\n  /** Base URL for API requests */\n  baseUrl: string;\n  /** API version prefix (e.g., 'v1') */\n  version?: string;\n  /** Default headers for all requests */\n  defaultHeaders?: Record<string, string>;\n  /** Callback for validation errors */\n  onValidationError?: (error: ZodError, endpoint: string, direction: 'request' | 'response') => void;\n  /** Custom response transformer */\n  transformResponse?: <T>(data: unknown, schema: ZodSchema<T>) => T;\n  /** Enable strict mode (throw on extra properties) */\n  strictMode?: boolean;\n  /** Default timeout (ms) */\n  timeout?: number;\n  /** Auth token getter */\n  getAuthToken?: () => string | null | Promise<string | null>;\n}\n\n// =============================================================================\n// ERRORS\n// =============================================================================\n\n/**\n * API validation error with detailed information\n */\nexport class ApiValidationError extends Error {\n  readonly zodError: ZodError;\n  readonly isValidationError = true;\n  readonly endpoint: string;\n  readonly direction: 'request' | 'response';\n  readonly issues: z.ZodIssue[];\n\n  constructor(message: string, zodError: ZodError, endpoint: string, direction: 'request' | 'response') {\n    super(message);\n    this.name = 'ApiValidationError';\n    this.zodError = zodError;\n    this.endpoint = endpoint;\n    this.direction = direction;\n    this.issues = zodError.issues;\n  }\n\n  /**\n   * Get formatted error messages\n   */\n  getFormattedErrors(): string[] {\n    return this.issues.map((issue) => {\n      const path = issue.path.join('.');\n      return path ? `${path}: ${issue.message}` : issue.message;\n    });\n  }\n\n  /**\n   * Get field-level errors\n   */\n  getFieldErrors(): Record<string, string[]> {\n    const errors: Record<string, string[]> = {};\n    for (const issue of this.issues) {\n      const path = issue.path.join('.') || '_root';\n      errors[path] ??= [];\n      errors[path].push(issue.message);\n    }\n    return errors;\n  }\n}\n\n/**\n * API contract error for invalid endpoint definitions\n */\nexport class ApiContractError extends Error {\n  readonly isContractError = true;\n  readonly endpoint: string;\n\n  constructor(message: string, endpoint: string) {\n    super(message);\n    this.name = 'ApiContractError';\n    this.endpoint = endpoint;\n  }\n}\n\n// =============================================================================\n// UTILITY FUNCTIONS\n// =============================================================================\n\n/**\n * Interpolate path parameters into URL path\n */\nfunction interpolatePath(path: string, params: Record<string, string | number>): string {\n  return path.replace(/:(\\w+)/g, (_, key: string) => {\n    const value = params[key];\n    if (value === undefined) {\n      throw new ApiContractError(`Missing path parameter: ${key}`, path);\n    }\n    return encodeURIComponent(String(value));\n  });\n}\n\n/**\n * Build query string from parameters\n */\nfunction buildQueryString(params: Record<string, unknown>): Record<string, string | number | boolean | undefined> {\n  const result: Record<string, string | number | boolean | undefined> = {};\n\n  for (const [key, value] of Object.entries(params)) {\n    if (value === undefined || value === null) {\n      continue;\n    }\n    if (Array.isArray(value)) {\n      // Handle array parameters (e.g., ?ids[]=1&ids[]=2)\n      result[key] = value.join(',');\n    } else if (typeof value === 'object') {\n      result[key] = JSON.stringify(value);\n    } else {\n      result[key] = value as string | number | boolean;\n    }\n  }\n\n  return result;\n}\n\n/**\n * Validate data against schema with error handling\n */\nfunction validateSchema<T>(\n  schema: ZodSchema<T>,\n  data: unknown,\n  endpoint: string,\n  direction: 'request' | 'response',\n  onError?: (error: ZodError, endpoint: string, direction: 'request' | 'response') => void\n): T {\n  const result = schema.safeParse(data);\n\n  if (!result.success) {\n    onError?.(result.error, endpoint, direction);\n    throw new ApiValidationError(\n      `${direction === 'request' ? 'Request' : 'Response'} validation failed for ${endpoint}`,\n      result.error,\n      endpoint,\n      direction\n    );\n  }\n\n  return result.data;\n}\n\n// =============================================================================\n// CLIENT FACTORY\n// =============================================================================\n\n/**\n * Create a type-safe API client from contract definition\n */\nexport function createTypedApiClient<T extends ApiContract>(\n  contract: T,\n  config: TypedApiClientConfig\n): TypedApiClient<T> & {\n  /** Get contract definition */\n  getContract: () => T;\n  /** Get configuration */\n  getConfig: () => TypedApiClientConfig;\n  /** Invalidate cache by tags */\n  invalidateByTags: (tags: string[]) => void;\n} {\n  const client = {} as TypedApiClient<T> & {\n    getContract: () => T;\n    getConfig: () => TypedApiClientConfig;\n    invalidateByTags: (tags: string[]) => void;\n  };\n\n  // Add metadata methods\n  client.getContract = () => contract;\n  client.getConfig = () => config;\n  client.invalidateByTags = (_tags: string[]) => {\n    // This would integrate with the cache system\n    // Intentionally a no-op for now - would integrate with cache system\n  };\n\n  // Generate typed methods for each endpoint\n  for (const [name, endpoint] of Object.entries(contract)) {\n    (client as Record<string, unknown>)[name] = async (\n      options: RequestOptions<typeof endpoint>\n    ): Promise<InferResponse<typeof endpoint>> => {\n      const { params, query, body, signal, skipValidation, headers: optionHeaders, timeout: optionTimeout } =\n        options as {\n          params?: Record<string, unknown>;\n          query?: Record<string, unknown>;\n          body?: unknown;\n          signal?: AbortSignal;\n          skipValidation?: boolean;\n          headers?: Record<string, string>;\n          timeout?: number;\n        };\n\n      // Validate request parameters\n      if (skipValidation !== true) {\n        if (endpoint.params !== undefined && params !== undefined) {\n          validateSchema(endpoint.params, params, name, 'request', config.onValidationError);\n        }\n        if (endpoint.query !== undefined && query !== undefined) {\n          validateSchema(endpoint.query, query, name, 'request', config.onValidationError);\n        }\n        if (endpoint.body !== undefined && body !== undefined) {\n          validateSchema(endpoint.body, body, name, 'request', config.onValidationError);\n        }\n      }\n\n      // Build URL with path parameters\n      let url = endpoint.path;\n      if (params !== undefined) {\n        url = interpolatePath(url, params as Record<string, string | number>);\n      }\n\n      // Add version prefix\n      if (config.version !== undefined) {\n        url = `/${config.version}${url}`;\n      }\n\n      // Build request configuration using the centralized apiClient format\n      const requestConfig: RequestConfig = {\n        url,\n        method: endpoint.method,\n        headers: {\n          ...config.defaultHeaders,\n          ...endpoint.headers,\n          ...optionHeaders,\n        },\n        params: query !== undefined ? buildQueryString(query) : undefined,\n        body,\n        timeout: optionTimeout ?? endpoint.timeout ?? config.timeout,\n        signal,\n        meta: {\n          skipAuth: endpoint.requiresAuth === false,\n        },\n      };\n\n      // Add auth token if available (apiClient handles this via token provider,\n      // but we support custom getAuthToken for backward compatibility)\n      if (config.getAuthToken !== undefined && endpoint.requiresAuth !== false) {\n        const token = await config.getAuthToken();\n        if (token !== null && token !== undefined) {\n          requestConfig.headers = {\n            ...requestConfig.headers,\n            Authorization: `Bearer ${token}`,\n          };\n        }\n      }\n\n      try {\n        // Use the centralized apiClient instead of the deprecated httpClient\n        const response = await apiClient.request(requestConfig);\n\n        // Validate and transform response\n        if (skipValidation !== true) {\n          if (config.transformResponse !== undefined) {\n            return config.transformResponse(response.data, endpoint.response);\n          }\n          return validateSchema(endpoint.response, response.data, name, 'response', config.onValidationError);\n        }\n\n        return response.data;\n      } catch (error) {\n        if (error instanceof ApiValidationError) {\n          throw error;\n        }\n        // ApiError from the centralized client is compatible with the old HttpError\n        if (error !== null && typeof error === 'object' && 'name' in error && (error as ApiError).name === 'ApiError') {\n          throw error;\n        }\n        throw error;\n      }\n    };\n  }\n\n  return client;\n}\n\n// =============================================================================\n// ENDPOINT DEFINITION HELPERS\n// =============================================================================\n\n/**\n * Define an API endpoint with type inference\n */\nexport function defineEndpoint<\n  TParams extends ZodType = never,\n  TQuery extends ZodType = never,\n  TBody extends ZodType = never,\n  TResponse extends ZodType = ZodType,\n>(\n  definition: EndpointDefinition<TParams, TQuery, TBody, TResponse>\n): EndpointDefinition<TParams, TQuery, TBody, TResponse> {\n  return definition;\n}\n\n/**\n * Define a GET endpoint\n */\nexport function defineGet<TResponse extends ZodType, TParams extends ZodType = never, TQuery extends ZodType = never>(\n  path: string,\n  response: TResponse,\n  options?: Omit<EndpointDefinition<TParams, TQuery, never, TResponse>, 'method' | 'path' | 'response' | 'body'>\n): EndpointDefinition<TParams, TQuery, never, TResponse> {\n  return {\n    method: 'GET',\n    path,\n    response,\n    ...options,\n  } as EndpointDefinition<TParams, TQuery, never, TResponse>;\n}\n\n/**\n * Define a POST endpoint\n */\nexport function definePost<\n  TParams extends ZodType = never,\n  TBody extends ZodType = never,\n  TResponse extends ZodType = ZodType,\n>(\n  path: string,\n  response: TResponse,\n  options?: Omit<EndpointDefinition<TParams, never, TBody, TResponse>, 'method' | 'path' | 'response'>\n): EndpointDefinition<TParams, never, TBody, TResponse> {\n  return {\n    method: 'POST',\n    path,\n    response,\n    ...options,\n  } as EndpointDefinition<TParams, never, TBody, TResponse>;\n}\n\n/**\n * Define a PUT endpoint\n */\nexport function definePut<\n  TParams extends ZodType = never,\n  TBody extends ZodType = never,\n  TResponse extends ZodType = ZodType,\n>(\n  path: string,\n  response: TResponse,\n  options?: Omit<EndpointDefinition<TParams, never, TBody, TResponse>, 'method' | 'path' | 'response'>\n): EndpointDefinition<TParams, never, TBody, TResponse> {\n  return {\n    method: 'PUT',\n    path,\n    response,\n    ...options,\n  } as EndpointDefinition<TParams, never, TBody, TResponse>;\n}\n\n/**\n * Define a PATCH endpoint\n */\nexport function definePatch<\n  TParams extends ZodType = never,\n  TBody extends ZodType = never,\n  TResponse extends ZodType = ZodType,\n>(\n  path: string,\n  response: TResponse,\n  options?: Omit<EndpointDefinition<TParams, never, TBody, TResponse>, 'method' | 'path' | 'response'>\n): EndpointDefinition<TParams, never, TBody, TResponse> {\n  return {\n    method: 'PATCH',\n    path,\n    response,\n    ...options,\n  } as EndpointDefinition<TParams, never, TBody, TResponse>;\n}\n\n/**\n * Define a DELETE endpoint\n */\nexport function defineDelete<TParams extends ZodType = never, TResponse extends ZodType = ZodType>(\n  path: string,\n  response: TResponse,\n  options?: Omit<EndpointDefinition<TParams, never, never, TResponse>, 'method' | 'path' | 'response' | 'body'>\n): EndpointDefinition<TParams, never, never, TResponse> {\n  return {\n    method: 'DELETE',\n    path,\n    response,\n    ...options,\n  } as EndpointDefinition<TParams, never, never, TResponse>;\n}\n\n// =============================================================================\n// COMMON SCHEMAS\n// =============================================================================\n\n/**\n * Common pagination schema\n */\nexport const paginationSchema = z.object({\n  page: z.number().int().positive().optional().default(1),\n  pageSize: z.number().int().positive().max(100).optional().default(20),\n  sortBy: z.string().optional(),\n  sortOrder: z.enum(['asc', 'desc']).optional().default('asc'),\n});\n\nexport type PaginationParams = z.infer<typeof paginationSchema>;\n\n/**\n * Common paginated response schema factory\n */\nexport function createPaginatedResponseSchema<T extends ZodType>(itemSchema: T): z.ZodObject<{\n  items: z.ZodArray<T>;\n  total: z.ZodNumber;\n  page: z.ZodNumber;\n  pageSize: z.ZodNumber;\n  totalPages: z.ZodNumber;\n  hasNextPage: z.ZodOptional<z.ZodBoolean>;\n  hasPreviousPage: z.ZodOptional<z.ZodBoolean>;\n}> {\n  return z.object({\n    items: z.array(itemSchema),\n    total: z.number().int().nonnegative(),\n    page: z.number().int().positive(),\n    pageSize: z.number().int().positive(),\n    totalPages: z.number().int().nonnegative(),\n    hasNextPage: z.boolean().optional(),\n    hasPreviousPage: z.boolean().optional(),\n  });\n}\n\n/**\n * Common ID parameter schema\n */\nexport const idParamSchema = z.object({\n  id: z.string().uuid(),\n});\n\n/**\n * Common error response schema\n */\nexport const errorResponseSchema = z.object({\n  error: z.object({\n    code: z.string(),\n    message: z.string(),\n    details: z.record(z.string(), z.unknown()).optional(),\n    traceId: z.string().optional(),\n  }),\n});\n\n/**\n * Common success response schema\n */\nexport const successResponseSchema = z.object({\n  success: z.literal(true),\n  message: z.string().optional(),\n});\n\n// =============================================================================\n// EXAMPLE USAGE - USER API CONTRACT\n// =============================================================================\n\n/**\n * User schema\n */\nexport const userSchema = z.object({\n  id: z.string().uuid(),\n  email: z.string().email(),\n  name: z.string().min(1),\n  role: z.enum(['admin', 'user', 'viewer']),\n  status: z.enum(['active', 'inactive', 'pending']).optional(),\n  profile: z\n    .object({\n      avatar: z.string().url().optional(),\n      bio: z.string().max(500).optional(),\n    })\n    .optional(),\n  createdAt: z.string().datetime(),\n  updatedAt: z.string().datetime(),\n});\n\nexport type User = z.infer<typeof userSchema>;\n\n/**\n * Example user API contract\n */\nexport const userApiContract = {\n  getUsers: defineEndpoint({\n    method: 'GET',\n    path: '/users',\n    query: paginationSchema.extend({\n      search: z.string().optional(),\n      role: z.enum(['admin', 'user', 'viewer']).optional(),\n      status: z.enum(['active', 'inactive', 'pending']).optional(),\n    }),\n    response: createPaginatedResponseSchema(userSchema),\n    tags: ['users'],\n    description: 'Get paginated list of users',\n  }),\n\n  getUserById: defineEndpoint({\n    method: 'GET',\n    path: '/users/:id',\n    params: idParamSchema,\n    response: userSchema,\n    tags: ['users'],\n    description: 'Get user by ID',\n  }),\n\n  createUser: defineEndpoint({\n    method: 'POST',\n    path: '/users',\n    body: z.object({\n      email: z.string().email(),\n      name: z.string().min(2),\n      role: z.enum(['admin', 'user', 'viewer']),\n      password: z.string().min(8),\n    }),\n    response: userSchema,\n    tags: ['users'],\n    description: 'Create a new user',\n  }),\n\n  updateUser: defineEndpoint({\n    method: 'PATCH',\n    path: '/users/:id',\n    params: idParamSchema,\n    body: z.object({\n      name: z.string().min(2).optional(),\n      role: z.enum(['admin', 'user', 'viewer']).optional(),\n      status: z.enum(['active', 'inactive', 'pending']).optional(),\n      profile: z\n        .object({\n          avatar: z.string().url().optional(),\n          bio: z.string().max(500).optional(),\n        })\n        .optional(),\n    }),\n    response: userSchema,\n    tags: ['users'],\n    description: 'Update an existing user',\n  }),\n\n  deleteUser: defineEndpoint({\n    method: 'DELETE',\n    path: '/users/:id',\n    params: idParamSchema,\n    response: successResponseSchema,\n    tags: ['users'],\n    description: 'Delete a user',\n  }),\n} as const;\n\n/**\n * Create typed user API client\n */\nexport function createUserApiClient(config?: Partial<TypedApiClientConfig>): TypedApiClient<typeof userApiContract> {\n  return createTypedApiClient(userApiContract, {\n    baseUrl: '/api',\n    version: 'v1',\n    onValidationError: (error, endpoint, direction) => {\n       \n      console.error(`[API Validation] ${direction} for ${endpoint}:`, error.issues);\n    },\n    ...config,\n  });\n}\n\n// Usage example:\n// const userApi = createUserApiClient();\n// const users = await userApi.getUsers({ query: { page: 1, role: 'admin' } });\n// const user = await userApi.getUserById({ params: { id: 'uuid-here' } });\n// const newUser = await userApi.createUser({ body: { email: 'test@example.com', name: 'Test', role: 'user', password: 'password123' } });\n"],"names":["ApiValidationError","message","zodError","endpoint","direction","issue","path","errors","ApiContractError","interpolatePath","params","_","key","value","buildQueryString","result","validateSchema","schema","data","onError","createTypedApiClient","contract","config","client","_tags","name","options","query","body","signal","skipValidation","optionHeaders","optionTimeout","url","requestConfig","token","response","apiClient","error","defineEndpoint","definition","defineGet","definePost","definePut","definePatch","defineDelete","paginationSchema","z","createPaginatedResponseSchema","itemSchema","idParamSchema","errorResponseSchema","successResponseSchema","userSchema","userApiContract","createUserApiClient"],"mappings":";;;AAiKO,MAAMA,UAA2B,MAAM;AA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