const API_ERROR_CODES = {
  /** Role-based permission check failed (checkPermission) */
  PERMISSION_DENIED: "PERMISSION_DENIED",
  /** API key scope check failed (hasRequiredScope) */
  INSUFFICIENT_SCOPE: "INSUFFICIENT_SCOPE"
};
class ApiError extends Error {
  code;
  status;
  details;
  constructor(message, options) {
    super(message);
    this.name = "ApiError";
    this.code = options == null ? void 0 : options.code;
    this.status = options == null ? void 0 : options.status;
    this.details = options == null ? void 0 : options.details;
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ApiError);
    }
  }
  /**
   * Check if this is a permission denied error
   */
  isPermissionDenied() {
    return this.code === API_ERROR_CODES.PERMISSION_DENIED && this.status === 403;
  }
  /**
   * Parse API error from fetch response
   * Handles both flat and nested error structures:
   * - Flat: { error: "msg", code: "CODE" }
   * - Nested: { error: { message: "msg", code: "CODE" } }
   */
  static async fromResponse(response, fallbackMessage) {
    let errorData = {};
    try {
      errorData = await response.json();
    } catch {
    }
    let message;
    let code;
    let details;
    if (errorData.error && typeof errorData.error === "object") {
      message = errorData.error.message || fallbackMessage;
      code = errorData.error.code || errorData.code;
      details = errorData.error.details || errorData.details;
    } else {
      message = errorData.error || errorData.message || fallbackMessage;
      code = errorData.code;
      details = errorData.details;
    }
    return new ApiError(message, {
      code,
      status: response.status,
      details
    });
  }
}
export {
  API_ERROR_CODES,
  ApiError
};
