var u = Object.defineProperty;
var f = (s, e) => u(s, "name", { value: e, configurable: !0 });
import { Code as d } from "./code.js";
import { codeToString as o } from "./protocol-connect/code-string.js";
class r extends Error {
  static {
    f(this, "ConnectError");
  }
  /**
   * Create a new ConnectError.
   * If no code is provided, code "unknown" is used.
   * Outgoing details are only relevant for the server side - a service may
   * raise an error with details, and it is up to the protocol implementation
   * to encode and send the details along with error.
   */
  constructor(e, n = d.Unknown, i, t, a) {
    super(c(e, n)), this.name = "ConnectError", Object.setPrototypeOf(this, new.target.prototype), this.rawMessage = e, this.code = n, this.metadata = new Headers(i ?? {}), this.details = t ?? [], this.cause = a;
  }
  /**
   * Convert any value - typically a caught error into a ConnectError,
   * following these rules:
   * - If the value is already a ConnectError, return it as is.
   * - If the value is an AbortError from the fetch API, return the message
   *   of the AbortError with code Canceled.
   * - For other Errors, return the error message with code Unknown by default.
   * - For other values, return the values String representation as a message,
   *   with the code Unknown by default.
   * The original value will be used for the "cause" property for the new
   * ConnectError.
   */
  static from(e, n = d.Unknown) {
    return e instanceof r ? e : e instanceof Error ? e.name == "AbortError" ? new r(e.message, d.Canceled) : new r(e.message, n, void 0, void 0, e) : new r(String(e), n, void 0, void 0, e);
  }
  static [Symbol.hasInstance](e) {
    return e instanceof Error ? Object.getPrototypeOf(e) === r.prototype ? !0 : e.name === "ConnectError" && "code" in e && typeof e.code == "number" && "metadata" in e && "details" in e && Array.isArray(e.details) && "rawMessage" in e && typeof e.rawMessage == "string" && "cause" in e : !1;
  }
  findDetails(e) {
    const n = "typeName" in e ? {
      findMessage: /* @__PURE__ */ f((t) => t === e.typeName ? e : void 0, "findMessage")
    } : e, i = [];
    for (const t of this.details) {
      if ("getType" in t) {
        n.findMessage(t.getType().typeName) && i.push(t);
        continue;
      }
      const a = n.findMessage(t.type);
      if (a)
        try {
          i.push(a.fromBinary(t.value));
        } catch {
        }
    }
    return i;
  }
}
function c(s, e) {
  return s.length ? `[${o(e)}] ${s}` : `[${o(e)}]`;
}
f(c, "createMessage");
export {
  r as ConnectError
};
