A large-deviations approach to gelation