"use strict";
/**
 * Copyright: (c) Myia SAS 2026.
 * This file and its contents are licensed under the AGPLv3 License.
 * Please see the LICENSE file at the root of this repository
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.serializeError = serializeError;
const PLAYWRIGHT_ERROR_CTOR = /^(TimeoutError|PlaywrightError|LocatorError|PlaywrightTestError)$/;
const PLAYWRIGHT_STACK = /(node_modules\/playwright|node_modules\/@playwright)/;
const PLAYWRIGHT_TIMEOUT_MSG = /^Test timeout of \d+ms exceeded/;
// CSI sequence: ESC [ … letter. Covers the SGR color codes
// Playwright uses (`\x1b[31m`, `\x1b[39m`) and any other Select
// Graphic Rendition the runtime might emit.
const ANSI_REGEX = /\x1b\[[0-9;]*m/g;
function stripAnsi(s) {
    return s.replace(ANSI_REGEX, '');
}
function serializeError(err) {
    if (err == null)
        return { message: String(err) };
    if (typeof err !== 'object')
        return { message: String(err) };
    const e = err;
    const ctorName = (e.constructor && e.constructor.name) || '';
    const stackStr = e.stack
        ? stripAnsi(String(e.stack).split('\n').slice(0, 20).join('\n'))
        : undefined;
    const message = stripAnsi(e.message != null ? String(e.message) : String(err));
    let name = e.name || ctorName || 'Error';
    const isPwStack = PLAYWRIGHT_STACK.test(stackStr || '');
    const looksLikeTimeout = PLAYWRIGHT_TIMEOUT_MSG.test(message);
    // Playwright's `testInfo.errors[i]` is a `TestInfoError`-shaped
    // plain object with no `.name` and constructor `Object`. When we
    // can prove the throw came from Playwright (stack path or
    // timeout message), upgrade the class name so consumers get a
    // useful discriminator instead of `Object` / `Error`.
    if ((name === 'Object' || name === 'Error') && (isPwStack || looksLikeTimeout)) {
        name = looksLikeTimeout ? 'TimeoutError' : 'PlaywrightError';
    }
    const result = { name, message };
    if (stackStr)
        result.stack = stackStr;
    result.isPlaywrightError = PLAYWRIGHT_ERROR_CTOR.test(ctorName) || isPwStack || looksLikeTimeout;
    const causes = [];
    let cur = e.cause;
    let d = 0;
    while (cur != null && d < 5) {
        if (typeof cur === 'object') {
            const c = cur;
            causes.push({
                name: c.name || (c.constructor && c.constructor.name) || 'Error',
                message: stripAnsi(c.message != null ? String(c.message) : String(cur)),
                stack: c.stack ? stripAnsi(String(c.stack).split('\n').slice(0, 10).join('\n')) : undefined,
            });
            cur = c.cause;
        }
        else {
            causes.push({ message: stripAnsi(String(cur)) });
            break;
        }
        d++;
    }
    if (causes.length)
        result.causes = causes;
    return result;
}
