Tesla has become the most valuable and (by some measures) the most profitable automaker in the world, But a short while ago it nearly toppled into bankruptcy.