  The $p_\mathrm{T}$-differential production cross sections of prompt and
non-prompt (produced in beauty-hadron decays) D mesons were measured by the
ALICE experiment at midrapidity ($|y|<0.5$) in proton--proton collisions at
$\sqrt{s}=5.02~\mathrm{TeV}$. The data sample used in the analysis corresponds
to an integrated luminosity of $(19.3\pm0.4)~\mathrm{nb^{-1}}$. D mesons were
reconstructed from their decays $\mathrm{D^0 \to K^-\pi^+}$, $\mathrm{D^+\to
K^-\pi^+\pi^+}$, and $\mathrm{D_s^+\to \phi\pi^+\to K^-K^+\pi^+}$ and their
charge conjugates. Compared to previous measurements in the same rapidity
region, the cross sections of prompt $\mathrm{D^+}$ and $\mathrm{D_s^+}$ mesons
have an extended $p_\mathrm{T}$ coverage and total uncertainties reduced by a
factor ranging from 1.05 to 1.6, depending on $p_\mathrm{T}$, allowing for a
more precise determination of their $p_\mathrm{T}$-integrated cross sections.
The results are well described by perturbative QCD calculations. The
fragmentation fraction of heavy quarks to strange mesons divided by the one to
non-strange mesons, $f_\mathrm{s}/(f_\mathrm{u}+f_\mathrm{d})$, is compatible
for charm and beauty quarks and with previous measurements at different
centre-of-mass energies and collision systems. The $\mathrm{b\overline{b}}$
production cross section per rapidity unit at midrapidity, estimated from
non-prompt D-meson measurements, is
$\mathrm{d}\sigma_\mathrm{b\overline{b}}/\mathrm{d} y|_\mathrm{|y|<0.5} = 34.5
\pm 2.4 (\mathrm{stat.}) ^{+4.7}_{-2.9} (\mathrm{tot. syst.})~\mu\mathrm{b}$.
It is compatible with previous measurements at the same centre-of-mass energy
and with the cross section predicted by perturbative QCD calculations.
