import { useEffect } from 'react';
import { isHydrationError } from '../../../is-hydration-error';
import { attachHydrationErrorState } from './attach-hydration-error-state';
import { isNextRouterError } from '../../../is-next-router-error';
import { storeHydrationErrorStateFromConsoleArgs } from './hydration-error-info';
import { formatConsoleArgs } from '../../../../lib/console';
import isError from '../../../../../lib/is-error';
import { ConsoleError } from './console-error';
const errorQueue = [];
const errorHandlers = [];
const rejectionQueue = [];
const rejectionHandlers = [];
export function handleClientError(originError, consoleErrorArgs) {
    let error;
    if (!originError || !isError(originError)) {
        // If it's not an error, format the args into an error
        const formattedErrorMessage = formatConsoleArgs(consoleErrorArgs);
        error = new ConsoleError(formattedErrorMessage);
    } else {
        error = originError;
    }
    storeHydrationErrorStateFromConsoleArgs(...consoleErrorArgs);
    attachHydrationErrorState(error);
    // TODO: change all to push error into errorQueue,
    // currently there's a async api error is always erroring while hydration error showing up.
    // Move hydration error to the front of the queue to unblock.
    if (isHydrationError(error)) {
        errorQueue.unshift(error);
    } else {
        errorQueue.push(error);
    }
    for (const handler of errorHandlers){
        handler(error);
    }
}
export function useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection) {
    useEffect(()=>{
        // Handle queued errors.
        errorQueue.forEach(handleOnUnhandledError);
        rejectionQueue.forEach(handleOnUnhandledRejection);
        // Listen to new errors.
        errorHandlers.push(handleOnUnhandledError);
        rejectionHandlers.push(handleOnUnhandledRejection);
        return ()=>{
            // Remove listeners.
            errorHandlers.splice(errorHandlers.indexOf(handleOnUnhandledError), 1);
            rejectionHandlers.splice(rejectionHandlers.indexOf(handleOnUnhandledRejection), 1);
        };
    }, [
        handleOnUnhandledError,
        handleOnUnhandledRejection
    ]);
}
export function handleGlobalErrors() {
    if (typeof window !== 'undefined') {
        try {
            // Increase the number of stack frames on the client
            Error.stackTraceLimit = 50;
        } catch (e) {}
        window.addEventListener('error', (event)=>{
            if (isNextRouterError(event.error)) {
                event.preventDefault();
                return false;
            }
            handleClientError(event.error, []);
        });
        window.addEventListener('unhandledrejection', (ev)=>{
            const reason = ev == null ? void 0 : ev.reason;
            if (isNextRouterError(reason)) {
                ev.preventDefault();
                return;
            }
            if (!reason || !(reason instanceof Error) || typeof reason.stack !== 'string') {
                // A non-error was thrown, we don't have anything to show. :-(
                return;
            }
            const e = reason;
            rejectionQueue.push(e);
            for (const handler of rejectionHandlers){
                handler(e);
            }
        });
    }
}

//# sourceMappingURL=use-error-handler.js.map