Consider the following MWE:
\documentclass{article}
\newcommand{\foo}{foo}
\begin{document}
test \foo bar
test {\foo} bar
test {\foo}.
\end{document}
My goal is to define \foo in such a way that it behaves as if it was braced in text {\foo} in order to maintain the space before the next word or ignore it in case of punctuation. Using \bgroup..\egroup in declaration doesn't seem to work. Bulk check for the next character via #1 for \foo is not desired because it's not versatile.
I'm curious about both plain tex and latex3 approach.

\foois consulted. But see thexspacepackage which can usually add a space back (although I don't recommend it) – David Carlisle Apr 30 '23 at 09:50\foo{}is better than{\foo}unless you know\foois not affected by being in a group. – David Carlisle Apr 30 '23 at 09:52