{"version":3,"file":"types.mjs","sources":["../../../src/lib/extensions/types.ts"],"sourcesContent":["/**\n * @file Extension System Types\n * @description Prisma-inspired type-safe extension system for Enzyme Library\n *\n * Key patterns implemented:\n * - Prisma: $extends API with immutable composition\n * - axios: Interceptor chains with priority-based execution\n * - socket.io: Middleware chains with async/await\n * - React: Hook-compatible design for useExtension/useExtensionManager\n *\n * @module lib/extensions/types\n */\n\nimport type { Brand } from '../shared/type-utils.js';\n\n// ============================================================================\n// Branded Types for Type Safety\n// ============================================================================\n\n/**\n * Unique extension identifier\n * Prevents mixing different extension types (compile-time safety)\n */\nexport type ExtensionId = Brand<string, 'ExtensionId'>;\n\n/**\n * Unique hook identifier\n */\nexport type HookId = Brand<string, 'HookId'>;\n\n/**\n * Unique component extension identifier\n */\nexport type ComponentExtensionId = Brand<string, 'ComponentExtensionId'>;\n\n/**\n * Type-safe extension ID constructor\n */\nexport function createExtensionId(id: string): ExtensionId {\n  if (!id || id.length < 1) {\n    throw new TypeError('Invalid extension ID: must be a non-empty string');\n  }\n  return id as ExtensionId;\n}\n\n/**\n * Type-safe hook ID constructor\n */\nexport function createHookId(id: string): HookId {\n  if (!id || id.length < 1) {\n    throw new TypeError('Invalid hook ID: must be a non-empty string');\n  }\n  return id as HookId;\n}\n\n// ============================================================================\n// Extension Lifecycle Hooks\n// ============================================================================\n\n/**\n * Extension priority for execution order\n * Higher priority extensions execute first\n */\nexport type ExtensionPriority = number;\n\n/**\n * Default priority values\n */\nexport const ExtensionPriorities = {\n  CRITICAL: 1000,\n  HIGH: 500,\n  NORMAL: 0,\n  LOW: -500,\n  LOWEST: -1000,\n} as const;\n\n/**\n * Context provided to onInit hook\n */\nexport interface InitContext {\n  /** Extension name */\n  extensionName: string;\n  /** Configuration passed to the client */\n  config: Record<string, unknown>;\n  /** Timestamp when initialized */\n  timestamp: number;\n}\n\n/**\n * Context provided to onMount hook (React lifecycle)\n */\nexport interface MountContext {\n  /** Extension name */\n  extensionName: string;\n  /** Component or module being mounted */\n  component?: string;\n  /** Mount-specific data */\n  data?: Record<string, unknown>;\n  /** Timestamp when mounted */\n  timestamp: number;\n}\n\n/**\n * Context provided to onUnmount hook (React lifecycle)\n */\nexport interface UnmountContext {\n  /** Extension name */\n  extensionName: string;\n  /** Component or module being unmounted */\n  component?: string;\n  /** Cleanup-specific data */\n  data?: Record<string, unknown>;\n  /** Timestamp when unmounted */\n  timestamp: number;\n}\n\n/**\n * Context provided to onError hook\n */\nexport interface ErrorContext {\n  /** Extension name where error occurred */\n  extensionName: string;\n  /** Hook name where error occurred */\n  hookName: string;\n  /** The error that was thrown */\n  error: Error;\n  /** Operation that was being performed */\n  operation: string;\n  /** Retry the failed operation */\n  retry: () => Promise<void>;\n  /** Timestamp when error occurred */\n  timestamp: number;\n}\n\n/**\n * Context provided to beforeOperation hook\n */\nexport interface BeforeOperationContext<TArgs = unknown> {\n  /** Extension name */\n  extensionName: string;\n  /** Operation name (e.g., 'fetch', 'mutate', 'render') */\n  operation: string;\n  /** Operation arguments (mutable) */\n  args: TArgs;\n  /** Modify arguments before execution */\n  modify: (changes: Partial<TArgs>) => void;\n  /** Cancel the operation */\n  cancel: () => void;\n  /** Operation metadata */\n  metadata?: Record<string, unknown>;\n  /** Timestamp */\n  timestamp: number;\n}\n\n/**\n * Context provided to afterOperation hook\n */\nexport interface AfterOperationContext<TArgs = unknown, TResult = unknown> {\n  /** Extension name */\n  extensionName: string;\n  /** Operation name */\n  operation: string;\n  /** Original operation arguments */\n  args: TArgs;\n  /** Operation result (mutable) */\n  result: TResult;\n  /** Modify result before returning */\n  modify: (changes: Partial<TResult>) => void;\n  /** Operation duration in ms */\n  duration: number;\n  /** Operation metadata */\n  metadata?: Record<string, unknown>;\n  /** Timestamp */\n  timestamp: number;\n}\n\n/**\n * Extension lifecycle hook function types\n */\nexport type InitHook = (context: InitContext) => Promise<void> | void;\nexport type MountHook = (context: MountContext) => Promise<void> | void;\nexport type UnmountHook = (context: UnmountContext) => Promise<void> | void;\nexport type ErrorHook = (context: ErrorContext) => Promise<void> | void;\nexport type BeforeOperationHook<TArgs = unknown> = (\n  context: BeforeOperationContext<TArgs>\n) => Promise<void> | void;\nexport type AfterOperationHook<TArgs = unknown, TResult = unknown> = (\n  context: AfterOperationContext<TArgs, TResult>\n) => Promise<void> | void;\n\n/**\n * Lifecycle hooks configuration\n */\nexport interface LifecycleHooks {\n  /** Called when extension is registered */\n  onInit?: InitHook;\n  /** Called when component/module mounts (React lifecycle) */\n  onMount?: MountHook;\n  /** Called when component/module unmounts (React lifecycle) */\n  onUnmount?: UnmountHook;\n  /** Called when an error occurs in any hook */\n  onError?: ErrorHook;\n  /** Called before any operation (middleware pattern) */\n  beforeOperation?: BeforeOperationHook;\n  /** Called after any operation (middleware pattern) */\n  afterOperation?: AfterOperationHook;\n}\n\n// ============================================================================\n// Component Extensions\n// ============================================================================\n\n/**\n * Component enhancer function type\n * Used to wrap or enhance React components\n */\nexport type ComponentEnhancer<TProps = unknown> = (\n  Component: React.ComponentType<TProps>\n) => React.ComponentType<TProps>;\n\n/**\n * Component hook type\n * Custom hooks provided by extensions\n */\nexport type ComponentHook<TResult = unknown> = (...args: unknown[]) => TResult;\n\n/**\n * Component extensions configuration\n */\nexport interface ComponentExtensions {\n  /** Component enhancers (HOCs) */\n  enhancers?: Record<string, ComponentEnhancer>;\n  /** Custom React hooks */\n  hooks?: Record<string, ComponentHook>;\n  /** Component-level utilities */\n  utils?: Record<string, (...args: unknown[]) => unknown>;\n}\n\n// ============================================================================\n// State Extensions\n// ============================================================================\n\n/**\n * State selector function type\n */\nexport type StateSelector<TState = unknown, TResult = unknown> = (\n  state: TState\n) => TResult;\n\n/**\n * State action creator type\n */\nexport type StateActionCreator<TPayload = unknown> = (\n  payload: TPayload\n) => { type: string; payload: TPayload };\n\n/**\n * State middleware function type\n */\nexport type StateMiddleware<TState = unknown> = (\n  state: TState,\n  action: { type: string; payload?: unknown }\n) => TState;\n\n/**\n * State extensions configuration\n */\nexport interface StateExtensions {\n  /** State selectors */\n  selectors?: Record<string, StateSelector>;\n  /** Action creators */\n  actions?: Record<string, StateActionCreator>;\n  /** State middleware */\n  middleware?: StateMiddleware[];\n  /** Initial state contributions */\n  initialState?: Record<string, unknown>;\n}\n\n// ============================================================================\n// API Extensions\n// ============================================================================\n\n/**\n * API endpoint definition\n */\nexport interface ApiEndpoint<TArgs = unknown, TResult = unknown> {\n  /** HTTP method or operation type */\n  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | string;\n  /** Endpoint path or operation name */\n  path?: string;\n  /** Endpoint handler */\n  handler: (args: TArgs) => Promise<TResult> | TResult;\n  /** Request transformer */\n  transformRequest?: (args: TArgs) => unknown;\n  /** Response transformer */\n  transformResponse?: (response: unknown) => TResult;\n  /** Error transformer */\n  transformError?: (error: unknown) => Error;\n}\n\n/**\n * API interceptor for request/response modification\n */\nexport interface ApiInterceptor {\n  /** Request interceptor */\n  request?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n  /** Response interceptor */\n  response?: <T>(response: T) => Promise<T> | T;\n  /** Error interceptor */\n  error?: (error: Error) => Promise<never> | never;\n}\n\n/**\n * Request configuration\n */\nexport interface RequestConfig {\n  url?: string;\n  method?: string;\n  headers?: Record<string, string>;\n  params?: Record<string, unknown>;\n  data?: unknown;\n  timeout?: number;\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * API extensions configuration\n */\nexport interface ApiExtensions {\n  /** Custom API endpoints */\n  endpoints?: Record<string, ApiEndpoint>;\n  /** Request/response interceptors */\n  interceptors?: ApiInterceptor[];\n  /** API-level utilities */\n  utils?: Record<string, (...args: unknown[]) => unknown>;\n}\n\n// ============================================================================\n// Main Extension Interface\n// ============================================================================\n\n/**\n * Complete Enzyme Extension definition\n * Inspired by Prisma's extension architecture\n *\n * @example\n * ```ts\n * const loggingExtension: EnzymeExtension = {\n *   name: 'logging',\n *   version: '1.0.0',\n *   description: 'Logs all operations',\n *   priority: ExtensionPriorities.HIGH,\n *   hooks: {\n *     beforeOperation: async (ctx) => {\n *       console.log(`[${ctx.operation}] Starting...`);\n *     },\n *     afterOperation: async (ctx) => {\n *       console.log(`[${ctx.operation}] Completed in ${ctx.duration}ms`);\n *     },\n *   },\n * };\n * ```\n */\nexport interface EnzymeExtension {\n  /** Extension name (required, must be unique) */\n  name: string;\n\n  /** Extension version (semver recommended) */\n  version?: string;\n\n  /** Extension description */\n  description?: string;\n\n  /** Execution priority (higher = earlier execution) */\n  priority?: ExtensionPriority;\n\n  /** Lifecycle hooks */\n  hooks?: LifecycleHooks;\n\n  /** Component-level extensions */\n  component?: ComponentExtensions;\n\n  /** State management extensions */\n  state?: StateExtensions;\n\n  /** API/network extensions */\n  api?: ApiExtensions;\n\n  /** Client-level methods and utilities */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  client?: Record<string, (...args: any[]) => any>;\n\n  /** Extension metadata */\n  metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Extension Manager Interface\n// ============================================================================\n\n/**\n * Extension manager interface\n */\nexport interface IExtensionManager {\n  /** Register an extension */\n  register(extension: EnzymeExtension): void;\n\n  /** Unregister an extension by name */\n  unregister(name: string): boolean;\n\n  /** Get all registered extensions */\n  getExtensions(): EnzymeExtension[];\n\n  /** Get extension by name */\n  getExtension(name: string): EnzymeExtension | undefined;\n\n  /** Check if extension is registered */\n  hasExtension(name: string): boolean;\n\n  /** Get extension count */\n  readonly count: number;\n\n  /** Execute lifecycle hooks */\n  executeHooks<T = void>(\n    hookName: keyof LifecycleHooks,\n    context: unknown\n  ): Promise<T | void>;\n\n  /** Clear all extensions */\n  clear(): void;\n}\n\n// ============================================================================\n// Type Utilities (Prisma-inspired)\n// ============================================================================\n\n/**\n * Exact type matching for strict checking\n * Prevents excess properties in extension definitions\n */\nexport type Exact<Input, Shape> = Input extends Shape\n  ? Exclude<keyof Input, keyof Shape> extends never\n    ? Input\n    : never\n  : never;\n\n/**\n * Deep partial type for configuration\n */\nexport type DeepPartial<T> = T extends object\n  ? { [P in keyof T]?: DeepPartial<T[P]> }\n  : T;\n\n/**\n * Extract extension client methods\n */\nexport type ExtensionClientMethods<T extends EnzymeExtension> =\n  T['client'] extends Record<string, (...args: unknown[]) => unknown>\n    ? T['client']\n    : Record<string, never>;\n\n/**\n * Merge multiple extension client methods\n */\nexport type MergeExtensionMethods<T extends EnzymeExtension[]> = T extends [\n  infer First extends EnzymeExtension,\n  ...infer Rest extends EnzymeExtension[]\n]\n  ? ExtensionClientMethods<First> & MergeExtensionMethods<Rest>\n  : Record<string, never>;\n\n/**\n * Extension client type with merged methods\n */\nexport type ExtendedClient<\n  TBase,\n  TExtensions extends EnzymeExtension[]\n> = TBase & MergeExtensionMethods<TExtensions>;\n\n// ============================================================================\n// Enzyme Namespace with Type Utilities\n// ============================================================================\n\n/**\n * Enzyme namespace for extension utilities\n */\nexport namespace Enzyme {\n  /**\n   * Define an extension with type inference and validation\n   *\n   * @example\n   * ```ts\n   * const myExtension = Enzyme.defineExtension({\n   *   name: 'my-extension',\n   *   version: '1.0.0',\n   *   hooks: {\n   *     onInit: async (ctx) => {\n   *       console.log('Initialized!');\n   *     },\n   *   },\n   * });\n   * ```\n   */\n  export function defineExtension<T extends EnzymeExtension>(extension: T): T {\n    if (!extension.name) {\n      throw new TypeError('Extension name is required');\n    }\n    return extension;\n  }\n\n  /**\n   * Create a typed hook context\n   */\n  export function createHookContext<T extends keyof LifecycleHooks>(\n    _hookName: T,\n    data: unknown\n  ): unknown {\n    return data;\n  }\n\n  /**\n   * Type guard for extension validation\n   */\n  export function isValidExtension(value: unknown): value is EnzymeExtension {\n    return (\n      typeof value === 'object' &&\n      value !== null &&\n      'name' in value &&\n      typeof (value as EnzymeExtension).name === 'string'\n    );\n  }\n\n  /**\n   * Extension builder for fluent API\n   *\n   * @example\n   * ```ts\n   * const ext = Enzyme.extension('my-ext')\n   *   .version('1.0.0')\n   *   .priority(ExtensionPriorities.HIGH)\n   *   .onInit(async (ctx) => { ... })\n   *   .build();\n   * ```\n   */\n  export function extension(name: string): ExtensionBuilder {\n    return new ExtensionBuilder(name);\n  }\n}\n\n/**\n * Fluent extension builder\n */\nexport class ExtensionBuilder {\n  private ext: Partial<EnzymeExtension>;\n\n  constructor(name: string) {\n    this.ext = { name };\n  }\n\n  version(v: string): this {\n    this.ext.version = v;\n    return this;\n  }\n\n  description(d: string): this {\n    this.ext.description = d;\n    return this;\n  }\n\n  priority(p: ExtensionPriority): this {\n    this.ext.priority = p;\n    return this;\n  }\n\n  onInit(hook: InitHook): this {\n    this.ext.hooks = { ...this.ext.hooks, onInit: hook };\n    return this;\n  }\n\n  onMount(hook: MountHook): this {\n    this.ext.hooks = { ...this.ext.hooks, onMount: hook };\n    return this;\n  }\n\n  onUnmount(hook: UnmountHook): this {\n    this.ext.hooks = { ...this.ext.hooks, onUnmount: hook };\n    return this;\n  }\n\n  onError(hook: ErrorHook): this {\n    this.ext.hooks = { ...this.ext.hooks, onError: hook };\n    return this;\n  }\n\n  beforeOperation(hook: BeforeOperationHook): this {\n    this.ext.hooks = { ...this.ext.hooks, beforeOperation: hook };\n    return this;\n  }\n\n  afterOperation(hook: AfterOperationHook): this {\n    this.ext.hooks = { ...this.ext.hooks, afterOperation: hook };\n    return this;\n  }\n\n  withComponent(component: ComponentExtensions): this {\n    this.ext.component = component;\n    return this;\n  }\n\n  withState(state: StateExtensions): this {\n    this.ext.state = state;\n    return this;\n  }\n\n  withApi(api: ApiExtensions): this {\n    this.ext.api = api;\n    return this;\n  }\n\n  withClient(client: Record<string, (...args: unknown[]) => unknown>): this {\n    this.ext.client = client;\n    return this;\n  }\n\n  withMetadata(metadata: Record<string, unknown>): this {\n    this.ext.metadata = metadata;\n    return this;\n  }\n\n  build(): EnzymeExtension {\n    if (!this.ext.name) {\n      throw new TypeError('Extension name is required');\n    }\n    return this.ext as EnzymeExtension;\n  }\n}\n\n// ============================================================================\n// Event Types for Extension Communication\n// ============================================================================\n\n/**\n * Extension event for pub/sub communication between extensions\n */\nexport interface ExtensionEvent<TPayload = unknown> {\n  /** Event type/name */\n  type: string;\n  /** Event payload */\n  payload: TPayload;\n  /** Source extension */\n  source: string;\n  /** Timestamp */\n  timestamp: number;\n  /** Event metadata */\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Extension event handler\n */\nexport type ExtensionEventHandler<TPayload = unknown> = (\n  event: ExtensionEvent<TPayload>\n) => Promise<void> | void;\n\n/**\n * Extension event emitter interface\n */\nexport interface IExtensionEventEmitter {\n  /** Emit an event */\n  emit<T>(type: string, payload: T, metadata?: Record<string, unknown>): void;\n\n  /** Subscribe to events */\n  on<T>(type: string, handler: ExtensionEventHandler<T>): () => void;\n\n  /** Subscribe to events (once) */\n  once<T>(type: string, handler: ExtensionEventHandler<T>): () => void;\n\n  /** Unsubscribe from events */\n  off<T>(type: string, handler: ExtensionEventHandler<T>): void;\n}\n"],"names":["createExtensionId","id","createHookId","ExtensionPriorities","Enzyme","defineExtension","extension","createHookContext","_hookName","data","isValidExtension","value","name","ExtensionBuilder","v","d","p","hook","component","state","api","client","metadata"],"mappings":"AAsCO,SAASA,EAAkBC,GAAyB;AACzD,MAAI,CAACA,KAAMA,EAAG,SAAS;AACrB,UAAM,IAAI,UAAU,kDAAkD;AAExE,SAAOA;AACT;AAKO,SAASC,EAAaD,GAAoB;AAC/C,MAAI,CAACA,KAAMA,EAAG,SAAS;AACrB,UAAM,IAAI,UAAU,6CAA6C;AAEnE,SAAOA;AACT;AAeO,MAAME,IAAsB;AAAA,EACjC,UAAU;AAAA,EACV,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,QAAQ;AACV;AA4ZO,IAAUC;AAAA,CAAV,CAAUA,MAAV;AAiBE,WAASC,EAA2CC,GAAiB;AAC1E,QAAI,CAACA,EAAU;AACb,YAAM,IAAI,UAAU,4BAA4B;AAElD,WAAOA;AAAAA,EACT;AALOF,EAAAA,EAAS,kBAAAC;AAUT,WAASE,EACdC,GACAC,GACS;AACT,WAAOA;AAAA,EACT;AALOL,E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