execute method

HookResult execute(
  1. HookType type,
  2. HookContext context
)

Execute all matching hooks for the given type synchronously.

This is a convenience wrapper around executeAsync for callers in synchronous contexts. Internally still async.

Implementation

HookResult execute(HookType type, HookContext context) {
  // For truly sync execution, we run hooks that have sync handlers only.
  final chain = _chains[type];
  if (chain == null || chain.isEmpty) return const HookContinue();

  final hooks = chain.activeRegistrations;
  if (hooks.isEmpty) return const HookContinue();

  HookResult lastResult = const HookContinue();

  for (final hook in hooks) {
    if (hook.isAsync) continue; // Skip async hooks in sync execution
    if (hook.matcher != null && !hook.matcher!(context)) continue;

    final stopwatch = Stopwatch()..start();
    try {
      lastResult = hook.handler!(context);
      stopwatch.stop();
      _recordEvent(
        HookExecutionEvent(
          hookId: hook.id,
          hookName: hook.name,
          type: type,
          context: context,
          result: lastResult,
          duration: stopwatch.elapsed,
          timestamp: DateTime.now(),
        ),
      );

      if (lastResult is HookAbort) return lastResult;
    } catch (e, st) {
      stopwatch.stop();
      _recordEvent(
        HookExecutionEvent(
          hookId: hook.id,
          hookName: hook.name,
          type: type,
          context: context,
          result: const HookContinue(),
          duration: stopwatch.elapsed,
          error: e,
          errorStackTrace: st,
          timestamp: DateTime.now(),
        ),
      );
    }
  }

  return lastResult;
}