/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { SdkError } from './SdkError.js';
/**
 * Type guard: returns `true` when `value` is a {@link SerializedError}.
 */
export function isSerializedError(value) {
    return (typeof value === 'object' &&
        value !== null &&
        value.__type === 'SerializedError');
}
/**
 * Convert any thrown value into a {@link SerializedError}.
 *
 * Duck-types against known SDK error shapes so callers don't need to import
 * concrete error classes:
 *
 * - `SdkError` instances -> extracts `code`, `details`
 * - Objects with `status: number` -> extracts as `httpStatus` (covers HttpError)
 * - Objects with `responseData` -> extracts as `details` (covers HttpError)
 * - Strings / primitives -> wraps as `{ name: 'Error', message: String(value) }`
 * - Already a `SerializedError` -> returns as-is (idempotent)
 *
 * **Security:** Deliberately omits `HttpError.config` which may contain auth
 * tokens in request headers.
 */
export function serializeError(error) {
    // Already serialized — return as-is.
    if (isSerializedError(error)) {
        return error;
    }
    // Non-object / null / primitive — wrap as a simple Error shape.
    if (typeof error !== 'object' || error === null) {
        return {
            __type: 'SerializedError',
            name: 'Error',
            message: String(error),
        };
    }
    const obj = error;
    const name = typeof obj.name === 'string' ? obj.name : 'Error';
    const message = typeof obj.message === 'string' ? obj.message : String(error);
    const stack = typeof obj.stack === 'string' ? obj.stack : undefined;
    // SdkError-derived: extract code + details.
    if (error instanceof SdkError) {
        const result = {
            __type: 'SerializedError',
            name,
            message,
            code: error.code,
            stack,
            details: error.details,
        };
        // Duck-type for HttpError's `status` property.
        if (typeof obj.status === 'number') {
            return { ...result, httpStatus: obj.status };
        }
        return result;
    }
    // Plain Error or unknown object — duck-type for HttpError-like shapes.
    const result = {
        __type: 'SerializedError',
        name,
        message,
        stack,
    };
    const code = typeof obj.code === 'string' ? obj.code : undefined;
    const httpStatus = typeof obj.status === 'number' ? obj.status : undefined;
    const details = obj.responseData !== undefined ? obj.responseData : obj.details;
    return {
        ...result,
        ...(code !== undefined && { code }),
        ...(httpStatus !== undefined && { httpStatus }),
        ...(details !== undefined && { details }),
    };
}
//# sourceMappingURL=ErrorSerialization.js.map