/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { AbortedError } from "#MatterError.js";
function considerAsError(error) {
  return typeof error === "object" && error !== null && error.message !== void 0;
}
function asError(e) {
  if (considerAsError(e)) {
    if (e instanceof DOMException && e.name === "AbortError") {
      const aborted = new AbortedError(e.message);
      aborted.stack = e.stack;
      aborted.cause = e.cause;
      return aborted;
    }
    return e;
  }
  return new Error(e?.toString() ?? "Unknown error");
}
function errorOf(cause) {
  if (cause?.construction?.error) {
    cause = cause?.construction.error;
  }
  if (cause === void 0 || cause === null) {
    return Error("Unknown error");
  }
  if (considerAsError(cause)) {
    return cause;
  }
  return new Error(cause.toString());
}
function causedBy(error, ...causes) {
  const e = asError(error);
  for (const cause of causes) {
    if (e instanceof cause) {
      return true;
    }
  }
  if (e.cause && causedBy(e.cause, ...causes)) {
    return true;
  }
  if (e instanceof AggregateError && e.errors) {
    for (const e2 of e.errors) {
      if (causedBy(e2, ...causes)) {
        return true;
      }
    }
  }
  return false;
}
function repackErrorAs(error, repackAsErrorClass, message) {
  if (error instanceof repackAsErrorClass) {
    return error;
  }
  if (considerAsError(error)) {
    const repackedError = new repackAsErrorClass(message ?? error.message);
    repackedError.cause = error;
    return repackedError;
  }
  throw new TypeError("Cannot repackage non-Error object");
}
export {
  asError,
  causedBy,
  errorOf,
  repackErrorAs
};
//# sourceMappingURL=Error.js.map
