@context-action/core 0.7.5 → 0.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/package.json +32 -17
- package/LICENSE +0 -201
package/dist/index.js
CHANGED
|
@@ -775,7 +775,7 @@ var ActionRegister = class {
|
|
|
775
775
|
this.name = config.name || "ActionRegister";
|
|
776
776
|
this.registryConfig = config.registry;
|
|
777
777
|
this.maxHandlersPerAction = config.registry?.maxHandlersPerAction ?? 1e3;
|
|
778
|
-
this.isDebugMode = Boolean(this.registryConfig?.debug &&
|
|
778
|
+
this.isDebugMode = Boolean(this.registryConfig?.debug && true);
|
|
779
779
|
this.actionGuard = new ActionGuard(this.registryConfig?.autoCleanup !== false);
|
|
780
780
|
if (config.registry?.useConcurrencyQueue !== false) this.dispatchQueue = new OperationQueue(`${this.name}-Dispatch`);
|
|
781
781
|
if (this.registryConfig?.defaultExecutionMode) this.executionMode = this.registryConfig.defaultExecutionMode;
|
|
@@ -983,7 +983,7 @@ var ActionRegister = class {
|
|
|
983
983
|
options: options ? Object.keys(options) : "none",
|
|
984
984
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
985
985
|
});
|
|
986
|
-
if (payload instanceof Event &&
|
|
986
|
+
if (payload instanceof Event && true) console.warn(`Event object passed to action "${String(action)}"`, payload.type);
|
|
987
987
|
const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);
|
|
988
988
|
if (options?.autoAbort?.onControllerCreated && autoAbortController) options.autoAbort.onControllerCreated(autoAbortController);
|
|
989
989
|
if (effectiveSignal?.aborted) {
|
|
@@ -1411,7 +1411,7 @@ var ActionRegister = class {
|
|
|
1411
1411
|
const index = pipeline.findIndex((reg) => reg.id === registration.id);
|
|
1412
1412
|
if (index !== -1) {
|
|
1413
1413
|
pipeline.splice(index, 1);
|
|
1414
|
-
if (this.registryConfig?.debug &&
|
|
1414
|
+
if (this.registryConfig?.debug && true) console.log(`🎯 One-time handler removed: ${String(action)}`, {
|
|
1415
1415
|
handlerId: registration.id,
|
|
1416
1416
|
remainingHandlers: pipeline.length,
|
|
1417
1417
|
registry: this.name
|
|
@@ -1558,7 +1558,7 @@ var ActionRegister = class {
|
|
|
1558
1558
|
*/
|
|
1559
1559
|
setExecutionMode(mode) {
|
|
1560
1560
|
this.executionMode = mode;
|
|
1561
|
-
if (this.registryConfig?.debug &&
|
|
1561
|
+
if (this.registryConfig?.debug && true) console.log(`🎯 Global execution mode set to: ${mode}`);
|
|
1562
1562
|
}
|
|
1563
1563
|
/**
|
|
1564
1564
|
* Set execution mode for a specific action
|
|
@@ -1568,7 +1568,7 @@ var ActionRegister = class {
|
|
|
1568
1568
|
*/
|
|
1569
1569
|
setActionExecutionMode(action, mode) {
|
|
1570
1570
|
this.actionExecutionModes.set(action, mode);
|
|
1571
|
-
if (this.registryConfig?.debug &&
|
|
1571
|
+
if (this.registryConfig?.debug && true) console.log(`🎯 Execution mode set for action '${String(action)}': ${mode}`);
|
|
1572
1572
|
}
|
|
1573
1573
|
/**
|
|
1574
1574
|
* Get execution mode for a specific action
|
|
@@ -1586,7 +1586,7 @@ var ActionRegister = class {
|
|
|
1586
1586
|
*/
|
|
1587
1587
|
removeActionExecutionMode(action) {
|
|
1588
1588
|
this.actionExecutionModes.delete(action);
|
|
1589
|
-
if (this.registryConfig?.debug &&
|
|
1589
|
+
if (this.registryConfig?.debug && true) console.log(`🎯 Execution mode reset for action '${String(action)}' to default: ${this.executionMode}`);
|
|
1590
1590
|
}
|
|
1591
1591
|
/**
|
|
1592
1592
|
* Get registry configuration (for debugging and inspection)
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["nonBlockingPromises: Array<Promise<any>>","errors: HandlerError[]","error: any","handlerResult: R | undefined","keysToDelete: string[]","name: string","queuedOperation: QueuedOperation<T>","signals: AbortSignal[]","cleanups: (() => void)[]","autoAbortController: AbortController | undefined","effectiveSignal: AbortSignal","registration: HandlerRegistration<T[K], R>","throttleMs: number | undefined","debounceMs: number | undefined","context: PipelineContext<T[K], any>","context: PipelineContext<T[K], R>","executionError: Error | undefined","handlerResults: Array<{\n id: string;\n executed: boolean;\n duration: number | undefined;\n result: R | undefined;\n error: Error | undefined;\n metadata: Record<string, any> | undefined;\n }>","errors: HandlerError[]","executionResult: ExecutionResult<R>","parts: string[]","finalConfig: Required<HandlerConfig>","currentUnregister: UnregisterFunction | undefined"],"sources":["../src/execution-modes.ts","../src/action-guard.ts","../src/concurrency/OperationQueue.ts","../src/ActionRegister.ts","../src/react-helpers.ts"],"sourcesContent":["/**\n * @fileoverview Execution mode implementations for ActionRegister\n * \n * Provides three different execution strategies for action handler pipelines:\n * - Sequential: Execute handlers one after another in priority order\n * - Parallel: Execute all handlers simultaneously\n * - Race: First handler to complete wins, others are cancelled\n */\n\nimport type { \n HandlerRegistration, \n PipelineContext, \n PipelineController,\n HandlerError\n} from './types.js';\n\n/**\n * Create standardized error handling for handlers\n * \n * @param error - The error that occurred\n * @param registration - The handler registration that failed\n * @returns Standardized HandlerError object\n * \n * @internal\n */\nfunction handleExecutionError<T, R>(\n error: any,\n registration: HandlerRegistration<T, R>\n): HandlerError {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n return {\n handlerId: registration.id,\n error: errorObj,\n timestamp: Date.now(),\n severity: registration.config.blocking ? 'blocking' : 'non-blocking'\n };\n}\n\n/**\n * Execute handlers in sequential mode (one after another)\n * \n * Executes action handlers one at a time in priority order (highest first).\n * Supports both blocking and non-blocking handlers, with proper abort and\n * termination handling. Handlers can modify payload for subsequent handlers\n * and jump to different priority levels.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When a blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns\n * \n * @public\n */\nexport async function executeSequential<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n let i = 0;\n const nonBlockingPromises: Array<Promise<any>> = [];\n const errors: HandlerError[] = [];\n \n while (i < context.handlers.length) {\n // Check for abort or termination\n if (context.aborted || context.terminated) {\n break;\n }\n\n const registration = context.handlers[i];\n if (!registration) {\n continue; // Skip if handler not found\n }\n context.currentIndex = i;\n const controller = createController(registration, i);\n\n try {\n // Check for abort before executing handler\n if (context.aborted) {\n break;\n }\n\n // 🔧 Fix: Check handler condition before execution\n if (registration.config.condition) {\n try {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n i++; // Skip this handler\n continue;\n }\n } catch {\n // If condition function throws, skip the handler\n i++;\n continue;\n }\n }\n\n const result = registration.handler(context.payload, controller);\n\n if (registration.config.blocking) {\n // 🆕 Blocking handlers: Wait for completion (sync or async)\n const handlerResult = result instanceof Promise ? await result : result;\n if (handlerResult !== undefined && !context.terminated) {\n context.results.push(handlerResult as R);\n }\n } else {\n // 🆕 Non-blocking handlers: Handle differently for sync vs async\n if (result instanceof Promise) {\n // Non-blocking async: Track promise with error handling\n const promiseWithErrorHandling = result\n .then(asyncResult => {\n if (asyncResult !== undefined && !context.terminated) {\n context.results.push(asyncResult as R);\n }\n return asyncResult;\n })\n .catch(error => {\n // 🆕 Non-blocking async handler error collection\n const handlerError = handleExecutionError(error, registration);\n errors.push({\n handlerId: handlerError.handlerId,\n error: handlerError.error,\n timestamp: handlerError.timestamp,\n severity: 'non-blocking'\n });\n return undefined; // Return undefined for failed non-blocking handlers\n });\n \n nonBlockingPromises.push(promiseWithErrorHandling);\n } else if (result !== undefined && !context.terminated) {\n // Non-blocking sync: Immediately collect result\n context.results.push(result as R);\n }\n }\n\n /** Check if pipeline was terminated by controller.return() */\n if (context.terminated) {\n break;\n }\n\n /** Handle jump to priority AFTER handler execution */\n if (context.jumpToPriority !== undefined) {\n // Check if we've exceeded maximum jumps to prevent infinite loops\n context.jumpCount = (context.jumpCount || 0) + 1;\n if (context.jumpCount > (context.maxJumps || 10)) {\n console.error(\n `[ActionRegister] ERROR: Maximum jump limit (${context.maxJumps || 10}) exceeded. ` +\n `Aborting to prevent infinite loop. Check your jumpToPriority logic and conditions.`\n );\n context.aborted = true;\n context.abortReason = `Maximum jump limit exceeded (${context.jumpCount} jumps)`;\n context.jumpToPriority = undefined;\n break;\n }\n\n // Find first handler with priority <= jumpToPriority\n const jumpIndex = context.handlers.findIndex(\n handler => (handler.config.priority || 0) <= context.jumpToPriority!\n );\n\n if (jumpIndex !== -1 && jumpIndex !== i) {\n if (jumpIndex < i) {\n // ⚠️ WARNING: Backward jump detected - risk of infinite loop!\n // Only allow backward jumps if handler has condition to prevent infinite loops\n const targetHandler = context.handlers[jumpIndex];\n if (targetHandler && !targetHandler.config.condition) {\n console.warn(\n `[ActionRegister] WARNING: Backward jumpToPriority to handler '${targetHandler.config.id || 'unnamed'}' without condition. ` +\n `This may cause infinite loops! Consider adding a condition to prevent re-execution. ` +\n `Jump count: ${context.jumpCount}/${context.maxJumps || 10}`\n );\n }\n }\n\n // Allow both forward and backward jumps\n i = jumpIndex;\n context.jumpToPriority = undefined;\n continue;\n } else {\n // No valid jump target found, or jumping to same handler\n context.jumpToPriority = undefined;\n i++;\n }\n } else {\n i++;\n }\n\n } catch (error: any) {\n // 🔧 Fix: Handle errors gracefully and continue pipeline execution\n const handlerError = handleExecutionError(error, registration);\n errors.push(handlerError);\n\n // 🔧 Fix: Only fail pipeline for blocking handlers, let non-blocking continue\n if (registration.config.blocking) {\n throw handlerError.error;\n }\n\n // For non-blocking handlers, continue to next handler\n i++;\n }\n }\n \n // 🆕 Wait for all non-blocking promises with error collection\n if (nonBlockingPromises.length > 0) {\n await Promise.allSettled(nonBlockingPromises);\n }\n\n // 🔧 Store collected errors in context for ExecutionResult with proper typing\n if (errors.length > 0) {\n // Convert to proper HandlerError format\n const handlerErrors: HandlerError[] = errors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n timestamp: err.timestamp,\n severity: 'non-blocking' as const\n }));\n \n // Add to context with proper typing\n (context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] }).collectedErrors = handlerErrors;\n }\n}\n\n/**\n * Execute handlers in parallel mode (all at once)\n * \n * Executes all qualifying action handlers simultaneously using Promise.allSettled.\n * Supports both blocking and non-blocking handlers. Blocking handlers can still\n * fail the entire pipeline if they throw errors.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When any blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#parallel-execution\n * \n * @public\n */\nexport async function executeParallel<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n /** All handlers are runnable */\n const runnableHandlers = context.handlers;\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const controller = createController(registration, _index);\n\n try {\n // 🔧 Fix: Check handler condition before execution\n if (registration.config.condition) {\n try {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n // Return a skipped result for conditions that don't pass\n return {\n success: true,\n handlerId: registration.id,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n } catch {\n // If condition function throws, skip the handler\n return {\n success: true,\n handlerId: registration.id,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n }\n\n const result = registration.handler(context.payload, controller);\n \n let handlerResult: R | undefined;\n if (result instanceof Promise) {\n const resolved = await result;\n handlerResult = resolved as R | undefined;\n } else {\n handlerResult = result as R | undefined;\n }\n \n /** Collect result if handler returned something and pipeline wasn't terminated */\n if (handlerResult !== undefined && !context.terminated) {\n context.results.push(handlerResult);\n }\n \n return { \n success: true, \n handlerId: registration.id, \n result: handlerResult,\n terminated: context.terminated \n };\n \n } catch (error: any) {\n // 🆕 Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n \n if (handlerError.severity === 'blocking') {\n throw handlerError.error;\n }\n \n return { success: false, handlerId: registration.id, error: handlerError.error };\n }\n });\n\n /** Wait for all handlers to complete */\n const results = await Promise.allSettled(handlerPromises);\n \n /** Check for any rejected blocking handlers */\n const failures = results.filter((result, index) => {\n if (result.status === 'rejected') {\n const registration = runnableHandlers[index];\n return registration?.config.blocking ?? false;\n }\n return false;\n });\n\n if (failures.length > 0) {\n const firstFailure = failures[0] as PromiseRejectedResult;\n throw firstFailure.reason;\n }\n\n /** Check if any handler terminated the pipeline */\n const terminatedResults = results.filter(result => \n result.status === 'fulfilled' && result.value.terminated\n );\n \n if (terminatedResults.length > 0) {\n context.terminated = true;\n // In parallel mode, we can't determine which handler's termination result to use,\n // so we use the first one that terminated\n const firstTerminated = terminatedResults[0] as PromiseFulfilledResult<any>;\n context.terminationResult = firstTerminated.value.result;\n }\n}\n\n/**\n * Execute handlers in race mode (first to complete wins)\n * \n * Executes all qualifying handlers simultaneously using Promise.race, where\n * the first handler to complete determines the pipeline result. Other handlers\n * are effectively cancelled. Useful for scenarios where you want the fastest\n * response from multiple equivalent handlers.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When the winning handler fails and is blocking\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#race-execution\n * \n * @public\n */\nexport async function executeRace<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n /** All handlers are runnable */\n const runnableHandlers = context.handlers;\n\n if (runnableHandlers.length === 0) {\n return;\n }\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const controller = createController(registration, _index);\n\n try {\n // 🔧 Fix: Check handler condition before execution\n if (registration.config.condition) {\n try {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n // Return a skipped result for conditions that don't pass\n return {\n success: true,\n handlerId: registration.id,\n registration,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n } catch {\n // If condition function throws, skip the handler\n return {\n success: true,\n handlerId: registration.id,\n registration,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n }\n\n const result = registration.handler(context.payload, controller);\n \n let handlerResult: R | undefined;\n if (result instanceof Promise) {\n const resolved = await result;\n handlerResult = resolved as R | undefined;\n } else {\n handlerResult = result as R | undefined;\n }\n \n return { \n success: true, \n handlerId: registration.id, \n registration,\n result: handlerResult,\n terminated: context.terminated\n };\n \n } catch (error: any) {\n // 🆕 Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n return { success: false, handlerId: registration.id, error: handlerError.error, registration };\n }\n });\n\n /** Race all handlers */\n const winner = await Promise.race(handlerPromises);\n\n /** If the winner failed and was blocking, throw the error */\n if (!winner.success && winner.registration?.config.blocking) {\n throw winner.error;\n }\n\n /** Collect result from the winning handler */\n if (winner.success && winner.result !== undefined) {\n context.results.push(winner.result);\n }\n\n /** Check if the winning handler terminated the pipeline */\n if (winner.success && winner.terminated) {\n context.terminated = true;\n context.terminationResult = winner.result;\n }\n}","/**\n * @fileoverview Action Guard system for debouncing, throttling and blocking\n * \n * Provides rate limiting and user experience optimization for actions through\n * debouncing (wait for pause) and throttling (limit frequency) mechanisms.\n * Used internally by ActionRegister to control action execution timing.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n */\n\n\n/**\n * Action guard state tracking for debouncing and throttling\n * \n * Tracks timing and execution state for action execution control.\n * Maintains separate state for each action to enable independent\n * rate limiting per action type.\n * \n * @internal\n */\ninterface GuardState {\n /** Timestamp of last successful execution for throttling calculations */\n lastExecuted: number;\n \n /** Active debounce timer - cleared when new debounce requests arrive */\n debounceTimer: NodeJS.Timeout | undefined;\n \n /** Active throttle timer - tracks when throttle period will end */\n throttleTimer: NodeJS.Timeout | undefined;\n \n /** Flag indicating if action is currently in throttled state */\n isThrottled: boolean;\n \n /** Current debounce promise - reused for concurrent calls */\n debouncePromise: Promise<boolean> | undefined;\n \n /** Resolve function for current debounce promise */\n debounceResolve: ((value: boolean) => void) | undefined;\n}\n\n/**\n * Action Guard system for managing action execution timing\n * \n * Provides performance optimization and user experience enhancement through\n * debouncing and throttling mechanisms. Debouncing waits for a pause in calls\n * before executing, while throttling limits execution frequency.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @example Manual Usage (Advanced)\n * ```typescript\n * const guard = new ActionGuard()\n * \n * // Manual debouncing\n * if (await guard.debounce('search', 300)) {\n * performSearch() // Only executes after 300ms pause\n * }\n * \n * // Manual throttling\n * if (guard.throttle('scroll', 100)) {\n * updateUI() // Max once per 100ms\n * }\n * ```\n * \n * @internal\n */\nexport class ActionGuard {\n private guards = new Map<string, GuardState>();\n private cleanupInterval: NodeJS.Timeout | undefined;\n private readonly maxIdleTime: number = 60000; // 1 minute\n private readonly cleanupIntervalMs: number = 30000; // 30 seconds\n\n constructor(autoCleanup: boolean = true) {\n if (autoCleanup) {\n this.startAutoCleanup();\n }\n }\n\n /**\n * Start automatic cleanup of idle guard states\n * \n * @internal\n */\n private startAutoCleanup(): void {\n this.cleanupInterval = setInterval(() => {\n const now = Date.now();\n const keysToDelete: string[] = [];\n \n // Collect keys to delete (avoid modifying map during iteration)\n this.guards.forEach((state, key) => {\n const isIdle = now - state.lastExecuted > this.maxIdleTime;\n const hasActiveTimers = state.debounceTimer || state.throttleTimer;\n \n if (isIdle && !hasActiveTimers) {\n keysToDelete.push(key);\n }\n });\n \n // Batch delete idle guards\n if (keysToDelete.length > 0) {\n keysToDelete.forEach(key => this.guards.delete(key));\n // Optional debug logging for cleanup\n if (typeof process !== 'undefined' && process.env?.DEBUG_CONTEXT_ACTION) {\n console.debug(`[ActionGuard] Cleaned up ${keysToDelete.length} idle guards`);\n }\n }\n }, this.cleanupIntervalMs);\n }\n\n /**\n * Apply debouncing to an action\n * \n * Debouncing waits for a specified delay after the last call before allowing\n * execution. Each new call resets the timer. Useful for search inputs, resize\n * handlers, and other high-frequency user interactions.\n * \n * @param actionKey - Unique identifier for the action being debounced\n * @param debounceMs - Delay in milliseconds to wait after the last call\n * \n * @returns Promise resolving to true if execution should proceed, false if cancelled\n * \n * @example Search Input Debouncing\n * ```typescript\n * // Only search after user stops typing for 300ms\n * if (await guard.debounce('userSearch', 300)) {\n * performSearch(query)\n * }\n * ```\n * \n * @internal\n */\n async debounce(actionKey: string, debounceMs: number): Promise<boolean> {\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastExecuted: 0,\n isThrottled: false,\n debounceTimer: undefined as NodeJS.Timeout | undefined,\n throttleTimer: undefined as NodeJS.Timeout | undefined,\n debouncePromise: undefined as Promise<boolean> | undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n };\n this.guards.set(actionKey, state);\n }\n\n /** Clear any existing debounce timer to restart the delay period */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Resolve previous debounce with false if exists\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined as ((value: boolean) => void) | undefined;\n }\n }\n\n /** Create new debounce promise */\n return new Promise<boolean>((resolve) => {\n // Store new resolve function\n state!.debounceResolve = resolve;\n \n // Set new timer\n state!.debounceTimer = setTimeout(() => {\n /** Clean up timer and resolver references */\n state!.debounceTimer = undefined as NodeJS.Timeout | undefined;\n state!.debounceResolve = undefined as ((value: boolean) => void) | undefined;\n /** Update last execution timestamp */\n state!.lastExecuted = Date.now();\n resolve(true);\n }, debounceMs);\n });\n }\n\n /**\n * Apply throttling to an action\n * \n * Throttling limits execution frequency by ensuring a minimum interval between\n * calls. Unlike debouncing, throttling executes immediately on the first call\n * and then blocks subsequent calls until the interval expires.\n * \n * @param actionKey - Unique identifier for the action being throttled\n * @param throttleMs - Minimum interval in milliseconds between executions\n * \n * @returns True if execution should proceed, false if currently throttled\n * \n * @example Scroll Handler Throttling\n * ```typescript\n * // Update scroll position max once per 100ms\n * if (guard.throttle('scrollUpdate', 100)) {\n * updateScrollPosition()\n * }\n * ```\n * \n * @internal\n */\n throttle(actionKey: string, throttleMs: number): boolean {\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastExecuted: 0,\n isThrottled: false,\n debounceTimer: undefined as NodeJS.Timeout | undefined,\n throttleTimer: undefined as NodeJS.Timeout | undefined,\n debouncePromise: undefined as Promise<boolean> | undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n };\n this.guards.set(actionKey, state);\n }\n\n const now = Date.now();\n const timeSinceLastExecution = now - state.lastExecuted;\n\n /** Check if enough time has passed since last execution */\n /** If throttle period has elapsed, allow immediate execution */\n if (timeSinceLastExecution >= throttleMs) {\n /** Update execution timestamp and clear throttled state */\n state.lastExecuted = now;\n state.isThrottled = false;\n \n \n return true;\n }\n\n /** If already in throttled state, don't create duplicate timers */\n /** This prevents timer accumulation and unnecessary processing */\n if (state.isThrottled) {\n return false;\n }\n\n /** Set throttle timer to automatically clear the throttled state */\n /** Calculate remaining time until throttle period expires */\n state.isThrottled = true;\n const remainingTime = throttleMs - timeSinceLastExecution;\n \n /** Create timer to reset throttled state when period expires */\n state.throttleTimer = setTimeout(() => {\n /** Clear throttled state and timer reference */\n state!.isThrottled = false;\n state!.throttleTimer = undefined as NodeJS.Timeout | undefined;\n }, remainingTime);\n\n\n return false;\n }\n\n /**\n * Clear all guard state for a specific action\n * \n * Removes debounce and throttle timers for the specified action,\n * preventing memory leaks and allowing immediate re-execution.\n * \n * @param actionKey - Action identifier to clear guards for\n * \n * @internal\n */\n clearGuards(actionKey: string): void {\n const state = this.guards.get(actionKey);\n if (state) {\n // Clear debounce timer and cancel pending promises to prevent memory leaks\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined;\n }\n state.debounceTimer = undefined;\n }\n \n // Clear throttle timer to prevent memory leaks\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n state.throttleTimer = undefined;\n }\n \n \n // Remove guard state from memory\n this.guards.delete(actionKey);\n }\n }\n\n /**\n * Clear all guard states for all actions\n * \n * Removes all active debounce and throttle timers, useful for cleanup\n * when shutting down the action system or resetting state.\n * \n * @internal\n */\n clearAll(): void {\n \n /** Iterate through all guard states and clear their timers */\n /** This prevents memory leaks when clearing the entire guard system */\n this.guards.forEach((state) => {\n /** Clear any active debounce timers */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Cancel waiting debounce calls\n if (state.debounceResolve) {\n state.debounceResolve(false);\n }\n }\n /** Clear any active throttle timers */\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n }\n });\n \n /** Remove all guard states from memory */\n this.guards.clear();\n }\n\n /**\n * Get current guard state for debugging purposes\n * \n * Returns the internal state for a specific action, including timer\n * information and execution timestamps.\n * \n * @param actionKey - Action identifier to inspect\n * @returns Guard state or undefined if no state exists\n * \n * @internal\n */\n getGuardState(actionKey: string): GuardState | undefined {\n return this.guards.get(actionKey);\n }\n\n /**\n * Get all active guard states for debugging purposes\n * \n * Returns a copy of all current guard states, useful for monitoring\n * and debugging rate limiting behavior across all actions.\n * \n * @returns Map of action keys to their guard states\n * \n * @internal\n */\n getAllGuardStates(): Map<string, GuardState> {\n return new Map(this.guards);\n }\n\n /**\n * 🆕 Explicit destroy method for comprehensive cleanup\n * \n * Cleans up all timers, promises, and intervals to prevent memory leaks.\n * Should be called when ActionGuard is no longer needed.\n * \n * @internal\n */\n destroy(): void {\n // Stop auto cleanup interval\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined as NodeJS.Timeout | undefined;\n }\n \n // Clear all existing guards\n this.clearAll();\n }\n\n /**\n * 🆕 Get statistics about active guards\n * \n * @returns Statistics about guard usage\n * \n * @internal\n */\n getStats(): { activeGuards: number; withTimers: number } {\n let withTimers = 0;\n this.guards.forEach(state => {\n if (state.debounceTimer || state.throttleTimer) {\n withTimers++;\n }\n });\n \n return {\n activeGuards: this.guards.size,\n withTimers\n };\n }\n}","/**\n * 동시성 문제 해결을 위한 작업 큐 시스템\n * \n * 모든 상태 변경 작업을 직렬화하여 race condition을 방지합니다.\n */\n\nexport interface QueuedOperation<T = any> {\n id: string;\n operation: () => T | Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n priority?: number;\n timestamp: number;\n}\n\n/**\n * 작업 큐 관리자\n *\n * 핵심 기능:\n * 1. 작업 직렬화 - 모든 작업을 순서대로 실행\n * 2. 우선순위 지원 - 중요한 작업 우선 처리\n * 3. 에러 처리 - 개별 작업 실패가 전체에 영향 주지 않음\n * 4. 메모리 관리 - 완료된 작업 자동 정리\n * 5. 🆕 동시성 제어 - maxConcurrency로 동시 실행 제한\n * 6. 🆕 비동기 지원 - Promise.all() 완벽 지원\n * 7. 🆕 이벤트 기반 처리 - 효율적인 큐 처리 시스템\n */\nexport class OperationQueue {\n private queue: QueuedOperation[] = [];\n private processingPromise: Promise<void> | null = null;\n private operationCounter = 0;\n \n // 🆕 Concurrency control\n private activeOperations = 0;\n private readonly maxConcurrency: number;\n \n constructor(\n private name: string = 'OperationQueue', \n maxConcurrency: number = 1\n ) {\n this.maxConcurrency = Math.max(1, maxConcurrency);\n }\n\n /**\n * 작업을 큐에 추가하고 실행 결과를 반환\n * \n * @param operation 실행할 작업\n * @param priority 우선순위 (높을수록 먼저 실행)\n * @returns Promise로 래핑된 작업 결과\n */\n enqueue<T>(operation: () => T | Promise<T>, priority: number = 0): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const queuedOperation: QueuedOperation<T> = {\n id: `${this.name}-${++this.operationCounter}`,\n operation,\n resolve,\n reject,\n priority,\n timestamp: Date.now()\n };\n\n\n // 우선순위에 따라 삽입 위치 결정 (높은 우선순위가 앞쪽)\n let insertIndex = this.queue.length;\n for (let i = 0; i < this.queue.length; i++) {\n const item = this.queue[i];\n // 현재 아이템의 우선순위가 새 아이템보다 낮으면, 새 아이템을 앞에 삽입\n if (item && (item.priority || 0) < priority) {\n insertIndex = i;\n break;\n }\n }\n\n this.queue.splice(insertIndex, 0, queuedOperation);\n\n // 큐 처리 시작 (이미 처리 중이면 무시됨)\n if (this.processingPromise) {\n // 이미 처리 중이라면, 대기 중인 프로세스에게 새로운 작업이 추가되었음을 알림\n this.notifyNewOperation();\n }\n this.processQueue();\n });\n }\n\n /**\n * 🆕 큐 처리 메인 로직 - 동시성 제어 및 비동기 지원\n *\n * 주요 특징:\n * - maxConcurrency에 따라 동시 실행 작업 수를 제한하여 동시성 문제 방지\n * - Promise.all() 시나리오에서 완벽한 순차적 실행 보장\n * - 이벤트 기반 알림 시스템으로 효율적인 비동기 처리\n * - 작업 완료 시 대기 중인 프로세스에게 자동 알림\n */\n private async processQueue(): Promise<void> {\n if (this.processingPromise) {\n return this.processingPromise;\n }\n\n this.processingPromise = this._doProcess();\n try {\n await this.processingPromise;\n } finally {\n this.processingPromise = null;\n }\n }\n \n private async _doProcess(): Promise<void> {\n while (this.queue.length > 0 || this.activeOperations > 0) {\n // 🆕 동시성 제어: maxConcurrency 만큼만 동시 실행\n while (this.queue.length > 0 && this.activeOperations < this.maxConcurrency) {\n const operation = this.queue.shift()!;\n\n // 🆕 비동기 작업 실행 (await를 사용하지 않음 - 병렬 실행을 위해)\n this.startOperation(operation);\n }\n\n // 🆕 실행 중인 작업이 있으면 하나가 완료될 때까지 대기\n if (this.activeOperations > 0) {\n await this.waitForAnyOperation();\n }\n }\n }\n\n /**\n * 🆕 개별 작업을 시작하고 완료를 추적\n */\n private startOperation<T>(operation: QueuedOperation<T>): void {\n this.activeOperations++;\n\n // 비동기로 작업 실행\n this.executeOperation(operation)\n .finally(() => {\n this.activeOperations--;\n\n // 대기 중인 프로세스에게 신호 보내기\n this.notifyOperationComplete();\n });\n }\n\n private pendingResolvers: Array<() => void> = [];\n\n /**\n * 🆕 하나의 작업이 완료될 때까지 대기하거나 새로운 작업이 추가될 때까지 대기\n */\n private waitForAnyOperation(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.pendingResolvers.push(resolve);\n });\n }\n\n /**\n * 🆕 작업 완료 신호 - 대기 중인 프로세스들에게 알림\n */\n private notifyOperationComplete(): void {\n // 대기 중인 모든 리졸버를 깨우기\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * 🆕 새로운 작업 추가 신호 - processQueue에서 호출\n */\n private notifyNewOperation(): void {\n // 새로운 작업이 추가되었으므로 대기 중인 프로세스를 깨워서 다시 확인하도록 함\n this.notifyOperationComplete();\n }\n \n /**\n * 🆕 개별 작업 실행 로직\n */\n private async executeOperation<T>(operation: QueuedOperation<T>): Promise<void> {\n try {\n // 작업 실행 (동기/비동기 모두 지원)\n const result = await Promise.resolve(operation.operation());\n operation.resolve(result);\n } catch (error) {\n // 개별 작업 실패는 전체 큐에 영향 주지 않음\n operation.reject(error);\n }\n }\n\n /**\n * 🆕 현재 큐 상태 조회 (디버깅용) - 동시성 정보 포함\n */\n getQueueInfo() {\n return {\n name: this.name,\n queueLength: this.queue.length,\n isProcessing: Boolean(this.processingPromise),\n activeOperations: this.activeOperations,\n maxConcurrency: this.maxConcurrency,\n operations: this.queue.map(op => ({\n id: op.id,\n priority: op.priority,\n timestamp: op.timestamp\n }))\n };\n }\n \n /**\n * 🆕 동시성 설정 조회\n */\n getConcurrencyInfo() {\n return {\n maxConcurrency: this.maxConcurrency,\n activeOperations: this.activeOperations,\n availableSlots: this.maxConcurrency - this.activeOperations,\n queuedOperations: this.queue.length,\n efficiency: this.activeOperations / this.maxConcurrency\n };\n }\n\n /**\n * 큐 비우기 (테스트용)\n */\n clear(): void {\n // 대기 중인 작업들에게 취소 알림\n this.queue.forEach(operation => {\n operation.reject(new Error('Queue cleared'));\n });\n\n this.queue = [];\n this.processingPromise = null;\n\n // 대기 중인 리졸버들도 정리\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * 큐 크기 조회\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * 처리 중 여부 조회 \n */\n get processing(): boolean {\n return Boolean(this.processingPromise);\n }\n}","\nimport {\n ActionPayloadMap,\n ActionHandler,\n HandlerConfig,\n HandlerRegistration,\n PipelineContext,\n PipelineController,\n ActionRegisterConfig,\n UnregisterFunction,\n ExecutionMode,\n ExecutionResult,\n ActionRegistryInfo,\n ActionHandlerStats,\n DispatchOptions,\n HandlerError,\n} from './types.js';\nimport { executeSequential, executeParallel, executeRace } from './execution-modes.js';\nimport { ActionGuard } from './action-guard.js';\nimport { OperationQueue } from './concurrency/OperationQueue.js';\n\n/**\n * Action Register for managing action handlers with priority-based execution\n * \n * Central action registration and dispatch system providing type-safe action pipeline management.\n * Supports sequential, parallel, and race execution modes with advanced handler filtering,\n * throttling, debouncing, and comprehensive result collection.\n * \n * @template TActionMap - Action payload mapping interface extending ActionPayloadMap\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/register-delegation\n * \n * @public\n */\nexport class ActionRegister<T extends ActionPayloadMap = ActionPayloadMap> {\n private pipelines = new Map<keyof T, Array<HandlerRegistration<any, any>>>();\n private readonly actionGuard: ActionGuard;\n private executionMode: ExecutionMode = 'sequential';\n private actionExecutionModes = new Map<keyof T, ExecutionMode>();\n \n // 🆕 Advanced unregister function management system\n private unregisterFunctions = new Map<string, UnregisterFunction>();\n\n // 🔧 Fix: Track last registration timestamps for getActionStats\n private lastRegisteredTimestamps = new Map<keyof T, Date>();\n \n public readonly name: string;\n private readonly registryConfig: ActionRegisterConfig['registry'];\n\n // 🆕 Performance optimizations\n private readonly isDebugMode: boolean;\n private readonly maxHandlersPerAction: number;\n\n // 🆕 동시성 문제 해결을 위한 큐 시스템 (conditional)\n private dispatchQueue?: OperationQueue;\n\n // 🧠 Filter cache disabled to prevent memory issues - direct filtering only\n private filterCacheDisabled = true;\n\n // 🔧 Performance optimization: Fast handler ID generation counter\n private handlerIdCounter = 0;\n\n // 🔧 Performance optimization: PipelineController pool for object reuse\n private controllerPool: PipelineController<any, any>[] = [];\n private readonly maxControllerPoolSize = 10;\n\n constructor(config: ActionRegisterConfig = {}) {\n this.name = config.name || 'ActionRegister';\n this.registryConfig = config.registry;\n this.maxHandlersPerAction = config.registry?.maxHandlersPerAction ?? 1000;\n \n // 🆕 Environment variable check cached (performance optimization)\n this.isDebugMode = Boolean(\n this.registryConfig?.debug && \n process.env.NODE_ENV === 'development'\n );\n \n // Guard creation with improved cleanup handling\n this.actionGuard = new ActionGuard(this.registryConfig?.autoCleanup !== false);\n \n // 🆕 Conditional queue system initialization\n if (config.registry?.useConcurrencyQueue !== false) {\n this.dispatchQueue = new OperationQueue(`${this.name}-Dispatch`);\n }\n \n if (this.registryConfig?.defaultExecutionMode) {\n this.executionMode = this.registryConfig.defaultExecutionMode;\n }\n \n this.log('ActionRegister initialized', {\n defaultExecutionMode: this.executionMode,\n autoCleanup: this.registryConfig?.autoCleanup !== false,\n concurrencyQueue: Boolean(this.dispatchQueue),\n debugMode: this.isDebugMode\n });\n }\n\n /**\n * Register an action handler with optional configuration\n * \n * @param action - The action type to register handler for\n * @param handler - The handler function to execute\n * @param config - Optional handler configuration including priority, tags, etc.\n * \n * @returns Unregister function to remove this handler\n * \n * @throws {Error} When maximum handlers limit is reached\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n register<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig = {}\n ): UnregisterFunction {\n // 🔄 임시로 기존 구현 유지하되 개선된 방식 적용\n // 동기적 API를 유지하면서 내부적으로만 동시성 보호\n \n // 🆕 Optimized handler ID generation\n const handlerId = config.id || this.generateHandlerId(action);\n \n // 🆕 Direct synchronous registration\n const unregisterFn = this._performRegistrationSync(action, handler, config, handlerId);\n \n return unregisterFn;\n }\n\n /**\n * 🆕 Unified logging method with cached debug mode check\n */\n private log(message: string, data?: unknown, level: 'log' | 'warn' | 'error' = 'log') {\n if (this.isDebugMode) {\n const timestamp = new Date().toISOString();\n console[level](`🎯 [${timestamp}] [${this.name}] ${message}`, data || '');\n }\n }\n\n /**\n * 🔧 Generate unique handler ID using optimized counter-based approach\n */\n private generateHandlerId<K extends keyof T>(action: K): string {\n // 🔧 Performance: Use simple counter instead of crypto.randomUUID()\n // This is safe for single-process apps and ~70% faster\n return `${String(action)}_${this.name}_${++this.handlerIdCounter}`;\n }\n\n /**\n * 🔧 Create and merge AbortSignal instances with proper cleanup\n * \n * @param options Dispatch options containing signal and autoAbort configuration\n * @returns [effectiveSignal, autoAbortController, cleanupFunction]\n */\n private createAbortSignal(options?: DispatchOptions): [\n AbortSignal | undefined, \n AbortController | undefined, \n () => void\n ] {\n const signals: AbortSignal[] = [];\n const cleanups: (() => void)[] = [];\n let autoAbortController: AbortController | undefined;\n\n // Add existing signal if provided\n if (options?.signal) {\n signals.push(options.signal);\n }\n\n // Create auto-abort controller if enabled\n if (options?.autoAbort?.enabled) {\n autoAbortController = new AbortController();\n signals.push(autoAbortController.signal);\n }\n\n // No signals to merge\n if (signals.length === 0) {\n return [undefined, autoAbortController, () => {}];\n }\n\n // Single signal - no merge needed\n if (signals.length === 1) {\n return [signals[0], autoAbortController, () => cleanups.forEach(c => c())];\n }\n\n // Multiple signals - use AbortSignal.any() if available, fallback to manual merge\n let effectiveSignal: AbortSignal;\n \n if (typeof AbortSignal.any === 'function') {\n // Modern browsers with AbortSignal.any()\n effectiveSignal = AbortSignal.any(signals);\n } else {\n // Fallback: Create controller and link all signals\n const mergedController = new AbortController();\n effectiveSignal = mergedController.signal;\n \n signals.forEach(signal => {\n if (signal.aborted) {\n mergedController.abort();\n } else {\n const abortHandler = () => mergedController.abort();\n signal.addEventListener('abort', abortHandler, { once: true });\n cleanups.push(() => signal.removeEventListener('abort', abortHandler));\n }\n });\n }\n\n const cleanup = () => {\n cleanups.forEach(c => {\n try {\n c();\n } catch (error) {\n this.log('Cleanup error during AbortSignal cleanup', error, 'warn');\n }\n });\n };\n\n return [effectiveSignal, autoAbortController, cleanup];\n }\n\n /**\n * 🆕 Perform synchronous handler registration\n */\n private _performRegistrationSync<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig,\n handlerId: string\n ): UnregisterFunction {\n // Create handler registration with defaults\n const registration: HandlerRegistration<T[K], R> = {\n handler,\n config: {\n priority: config.priority ?? 0,\n id: handlerId,\n blocking: config.blocking ?? false,\n once: config.once ?? false,\n debounce: config.debounce ?? undefined,\n throttle: config.throttle ?? undefined,\n replaceExisting: config.replaceExisting ?? true, // 🔧 Fix: Default to true for backward compatibility\n cleanup: config.cleanup, // 🔧 Preserve cleanup function from config\n condition: config.condition, // 🔧 Fix: Preserve condition function from config\n } as Required<HandlerConfig>,\n id: handlerId,\n };\n \n // Initialize pipeline if it doesn't exist\n if (!this.pipelines.has(action)) {\n this.pipelines.set(action, []);\n }\n\n const pipeline = this.pipelines.get(action)!;\n \n // Check handler limit\n if (pipeline.length >= this.maxHandlersPerAction) {\n console.warn(`Handler limit (${this.maxHandlersPerAction}) reached for action \"${String(action)}\". Registration ignored.`);\n return () => {}; // No-op unregister\n }\n const existingIndex = pipeline.findIndex(reg => reg.id === handlerId);\n\n // 🆕 Enhanced duplicate ID handling with replaceExisting support and cleanup\n if (existingIndex !== -1) {\n const existing = pipeline[existingIndex];\n const existingUnregister = this.unregisterFunctions.get(handlerId);\n \n if (registration.config.replaceExisting) {\n // 🔧 Fix: Clean up existing handler properly without removing from pipeline\n\n // Call cleanup if available on the old handler\n if (existing && existing.config.cleanup && typeof existing.config.cleanup === 'function') {\n try {\n existing.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error for replaced handler: ${String(action)}`, cleanupError, 'warn');\n }\n }\n\n // Clean up existing unregister function\n if (existingUnregister) {\n this.unregisterFunctions.delete(handlerId);\n }\n\n // Replace existing handler directly in pipeline\n pipeline[existingIndex] = registration;\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // 🔧 Fix: Update last registered timestamp when replacing\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create new unregister function and store it\n const newUnregister = this.createUnregisterFunction(action, handlerId, registration);\n this.unregisterFunctions.set(handlerId, newUnregister);\n \n this.log(`Handler replaced: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length,\n hadExistingUnregister: Boolean(existingUnregister)\n });\n \n return newUnregister;\n } else {\n // Return existing unregister function or create a new one\n // At this point, existing is guaranteed to be defined because we're in the duplicate handler block\n if (!existing) {\n throw new Error('Internal error: existing handler should be defined in duplicate handler block');\n }\n \n this.log(`Handler duplicate ignored, returning existing unregister: ${String(action)}`, {\n handlerId,\n existingPriority: existing.config.priority,\n newPriority: config.priority,\n existingBlocking: existing.config.blocking,\n newBlocking: config.blocking,\n note: 'Use replaceExisting:true to replace'\n }, 'warn');\n \n if (existingUnregister) {\n return existingUnregister;\n } else {\n // Create new unregister function if somehow missing\n const newUnregister = this.createUnregisterFunction(action, handlerId, existing);\n this.unregisterFunctions.set(handlerId, newUnregister);\n return newUnregister;\n }\n }\n }\n \n // Add handler to pipeline\n pipeline.push(registration);\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // 🔧 Fix: Update last registered timestamp\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create and store unregister function\n const unregister = this.createUnregisterFunction(action, handlerId, registration);\n this.unregisterFunctions.set(handlerId, unregister);\n\n this.log(`Handler registered: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length\n });\n\n return unregister;\n }\n\n\n /**\n * Dispatch an action with optional execution options\n * \n * @param action - The action type to dispatch\n * @param payload - The action payload data\n * @param options - Optional dispatch options (execution mode, filters, etc.)\n * \n * @returns Promise that resolves when all handlers complete\n * \n * @throws {Error} When action dispatching fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n async dispatch<K extends keyof T>(\n action: K,\n payload?: T[K],\n options?: DispatchOptions\n ): Promise<void> {\n // 🆕 Conditional queue usage for performance\n if (options?.immediate || !this.dispatchQueue) {\n // Bypass queue for immediate execution or when queues disabled\n return this._performDispatch(action, payload, options);\n } else {\n // Use queue for concurrency protection\n return this.dispatchQueue.enqueue(async () => {\n return this._performDispatch(action, payload, options);\n });\n }\n }\n\n /**\n * 🆕 실제 디스패치 작업 수행 (큐에서 호출됨)\n */\n private async _performDispatch<K extends keyof T>(\n action: K,\n payload?: T[K],\n options?: DispatchOptions\n ): Promise<void> {\n // 🔍 디스패치 시작 디버그\n this.log(`Starting dispatch for action '${String(action)}'`, {\n hasPayload: payload !== undefined,\n payloadType: payload?.constructor?.name || typeof payload,\n options: options ? Object.keys(options) : 'none',\n timestamp: new Date().toISOString()\n });\n \n // Simple Event object detection for development\n if (payload instanceof Event && process.env.NODE_ENV === 'development') {\n console.warn(`Event object passed to action \"${String(action)}\"`, payload.type);\n }\n \n // 🔧 Improved AbortSignal handling with cleaner merge logic\n const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);\n \n if (options?.autoAbort?.onControllerCreated && autoAbortController) {\n options.autoAbort.onControllerCreated(autoAbortController);\n }\n \n // Check if dispatch is aborted before starting\n if (effectiveSignal?.aborted) {\n this.log(`Dispatch aborted before execution for '${String(action)}'`);\n return;\n }\n \n const pipeline = this.pipelines.get(action);\n \n // 🔍 파이프라인 존재 여부 디버그\n this.log(`Pipeline lookup for '${String(action)}'`, {\n pipelineExists: Boolean(pipeline),\n handlersCount: pipeline?.length || 0,\n allRegisteredActions: Array.from(this.pipelines.keys()),\n pipelineMap: Object.fromEntries(Array.from(this.pipelines.entries()).map(([k, v]) => [k, v.length]))\n });\n \n if (!pipeline || pipeline.length === 0) {\n this.log(`No handlers found for action '${String(action)}', dispatch cancelled`, {}, 'warn');\n return;\n }\n\n // 🆕 Optimize filtering - only copy array if filtering is needed\n const filteredHandlers = options?.filter \n ? this.filterHandlers(pipeline, options.filter)\n : pipeline;\n\n // Apply ActionGuard controls - check both dispatch options and handler configs\n const actionKey = String(action);\n \n // Get throttle/debounce settings from dispatch options or handler configs\n let throttleMs: number | undefined;\n let debounceMs: number | undefined;\n \n // Priority: dispatch options > handler config\n if (options?.throttle !== undefined) {\n throttleMs = options.throttle;\n } else if (filteredHandlers.length > 0) {\n // Use throttle from the first handler that has it (handlers are sorted by priority)\n for (const handler of filteredHandlers) {\n if (handler.config.throttle !== undefined) {\n throttleMs = handler.config.throttle;\n break;\n }\n }\n }\n \n if (options?.debounce !== undefined) {\n debounceMs = options.debounce;\n } else if (filteredHandlers.length > 0) {\n // Use debounce from the first handler that has it (handlers are sorted by priority)\n for (const handler of filteredHandlers) {\n if (handler.config.debounce !== undefined) {\n debounceMs = handler.config.debounce;\n break;\n }\n }\n }\n \n // Apply debounce if specified\n if (debounceMs !== undefined) {\n const shouldProceed = await this.actionGuard.debounce(actionKey, debounceMs);\n if (!shouldProceed) {\n return; // Debounced - don't execute\n }\n }\n \n // Apply throttle if specified\n if (throttleMs !== undefined) {\n const shouldProceed = this.actionGuard.throttle(actionKey, throttleMs);\n if (!shouldProceed) {\n return; // Throttled - don't execute\n }\n }\n\n // Determine execution mode for this action (with option override)\n const currentExecutionMode = options?.executionMode || \n this.actionExecutionModes.get(action) || \n this.executionMode;\n\n // Create pipeline execution context\n const context: PipelineContext<T[K], any> = {\n action: String(action),\n payload: payload as T[K],\n handlers: filteredHandlers, // Use filtered handlers\n aborted: false,\n abortReason: undefined as string | undefined,\n currentIndex: 0,\n jumpToPriority: undefined as number | undefined,\n jumpCount: 0,\n maxJumps: 10, // Default max jumps to prevent infinite loops\n executionMode: currentExecutionMode,\n \n // New result collection fields\n results: [],\n terminated: false,\n terminationResult: undefined as any,\n };\n\n \n // Add abort listener if signal provided (use effectiveSignal for auto-abort)\n const abortHandler = effectiveSignal ? () => {\n context.aborted = true;\n context.abortReason = 'Action dispatch aborted by signal';\n } : undefined;\n \n if (effectiveSignal && abortHandler) {\n effectiveSignal.addEventListener('abort', abortHandler);\n }\n \n \n try {\n await this.executePipeline(context, autoAbortController, options?.autoAbort);\n this.log(`Pipeline execution succeeded for ${String(action)}`);\n } catch (error) {\n this.log(`Pipeline execution failed for ${String(action)}`, error, 'error');\n throw error;\n } finally {\n // 🔧 Use cleanup function from createAbortSignal\n cleanup();\n }\n }\n\n /**\n * Dispatch an action and return detailed execution results\n * \n * @param action - The action type to dispatch\n * @param payload - The action payload data\n * @param options - Optional dispatch options including result collection strategy\n * \n * @returns Promise resolving to comprehensive execution results\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n async dispatchWithResult<K extends keyof T, R = void>(\n action: K,\n payload?: T[K],\n options?: DispatchOptions\n ): Promise<ExecutionResult<R>> {\n const _startTime = Date.now();\n \n // 🔧 Improved AbortSignal handling with cleaner merge logic (same as dispatch)\n const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);\n \n if (options?.autoAbort?.onControllerCreated && autoAbortController) {\n options.autoAbort.onControllerCreated(autoAbortController);\n }\n \n // Check if dispatch is aborted before starting\n if (effectiveSignal?.aborted) {\n return {\n success: false,\n aborted: true,\n abortReason: 'Action dispatch aborted by signal',\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: 0,\n handlersExecuted: 0,\n handlersSkipped: 0,\n handlersFailed: 0,\n startTime: _startTime,\n endTime: _startTime,\n },\n handlers: [],\n errors: [],\n };\n }\n \n const pipeline = this.pipelines.get(action);\n \n if (!pipeline || pipeline.length === 0) {\n return {\n success: true,\n aborted: false,\n abortReason: undefined as string | undefined,\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: 0,\n handlersExecuted: 0,\n handlersSkipped: 0,\n handlersFailed: 0,\n startTime: _startTime,\n endTime: _startTime,\n },\n handlers: [],\n errors: [],\n };\n }\n\n // 🆕 Optimize filtering - only copy array if filtering is needed\n const filteredHandlers = options?.filter \n ? this.filterHandlers(pipeline, options.filter)\n : pipeline;\n\n // 🔧 Apply ActionGuard controls using unified method with ExecutionResult return\n const actionKey = String(action);\n const guardResult = await this.applyActionGuardControlsWithResult<R>(\n actionKey, \n filteredHandlers, \n options, \n _startTime, \n pipeline.length\n );\n if (guardResult) {\n return guardResult; // Throttled or debounced - return early with proper result\n }\n\n // Determine execution mode for this action (with option override)\n const currentExecutionMode = options?.executionMode || \n this.actionExecutionModes.get(action) || \n this.executionMode;\n\n // Create pipeline execution context\n const context: PipelineContext<T[K], R> = {\n action: String(action),\n payload: payload as T[K],\n handlers: filteredHandlers,\n aborted: false,\n abortReason: undefined as string | undefined,\n currentIndex: 0,\n jumpToPriority: undefined as number | undefined,\n jumpCount: 0,\n maxJumps: 10, // Default max jumps to prevent infinite loops\n executionMode: currentExecutionMode,\n \n // Result collection fields\n results: [],\n terminated: false,\n terminationResult: undefined as R | undefined,\n };\n\n let executionError: Error | undefined;\n const handlerResults: Array<{\n id: string;\n executed: boolean;\n duration: number | undefined;\n result: R | undefined;\n error: Error | undefined;\n metadata: Record<string, any> | undefined;\n }> = [];\n\n\n // Initialize handler tracking - all handlers start as not executed\n filteredHandlers.forEach(handler => {\n handlerResults.push({\n id: handler.config.id,\n executed: false,\n duration: undefined as number | undefined,\n result: undefined as R | undefined,\n error: undefined as Error | undefined,\n metadata: undefined as Record<string, any> | undefined,\n });\n });\n\n // Add abort listener if signal provided (use effectiveSignal for auto-abort)\n const abortHandler = effectiveSignal ? () => {\n context.aborted = true;\n context.abortReason = 'Action dispatch aborted by signal';\n } : undefined;\n \n if (effectiveSignal && abortHandler) {\n effectiveSignal.addEventListener('abort', abortHandler);\n }\n \n // 🔧 Initialize errors array (will be updated after pipeline execution)\n let errors: HandlerError[] = [];\n \n try {\n await this.executePipeline(context, autoAbortController, options?.autoAbort);\n \n // 🔧 Collect errors from execution context after pipeline execution\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n // Mark executed handlers based on context.currentIndex\n // In sequential mode, handlers 0 to currentIndex were executed\n // In parallel/race mode, all handlers that didn't error were executed\n const executedCount = Math.min(context.currentIndex + (context.aborted ? 0 : 1), filteredHandlers.length);\n for (let i = 0; i < executedCount; i++) {\n const handler = filteredHandlers[i];\n if (!handler) continue;\n const handlerResult = handlerResults.find(hr => hr.id === handler.config.id);\n if (handlerResult) {\n handlerResult.executed = true;\n }\n }\n } catch (error) {\n // 🔧 Collect errors from execution context before adding pipeline error\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n executionError = error instanceof Error ? error : new Error(String(error));\n errors.push({\n handlerId: 'pipeline',\n error: executionError,\n timestamp: Date.now(),\n severity: 'blocking'\n });\n \n // Mark executed handlers even when there's an error\n const executedCount = Math.min(context.currentIndex + 1, filteredHandlers.length);\n for (let i = 0; i < executedCount; i++) {\n const handler = filteredHandlers[i];\n if (!handler) continue;\n const handlerResult = handlerResults.find(hr => hr.id === handler.config.id);\n if (handlerResult) {\n handlerResult.executed = true;\n }\n }\n } finally {\n // 🔧 Use cleanup function from createAbortSignal\n cleanup();\n }\n\n const endTime = Date.now();\n \n // Process results based on options\n const processedResult = this.processResults(context, options?.result);\n\n // 🔧 Type safety: Separate successful results from failed ones\n const successResults = context.results.filter((result): result is R => result !== undefined);\n const failedResults = errors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n expectedType: typeof processedResult\n }));\n\n // Build execution result with improved type safety\n const executionResult: ExecutionResult<R> = {\n success: !executionError && !context.aborted,\n aborted: context.aborted,\n abortReason: context.abortReason,\n terminated: context.terminated,\n result: processedResult,\n successResults: successResults,\n results: context.results,\n failedResults,\n execution: {\n duration: endTime - _startTime,\n handlersExecuted: filteredHandlers.length === 0 ? 0 : context.currentIndex + (context.aborted ? 0 : 1),\n handlersSkipped: Math.max(0, filteredHandlers.length - (context.currentIndex + 1)),\n handlersFailed: errors.length,\n startTime: _startTime,\n endTime,\n },\n handlers: handlerResults,\n errors: errors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n timestamp: err.timestamp,\n severity: 'non-blocking' as const\n })),\n };\n\n /** Clean up one-time handlers after execution */\n this.cleanupOneTimeHandlers(action, context.handlers);\n\n return executionResult;\n }\n\n /**\n * 🔧 Unified method for dispatchWithResult that returns ExecutionResult on guard rejection\n */\n private async applyActionGuardControlsWithResult<R>(\n actionKey: string,\n filteredHandlers: HandlerRegistration<any, any>[],\n options: DispatchOptions | undefined,\n startTime: number,\n pipelineLength: number\n ): Promise<ExecutionResult<R> | null> {\n // Get throttle/debounce settings (same logic as above)\n let throttleMs: number | undefined;\n let debounceMs: number | undefined;\n \n if (options?.throttle !== undefined) {\n throttleMs = options.throttle;\n } else if (filteredHandlers.length > 0) {\n for (const handler of filteredHandlers) {\n if (handler.config.throttle !== undefined) {\n throttleMs = handler.config.throttle;\n break;\n }\n }\n }\n \n if (options?.debounce !== undefined) {\n debounceMs = options.debounce;\n } else if (filteredHandlers.length > 0) {\n for (const handler of filteredHandlers) {\n if (handler.config.debounce !== undefined) {\n debounceMs = handler.config.debounce;\n break;\n }\n }\n }\n \n // Apply debounce if specified\n if (debounceMs !== undefined) {\n const shouldProceed = await this.actionGuard.debounce(actionKey, debounceMs);\n if (!shouldProceed) {\n return {\n success: false,\n aborted: true,\n abortReason: 'Debounced execution',\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: Date.now() - startTime,\n handlersExecuted: 0,\n handlersSkipped: pipelineLength,\n handlersFailed: 0,\n startTime: startTime,\n endTime: Date.now(),\n },\n handlers: [],\n errors: [],\n };\n }\n }\n \n // Apply throttle if specified\n if (throttleMs !== undefined) {\n const shouldProceed = this.actionGuard.throttle(actionKey, throttleMs);\n if (!shouldProceed) {\n return {\n success: false,\n aborted: true,\n abortReason: 'Throttled execution',\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: Date.now() - startTime,\n handlersExecuted: 0,\n handlersSkipped: pipelineLength,\n handlersFailed: 0,\n startTime: startTime,\n endTime: Date.now(),\n },\n handlers: [],\n errors: [],\n };\n }\n }\n\n return null; // No guard intervention, proceed with execution\n }\n\n // Cache methods removed for memory stability\n\n /**\n * 🔧 Generate optimized cache key for filter options\n */\n private generateFilterCacheKey(filterOptions?: DispatchOptions['filter']): string {\n if (!filterOptions) {\n return 'no-filter';\n }\n\n // Use pre-sorted arrays to avoid repeated sorting\n const parts: string[] = [];\n\n if (filterOptions.handlerIds?.length) {\n parts.push(`h:${filterOptions.handlerIds.slice().sort().join(',')}`);\n }\n\n if (filterOptions.excludeHandlerIds?.length) {\n parts.push(`e:${filterOptions.excludeHandlerIds.slice().sort().join(',')}`);\n }\n\n if (filterOptions.priority) {\n const { min, max } = filterOptions.priority;\n if (min !== undefined || max !== undefined) {\n parts.push(`p:${min ?? '*'}-${max ?? '*'}`);\n }\n }\n\n // Custom filters cannot be cached\n if (filterOptions.custom) {\n return 'custom-' + Date.now() + Math.random(); // Unique non-cacheable key\n }\n\n return parts.length > 0 ? parts.join('|') : 'no-filter';\n }\n\n // Cache invalidation removed for memory stability\n\n /**\n * 🔧 Create or reuse PipelineController from pool for better performance\n */\n private getControllerFromPool<K extends keyof T>(\n context: PipelineContext<T[K], any>, \n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean }\n ): PipelineController<T[K], any> {\n // Try to reuse from pool\n let controller = this.controllerPool.pop();\n \n if (!controller) {\n // Create new controller if pool is empty\n controller = {} as PipelineController<T[K], any>;\n }\n\n // Configure/reset the controller for current context\n controller.abort = (reason?: string) => {\n context.aborted = true;\n context.abortReason = reason;\n \n // Auto-abort: Handler can trigger pipeline abort if enabled\n if (autoAbortController && autoAbortOptions?.allowHandlerAbort) {\n autoAbortController.abort(reason);\n }\n };\n\n controller.modifyPayload = (modifier: (payload: T[K]) => T[K]) => {\n try {\n context.payload = modifier(context.payload);\n } catch (modificationError) {\n // 🔧 Fix: Don't let payload modification errors crash the pipeline\n this.log('Payload modification error', modificationError, 'warn');\n // Keep original payload on modification error\n }\n };\n\n controller.getPayload = () => context.payload;\n\n controller.jumpToPriority = (priority: number) => {\n context.jumpToPriority = priority;\n };\n\n controller.return = (result: any) => {\n context.terminated = true;\n context.terminationResult = result;\n };\n\n controller.setResult = (result: any) => {\n context.results.push(result);\n };\n\n controller.getResults = () => {\n return [...context.results];\n };\n\n controller.mergeResult = (merger: (previousResults: any[], currentResult: any) => any) => {\n const currentResult = context.results[context.results.length - 1];\n const previousResults = context.results.slice(0, -1);\n const mergedResult = merger(previousResults, currentResult);\n context.results[context.results.length - 1] = mergedResult;\n };\n\n return controller;\n }\n\n /**\n * 🔧 Return controller to pool for reuse\n */\n private returnControllerToPool(controller: PipelineController<any, any>): void {\n // Only add to pool if we haven't exceeded max size\n if (this.controllerPool.length < this.maxControllerPoolSize) {\n this.controllerPool.push(controller);\n }\n }\n\n private filterHandlers(\n handlers: HandlerRegistration<any, any>[],\n filterOptions?: DispatchOptions['filter']\n ): HandlerRegistration<any, any>[] {\n if (!filterOptions) {\n return handlers;\n }\n\n // Cache disabled for memory stability\n\n // Cache disabled - using direct filtering for memory stability\n\n // Create Sets for fast lookup if arrays are provided\n const handlerIdSet = filterOptions.handlerIds ? new Set(filterOptions.handlerIds) : null;\n const excludeIdSet = filterOptions.excludeHandlerIds ? new Set(filterOptions.excludeHandlerIds) : null;\n\n // Filter handlers with optimized checks\n const filtered = handlers.filter(registration => {\n const config = registration.config;\n\n // Fast Set-based inclusion check\n if (handlerIdSet && !handlerIdSet.has(config.id)) {\n return false;\n }\n\n // Fast Set-based exclusion check\n if (excludeIdSet && excludeIdSet.has(config.id)) {\n return false;\n }\n\n // Priority range check\n if (filterOptions.priority) {\n const priority = config.priority;\n if (filterOptions.priority.min !== undefined && priority < filterOptions.priority.min) {\n return false;\n }\n if (filterOptions.priority.max !== undefined && priority > filterOptions.priority.max) {\n return false;\n }\n }\n\n // Custom filter (not cached)\n if (filterOptions.custom && !filterOptions.custom(config)) {\n return false;\n }\n\n return true;\n });\n\n // Cache disabled for memory stability\n\n return filtered;\n }\n\n private processResults<R>(\n context: PipelineContext<any, R>,\n resultOptions?: DispatchOptions['result']\n ): R | undefined {\n const results = context.results;\n\n // 🔧 Fix: Always handle termination result regardless of collect option\n if (context.terminated && context.terminationResult !== undefined) {\n return context.terminationResult;\n }\n\n // 🔧 Fix: Return undefined only if no results options specified AND no results available\n if (!resultOptions) {\n // If no result options specified but we have results, return the last one\n return results.length > 0 ? results[results.length - 1] : undefined;\n }\n\n // 🔧 Fix: Process results even when collect is false if we have a strategy specified\n if (!resultOptions.collect && !resultOptions.strategy) {\n return undefined;\n }\n\n // Apply maxResults limit\n const limitedResults = resultOptions.maxResults\n ? results.slice(0, resultOptions.maxResults)\n : results;\n\n if (limitedResults.length === 0) {\n return undefined;\n }\n\n // Process results based on strategy\n switch (resultOptions.strategy) {\n case 'first':\n return limitedResults[0];\n case 'last':\n return limitedResults[limitedResults.length - 1];\n case 'all':\n return limitedResults as unknown as R;\n case 'merge':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n // Default merge: return last result\n return limitedResults[limitedResults.length - 1];\n case 'custom':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n throw new Error('Custom result strategy requires a merger function');\n default:\n // 🔧 Fix: If collect is true but no strategy specified, return all results\n if (resultOptions.collect) {\n return limitedResults as unknown as R;\n }\n // Default: return last result if no strategy specified\n return limitedResults[limitedResults.length - 1];\n }\n }\n\n private async executePipeline<K extends keyof T>(\n context: PipelineContext<T[K], any>, \n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean }\n ): Promise<void> {\n const createController = (_registration: HandlerRegistration<T[K], any>, _index: number): PipelineController<T[K], any> => {\n return this.getControllerFromPool(context, autoAbortController, autoAbortOptions);\n };\n\n switch (context.executionMode) {\n case 'sequential':\n await executeSequential<T[K], any>(context, createController);\n break;\n case 'parallel':\n await executeParallel<T[K], any>(context, createController);\n break;\n case 'race':\n await executeRace<T[K], any>(context, createController);\n break;\n default:\n throw new Error(`Unknown execution mode: ${context.executionMode}`);\n }\n\n this.cleanupOneTimeHandlers(context.action as K, context.handlers);\n }\n\n private cleanupOneTimeHandlers<K extends keyof T>(action: K, executedHandlers: HandlerRegistration<any, any>[]): void {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) return;\n\n const oneTimeHandlers = executedHandlers.filter(reg => reg.config.once);\n if (oneTimeHandlers.length === 0) return;\n\n oneTimeHandlers.forEach(registration => {\n const index = pipeline.findIndex(reg => reg.id === registration.id);\n if (index !== -1) {\n pipeline.splice(index, 1);\n\n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 One-time handler removed: ${String(action)}`, {\n handlerId: registration.id,\n remainingHandlers: pipeline.length,\n registry: this.name\n });\n }\n }\n });\n\n // 🔧 Fix: Remove action key from pipelines map when pipeline becomes empty after cleanup\n if (pipeline.length === 0) {\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n }\n }\n\n\n /**\n * Get the number of registered handlers for an action\n * \n * @param action - The action type to count handlers for\n * \n * @returns Number of registered handlers\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getHandlerCount<K extends keyof T>(action: K): number {\n const pipeline = this.pipelines.get(action);\n return pipeline ? pipeline.length : 0;\n }\n\n /**\n * Check if an action has any registered handlers\n * \n * @param action - The action type to check\n * \n * @returns True if action has handlers, false otherwise\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n hasHandlers<K extends keyof T>(action: K): boolean {\n return this.getHandlerCount(action) > 0;\n }\n\n /**\n * Get all registered action types\n * \n * @returns Array of all registered action types\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getRegisteredActions(): (keyof T)[] {\n return Array.from(this.pipelines.keys());\n }\n\n /**\n * Remove all handlers for a specific action\n * \n * @param action - The action type to clear handlers for\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAction<K extends keyof T>(action: K): void {\n this.pipelines.delete(action);\n // 🔧 Fix: Clear last registered timestamp\n this.lastRegisteredTimestamps.delete(action);\n // 🔧 Invalidate filter cache when pipeline changes\n // Cache disabled\n }\n\n /**\n * Remove all handlers for all actions\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAll(): void {\n this.pipelines.clear();\n // 🔧 Fix: Clear all last registered timestamps\n this.lastRegisteredTimestamps.clear();\n // 🔧 Invalidate filter cache when pipeline changes\n // Cache disabled\n }\n\n /**\n * Get the name of this action register\n * \n * @returns The register name\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getName(): string {\n return this.name;\n }\n\n /**\n * Get comprehensive registry information (similar to DeclarativeStoreRegistry pattern)\n * \n * @returns Registry information including actions, handlers, and execution modes\n */\n getRegistryInfo(): ActionRegistryInfo<T> {\n const totalHandlers = Array.from(this.pipelines.values()).reduce(\n (total, pipeline) => total + pipeline.length, \n 0\n );\n \n return {\n name: this.name,\n totalActions: this.pipelines.size,\n totalHandlers,\n registeredActions: Array.from(this.pipelines.keys()),\n actionExecutionModes: new Map(this.actionExecutionModes),\n defaultExecutionMode: this.executionMode,\n };\n }\n\n /**\n * Get detailed statistics for a specific action\n * \n * @param action Action name to get statistics for\n * @returns Detailed handler statistics\n */\n getActionStats<K extends keyof T>(action: K): ActionHandlerStats<T> | null {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) {\n return null;\n }\n\n // Group handlers by priority\n const priorityMap = new Map<number, typeof pipeline>();\n pipeline.forEach(handler => {\n if (!priorityMap.has(handler.config.priority)) {\n priorityMap.set(handler.config.priority, []);\n }\n priorityMap.get(handler.config.priority)!.push(handler);\n });\n\n const handlersByPriority = Array.from(priorityMap.entries())\n .sort(([a], [b]) => b - a) // Sort by priority (highest first)\n .map(([priority, handlers]) => ({\n priority,\n handlers: handlers.map(h => ({\n id: h.config.id,\n }))\n }));\n\n // Execution statistics are no longer tracked\n const executionStats = undefined;\n\n return {\n action,\n handlerCount: pipeline.length,\n totalHandlers: pipeline.length,\n handlersByPriority,\n executionStats,\n lastRegistered: this.lastRegisteredTimestamps.get(action),\n };\n }\n\n /**\n * Get statistics for all registered actions\n * \n * @returns Array of statistics for all actions\n */\n getAllActionStats(): Array<ActionHandlerStats<T>> {\n return Array.from(this.pipelines.keys())\n .map(action => this.getActionStats(action))\n .filter((stats): stats is ActionHandlerStats<T> => stats !== null);\n }\n\n\n /**\n * Set global execution mode for all actions\n * \n * @param mode Execution mode to set\n */\n setExecutionMode(mode: ExecutionMode): void {\n this.executionMode = mode;\n \n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 Global execution mode set to: ${mode}`);\n }\n }\n\n /**\n * Set execution mode for a specific action\n * \n * @param action Action name\n * @param mode Execution mode to set\n */\n setActionExecutionMode<K extends keyof T>(action: K, mode: ExecutionMode): void {\n this.actionExecutionModes.set(action, mode);\n \n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 Execution mode set for action '${String(action)}': ${mode}`);\n }\n }\n\n /**\n * Get execution mode for a specific action\n * \n * @param action Action name\n * @returns Execution mode for the action, or default if not set\n */\n getActionExecutionMode<K extends keyof T>(action: K): ExecutionMode {\n return this.actionExecutionModes.get(action) || this.executionMode;\n }\n\n /**\n * Remove execution mode override for a specific action\n * \n * @param action Action name\n */\n removeActionExecutionMode<K extends keyof T>(action: K): void {\n this.actionExecutionModes.delete(action);\n \n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 Execution mode reset for action '${String(action)}' to default: ${this.executionMode}`);\n }\n }\n\n\n /**\n * Get registry configuration (for debugging and inspection)\n * \n * @returns Current registry configuration\n */\n getRegistryConfig(): ActionRegisterConfig['registry'] {\n return this.registryConfig;\n }\n\n /**\n * Check if registry has debug mode enabled\n * \n * @returns Whether debug mode is enabled\n */\n isDebugEnabled(): boolean {\n return this.isDebugMode;\n }\n\n /**\n * Creates a consistent unregister function for a handler\n * \n * @param action - Action key\n * @param handlerId - Handler identifier\n * @param registration - Handler registration object\n * @returns Unregister function\n * @private\n */\n private createUnregisterFunction<K extends keyof T>(\n action: K,\n handlerId: string,\n registration: HandlerRegistration<any, any>\n ): UnregisterFunction {\n return () => {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) return;\n\n const index = pipeline.findIndex(reg => reg.id === handlerId && reg === registration);\n if (index !== -1) {\n pipeline.splice(index, 1);\n // Cache disabled\n this.unregisterFunctions.delete(handlerId);\n\n // 🔧 Fix: Remove action key from pipelines map when pipeline becomes empty\n if (pipeline.length === 0) {\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n }\n\n // Execute cleanup function if available\n if (registration.config.cleanup && typeof registration.config.cleanup === 'function') {\n try {\n registration.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error during unregister: ${String(action)}`, cleanupError, 'warn');\n }\n }\n\n this.log(`Handler unregistered: ${String(action)}`, {\n handlerId,\n remainingHandlers: pipeline.length,\n actionRemoved: pipeline.length === 0\n });\n }\n };\n }\n\n /**\n * Gets the total count of registered unregister functions\n * \n * @returns Number of unregister functions\n * @public\n */\n getUnregisterFunctionCount(): number {\n return this.unregisterFunctions.size;\n }\n \n /**\n * Checks if an unregister function exists for the given handler ID\n * \n * @param handlerId - Handler identifier to check\n * @returns True if unregister function exists\n * @public\n */\n hasUnregisterFunction(handlerId: string): boolean {\n return this.unregisterFunctions.has(handlerId);\n }\n\n /**\n * 🆕 Destroy method for comprehensive cleanup\n * \n * Cleans up all internal resources including pipelines, guards, queues, and statistics.\n * Should be called when the ActionRegister is no longer needed to prevent memory leaks.\n * \n * @public\n */\n destroy(): void {\n // 🔧 Fix: Clean up resources without calling unregister functions to prevent circular references\n // Clear unregister functions without executing them to avoid potential memory leaks\n this.unregisterFunctions.clear();\n\n // Clean up all pipelines with handler cleanup\n for (const [action, pipeline] of this.pipelines.entries()) {\n for (const registration of pipeline) {\n if (registration.config.cleanup && typeof registration.config.cleanup === 'function') {\n try {\n registration.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error for handler during destroy: ${String(action)}`, cleanupError, 'warn');\n }\n }\n }\n }\n\n // Clean up all pipelines\n this.pipelines.clear();\n\n // 🔧 Fix: Clear all timestamps\n this.lastRegisteredTimestamps.clear();\n\n // Clean up guard system\n this.actionGuard.destroy();\n\n // Clean up queues if they exist\n this.dispatchQueue?.clear?.();\n\n this.actionExecutionModes.clear();\n\n // Cache disabled\n\n // 🔧 Clean up controller pool\n this.controllerPool.length = 0;\n\n this.log('ActionRegister destroyed');\n }\n}","/**\n * @fileoverview React integration helpers for ActionRegister\n * \n * Provides React-specific utilities and hooks for seamless integration\n * with React components and lifecycle management.\n * \n * Note: This file provides utilities for React integration but does not\n * have direct React dependencies. Import React types externally when used.\n */\n\nimport type { \n ActionPayloadMap, \n ActionHandler, \n HandlerConfig,\n UnregisterFunction\n} from './types.js';\nimport type { ActionRegister } from './ActionRegister.js';\n\n/**\n * 🔧 Create action handler registration configuration for React components\n * \n * Creates a configuration object that can be used with React's useEffect to properly\n * register and unregister action handlers with lifecycle management and cleanup.\n * This is NOT a hook - it's a factory function for React hook integration.\n * \n * @template T - ActionPayloadMap type\n * @template K - Action key type\n * \n * @param registry - ActionRegister instance\n * @param action - Action name to register handler for\n * @param handler - Handler function (should be memoized with useCallback)\n * @param config - Handler configuration\n * \n * @returns Configuration object with register/unregister functions\n * \n * @example Basic Usage with useEffect\n * ```tsx\n * import { useCallback, useEffect } from 'react';\n * import { createActionHandler } from '@context-action/core/react-helpers';\n * \n * function MyComponent() {\n * const registry = useActionRegister();\n * \n * const handleUserUpdate = useCallback(async (payload, controller) => {\n * // Handler logic here\n * }, []);\n * \n * useEffect(() => {\n * const { register, unregister } = createActionHandler(\n * registry,\n * 'updateUser',\n * handleUserUpdate,\n * { priority: 10 }\n * );\n * \n * const cleanup = register();\n * return () => {\n * cleanup();\n * unregister();\n * };\n * }, [registry, handleUserUpdate]);\n * }\n * ```\n * \n * @example With Automatic Cleanup\n * ```tsx\n * const [userId, setUserId] = useState('123');\n * \n * const handleUserUpdate = useCallback(async (payload, controller) => {\n * console.log('Updating user:', userId, payload);\n * }, [userId]);\n * \n * useEffect(() => {\n * const handlerManager = createActionHandler(\n * registry,\n * 'updateUser',\n * handleUserUpdate,\n * { priority: 10 }\n * );\n * \n * // Simplified registration with automatic cleanup\n * return handlerManager.registerWithCleanup();\n * }, [registry, handleUserUpdate, userId]);\n * ```\n * \n * @public\n */\nexport function createActionHandler<T extends ActionPayloadMap, K extends keyof T>(\n registry: ActionRegister<T>,\n action: K,\n handler: ActionHandler<T[K]>,\n config?: HandlerConfig\n): {\n register: () => UnregisterFunction;\n unregister: () => void;\n registerWithCleanup: () => () => void;\n config: Required<HandlerConfig>;\n} {\n // Inline React-optimized handler configuration\n const timestamp = Date.now();\n const random = Math.random().toString(36).substr(2, 5);\n \n const finalConfig: Required<HandlerConfig> = {\n priority: config?.priority ?? 0,\n id: config?.id || `react_${String(action)}_${timestamp}_${random}`,\n blocking: config?.blocking ?? false,\n once: config?.once ?? false,\n debounce: config?.debounce ?? undefined,\n throttle: config?.throttle ?? undefined,\n // React-optimized defaults\n replaceExisting: true, // Always replace in React (handles HMR/remounting)\n } as Required<HandlerConfig>;\n let currentUnregister: UnregisterFunction | undefined;\n let isRegistered = false;\n \n return {\n /**\n * Register the handler and return cleanup function\n */\n register(): UnregisterFunction {\n if (isRegistered && currentUnregister) {\n // Clean up previous registration\n currentUnregister();\n }\n \n currentUnregister = registry.register(action, handler, finalConfig);\n isRegistered = true;\n \n return currentUnregister;\n },\n \n /**\n * Unregister the handler if currently registered\n */\n unregister(): void {\n if (isRegistered && currentUnregister) {\n currentUnregister();\n currentUnregister = undefined;\n isRegistered = false;\n }\n },\n \n /**\n * Register and return cleanup function (React useEffect pattern)\n */\n registerWithCleanup(): () => void {\n const unregisterFn = this.register();\n \n return () => {\n unregisterFn();\n this.unregister();\n };\n },\n \n config: finalConfig\n };\n}\n\n\n/**\n * 🆕 React development utilities\n * \n * Provides debugging and development helpers specifically for React environments.\n */\nexport const ReactDevUtils = {\n /**\n * Enable detailed React integration debugging\n */\n enableDebugMode(): void {\n if (typeof window !== 'undefined') {\n (window as any).__CONTEXT_ACTION_REACT_DEBUG__ = true;\n }\n },\n\n /**\n * Disable React integration debugging\n */\n disableDebugMode(): void {\n if (typeof window !== 'undefined') {\n (window as any).__CONTEXT_ACTION_REACT_DEBUG__ = false;\n }\n },\n\n /**\n * Check if React debug mode is enabled\n */\n isDebugMode(): boolean {\n return typeof window !== 'undefined' && \n Boolean((window as any).__CONTEXT_ACTION_REACT_DEBUG__);\n },\n\n /**\n * Log React-specific debugging information\n */\n log(component: string, action: string, message: string, data?: any): void {\n if (this.isDebugMode()) {\n console.log(`🎯 [React-ActionRegister] [${component}] ${action}: ${message}`, data || '');\n }\n },\n\n /**\n * Get React integration statistics\n */\n getStats(registry: ActionRegister<any>): {\n totalHandlers: number;\n reactHandlers: number;\n registryInfo: ReturnType<ActionRegister<any>['getRegistryInfo']>;\n } {\n const registryInfo = registry.getRegistryInfo();\n \n // Count React handlers (handlers with 'react' in their ID)\n let reactHandlers = 0;\n registry.getRegisteredActions().forEach((action: keyof any) => {\n const stats = registry.getActionStats(action);\n if (stats) {\n stats.handlersByPriority.forEach((priorityGroup: any) => {\n priorityGroup.handlers.forEach((handler: any) => {\n if (handler.id.includes('react')) {\n reactHandlers++;\n }\n });\n });\n }\n });\n\n return {\n totalHandlers: registryInfo.totalHandlers,\n reactHandlers,\n registryInfo\n };\n }\n};\n\n/**\n * 🆕 React Error Boundary integration\n * \n * Utilities for integrating ActionRegister errors with React Error Boundaries.\n */\nexport class ReactActionError extends Error {\n public readonly action: string;\n public readonly payload?: any;\n public readonly handlerId: string | undefined;\n public readonly timestamp: number;\n\n constructor(\n message: string,\n action: string,\n payload?: any,\n handlerId: string | undefined = undefined,\n originalError?: Error\n ) {\n super(message);\n this.name = 'ReactActionError';\n this.action = action;\n this.payload = payload;\n this.handlerId = handlerId;\n this.timestamp = Date.now();\n\n // Maintain original error stack if available\n if (originalError && originalError.stack) {\n this.stack = originalError.stack;\n }\n }\n\n /**\n * Create a React Error Boundary compatible error\n */\n static fromActionError(\n originalError: Error,\n action: string,\n payload?: any,\n handlerId?: string\n ): ReactActionError {\n return new ReactActionError(\n `Action '${action}' failed: ${originalError.message}`,\n action,\n payload,\n handlerId,\n originalError\n );\n }\n}\n\n/**\n * 🆕 Type guard for React Action Errors\n * \n * @param error - Error to check\n * @returns True if error is a ReactActionError\n */\nexport function isReactActionError(error: any): error is ReactActionError {\n return error instanceof ReactActionError;\n}"],"mappings":";;;;;;;;;;AAyBA,SAAS,qBACP,OACA,cACc;CACd,MAAM,WAAW,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;AAC1E,QAAO;EACL,WAAW,aAAa;EACxB,OAAO;EACP,WAAW,KAAK,KAAK;EACrB,UAAU,aAAa,OAAO,WAAW,aAAa;EACvD;;;;;;;;;;;;;;;;;;;;;;AAuBH,eAAsB,kBACpB,SACA,kBACe;CAEf,IAAI,IAAI;CACR,MAAMA,sBAA2C,EAAE;CACnD,MAAMC,SAAyB,EAAE;AAEjC,QAAO,IAAI,QAAQ,SAAS,QAAQ;AAElC,MAAI,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AsB,CAAC,SAAS,WAAsB;GAC7D,MAAM,QAAQ,SAAS,eAAe,OAAO;AAC7C,OAAI,MACF,OAAM,mBAAmB,SAAS,kBAAuB;AACvD,kBAAc,SAAS,SAAS,YAAiB;AAC/C,SAAI,QAAQ,GAAG,SAAS,QAAQ,CAC9B;MAEF;KACF;IAEJ;AAEF,SAAO;GACL,eAAe,aAAa;GAC5B;GACA;GACD;;CAEJ;;;;;;AAOD,IAAa,mBAAb,MAAa,yBAAyB,MAAM;CAM1C,YACE,SACA,QACA,SACA,YAAgC,QAChC,eACA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;AACd,OAAK,UAAU;AACf,OAAK,YAAY;AACjB,OAAK,YAAY,KAAK,KAAK;AAG3B,MAAI,iBAAiB,cAAc,MACjC,MAAK,QAAQ,cAAc;;;;;CAO/B,OAAO,gBACL,eACA,QACA,SACA,WACkB;AAClB,SAAO,IAAI,iBACT,WAAW,OAAO,YAAY,cAAc,WAC5C,QACA,SACA,WACA,cACD;;;;;;;;;AAUL,SAAgB,mBAAmB,OAAuC;AACxE,QAAO,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["nonBlockingPromises: Array<Promise<any>>","errors: HandlerError[]","error: any","handlerResult: R | undefined","keysToDelete: string[]","name: string","queuedOperation: QueuedOperation<T>","signals: AbortSignal[]","cleanups: (() => void)[]","autoAbortController: AbortController | undefined","effectiveSignal: AbortSignal","registration: HandlerRegistration<T[K], R>","throttleMs: number | undefined","debounceMs: number | undefined","context: PipelineContext<T[K], any>","context: PipelineContext<T[K], R>","executionError: Error | undefined","handlerResults: Array<{\n id: string;\n executed: boolean;\n duration: number | undefined;\n result: R | undefined;\n error: Error | undefined;\n metadata: Record<string, any> | undefined;\n }>","errors: HandlerError[]","executionResult: ExecutionResult<R>","parts: string[]","finalConfig: Required<HandlerConfig>","currentUnregister: UnregisterFunction | undefined"],"sources":["../src/execution-modes.ts","../src/action-guard.ts","../src/concurrency/OperationQueue.ts","../src/ActionRegister.ts","../src/react-helpers.ts"],"sourcesContent":["/**\n * @fileoverview Execution mode implementations for ActionRegister\n * \n * Provides three different execution strategies for action handler pipelines:\n * - Sequential: Execute handlers one after another in priority order\n * - Parallel: Execute all handlers simultaneously\n * - Race: First handler to complete wins, others are cancelled\n */\n\nimport type { \n HandlerRegistration, \n PipelineContext, \n PipelineController,\n HandlerError\n} from './types.js';\n\n/**\n * Create standardized error handling for handlers\n * \n * @param error - The error that occurred\n * @param registration - The handler registration that failed\n * @returns Standardized HandlerError object\n * \n * @internal\n */\nfunction handleExecutionError<T, R>(\n error: any,\n registration: HandlerRegistration<T, R>\n): HandlerError {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n return {\n handlerId: registration.id,\n error: errorObj,\n timestamp: Date.now(),\n severity: registration.config.blocking ? 'blocking' : 'non-blocking'\n };\n}\n\n/**\n * Execute handlers in sequential mode (one after another)\n * \n * Executes action handlers one at a time in priority order (highest first).\n * Supports both blocking and non-blocking handlers, with proper abort and\n * termination handling. Handlers can modify payload for subsequent handlers\n * and jump to different priority levels.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When a blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns\n * \n * @public\n */\nexport async function executeSequential<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n let i = 0;\n const nonBlockingPromises: Array<Promise<any>> = [];\n const errors: HandlerError[] = [];\n \n while (i < context.handlers.length) {\n // Check for abort or termination\n if (context.aborted || context.terminated) {\n break;\n }\n\n const registration = context.handlers[i];\n if (!registration) {\n continue; // Skip if handler not found\n }\n context.currentIndex = i;\n const controller = createController(registration, i);\n\n try {\n // Check for abort before executing handler\n if (context.aborted) {\n break;\n }\n\n // 🔧 Fix: Check handler condition before execution\n if (registration.config.condition) {\n try {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n i++; // Skip this handler\n continue;\n }\n } catch {\n // If condition function throws, skip the handler\n i++;\n continue;\n }\n }\n\n const result = registration.handler(context.payload, controller);\n\n if (registration.config.blocking) {\n // 🆕 Blocking handlers: Wait for completion (sync or async)\n const handlerResult = result instanceof Promise ? await result : result;\n if (handlerResult !== undefined && !context.terminated) {\n context.results.push(handlerResult as R);\n }\n } else {\n // 🆕 Non-blocking handlers: Handle differently for sync vs async\n if (result instanceof Promise) {\n // Non-blocking async: Track promise with error handling\n const promiseWithErrorHandling = result\n .then(asyncResult => {\n if (asyncResult !== undefined && !context.terminated) {\n context.results.push(asyncResult as R);\n }\n return asyncResult;\n })\n .catch(error => {\n // 🆕 Non-blocking async handler error collection\n const handlerError = handleExecutionError(error, registration);\n errors.push({\n handlerId: handlerError.handlerId,\n error: handlerError.error,\n timestamp: handlerError.timestamp,\n severity: 'non-blocking'\n });\n return undefined; // Return undefined for failed non-blocking handlers\n });\n \n nonBlockingPromises.push(promiseWithErrorHandling);\n } else if (result !== undefined && !context.terminated) {\n // Non-blocking sync: Immediately collect result\n context.results.push(result as R);\n }\n }\n\n /** Check if pipeline was terminated by controller.return() */\n if (context.terminated) {\n break;\n }\n\n /** Handle jump to priority AFTER handler execution */\n if (context.jumpToPriority !== undefined) {\n // Check if we've exceeded maximum jumps to prevent infinite loops\n context.jumpCount = (context.jumpCount || 0) + 1;\n if (context.jumpCount > (context.maxJumps || 10)) {\n console.error(\n `[ActionRegister] ERROR: Maximum jump limit (${context.maxJumps || 10}) exceeded. ` +\n `Aborting to prevent infinite loop. Check your jumpToPriority logic and conditions.`\n );\n context.aborted = true;\n context.abortReason = `Maximum jump limit exceeded (${context.jumpCount} jumps)`;\n context.jumpToPriority = undefined;\n break;\n }\n\n // Find first handler with priority <= jumpToPriority\n const jumpIndex = context.handlers.findIndex(\n handler => (handler.config.priority || 0) <= context.jumpToPriority!\n );\n\n if (jumpIndex !== -1 && jumpIndex !== i) {\n if (jumpIndex < i) {\n // ⚠️ WARNING: Backward jump detected - risk of infinite loop!\n // Only allow backward jumps if handler has condition to prevent infinite loops\n const targetHandler = context.handlers[jumpIndex];\n if (targetHandler && !targetHandler.config.condition) {\n console.warn(\n `[ActionRegister] WARNING: Backward jumpToPriority to handler '${targetHandler.config.id || 'unnamed'}' without condition. ` +\n `This may cause infinite loops! Consider adding a condition to prevent re-execution. ` +\n `Jump count: ${context.jumpCount}/${context.maxJumps || 10}`\n );\n }\n }\n\n // Allow both forward and backward jumps\n i = jumpIndex;\n context.jumpToPriority = undefined;\n continue;\n } else {\n // No valid jump target found, or jumping to same handler\n context.jumpToPriority = undefined;\n i++;\n }\n } else {\n i++;\n }\n\n } catch (error: any) {\n // 🔧 Fix: Handle errors gracefully and continue pipeline execution\n const handlerError = handleExecutionError(error, registration);\n errors.push(handlerError);\n\n // 🔧 Fix: Only fail pipeline for blocking handlers, let non-blocking continue\n if (registration.config.blocking) {\n throw handlerError.error;\n }\n\n // For non-blocking handlers, continue to next handler\n i++;\n }\n }\n \n // 🆕 Wait for all non-blocking promises with error collection\n if (nonBlockingPromises.length > 0) {\n await Promise.allSettled(nonBlockingPromises);\n }\n\n // 🔧 Store collected errors in context for ExecutionResult with proper typing\n if (errors.length > 0) {\n // Convert to proper HandlerError format\n const handlerErrors: HandlerError[] = errors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n timestamp: err.timestamp,\n severity: 'non-blocking' as const\n }));\n \n // Add to context with proper typing\n (context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] }).collectedErrors = handlerErrors;\n }\n}\n\n/**\n * Execute handlers in parallel mode (all at once)\n * \n * Executes all qualifying action handlers simultaneously using Promise.allSettled.\n * Supports both blocking and non-blocking handlers. Blocking handlers can still\n * fail the entire pipeline if they throw errors.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When any blocking handler fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#parallel-execution\n * \n * @public\n */\nexport async function executeParallel<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n /** All handlers are runnable */\n const runnableHandlers = context.handlers;\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const controller = createController(registration, _index);\n\n try {\n // 🔧 Fix: Check handler condition before execution\n if (registration.config.condition) {\n try {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n // Return a skipped result for conditions that don't pass\n return {\n success: true,\n handlerId: registration.id,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n } catch {\n // If condition function throws, skip the handler\n return {\n success: true,\n handlerId: registration.id,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n }\n\n const result = registration.handler(context.payload, controller);\n \n let handlerResult: R | undefined;\n if (result instanceof Promise) {\n const resolved = await result;\n handlerResult = resolved as R | undefined;\n } else {\n handlerResult = result as R | undefined;\n }\n \n /** Collect result if handler returned something and pipeline wasn't terminated */\n if (handlerResult !== undefined && !context.terminated) {\n context.results.push(handlerResult);\n }\n \n return { \n success: true, \n handlerId: registration.id, \n result: handlerResult,\n terminated: context.terminated \n };\n \n } catch (error: any) {\n // 🆕 Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n \n if (handlerError.severity === 'blocking') {\n throw handlerError.error;\n }\n \n return { success: false, handlerId: registration.id, error: handlerError.error };\n }\n });\n\n /** Wait for all handlers to complete */\n const results = await Promise.allSettled(handlerPromises);\n \n /** Check for any rejected blocking handlers */\n const failures = results.filter((result, index) => {\n if (result.status === 'rejected') {\n const registration = runnableHandlers[index];\n return registration?.config.blocking ?? false;\n }\n return false;\n });\n\n if (failures.length > 0) {\n const firstFailure = failures[0] as PromiseRejectedResult;\n throw firstFailure.reason;\n }\n\n /** Check if any handler terminated the pipeline */\n const terminatedResults = results.filter(result => \n result.status === 'fulfilled' && result.value.terminated\n );\n \n if (terminatedResults.length > 0) {\n context.terminated = true;\n // In parallel mode, we can't determine which handler's termination result to use,\n // so we use the first one that terminated\n const firstTerminated = terminatedResults[0] as PromiseFulfilledResult<any>;\n context.terminationResult = firstTerminated.value.result;\n }\n}\n\n/**\n * Execute handlers in race mode (first to complete wins)\n * \n * Executes all qualifying handlers simultaneously using Promise.race, where\n * the first handler to complete determines the pipeline result. Other handlers\n * are effectively cancelled. Useful for scenarios where you want the fastest\n * response from multiple equivalent handlers.\n * \n * @template T - The payload type for the action\n * @template R - The result type for handlers\n * \n * @param context - Pipeline execution context containing handlers and state\n * @param createController - Factory function for creating pipeline controllers\n * \n * @throws {Error} When the winning handler fails and is blocking\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/dispatch-patterns#race-execution\n * \n * @public\n */\nexport async function executeRace<T, R = void>(\n context: PipelineContext<T, R>,\n createController: (registration: HandlerRegistration<T, R>, index: number) => PipelineController<T, R>\n): Promise<void> {\n\n /** All handlers are runnable */\n const runnableHandlers = context.handlers;\n\n if (runnableHandlers.length === 0) {\n return;\n }\n\n /** Create promises for all handlers */\n const handlerPromises = runnableHandlers.map(async (registration, _index) => {\n const controller = createController(registration, _index);\n\n try {\n // 🔧 Fix: Check handler condition before execution\n if (registration.config.condition) {\n try {\n const shouldExecute = registration.config.condition(context.payload);\n if (!shouldExecute) {\n // Return a skipped result for conditions that don't pass\n return {\n success: true,\n handlerId: registration.id,\n registration,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n } catch {\n // If condition function throws, skip the handler\n return {\n success: true,\n handlerId: registration.id,\n registration,\n result: undefined,\n terminated: false,\n skipped: true\n };\n }\n }\n\n const result = registration.handler(context.payload, controller);\n \n let handlerResult: R | undefined;\n if (result instanceof Promise) {\n const resolved = await result;\n handlerResult = resolved as R | undefined;\n } else {\n handlerResult = result as R | undefined;\n }\n \n return { \n success: true, \n handlerId: registration.id, \n registration,\n result: handlerResult,\n terminated: context.terminated\n };\n \n } catch (error: any) {\n // 🆕 Consistent error object creation\n const handlerError = handleExecutionError(error, registration);\n return { success: false, handlerId: registration.id, error: handlerError.error, registration };\n }\n });\n\n /** Race all handlers */\n const winner = await Promise.race(handlerPromises);\n\n /** If the winner failed and was blocking, throw the error */\n if (!winner.success && winner.registration?.config.blocking) {\n throw winner.error;\n }\n\n /** Collect result from the winning handler */\n if (winner.success && winner.result !== undefined) {\n context.results.push(winner.result);\n }\n\n /** Check if the winning handler terminated the pipeline */\n if (winner.success && winner.terminated) {\n context.terminated = true;\n context.terminationResult = winner.result;\n }\n}","/**\n * @fileoverview Action Guard system for debouncing, throttling and blocking\n * \n * Provides rate limiting and user experience optimization for actions through\n * debouncing (wait for pause) and throttling (limit frequency) mechanisms.\n * Used internally by ActionRegister to control action execution timing.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n */\n\n\n/**\n * Action guard state tracking for debouncing and throttling\n * \n * Tracks timing and execution state for action execution control.\n * Maintains separate state for each action to enable independent\n * rate limiting per action type.\n * \n * @internal\n */\ninterface GuardState {\n /** Timestamp of last successful execution for throttling calculations */\n lastExecuted: number;\n \n /** Active debounce timer - cleared when new debounce requests arrive */\n debounceTimer: NodeJS.Timeout | undefined;\n \n /** Active throttle timer - tracks when throttle period will end */\n throttleTimer: NodeJS.Timeout | undefined;\n \n /** Flag indicating if action is currently in throttled state */\n isThrottled: boolean;\n \n /** Current debounce promise - reused for concurrent calls */\n debouncePromise: Promise<boolean> | undefined;\n \n /** Resolve function for current debounce promise */\n debounceResolve: ((value: boolean) => void) | undefined;\n}\n\n/**\n * Action Guard system for managing action execution timing\n * \n * Provides performance optimization and user experience enhancement through\n * debouncing and throttling mechanisms. Debouncing waits for a pause in calls\n * before executing, while throttling limits execution frequency.\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @example Manual Usage (Advanced)\n * ```typescript\n * const guard = new ActionGuard()\n * \n * // Manual debouncing\n * if (await guard.debounce('search', 300)) {\n * performSearch() // Only executes after 300ms pause\n * }\n * \n * // Manual throttling\n * if (guard.throttle('scroll', 100)) {\n * updateUI() // Max once per 100ms\n * }\n * ```\n * \n * @internal\n */\nexport class ActionGuard {\n private guards = new Map<string, GuardState>();\n private cleanupInterval: NodeJS.Timeout | undefined;\n private readonly maxIdleTime: number = 60000; // 1 minute\n private readonly cleanupIntervalMs: number = 30000; // 30 seconds\n\n constructor(autoCleanup: boolean = true) {\n if (autoCleanup) {\n this.startAutoCleanup();\n }\n }\n\n /**\n * Start automatic cleanup of idle guard states\n * \n * @internal\n */\n private startAutoCleanup(): void {\n this.cleanupInterval = setInterval(() => {\n const now = Date.now();\n const keysToDelete: string[] = [];\n \n // Collect keys to delete (avoid modifying map during iteration)\n this.guards.forEach((state, key) => {\n const isIdle = now - state.lastExecuted > this.maxIdleTime;\n const hasActiveTimers = state.debounceTimer || state.throttleTimer;\n \n if (isIdle && !hasActiveTimers) {\n keysToDelete.push(key);\n }\n });\n \n // Batch delete idle guards\n if (keysToDelete.length > 0) {\n keysToDelete.forEach(key => this.guards.delete(key));\n // Optional debug logging for cleanup\n if (typeof process !== 'undefined' && process.env?.DEBUG_CONTEXT_ACTION) {\n console.debug(`[ActionGuard] Cleaned up ${keysToDelete.length} idle guards`);\n }\n }\n }, this.cleanupIntervalMs);\n }\n\n /**\n * Apply debouncing to an action\n * \n * Debouncing waits for a specified delay after the last call before allowing\n * execution. Each new call resets the timer. Useful for search inputs, resize\n * handlers, and other high-frequency user interactions.\n * \n * @param actionKey - Unique identifier for the action being debounced\n * @param debounceMs - Delay in milliseconds to wait after the last call\n * \n * @returns Promise resolving to true if execution should proceed, false if cancelled\n * \n * @example Search Input Debouncing\n * ```typescript\n * // Only search after user stops typing for 300ms\n * if (await guard.debounce('userSearch', 300)) {\n * performSearch(query)\n * }\n * ```\n * \n * @internal\n */\n async debounce(actionKey: string, debounceMs: number): Promise<boolean> {\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastExecuted: 0,\n isThrottled: false,\n debounceTimer: undefined as NodeJS.Timeout | undefined,\n throttleTimer: undefined as NodeJS.Timeout | undefined,\n debouncePromise: undefined as Promise<boolean> | undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n };\n this.guards.set(actionKey, state);\n }\n\n /** Clear any existing debounce timer to restart the delay period */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Resolve previous debounce with false if exists\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined as ((value: boolean) => void) | undefined;\n }\n }\n\n /** Create new debounce promise */\n return new Promise<boolean>((resolve) => {\n // Store new resolve function\n state!.debounceResolve = resolve;\n \n // Set new timer\n state!.debounceTimer = setTimeout(() => {\n /** Clean up timer and resolver references */\n state!.debounceTimer = undefined as NodeJS.Timeout | undefined;\n state!.debounceResolve = undefined as ((value: boolean) => void) | undefined;\n /** Update last execution timestamp */\n state!.lastExecuted = Date.now();\n resolve(true);\n }, debounceMs);\n });\n }\n\n /**\n * Apply throttling to an action\n * \n * Throttling limits execution frequency by ensuring a minimum interval between\n * calls. Unlike debouncing, throttling executes immediately on the first call\n * and then blocks subsequent calls until the interval expires.\n * \n * @param actionKey - Unique identifier for the action being throttled\n * @param throttleMs - Minimum interval in milliseconds between executions\n * \n * @returns True if execution should proceed, false if currently throttled\n * \n * @example Scroll Handler Throttling\n * ```typescript\n * // Update scroll position max once per 100ms\n * if (guard.throttle('scrollUpdate', 100)) {\n * updateScrollPosition()\n * }\n * ```\n * \n * @internal\n */\n throttle(actionKey: string, throttleMs: number): boolean {\n\n /** Get or create guard state for this action */\n let state = this.guards.get(actionKey);\n if (!state) {\n /** Initialize new guard state with default values */\n state = {\n lastExecuted: 0,\n isThrottled: false,\n debounceTimer: undefined as NodeJS.Timeout | undefined,\n throttleTimer: undefined as NodeJS.Timeout | undefined,\n debouncePromise: undefined as Promise<boolean> | undefined,\n debounceResolve: undefined as ((value: boolean) => void) | undefined,\n };\n this.guards.set(actionKey, state);\n }\n\n const now = Date.now();\n const timeSinceLastExecution = now - state.lastExecuted;\n\n /** Check if enough time has passed since last execution */\n /** If throttle period has elapsed, allow immediate execution */\n if (timeSinceLastExecution >= throttleMs) {\n /** Update execution timestamp and clear throttled state */\n state.lastExecuted = now;\n state.isThrottled = false;\n \n \n return true;\n }\n\n /** If already in throttled state, don't create duplicate timers */\n /** This prevents timer accumulation and unnecessary processing */\n if (state.isThrottled) {\n return false;\n }\n\n /** Set throttle timer to automatically clear the throttled state */\n /** Calculate remaining time until throttle period expires */\n state.isThrottled = true;\n const remainingTime = throttleMs - timeSinceLastExecution;\n \n /** Create timer to reset throttled state when period expires */\n state.throttleTimer = setTimeout(() => {\n /** Clear throttled state and timer reference */\n state!.isThrottled = false;\n state!.throttleTimer = undefined as NodeJS.Timeout | undefined;\n }, remainingTime);\n\n\n return false;\n }\n\n /**\n * Clear all guard state for a specific action\n * \n * Removes debounce and throttle timers for the specified action,\n * preventing memory leaks and allowing immediate re-execution.\n * \n * @param actionKey - Action identifier to clear guards for\n * \n * @internal\n */\n clearGuards(actionKey: string): void {\n const state = this.guards.get(actionKey);\n if (state) {\n // Clear debounce timer and cancel pending promises to prevent memory leaks\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n if (state.debounceResolve) {\n state.debounceResolve(false);\n state.debounceResolve = undefined;\n }\n state.debounceTimer = undefined;\n }\n \n // Clear throttle timer to prevent memory leaks\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n state.throttleTimer = undefined;\n }\n \n \n // Remove guard state from memory\n this.guards.delete(actionKey);\n }\n }\n\n /**\n * Clear all guard states for all actions\n * \n * Removes all active debounce and throttle timers, useful for cleanup\n * when shutting down the action system or resetting state.\n * \n * @internal\n */\n clearAll(): void {\n \n /** Iterate through all guard states and clear their timers */\n /** This prevents memory leaks when clearing the entire guard system */\n this.guards.forEach((state) => {\n /** Clear any active debounce timers */\n if (state.debounceTimer) {\n clearTimeout(state.debounceTimer);\n // Cancel waiting debounce calls\n if (state.debounceResolve) {\n state.debounceResolve(false);\n }\n }\n /** Clear any active throttle timers */\n if (state.throttleTimer) {\n clearTimeout(state.throttleTimer);\n }\n });\n \n /** Remove all guard states from memory */\n this.guards.clear();\n }\n\n /**\n * Get current guard state for debugging purposes\n * \n * Returns the internal state for a specific action, including timer\n * information and execution timestamps.\n * \n * @param actionKey - Action identifier to inspect\n * @returns Guard state or undefined if no state exists\n * \n * @internal\n */\n getGuardState(actionKey: string): GuardState | undefined {\n return this.guards.get(actionKey);\n }\n\n /**\n * Get all active guard states for debugging purposes\n * \n * Returns a copy of all current guard states, useful for monitoring\n * and debugging rate limiting behavior across all actions.\n * \n * @returns Map of action keys to their guard states\n * \n * @internal\n */\n getAllGuardStates(): Map<string, GuardState> {\n return new Map(this.guards);\n }\n\n /**\n * 🆕 Explicit destroy method for comprehensive cleanup\n * \n * Cleans up all timers, promises, and intervals to prevent memory leaks.\n * Should be called when ActionGuard is no longer needed.\n * \n * @internal\n */\n destroy(): void {\n // Stop auto cleanup interval\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined as NodeJS.Timeout | undefined;\n }\n \n // Clear all existing guards\n this.clearAll();\n }\n\n /**\n * 🆕 Get statistics about active guards\n * \n * @returns Statistics about guard usage\n * \n * @internal\n */\n getStats(): { activeGuards: number; withTimers: number } {\n let withTimers = 0;\n this.guards.forEach(state => {\n if (state.debounceTimer || state.throttleTimer) {\n withTimers++;\n }\n });\n \n return {\n activeGuards: this.guards.size,\n withTimers\n };\n }\n}","/**\n * 동시성 문제 해결을 위한 작업 큐 시스템\n * \n * 모든 상태 변경 작업을 직렬화하여 race condition을 방지합니다.\n */\n\nexport interface QueuedOperation<T = any> {\n id: string;\n operation: () => T | Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n priority?: number;\n timestamp: number;\n}\n\n/**\n * 작업 큐 관리자\n *\n * 핵심 기능:\n * 1. 작업 직렬화 - 모든 작업을 순서대로 실행\n * 2. 우선순위 지원 - 중요한 작업 우선 처리\n * 3. 에러 처리 - 개별 작업 실패가 전체에 영향 주지 않음\n * 4. 메모리 관리 - 완료된 작업 자동 정리\n * 5. 🆕 동시성 제어 - maxConcurrency로 동시 실행 제한\n * 6. 🆕 비동기 지원 - Promise.all() 완벽 지원\n * 7. 🆕 이벤트 기반 처리 - 효율적인 큐 처리 시스템\n */\nexport class OperationQueue {\n private queue: QueuedOperation[] = [];\n private processingPromise: Promise<void> | null = null;\n private operationCounter = 0;\n \n // 🆕 Concurrency control\n private activeOperations = 0;\n private readonly maxConcurrency: number;\n \n constructor(\n private name: string = 'OperationQueue', \n maxConcurrency: number = 1\n ) {\n this.maxConcurrency = Math.max(1, maxConcurrency);\n }\n\n /**\n * 작업을 큐에 추가하고 실행 결과를 반환\n * \n * @param operation 실행할 작업\n * @param priority 우선순위 (높을수록 먼저 실행)\n * @returns Promise로 래핑된 작업 결과\n */\n enqueue<T>(operation: () => T | Promise<T>, priority: number = 0): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const queuedOperation: QueuedOperation<T> = {\n id: `${this.name}-${++this.operationCounter}`,\n operation,\n resolve,\n reject,\n priority,\n timestamp: Date.now()\n };\n\n\n // 우선순위에 따라 삽입 위치 결정 (높은 우선순위가 앞쪽)\n let insertIndex = this.queue.length;\n for (let i = 0; i < this.queue.length; i++) {\n const item = this.queue[i];\n // 현재 아이템의 우선순위가 새 아이템보다 낮으면, 새 아이템을 앞에 삽입\n if (item && (item.priority || 0) < priority) {\n insertIndex = i;\n break;\n }\n }\n\n this.queue.splice(insertIndex, 0, queuedOperation);\n\n // 큐 처리 시작 (이미 처리 중이면 무시됨)\n if (this.processingPromise) {\n // 이미 처리 중이라면, 대기 중인 프로세스에게 새로운 작업이 추가되었음을 알림\n this.notifyNewOperation();\n }\n this.processQueue();\n });\n }\n\n /**\n * 🆕 큐 처리 메인 로직 - 동시성 제어 및 비동기 지원\n *\n * 주요 특징:\n * - maxConcurrency에 따라 동시 실행 작업 수를 제한하여 동시성 문제 방지\n * - Promise.all() 시나리오에서 완벽한 순차적 실행 보장\n * - 이벤트 기반 알림 시스템으로 효율적인 비동기 처리\n * - 작업 완료 시 대기 중인 프로세스에게 자동 알림\n */\n private async processQueue(): Promise<void> {\n if (this.processingPromise) {\n return this.processingPromise;\n }\n\n this.processingPromise = this._doProcess();\n try {\n await this.processingPromise;\n } finally {\n this.processingPromise = null;\n }\n }\n \n private async _doProcess(): Promise<void> {\n while (this.queue.length > 0 || this.activeOperations > 0) {\n // 🆕 동시성 제어: maxConcurrency 만큼만 동시 실행\n while (this.queue.length > 0 && this.activeOperations < this.maxConcurrency) {\n const operation = this.queue.shift()!;\n\n // 🆕 비동기 작업 실행 (await를 사용하지 않음 - 병렬 실행을 위해)\n this.startOperation(operation);\n }\n\n // 🆕 실행 중인 작업이 있으면 하나가 완료될 때까지 대기\n if (this.activeOperations > 0) {\n await this.waitForAnyOperation();\n }\n }\n }\n\n /**\n * 🆕 개별 작업을 시작하고 완료를 추적\n */\n private startOperation<T>(operation: QueuedOperation<T>): void {\n this.activeOperations++;\n\n // 비동기로 작업 실행\n this.executeOperation(operation)\n .finally(() => {\n this.activeOperations--;\n\n // 대기 중인 프로세스에게 신호 보내기\n this.notifyOperationComplete();\n });\n }\n\n private pendingResolvers: Array<() => void> = [];\n\n /**\n * 🆕 하나의 작업이 완료될 때까지 대기하거나 새로운 작업이 추가될 때까지 대기\n */\n private waitForAnyOperation(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.pendingResolvers.push(resolve);\n });\n }\n\n /**\n * 🆕 작업 완료 신호 - 대기 중인 프로세스들에게 알림\n */\n private notifyOperationComplete(): void {\n // 대기 중인 모든 리졸버를 깨우기\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * 🆕 새로운 작업 추가 신호 - processQueue에서 호출\n */\n private notifyNewOperation(): void {\n // 새로운 작업이 추가되었으므로 대기 중인 프로세스를 깨워서 다시 확인하도록 함\n this.notifyOperationComplete();\n }\n \n /**\n * 🆕 개별 작업 실행 로직\n */\n private async executeOperation<T>(operation: QueuedOperation<T>): Promise<void> {\n try {\n // 작업 실행 (동기/비동기 모두 지원)\n const result = await Promise.resolve(operation.operation());\n operation.resolve(result);\n } catch (error) {\n // 개별 작업 실패는 전체 큐에 영향 주지 않음\n operation.reject(error);\n }\n }\n\n /**\n * 🆕 현재 큐 상태 조회 (디버깅용) - 동시성 정보 포함\n */\n getQueueInfo() {\n return {\n name: this.name,\n queueLength: this.queue.length,\n isProcessing: Boolean(this.processingPromise),\n activeOperations: this.activeOperations,\n maxConcurrency: this.maxConcurrency,\n operations: this.queue.map(op => ({\n id: op.id,\n priority: op.priority,\n timestamp: op.timestamp\n }))\n };\n }\n \n /**\n * 🆕 동시성 설정 조회\n */\n getConcurrencyInfo() {\n return {\n maxConcurrency: this.maxConcurrency,\n activeOperations: this.activeOperations,\n availableSlots: this.maxConcurrency - this.activeOperations,\n queuedOperations: this.queue.length,\n efficiency: this.activeOperations / this.maxConcurrency\n };\n }\n\n /**\n * 큐 비우기 (테스트용)\n */\n clear(): void {\n // 대기 중인 작업들에게 취소 알림\n this.queue.forEach(operation => {\n operation.reject(new Error('Queue cleared'));\n });\n\n this.queue = [];\n this.processingPromise = null;\n\n // 대기 중인 리졸버들도 정리\n const resolvers = this.pendingResolvers.splice(0);\n resolvers.forEach(resolve => resolve());\n }\n\n /**\n * 큐 크기 조회\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * 처리 중 여부 조회 \n */\n get processing(): boolean {\n return Boolean(this.processingPromise);\n }\n}","\nimport {\n ActionPayloadMap,\n ActionHandler,\n HandlerConfig,\n HandlerRegistration,\n PipelineContext,\n PipelineController,\n ActionRegisterConfig,\n UnregisterFunction,\n ExecutionMode,\n ExecutionResult,\n ActionRegistryInfo,\n ActionHandlerStats,\n DispatchOptions,\n HandlerError,\n} from './types.js';\nimport { executeSequential, executeParallel, executeRace } from './execution-modes.js';\nimport { ActionGuard } from './action-guard.js';\nimport { OperationQueue } from './concurrency/OperationQueue.js';\n\n/**\n * Action Register for managing action handlers with priority-based execution\n * \n * Central action registration and dispatch system providing type-safe action pipeline management.\n * Supports sequential, parallel, and race execution modes with advanced handler filtering,\n * throttling, debouncing, and comprehensive result collection.\n * \n * @template TActionMap - Action payload mapping interface extending ActionPayloadMap\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/register-delegation\n * \n * @public\n */\nexport class ActionRegister<T extends ActionPayloadMap = ActionPayloadMap> {\n private pipelines = new Map<keyof T, Array<HandlerRegistration<any, any>>>();\n private readonly actionGuard: ActionGuard;\n private executionMode: ExecutionMode = 'sequential';\n private actionExecutionModes = new Map<keyof T, ExecutionMode>();\n \n // 🆕 Advanced unregister function management system\n private unregisterFunctions = new Map<string, UnregisterFunction>();\n\n // 🔧 Fix: Track last registration timestamps for getActionStats\n private lastRegisteredTimestamps = new Map<keyof T, Date>();\n \n public readonly name: string;\n private readonly registryConfig: ActionRegisterConfig['registry'];\n\n // 🆕 Performance optimizations\n private readonly isDebugMode: boolean;\n private readonly maxHandlersPerAction: number;\n\n // 🆕 동시성 문제 해결을 위한 큐 시스템 (conditional)\n private dispatchQueue?: OperationQueue;\n\n // 🧠 Filter cache disabled to prevent memory issues - direct filtering only\n private filterCacheDisabled = true;\n\n // 🔧 Performance optimization: Fast handler ID generation counter\n private handlerIdCounter = 0;\n\n // 🔧 Performance optimization: PipelineController pool for object reuse\n private controllerPool: PipelineController<any, any>[] = [];\n private readonly maxControllerPoolSize = 10;\n\n constructor(config: ActionRegisterConfig = {}) {\n this.name = config.name || 'ActionRegister';\n this.registryConfig = config.registry;\n this.maxHandlersPerAction = config.registry?.maxHandlersPerAction ?? 1000;\n \n // 🆕 Environment variable check cached (performance optimization)\n this.isDebugMode = Boolean(\n this.registryConfig?.debug && \n process.env.NODE_ENV === 'development'\n );\n \n // Guard creation with improved cleanup handling\n this.actionGuard = new ActionGuard(this.registryConfig?.autoCleanup !== false);\n \n // 🆕 Conditional queue system initialization\n if (config.registry?.useConcurrencyQueue !== false) {\n this.dispatchQueue = new OperationQueue(`${this.name}-Dispatch`);\n }\n \n if (this.registryConfig?.defaultExecutionMode) {\n this.executionMode = this.registryConfig.defaultExecutionMode;\n }\n \n this.log('ActionRegister initialized', {\n defaultExecutionMode: this.executionMode,\n autoCleanup: this.registryConfig?.autoCleanup !== false,\n concurrencyQueue: Boolean(this.dispatchQueue),\n debugMode: this.isDebugMode\n });\n }\n\n /**\n * Register an action handler with optional configuration\n * \n * @param action - The action type to register handler for\n * @param handler - The handler function to execute\n * @param config - Optional handler configuration including priority, tags, etc.\n * \n * @returns Unregister function to remove this handler\n * \n * @throws {Error} When maximum handlers limit is reached\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n register<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig = {}\n ): UnregisterFunction {\n // 🔄 임시로 기존 구현 유지하되 개선된 방식 적용\n // 동기적 API를 유지하면서 내부적으로만 동시성 보호\n \n // 🆕 Optimized handler ID generation\n const handlerId = config.id || this.generateHandlerId(action);\n \n // 🆕 Direct synchronous registration\n const unregisterFn = this._performRegistrationSync(action, handler, config, handlerId);\n \n return unregisterFn;\n }\n\n /**\n * 🆕 Unified logging method with cached debug mode check\n */\n private log(message: string, data?: unknown, level: 'log' | 'warn' | 'error' = 'log') {\n if (this.isDebugMode) {\n const timestamp = new Date().toISOString();\n console[level](`🎯 [${timestamp}] [${this.name}] ${message}`, data || '');\n }\n }\n\n /**\n * 🔧 Generate unique handler ID using optimized counter-based approach\n */\n private generateHandlerId<K extends keyof T>(action: K): string {\n // 🔧 Performance: Use simple counter instead of crypto.randomUUID()\n // This is safe for single-process apps and ~70% faster\n return `${String(action)}_${this.name}_${++this.handlerIdCounter}`;\n }\n\n /**\n * 🔧 Create and merge AbortSignal instances with proper cleanup\n * \n * @param options Dispatch options containing signal and autoAbort configuration\n * @returns [effectiveSignal, autoAbortController, cleanupFunction]\n */\n private createAbortSignal(options?: DispatchOptions): [\n AbortSignal | undefined, \n AbortController | undefined, \n () => void\n ] {\n const signals: AbortSignal[] = [];\n const cleanups: (() => void)[] = [];\n let autoAbortController: AbortController | undefined;\n\n // Add existing signal if provided\n if (options?.signal) {\n signals.push(options.signal);\n }\n\n // Create auto-abort controller if enabled\n if (options?.autoAbort?.enabled) {\n autoAbortController = new AbortController();\n signals.push(autoAbortController.signal);\n }\n\n // No signals to merge\n if (signals.length === 0) {\n return [undefined, autoAbortController, () => {}];\n }\n\n // Single signal - no merge needed\n if (signals.length === 1) {\n return [signals[0], autoAbortController, () => cleanups.forEach(c => c())];\n }\n\n // Multiple signals - use AbortSignal.any() if available, fallback to manual merge\n let effectiveSignal: AbortSignal;\n \n if (typeof AbortSignal.any === 'function') {\n // Modern browsers with AbortSignal.any()\n effectiveSignal = AbortSignal.any(signals);\n } else {\n // Fallback: Create controller and link all signals\n const mergedController = new AbortController();\n effectiveSignal = mergedController.signal;\n \n signals.forEach(signal => {\n if (signal.aborted) {\n mergedController.abort();\n } else {\n const abortHandler = () => mergedController.abort();\n signal.addEventListener('abort', abortHandler, { once: true });\n cleanups.push(() => signal.removeEventListener('abort', abortHandler));\n }\n });\n }\n\n const cleanup = () => {\n cleanups.forEach(c => {\n try {\n c();\n } catch (error) {\n this.log('Cleanup error during AbortSignal cleanup', error, 'warn');\n }\n });\n };\n\n return [effectiveSignal, autoAbortController, cleanup];\n }\n\n /**\n * 🆕 Perform synchronous handler registration\n */\n private _performRegistrationSync<K extends keyof T, R = void>(\n action: K,\n handler: ActionHandler<T[K], R>,\n config: HandlerConfig,\n handlerId: string\n ): UnregisterFunction {\n // Create handler registration with defaults\n const registration: HandlerRegistration<T[K], R> = {\n handler,\n config: {\n priority: config.priority ?? 0,\n id: handlerId,\n blocking: config.blocking ?? false,\n once: config.once ?? false,\n debounce: config.debounce ?? undefined,\n throttle: config.throttle ?? undefined,\n replaceExisting: config.replaceExisting ?? true, // 🔧 Fix: Default to true for backward compatibility\n cleanup: config.cleanup, // 🔧 Preserve cleanup function from config\n condition: config.condition, // 🔧 Fix: Preserve condition function from config\n } as Required<HandlerConfig>,\n id: handlerId,\n };\n \n // Initialize pipeline if it doesn't exist\n if (!this.pipelines.has(action)) {\n this.pipelines.set(action, []);\n }\n\n const pipeline = this.pipelines.get(action)!;\n \n // Check handler limit\n if (pipeline.length >= this.maxHandlersPerAction) {\n console.warn(`Handler limit (${this.maxHandlersPerAction}) reached for action \"${String(action)}\". Registration ignored.`);\n return () => {}; // No-op unregister\n }\n const existingIndex = pipeline.findIndex(reg => reg.id === handlerId);\n\n // 🆕 Enhanced duplicate ID handling with replaceExisting support and cleanup\n if (existingIndex !== -1) {\n const existing = pipeline[existingIndex];\n const existingUnregister = this.unregisterFunctions.get(handlerId);\n \n if (registration.config.replaceExisting) {\n // 🔧 Fix: Clean up existing handler properly without removing from pipeline\n\n // Call cleanup if available on the old handler\n if (existing && existing.config.cleanup && typeof existing.config.cleanup === 'function') {\n try {\n existing.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error for replaced handler: ${String(action)}`, cleanupError, 'warn');\n }\n }\n\n // Clean up existing unregister function\n if (existingUnregister) {\n this.unregisterFunctions.delete(handlerId);\n }\n\n // Replace existing handler directly in pipeline\n pipeline[existingIndex] = registration;\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // 🔧 Fix: Update last registered timestamp when replacing\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create new unregister function and store it\n const newUnregister = this.createUnregisterFunction(action, handlerId, registration);\n this.unregisterFunctions.set(handlerId, newUnregister);\n \n this.log(`Handler replaced: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length,\n hadExistingUnregister: Boolean(existingUnregister)\n });\n \n return newUnregister;\n } else {\n // Return existing unregister function or create a new one\n // At this point, existing is guaranteed to be defined because we're in the duplicate handler block\n if (!existing) {\n throw new Error('Internal error: existing handler should be defined in duplicate handler block');\n }\n \n this.log(`Handler duplicate ignored, returning existing unregister: ${String(action)}`, {\n handlerId,\n existingPriority: existing.config.priority,\n newPriority: config.priority,\n existingBlocking: existing.config.blocking,\n newBlocking: config.blocking,\n note: 'Use replaceExisting:true to replace'\n }, 'warn');\n \n if (existingUnregister) {\n return existingUnregister;\n } else {\n // Create new unregister function if somehow missing\n const newUnregister = this.createUnregisterFunction(action, handlerId, existing);\n this.unregisterFunctions.set(handlerId, newUnregister);\n return newUnregister;\n }\n }\n }\n \n // Add handler to pipeline\n pipeline.push(registration);\n pipeline.sort((a, b) => b.config.priority - a.config.priority);\n // Cache disabled\n\n // 🔧 Fix: Update last registered timestamp\n this.lastRegisteredTimestamps.set(action, new Date());\n\n // Create and store unregister function\n const unregister = this.createUnregisterFunction(action, handlerId, registration);\n this.unregisterFunctions.set(handlerId, unregister);\n\n this.log(`Handler registered: ${String(action)}`, {\n handlerId,\n priority: config.priority,\n totalHandlers: pipeline.length\n });\n\n return unregister;\n }\n\n\n /**\n * Dispatch an action with optional execution options\n * \n * @param action - The action type to dispatch\n * @param payload - The action payload data\n * @param options - Optional dispatch options (execution mode, filters, etc.)\n * \n * @returns Promise that resolves when all handlers complete\n * \n * @throws {Error} When action dispatching fails\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n async dispatch<K extends keyof T>(\n action: K,\n payload?: T[K],\n options?: DispatchOptions\n ): Promise<void> {\n // 🆕 Conditional queue usage for performance\n if (options?.immediate || !this.dispatchQueue) {\n // Bypass queue for immediate execution or when queues disabled\n return this._performDispatch(action, payload, options);\n } else {\n // Use queue for concurrency protection\n return this.dispatchQueue.enqueue(async () => {\n return this._performDispatch(action, payload, options);\n });\n }\n }\n\n /**\n * 🆕 실제 디스패치 작업 수행 (큐에서 호출됨)\n */\n private async _performDispatch<K extends keyof T>(\n action: K,\n payload?: T[K],\n options?: DispatchOptions\n ): Promise<void> {\n // 🔍 디스패치 시작 디버그\n this.log(`Starting dispatch for action '${String(action)}'`, {\n hasPayload: payload !== undefined,\n payloadType: payload?.constructor?.name || typeof payload,\n options: options ? Object.keys(options) : 'none',\n timestamp: new Date().toISOString()\n });\n \n // Simple Event object detection for development\n if (payload instanceof Event && process.env.NODE_ENV === 'development') {\n console.warn(`Event object passed to action \"${String(action)}\"`, payload.type);\n }\n \n // 🔧 Improved AbortSignal handling with cleaner merge logic\n const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);\n \n if (options?.autoAbort?.onControllerCreated && autoAbortController) {\n options.autoAbort.onControllerCreated(autoAbortController);\n }\n \n // Check if dispatch is aborted before starting\n if (effectiveSignal?.aborted) {\n this.log(`Dispatch aborted before execution for '${String(action)}'`);\n return;\n }\n \n const pipeline = this.pipelines.get(action);\n \n // 🔍 파이프라인 존재 여부 디버그\n this.log(`Pipeline lookup for '${String(action)}'`, {\n pipelineExists: Boolean(pipeline),\n handlersCount: pipeline?.length || 0,\n allRegisteredActions: Array.from(this.pipelines.keys()),\n pipelineMap: Object.fromEntries(Array.from(this.pipelines.entries()).map(([k, v]) => [k, v.length]))\n });\n \n if (!pipeline || pipeline.length === 0) {\n this.log(`No handlers found for action '${String(action)}', dispatch cancelled`, {}, 'warn');\n return;\n }\n\n // 🆕 Optimize filtering - only copy array if filtering is needed\n const filteredHandlers = options?.filter \n ? this.filterHandlers(pipeline, options.filter)\n : pipeline;\n\n // Apply ActionGuard controls - check both dispatch options and handler configs\n const actionKey = String(action);\n \n // Get throttle/debounce settings from dispatch options or handler configs\n let throttleMs: number | undefined;\n let debounceMs: number | undefined;\n \n // Priority: dispatch options > handler config\n if (options?.throttle !== undefined) {\n throttleMs = options.throttle;\n } else if (filteredHandlers.length > 0) {\n // Use throttle from the first handler that has it (handlers are sorted by priority)\n for (const handler of filteredHandlers) {\n if (handler.config.throttle !== undefined) {\n throttleMs = handler.config.throttle;\n break;\n }\n }\n }\n \n if (options?.debounce !== undefined) {\n debounceMs = options.debounce;\n } else if (filteredHandlers.length > 0) {\n // Use debounce from the first handler that has it (handlers are sorted by priority)\n for (const handler of filteredHandlers) {\n if (handler.config.debounce !== undefined) {\n debounceMs = handler.config.debounce;\n break;\n }\n }\n }\n \n // Apply debounce if specified\n if (debounceMs !== undefined) {\n const shouldProceed = await this.actionGuard.debounce(actionKey, debounceMs);\n if (!shouldProceed) {\n return; // Debounced - don't execute\n }\n }\n \n // Apply throttle if specified\n if (throttleMs !== undefined) {\n const shouldProceed = this.actionGuard.throttle(actionKey, throttleMs);\n if (!shouldProceed) {\n return; // Throttled - don't execute\n }\n }\n\n // Determine execution mode for this action (with option override)\n const currentExecutionMode = options?.executionMode || \n this.actionExecutionModes.get(action) || \n this.executionMode;\n\n // Create pipeline execution context\n const context: PipelineContext<T[K], any> = {\n action: String(action),\n payload: payload as T[K],\n handlers: filteredHandlers, // Use filtered handlers\n aborted: false,\n abortReason: undefined as string | undefined,\n currentIndex: 0,\n jumpToPriority: undefined as number | undefined,\n jumpCount: 0,\n maxJumps: 10, // Default max jumps to prevent infinite loops\n executionMode: currentExecutionMode,\n \n // New result collection fields\n results: [],\n terminated: false,\n terminationResult: undefined as any,\n };\n\n \n // Add abort listener if signal provided (use effectiveSignal for auto-abort)\n const abortHandler = effectiveSignal ? () => {\n context.aborted = true;\n context.abortReason = 'Action dispatch aborted by signal';\n } : undefined;\n \n if (effectiveSignal && abortHandler) {\n effectiveSignal.addEventListener('abort', abortHandler);\n }\n \n \n try {\n await this.executePipeline(context, autoAbortController, options?.autoAbort);\n this.log(`Pipeline execution succeeded for ${String(action)}`);\n } catch (error) {\n this.log(`Pipeline execution failed for ${String(action)}`, error, 'error');\n throw error;\n } finally {\n // 🔧 Use cleanup function from createAbortSignal\n cleanup();\n }\n }\n\n /**\n * Dispatch an action and return detailed execution results\n * \n * @param action - The action type to dispatch\n * @param payload - The action payload data\n * @param options - Optional dispatch options including result collection strategy\n * \n * @returns Promise resolving to comprehensive execution results\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n async dispatchWithResult<K extends keyof T, R = void>(\n action: K,\n payload?: T[K],\n options?: DispatchOptions\n ): Promise<ExecutionResult<R>> {\n const _startTime = Date.now();\n \n // 🔧 Improved AbortSignal handling with cleaner merge logic (same as dispatch)\n const [effectiveSignal, autoAbortController, cleanup] = this.createAbortSignal(options);\n \n if (options?.autoAbort?.onControllerCreated && autoAbortController) {\n options.autoAbort.onControllerCreated(autoAbortController);\n }\n \n // Check if dispatch is aborted before starting\n if (effectiveSignal?.aborted) {\n return {\n success: false,\n aborted: true,\n abortReason: 'Action dispatch aborted by signal',\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: 0,\n handlersExecuted: 0,\n handlersSkipped: 0,\n handlersFailed: 0,\n startTime: _startTime,\n endTime: _startTime,\n },\n handlers: [],\n errors: [],\n };\n }\n \n const pipeline = this.pipelines.get(action);\n \n if (!pipeline || pipeline.length === 0) {\n return {\n success: true,\n aborted: false,\n abortReason: undefined as string | undefined,\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: 0,\n handlersExecuted: 0,\n handlersSkipped: 0,\n handlersFailed: 0,\n startTime: _startTime,\n endTime: _startTime,\n },\n handlers: [],\n errors: [],\n };\n }\n\n // 🆕 Optimize filtering - only copy array if filtering is needed\n const filteredHandlers = options?.filter \n ? this.filterHandlers(pipeline, options.filter)\n : pipeline;\n\n // 🔧 Apply ActionGuard controls using unified method with ExecutionResult return\n const actionKey = String(action);\n const guardResult = await this.applyActionGuardControlsWithResult<R>(\n actionKey, \n filteredHandlers, \n options, \n _startTime, \n pipeline.length\n );\n if (guardResult) {\n return guardResult; // Throttled or debounced - return early with proper result\n }\n\n // Determine execution mode for this action (with option override)\n const currentExecutionMode = options?.executionMode || \n this.actionExecutionModes.get(action) || \n this.executionMode;\n\n // Create pipeline execution context\n const context: PipelineContext<T[K], R> = {\n action: String(action),\n payload: payload as T[K],\n handlers: filteredHandlers,\n aborted: false,\n abortReason: undefined as string | undefined,\n currentIndex: 0,\n jumpToPriority: undefined as number | undefined,\n jumpCount: 0,\n maxJumps: 10, // Default max jumps to prevent infinite loops\n executionMode: currentExecutionMode,\n \n // Result collection fields\n results: [],\n terminated: false,\n terminationResult: undefined as R | undefined,\n };\n\n let executionError: Error | undefined;\n const handlerResults: Array<{\n id: string;\n executed: boolean;\n duration: number | undefined;\n result: R | undefined;\n error: Error | undefined;\n metadata: Record<string, any> | undefined;\n }> = [];\n\n\n // Initialize handler tracking - all handlers start as not executed\n filteredHandlers.forEach(handler => {\n handlerResults.push({\n id: handler.config.id,\n executed: false,\n duration: undefined as number | undefined,\n result: undefined as R | undefined,\n error: undefined as Error | undefined,\n metadata: undefined as Record<string, any> | undefined,\n });\n });\n\n // Add abort listener if signal provided (use effectiveSignal for auto-abort)\n const abortHandler = effectiveSignal ? () => {\n context.aborted = true;\n context.abortReason = 'Action dispatch aborted by signal';\n } : undefined;\n \n if (effectiveSignal && abortHandler) {\n effectiveSignal.addEventListener('abort', abortHandler);\n }\n \n // 🔧 Initialize errors array (will be updated after pipeline execution)\n let errors: HandlerError[] = [];\n \n try {\n await this.executePipeline(context, autoAbortController, options?.autoAbort);\n \n // 🔧 Collect errors from execution context after pipeline execution\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n // Mark executed handlers based on context.currentIndex\n // In sequential mode, handlers 0 to currentIndex were executed\n // In parallel/race mode, all handlers that didn't error were executed\n const executedCount = Math.min(context.currentIndex + (context.aborted ? 0 : 1), filteredHandlers.length);\n for (let i = 0; i < executedCount; i++) {\n const handler = filteredHandlers[i];\n if (!handler) continue;\n const handlerResult = handlerResults.find(hr => hr.id === handler.config.id);\n if (handlerResult) {\n handlerResult.executed = true;\n }\n }\n } catch (error) {\n // 🔧 Collect errors from execution context before adding pipeline error\n const contextWithErrors = context as PipelineContext<any, any> & { collectedErrors?: HandlerError[] };\n errors = contextWithErrors.collectedErrors || [];\n \n executionError = error instanceof Error ? error : new Error(String(error));\n errors.push({\n handlerId: 'pipeline',\n error: executionError,\n timestamp: Date.now(),\n severity: 'blocking'\n });\n \n // Mark executed handlers even when there's an error\n const executedCount = Math.min(context.currentIndex + 1, filteredHandlers.length);\n for (let i = 0; i < executedCount; i++) {\n const handler = filteredHandlers[i];\n if (!handler) continue;\n const handlerResult = handlerResults.find(hr => hr.id === handler.config.id);\n if (handlerResult) {\n handlerResult.executed = true;\n }\n }\n } finally {\n // 🔧 Use cleanup function from createAbortSignal\n cleanup();\n }\n\n const endTime = Date.now();\n \n // Process results based on options\n const processedResult = this.processResults(context, options?.result);\n\n // 🔧 Type safety: Separate successful results from failed ones\n const successResults = context.results.filter((result): result is R => result !== undefined);\n const failedResults = errors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n expectedType: typeof processedResult\n }));\n\n // Build execution result with improved type safety\n const executionResult: ExecutionResult<R> = {\n success: !executionError && !context.aborted,\n aborted: context.aborted,\n abortReason: context.abortReason,\n terminated: context.terminated,\n result: processedResult,\n successResults: successResults,\n results: context.results,\n failedResults,\n execution: {\n duration: endTime - _startTime,\n handlersExecuted: filteredHandlers.length === 0 ? 0 : context.currentIndex + (context.aborted ? 0 : 1),\n handlersSkipped: Math.max(0, filteredHandlers.length - (context.currentIndex + 1)),\n handlersFailed: errors.length,\n startTime: _startTime,\n endTime,\n },\n handlers: handlerResults,\n errors: errors.map(err => ({\n handlerId: err.handlerId,\n error: err.error,\n timestamp: err.timestamp,\n severity: 'non-blocking' as const\n })),\n };\n\n /** Clean up one-time handlers after execution */\n this.cleanupOneTimeHandlers(action, context.handlers);\n\n return executionResult;\n }\n\n /**\n * 🔧 Unified method for dispatchWithResult that returns ExecutionResult on guard rejection\n */\n private async applyActionGuardControlsWithResult<R>(\n actionKey: string,\n filteredHandlers: HandlerRegistration<any, any>[],\n options: DispatchOptions | undefined,\n startTime: number,\n pipelineLength: number\n ): Promise<ExecutionResult<R> | null> {\n // Get throttle/debounce settings (same logic as above)\n let throttleMs: number | undefined;\n let debounceMs: number | undefined;\n \n if (options?.throttle !== undefined) {\n throttleMs = options.throttle;\n } else if (filteredHandlers.length > 0) {\n for (const handler of filteredHandlers) {\n if (handler.config.throttle !== undefined) {\n throttleMs = handler.config.throttle;\n break;\n }\n }\n }\n \n if (options?.debounce !== undefined) {\n debounceMs = options.debounce;\n } else if (filteredHandlers.length > 0) {\n for (const handler of filteredHandlers) {\n if (handler.config.debounce !== undefined) {\n debounceMs = handler.config.debounce;\n break;\n }\n }\n }\n \n // Apply debounce if specified\n if (debounceMs !== undefined) {\n const shouldProceed = await this.actionGuard.debounce(actionKey, debounceMs);\n if (!shouldProceed) {\n return {\n success: false,\n aborted: true,\n abortReason: 'Debounced execution',\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: Date.now() - startTime,\n handlersExecuted: 0,\n handlersSkipped: pipelineLength,\n handlersFailed: 0,\n startTime: startTime,\n endTime: Date.now(),\n },\n handlers: [],\n errors: [],\n };\n }\n }\n \n // Apply throttle if specified\n if (throttleMs !== undefined) {\n const shouldProceed = this.actionGuard.throttle(actionKey, throttleMs);\n if (!shouldProceed) {\n return {\n success: false,\n aborted: true,\n abortReason: 'Throttled execution',\n terminated: false,\n result: undefined as any,\n successResults: [] as any,\n results: [],\n failedResults: [],\n execution: {\n duration: Date.now() - startTime,\n handlersExecuted: 0,\n handlersSkipped: pipelineLength,\n handlersFailed: 0,\n startTime: startTime,\n endTime: Date.now(),\n },\n handlers: [],\n errors: [],\n };\n }\n }\n\n return null; // No guard intervention, proceed with execution\n }\n\n // Cache methods removed for memory stability\n\n /**\n * 🔧 Generate optimized cache key for filter options\n */\n private generateFilterCacheKey(filterOptions?: DispatchOptions['filter']): string {\n if (!filterOptions) {\n return 'no-filter';\n }\n\n // Use pre-sorted arrays to avoid repeated sorting\n const parts: string[] = [];\n\n if (filterOptions.handlerIds?.length) {\n parts.push(`h:${filterOptions.handlerIds.slice().sort().join(',')}`);\n }\n\n if (filterOptions.excludeHandlerIds?.length) {\n parts.push(`e:${filterOptions.excludeHandlerIds.slice().sort().join(',')}`);\n }\n\n if (filterOptions.priority) {\n const { min, max } = filterOptions.priority;\n if (min !== undefined || max !== undefined) {\n parts.push(`p:${min ?? '*'}-${max ?? '*'}`);\n }\n }\n\n // Custom filters cannot be cached\n if (filterOptions.custom) {\n return 'custom-' + Date.now() + Math.random(); // Unique non-cacheable key\n }\n\n return parts.length > 0 ? parts.join('|') : 'no-filter';\n }\n\n // Cache invalidation removed for memory stability\n\n /**\n * 🔧 Create or reuse PipelineController from pool for better performance\n */\n private getControllerFromPool<K extends keyof T>(\n context: PipelineContext<T[K], any>, \n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean }\n ): PipelineController<T[K], any> {\n // Try to reuse from pool\n let controller = this.controllerPool.pop();\n \n if (!controller) {\n // Create new controller if pool is empty\n controller = {} as PipelineController<T[K], any>;\n }\n\n // Configure/reset the controller for current context\n controller.abort = (reason?: string) => {\n context.aborted = true;\n context.abortReason = reason;\n \n // Auto-abort: Handler can trigger pipeline abort if enabled\n if (autoAbortController && autoAbortOptions?.allowHandlerAbort) {\n autoAbortController.abort(reason);\n }\n };\n\n controller.modifyPayload = (modifier: (payload: T[K]) => T[K]) => {\n try {\n context.payload = modifier(context.payload);\n } catch (modificationError) {\n // 🔧 Fix: Don't let payload modification errors crash the pipeline\n this.log('Payload modification error', modificationError, 'warn');\n // Keep original payload on modification error\n }\n };\n\n controller.getPayload = () => context.payload;\n\n controller.jumpToPriority = (priority: number) => {\n context.jumpToPriority = priority;\n };\n\n controller.return = (result: any) => {\n context.terminated = true;\n context.terminationResult = result;\n };\n\n controller.setResult = (result: any) => {\n context.results.push(result);\n };\n\n controller.getResults = () => {\n return [...context.results];\n };\n\n controller.mergeResult = (merger: (previousResults: any[], currentResult: any) => any) => {\n const currentResult = context.results[context.results.length - 1];\n const previousResults = context.results.slice(0, -1);\n const mergedResult = merger(previousResults, currentResult);\n context.results[context.results.length - 1] = mergedResult;\n };\n\n return controller;\n }\n\n /**\n * 🔧 Return controller to pool for reuse\n */\n private returnControllerToPool(controller: PipelineController<any, any>): void {\n // Only add to pool if we haven't exceeded max size\n if (this.controllerPool.length < this.maxControllerPoolSize) {\n this.controllerPool.push(controller);\n }\n }\n\n private filterHandlers(\n handlers: HandlerRegistration<any, any>[],\n filterOptions?: DispatchOptions['filter']\n ): HandlerRegistration<any, any>[] {\n if (!filterOptions) {\n return handlers;\n }\n\n // Cache disabled for memory stability\n\n // Cache disabled - using direct filtering for memory stability\n\n // Create Sets for fast lookup if arrays are provided\n const handlerIdSet = filterOptions.handlerIds ? new Set(filterOptions.handlerIds) : null;\n const excludeIdSet = filterOptions.excludeHandlerIds ? new Set(filterOptions.excludeHandlerIds) : null;\n\n // Filter handlers with optimized checks\n const filtered = handlers.filter(registration => {\n const config = registration.config;\n\n // Fast Set-based inclusion check\n if (handlerIdSet && !handlerIdSet.has(config.id)) {\n return false;\n }\n\n // Fast Set-based exclusion check\n if (excludeIdSet && excludeIdSet.has(config.id)) {\n return false;\n }\n\n // Priority range check\n if (filterOptions.priority) {\n const priority = config.priority;\n if (filterOptions.priority.min !== undefined && priority < filterOptions.priority.min) {\n return false;\n }\n if (filterOptions.priority.max !== undefined && priority > filterOptions.priority.max) {\n return false;\n }\n }\n\n // Custom filter (not cached)\n if (filterOptions.custom && !filterOptions.custom(config)) {\n return false;\n }\n\n return true;\n });\n\n // Cache disabled for memory stability\n\n return filtered;\n }\n\n private processResults<R>(\n context: PipelineContext<any, R>,\n resultOptions?: DispatchOptions['result']\n ): R | undefined {\n const results = context.results;\n\n // 🔧 Fix: Always handle termination result regardless of collect option\n if (context.terminated && context.terminationResult !== undefined) {\n return context.terminationResult;\n }\n\n // 🔧 Fix: Return undefined only if no results options specified AND no results available\n if (!resultOptions) {\n // If no result options specified but we have results, return the last one\n return results.length > 0 ? results[results.length - 1] : undefined;\n }\n\n // 🔧 Fix: Process results even when collect is false if we have a strategy specified\n if (!resultOptions.collect && !resultOptions.strategy) {\n return undefined;\n }\n\n // Apply maxResults limit\n const limitedResults = resultOptions.maxResults\n ? results.slice(0, resultOptions.maxResults)\n : results;\n\n if (limitedResults.length === 0) {\n return undefined;\n }\n\n // Process results based on strategy\n switch (resultOptions.strategy) {\n case 'first':\n return limitedResults[0];\n case 'last':\n return limitedResults[limitedResults.length - 1];\n case 'all':\n return limitedResults as unknown as R;\n case 'merge':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n // Default merge: return last result\n return limitedResults[limitedResults.length - 1];\n case 'custom':\n if (resultOptions.merger) {\n return resultOptions.merger(limitedResults);\n }\n throw new Error('Custom result strategy requires a merger function');\n default:\n // 🔧 Fix: If collect is true but no strategy specified, return all results\n if (resultOptions.collect) {\n return limitedResults as unknown as R;\n }\n // Default: return last result if no strategy specified\n return limitedResults[limitedResults.length - 1];\n }\n }\n\n private async executePipeline<K extends keyof T>(\n context: PipelineContext<T[K], any>, \n autoAbortController?: AbortController,\n autoAbortOptions?: { allowHandlerAbort?: boolean }\n ): Promise<void> {\n const createController = (_registration: HandlerRegistration<T[K], any>, _index: number): PipelineController<T[K], any> => {\n return this.getControllerFromPool(context, autoAbortController, autoAbortOptions);\n };\n\n switch (context.executionMode) {\n case 'sequential':\n await executeSequential<T[K], any>(context, createController);\n break;\n case 'parallel':\n await executeParallel<T[K], any>(context, createController);\n break;\n case 'race':\n await executeRace<T[K], any>(context, createController);\n break;\n default:\n throw new Error(`Unknown execution mode: ${context.executionMode}`);\n }\n\n this.cleanupOneTimeHandlers(context.action as K, context.handlers);\n }\n\n private cleanupOneTimeHandlers<K extends keyof T>(action: K, executedHandlers: HandlerRegistration<any, any>[]): void {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) return;\n\n const oneTimeHandlers = executedHandlers.filter(reg => reg.config.once);\n if (oneTimeHandlers.length === 0) return;\n\n oneTimeHandlers.forEach(registration => {\n const index = pipeline.findIndex(reg => reg.id === registration.id);\n if (index !== -1) {\n pipeline.splice(index, 1);\n\n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 One-time handler removed: ${String(action)}`, {\n handlerId: registration.id,\n remainingHandlers: pipeline.length,\n registry: this.name\n });\n }\n }\n });\n\n // 🔧 Fix: Remove action key from pipelines map when pipeline becomes empty after cleanup\n if (pipeline.length === 0) {\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n }\n }\n\n\n /**\n * Get the number of registered handlers for an action\n * \n * @param action - The action type to count handlers for\n * \n * @returns Number of registered handlers\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getHandlerCount<K extends keyof T>(action: K): number {\n const pipeline = this.pipelines.get(action);\n return pipeline ? pipeline.length : 0;\n }\n\n /**\n * Check if an action has any registered handlers\n * \n * @param action - The action type to check\n * \n * @returns True if action has handlers, false otherwise\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n hasHandlers<K extends keyof T>(action: K): boolean {\n return this.getHandlerCount(action) > 0;\n }\n\n /**\n * Get all registered action types\n * \n * @returns Array of all registered action types\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getRegisteredActions(): (keyof T)[] {\n return Array.from(this.pipelines.keys());\n }\n\n /**\n * Remove all handlers for a specific action\n * \n * @param action - The action type to clear handlers for\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAction<K extends keyof T>(action: K): void {\n this.pipelines.delete(action);\n // 🔧 Fix: Clear last registered timestamp\n this.lastRegisteredTimestamps.delete(action);\n // 🔧 Invalidate filter cache when pipeline changes\n // Cache disabled\n }\n\n /**\n * Remove all handlers for all actions\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n clearAll(): void {\n this.pipelines.clear();\n // 🔧 Fix: Clear all last registered timestamps\n this.lastRegisteredTimestamps.clear();\n // 🔧 Invalidate filter cache when pipeline changes\n // Cache disabled\n }\n\n /**\n * Get the name of this action register\n * \n * @returns The register name\n * \n * @see https://mineclover.github.io/context-action/en/guide/patterns/action/basic-usage\n * \n * @public\n */\n getName(): string {\n return this.name;\n }\n\n /**\n * Get comprehensive registry information (similar to DeclarativeStoreRegistry pattern)\n * \n * @returns Registry information including actions, handlers, and execution modes\n */\n getRegistryInfo(): ActionRegistryInfo<T> {\n const totalHandlers = Array.from(this.pipelines.values()).reduce(\n (total, pipeline) => total + pipeline.length, \n 0\n );\n \n return {\n name: this.name,\n totalActions: this.pipelines.size,\n totalHandlers,\n registeredActions: Array.from(this.pipelines.keys()),\n actionExecutionModes: new Map(this.actionExecutionModes),\n defaultExecutionMode: this.executionMode,\n };\n }\n\n /**\n * Get detailed statistics for a specific action\n * \n * @param action Action name to get statistics for\n * @returns Detailed handler statistics\n */\n getActionStats<K extends keyof T>(action: K): ActionHandlerStats<T> | null {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) {\n return null;\n }\n\n // Group handlers by priority\n const priorityMap = new Map<number, typeof pipeline>();\n pipeline.forEach(handler => {\n if (!priorityMap.has(handler.config.priority)) {\n priorityMap.set(handler.config.priority, []);\n }\n priorityMap.get(handler.config.priority)!.push(handler);\n });\n\n const handlersByPriority = Array.from(priorityMap.entries())\n .sort(([a], [b]) => b - a) // Sort by priority (highest first)\n .map(([priority, handlers]) => ({\n priority,\n handlers: handlers.map(h => ({\n id: h.config.id,\n }))\n }));\n\n // Execution statistics are no longer tracked\n const executionStats = undefined;\n\n return {\n action,\n handlerCount: pipeline.length,\n totalHandlers: pipeline.length,\n handlersByPriority,\n executionStats,\n lastRegistered: this.lastRegisteredTimestamps.get(action),\n };\n }\n\n /**\n * Get statistics for all registered actions\n * \n * @returns Array of statistics for all actions\n */\n getAllActionStats(): Array<ActionHandlerStats<T>> {\n return Array.from(this.pipelines.keys())\n .map(action => this.getActionStats(action))\n .filter((stats): stats is ActionHandlerStats<T> => stats !== null);\n }\n\n\n /**\n * Set global execution mode for all actions\n * \n * @param mode Execution mode to set\n */\n setExecutionMode(mode: ExecutionMode): void {\n this.executionMode = mode;\n \n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 Global execution mode set to: ${mode}`);\n }\n }\n\n /**\n * Set execution mode for a specific action\n * \n * @param action Action name\n * @param mode Execution mode to set\n */\n setActionExecutionMode<K extends keyof T>(action: K, mode: ExecutionMode): void {\n this.actionExecutionModes.set(action, mode);\n \n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 Execution mode set for action '${String(action)}': ${mode}`);\n }\n }\n\n /**\n * Get execution mode for a specific action\n * \n * @param action Action name\n * @returns Execution mode for the action, or default if not set\n */\n getActionExecutionMode<K extends keyof T>(action: K): ExecutionMode {\n return this.actionExecutionModes.get(action) || this.executionMode;\n }\n\n /**\n * Remove execution mode override for a specific action\n * \n * @param action Action name\n */\n removeActionExecutionMode<K extends keyof T>(action: K): void {\n this.actionExecutionModes.delete(action);\n \n if (this.registryConfig?.debug && process.env.NODE_ENV === 'development') {\n console.log(`🎯 Execution mode reset for action '${String(action)}' to default: ${this.executionMode}`);\n }\n }\n\n\n /**\n * Get registry configuration (for debugging and inspection)\n * \n * @returns Current registry configuration\n */\n getRegistryConfig(): ActionRegisterConfig['registry'] {\n return this.registryConfig;\n }\n\n /**\n * Check if registry has debug mode enabled\n * \n * @returns Whether debug mode is enabled\n */\n isDebugEnabled(): boolean {\n return this.isDebugMode;\n }\n\n /**\n * Creates a consistent unregister function for a handler\n * \n * @param action - Action key\n * @param handlerId - Handler identifier\n * @param registration - Handler registration object\n * @returns Unregister function\n * @private\n */\n private createUnregisterFunction<K extends keyof T>(\n action: K,\n handlerId: string,\n registration: HandlerRegistration<any, any>\n ): UnregisterFunction {\n return () => {\n const pipeline = this.pipelines.get(action);\n if (!pipeline) return;\n\n const index = pipeline.findIndex(reg => reg.id === handlerId && reg === registration);\n if (index !== -1) {\n pipeline.splice(index, 1);\n // Cache disabled\n this.unregisterFunctions.delete(handlerId);\n\n // 🔧 Fix: Remove action key from pipelines map when pipeline becomes empty\n if (pipeline.length === 0) {\n this.pipelines.delete(action);\n this.lastRegisteredTimestamps.delete(action);\n }\n\n // Execute cleanup function if available\n if (registration.config.cleanup && typeof registration.config.cleanup === 'function') {\n try {\n registration.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error during unregister: ${String(action)}`, cleanupError, 'warn');\n }\n }\n\n this.log(`Handler unregistered: ${String(action)}`, {\n handlerId,\n remainingHandlers: pipeline.length,\n actionRemoved: pipeline.length === 0\n });\n }\n };\n }\n\n /**\n * Gets the total count of registered unregister functions\n * \n * @returns Number of unregister functions\n * @public\n */\n getUnregisterFunctionCount(): number {\n return this.unregisterFunctions.size;\n }\n \n /**\n * Checks if an unregister function exists for the given handler ID\n * \n * @param handlerId - Handler identifier to check\n * @returns True if unregister function exists\n * @public\n */\n hasUnregisterFunction(handlerId: string): boolean {\n return this.unregisterFunctions.has(handlerId);\n }\n\n /**\n * 🆕 Destroy method for comprehensive cleanup\n * \n * Cleans up all internal resources including pipelines, guards, queues, and statistics.\n * Should be called when the ActionRegister is no longer needed to prevent memory leaks.\n * \n * @public\n */\n destroy(): void {\n // 🔧 Fix: Clean up resources without calling unregister functions to prevent circular references\n // Clear unregister functions without executing them to avoid potential memory leaks\n this.unregisterFunctions.clear();\n\n // Clean up all pipelines with handler cleanup\n for (const [action, pipeline] of this.pipelines.entries()) {\n for (const registration of pipeline) {\n if (registration.config.cleanup && typeof registration.config.cleanup === 'function') {\n try {\n registration.config.cleanup();\n } catch (cleanupError) {\n this.log(`Cleanup error for handler during destroy: ${String(action)}`, cleanupError, 'warn');\n }\n }\n }\n }\n\n // Clean up all pipelines\n this.pipelines.clear();\n\n // 🔧 Fix: Clear all timestamps\n this.lastRegisteredTimestamps.clear();\n\n // Clean up guard system\n this.actionGuard.destroy();\n\n // Clean up queues if they exist\n this.dispatchQueue?.clear?.();\n\n this.actionExecutionModes.clear();\n\n // Cache disabled\n\n // 🔧 Clean up controller pool\n this.controllerPool.length = 0;\n\n this.log('ActionRegister destroyed');\n }\n}","/**\n * @fileoverview React integration helpers for ActionRegister\n * \n * Provides React-specific utilities and hooks for seamless integration\n * with React components and lifecycle management.\n * \n * Note: This file provides utilities for React integration but does not\n * have direct React dependencies. Import React types externally when used.\n */\n\nimport type { \n ActionPayloadMap, \n ActionHandler, \n HandlerConfig,\n UnregisterFunction\n} from './types.js';\nimport type { ActionRegister } from './ActionRegister.js';\n\n/**\n * 🔧 Create action handler registration configuration for React components\n * \n * Creates a configuration object that can be used with React's useEffect to properly\n * register and unregister action handlers with lifecycle management and cleanup.\n * This is NOT a hook - it's a factory function for React hook integration.\n * \n * @template T - ActionPayloadMap type\n * @template K - Action key type\n * \n * @param registry - ActionRegister instance\n * @param action - Action name to register handler for\n * @param handler - Handler function (should be memoized with useCallback)\n * @param config - Handler configuration\n * \n * @returns Configuration object with register/unregister functions\n * \n * @example Basic Usage with useEffect\n * ```tsx\n * import { useCallback, useEffect } from 'react';\n * import { createActionHandler } from '@context-action/core/react-helpers';\n * \n * function MyComponent() {\n * const registry = useActionRegister();\n * \n * const handleUserUpdate = useCallback(async (payload, controller) => {\n * // Handler logic here\n * }, []);\n * \n * useEffect(() => {\n * const { register, unregister } = createActionHandler(\n * registry,\n * 'updateUser',\n * handleUserUpdate,\n * { priority: 10 }\n * );\n * \n * const cleanup = register();\n * return () => {\n * cleanup();\n * unregister();\n * };\n * }, [registry, handleUserUpdate]);\n * }\n * ```\n * \n * @example With Automatic Cleanup\n * ```tsx\n * const [userId, setUserId] = useState('123');\n * \n * const handleUserUpdate = useCallback(async (payload, controller) => {\n * console.log('Updating user:', userId, payload);\n * }, [userId]);\n * \n * useEffect(() => {\n * const handlerManager = createActionHandler(\n * registry,\n * 'updateUser',\n * handleUserUpdate,\n * { priority: 10 }\n * );\n * \n * // Simplified registration with automatic cleanup\n * return handlerManager.registerWithCleanup();\n * }, [registry, handleUserUpdate, userId]);\n * ```\n * \n * @public\n */\nexport function createActionHandler<T extends ActionPayloadMap, K extends keyof T>(\n registry: ActionRegister<T>,\n action: K,\n handler: ActionHandler<T[K]>,\n config?: HandlerConfig\n): {\n register: () => UnregisterFunction;\n unregister: () => void;\n registerWithCleanup: () => () => void;\n config: Required<HandlerConfig>;\n} {\n // Inline React-optimized handler configuration\n const timestamp = Date.now();\n const random = Math.random().toString(36).substr(2, 5);\n \n const finalConfig: Required<HandlerConfig> = {\n priority: config?.priority ?? 0,\n id: config?.id || `react_${String(action)}_${timestamp}_${random}`,\n blocking: config?.blocking ?? false,\n once: config?.once ?? false,\n debounce: config?.debounce ?? undefined,\n throttle: config?.throttle ?? undefined,\n // React-optimized defaults\n replaceExisting: true, // Always replace in React (handles HMR/remounting)\n } as Required<HandlerConfig>;\n let currentUnregister: UnregisterFunction | undefined;\n let isRegistered = false;\n \n return {\n /**\n * Register the handler and return cleanup function\n */\n register(): UnregisterFunction {\n if (isRegistered && currentUnregister) {\n // Clean up previous registration\n currentUnregister();\n }\n \n currentUnregister = registry.register(action, handler, finalConfig);\n isRegistered = true;\n \n return currentUnregister;\n },\n \n /**\n * Unregister the handler if currently registered\n */\n unregister(): void {\n if (isRegistered && currentUnregister) {\n currentUnregister();\n currentUnregister = undefined;\n isRegistered = false;\n }\n },\n \n /**\n * Register and return cleanup function (React useEffect pattern)\n */\n registerWithCleanup(): () => void {\n const unregisterFn = this.register();\n \n return () => {\n unregisterFn();\n this.unregister();\n };\n },\n \n config: finalConfig\n };\n}\n\n\n/**\n * 🆕 React development utilities\n * \n * Provides debugging and development helpers specifically for React environments.\n */\nexport const ReactDevUtils = {\n /**\n * Enable detailed React integration debugging\n */\n enableDebugMode(): void {\n if (typeof window !== 'undefined') {\n (window as any).__CONTEXT_ACTION_REACT_DEBUG__ = true;\n }\n },\n\n /**\n * Disable React integration debugging\n */\n disableDebugMode(): void {\n if (typeof window !== 'undefined') {\n (window as any).__CONTEXT_ACTION_REACT_DEBUG__ = false;\n }\n },\n\n /**\n * Check if React debug mode is enabled\n */\n isDebugMode(): boolean {\n return typeof window !== 'undefined' && \n Boolean((window as any).__CONTEXT_ACTION_REACT_DEBUG__);\n },\n\n /**\n * Log React-specific debugging information\n */\n log(component: string, action: string, message: string, data?: any): void {\n if (this.isDebugMode()) {\n console.log(`🎯 [React-ActionRegister] [${component}] ${action}: ${message}`, data || '');\n }\n },\n\n /**\n * Get React integration statistics\n */\n getStats(registry: ActionRegister<any>): {\n totalHandlers: number;\n reactHandlers: number;\n registryInfo: ReturnType<ActionRegister<any>['getRegistryInfo']>;\n } {\n const registryInfo = registry.getRegistryInfo();\n \n // Count React handlers (handlers with 'react' in their ID)\n let reactHandlers = 0;\n registry.getRegisteredActions().forEach((action: keyof any) => {\n const stats = registry.getActionStats(action);\n if (stats) {\n stats.handlersByPriority.forEach((priorityGroup: any) => {\n priorityGroup.handlers.forEach((handler: any) => {\n if (handler.id.includes('react')) {\n reactHandlers++;\n }\n });\n });\n }\n });\n\n return {\n totalHandlers: registryInfo.totalHandlers,\n reactHandlers,\n registryInfo\n };\n }\n};\n\n/**\n * 🆕 React Error Boundary integration\n * \n * Utilities for integrating ActionRegister errors with React Error Boundaries.\n */\nexport class ReactActionError extends Error {\n public readonly action: string;\n public readonly payload?: any;\n public readonly handlerId: string | undefined;\n public readonly timestamp: number;\n\n constructor(\n message: string,\n action: string,\n payload?: any,\n handlerId: string | undefined = undefined,\n originalError?: Error\n ) {\n super(message);\n this.name = 'ReactActionError';\n this.action = action;\n this.payload = payload;\n this.handlerId = handlerId;\n this.timestamp = Date.now();\n\n // Maintain original error stack if available\n if (originalError && originalError.stack) {\n this.stack = originalError.stack;\n }\n }\n\n /**\n * Create a React Error Boundary compatible error\n */\n static fromActionError(\n originalError: Error,\n action: string,\n payload?: any,\n handlerId?: string\n ): ReactActionError {\n return new ReactActionError(\n `Action '${action}' failed: ${originalError.message}`,\n action,\n payload,\n handlerId,\n originalError\n );\n }\n}\n\n/**\n * 🆕 Type guard for React Action Errors\n * \n * @param error - Error to check\n * @returns True if error is a ReactActionError\n */\nexport function isReactActionError(error: any): error is ReactActionError {\n return error instanceof ReactActionError;\n}"],"mappings":";;;;;;;;;;AAyBA,SAAS,qBACP,OACA,cACc;CACd,MAAM,WAAW,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;AAC1E,QAAO;EACL,WAAW,aAAa;EACxB,OAAO;EACP,WAAW,KAAK,KAAK;EACrB,UAAU,aAAa,OAAO,WAAW,aAAa;EACvD;;;;;;;;;;;;;;;;;;;;;;AAuBH,eAAsB,kBACpB,SACA,kBACe;CAEf,IAAI,IAAI;CACR,MAAMA,sBAA2C,EAAE;CACnD,MAAMC,SAAyB,EAAE;AAEjC,QAAO,IAAI,QAAQ,SAAS,QAAQ;AAElC,MAAI,QAAQ,WAAW,QAAQ,WAC7B;EAGF,MAAM,eAAe,QAAQ,SAAS;AACtC,MAAI,CAAC,aACH;AAEF,UAAQ,eAAe;EACvB,MAAM,aAAa,iBAAiB,cAAc,EAAE;AAEpD,MAAI;AAEF,OAAI,QAAQ,QACV;AAIF,OAAI,aAAa,OAAO,UACtB,KAAI;AAEF,QAAI,CADkB,aAAa,OAAO,UAAU,QAAQ,QAAQ,EAChD;AAClB;AACA;;WAEI;AAEN;AACA;;GAIJ,MAAM,SAAS,aAAa,QAAQ,QAAQ,SAAS,WAAW;AAEhE,OAAI,aA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AAiB,cAAc,MACjC,MAAK,QAAQ,cAAc;;;;;CAO/B,OAAO,gBACL,eACA,QACA,SACA,WACkB;AAClB,SAAO,IAAI,iBACT,WAAW,OAAO,YAAY,cAAc,WAC5C,QACA,SACA,WACA,cACD;;;;;;;;;AAUL,SAAgB,mBAAmB,OAAuC;AACxE,QAAO,iBAAiB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@context-action/core",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Type-safe action pipeline management library for JavaScript/TypeScript",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -24,6 +24,22 @@
|
|
|
24
24
|
"README.ko.md",
|
|
25
25
|
"LICENSE"
|
|
26
26
|
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsdown",
|
|
29
|
+
"build:watch": "tsdown --watch",
|
|
30
|
+
"test": "NODE_OPTIONS=--max-old-space-size=8192 jest --runInBand --logHeapUsage",
|
|
31
|
+
"test:watch": "jest --watch",
|
|
32
|
+
"test:coverage": "jest --coverage",
|
|
33
|
+
"test:ci": "jest --ci --coverage --maxWorkers=2",
|
|
34
|
+
"lint": "eslint src --ext .ts",
|
|
35
|
+
"lint:fix": "eslint src --ext .ts --fix",
|
|
36
|
+
"type-check": "tsc --noEmit",
|
|
37
|
+
"clean": "rimraf dist coverage",
|
|
38
|
+
"security:audit": "pnpm audit --audit-level high",
|
|
39
|
+
"security:outdated": "pnpm outdated",
|
|
40
|
+
"security:check": "pnpm security:audit && pnpm security:outdated",
|
|
41
|
+
"prepublishOnly": "pnpm run build"
|
|
42
|
+
},
|
|
27
43
|
"keywords": [
|
|
28
44
|
"typescript",
|
|
29
45
|
"javascript",
|
|
@@ -59,19 +75,18 @@
|
|
|
59
75
|
"engines": {
|
|
60
76
|
"node": ">=18.0.0"
|
|
61
77
|
},
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
+
"browser": {
|
|
79
|
+
"node:module": false,
|
|
80
|
+
"node:path": false,
|
|
81
|
+
"node:fs": false,
|
|
82
|
+
"node:url": false,
|
|
83
|
+
"node:crypto": false,
|
|
84
|
+
"node:buffer": false
|
|
85
|
+
},
|
|
86
|
+
"browserslist": [
|
|
87
|
+
"> 1%",
|
|
88
|
+
"last 2 versions",
|
|
89
|
+
"not dead",
|
|
90
|
+
"not ie 11"
|
|
91
|
+
]
|
|
92
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
Apache License
|
|
2
|
-
Version 2.0, January 2004
|
|
3
|
-
http://www.apache.org/licenses/
|
|
4
|
-
|
|
5
|
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
-
|
|
7
|
-
1. Definitions.
|
|
8
|
-
|
|
9
|
-
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
-
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
-
|
|
12
|
-
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
-
the copyright owner that is granting the License.
|
|
14
|
-
|
|
15
|
-
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
-
other entities that control, are controlled by, or are under common
|
|
17
|
-
control with that entity. For the purposes of this definition,
|
|
18
|
-
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
-
direction or management of such entity, whether by contract or
|
|
20
|
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for reasonable and customary use in describing the
|
|
141
|
-
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|
|
177
|
-
|
|
178
|
-
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
-
|
|
180
|
-
To apply the Apache License to your work, attach the following
|
|
181
|
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
-
replaced with your own identifying information. (Don't include
|
|
183
|
-
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
-
comment syntax for the file format. We also recommend that a
|
|
185
|
-
file or class name and description of purpose be included on the
|
|
186
|
-
same "printed page" as the copyright notice for easier
|
|
187
|
-
identification within third-party archives.
|
|
188
|
-
|
|
189
|
-
Copyright 2024 Jun Woo Bang
|
|
190
|
-
|
|
191
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
-
you may not use this file except in compliance with the License.
|
|
193
|
-
You may obtain a copy of the License at
|
|
194
|
-
|
|
195
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
-
|
|
197
|
-
Unless required by applicable law or agreed to in writing, software
|
|
198
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
-
See the License for the specific language governing permissions and
|
|
201
|
-
limitations under the License.
|