Hreflang Tag Generator — C++ source
Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.
This is the C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.
// hreflang-tag-generator — C++ port: locale-list validation + alternate-link
// emission for the hreflang tool. C++20, standard library only.
// CosmoDev polyglot port of the SEO/meta trio's hreflang logic.
// Port of src/lib/hreflang.ts — same logic as this dir's typescript.ts and
// the live Go twin at cli/hreflang-tag-generator/hreflang-tag-generator.go.
#include <cctype>
#include <optional>
#include <regex>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>
namespace cosmodev::hreflang {
/** One locale/URL pair. Mirrors the TS HreflangRow interface. */
struct HreflangRow {
std::string locale;
std::string url;
};
/** The field set for buildHreflang — rows plus an optional x-default URL. */
struct HreflangInput {
std::vector<HreflangRow> rows;
std::optional<std::string> x_default_url;
};
/** Diagnostics plus both emitted flavors. On failure ok is false, errors
* lists every row-located problem, and normalized/html/sitemap are empty —
* exactly like the TS result. */
struct HreflangResult {
bool ok = false;
std::vector<std::string> errors;
std::vector<HreflangRow> normalized;
std::string html;
std::string sitemap;
};
// ll (ISO-639-1 language) — two ASCII letters; ll-CC — language + region
// (ISO-3166); http:// or https:// scheme prefix.
const std::regex SINGLE_LOCALE(R"(^([a-zA-Z]{2})$)");
const std::regex REGION_LOCALE(R"(^([a-zA-Z]{2})-([a-zA-Z]{2})$)");
const std::regex VALID_URL_RE(R"(^https?://)");
/** Normalize a locale tag to Google's hreflang grammar: ll (ISO-639-1,
* lowercase) or ll-CC (region uppercase, ISO-3166). Case and surrounding
* whitespace are corrected ("en-us" -> "en-US"); anything else is invalid
* and returns nullopt. The C++ twin of normalizeLocale() in
* src/lib/hreflang.ts — nullopt stands in for the TS null. */
inline std::optional<std::string> normalizeLocale(const std::string& raw) {
std::string t = raw;
t.erase(0, t.find_first_not_of(" \t\r\n\v\f"));
std::string::size_type end = t.find_last_not_of(" \t\r\n\v\f");
t = end == std::string::npos ? "" : t.substr(0, end + 1);
std::smatch m;
if (std::regex_match(t, m, SINGLE_LOCALE)) {
std::string out = m[1].str();
for (char& c : out) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return out;
}
if (std::regex_match(t, m, REGION_LOCALE)) {
std::string lang = m[1].str();
std::string region = m[2].str();
for (char& c : lang) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
for (char& c : region) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
return lang + "-" + region;
}
return std::nullopt;
}
/** Trim raw and return it when it starts with http:// or https://, otherwise
* nullopt. Mirrors the TS validUrl() helper. */
inline std::optional<std::string> validUrl(const std::string& raw) {
std::string t = raw;
t.erase(0, t.find_first_not_of(" \t\r\n\v\f"));
std::string::size_type end = t.find_last_not_of(" \t\r\n\v\f");
t = end == std::string::npos ? "" : t.substr(0, end + 1);
if (std::regex_search(t, VALID_URL_RE)) return t;
return std::nullopt;
}
/** Validate a locale/URL table and emit both hreflang flavors. Invalid input
* collects every error (row-located) and emits empty blocks; valid input
* normalizes locales, preserves row order, and appends x-default last. */
inline HreflangResult buildHreflang(const HreflangInput& input) {
HreflangResult result;
std::set<std::string> seen;
for (size_t i = 0; i < input.rows.size(); i++) {
const std::size_t n = i + 1;
const HreflangRow& row = input.rows[i];
const std::string raw_locale = row.locale;
auto locale = normalizeLocale(raw_locale);
if (!locale) {
std::string trimmed = raw_locale;
trimmed.erase(0, trimmed.find_first_not_of(" \t\r\n\v\f"));
std::string::size_type e = trimmed.find_last_not_of(" \t\r\n\v\f");
trimmed = e == std::string::npos ? "" : trimmed.substr(0, e + 1);
result.errors.push_back(
"Row " + std::to_string(n) + ": \"" + trimmed +
"\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).");
continue;
}
if (seen.count(*locale)) {
result.errors.push_back("Row " + std::to_string(n) + ": locale \"" +
*locale + "\" is already used.");
continue;
}
std::string url_trimmed = row.url;
url_trimmed.erase(0, url_trimmed.find_first_not_of(" \t\r\n\v\f"));
if (url_trimmed.empty() ||
url_trimmed.find_last_not_of(" \t\r\n\v\f") == std::string::npos) {
result.errors.push_back("Row " + std::to_string(n) + ": URL is required.");
continue;
}
auto url = validUrl(row.url);
if (!url) {
result.errors.push_back("Row " + std::to_string(n) +
": URL must start with http:// or https://.");
continue;
}
seen.insert(*locale);
result.normalized.push_back(HreflangRow{*locale, *url});
}
std::optional<std::string> x_default;
if (input.x_default_url && !(*input.x_default_url).empty()) {
std::string trimmed = *input.x_default_url;
trimmed.erase(0, trimmed.find_first_not_of(" \t\r\n\v\f"));
if (!trimmed.empty()) {
x_default = validUrl(*input.x_default_url);
if (!x_default) {
result.errors.push_back(
"x-default: URL must start with http:// or https://.");
}
}
}
if (!result.errors.empty()) {
result.ok = false;
result.normalized.clear();
result.html = "";
result.sitemap = "";
return result;
}
for (const HreflangRow& r : result.normalized) {
result.html += "<link rel=\"alternate\" href=\"" + r.url +
"\" hreflang=\"" + r.locale + "\" />\n";
result.sitemap += " <xhtml:link rel=\"alternate\" hreflang=\"" +
r.locale + "\" href=\"" + r.url + "\"/>\n";
}
if (x_default) {
result.html += "<link rel=\"alternate\" href=\"" + *x_default +
"\" hreflang=\"x-default\" />\n";
result.sitemap += " <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"" +
*x_default + "\"/>\n";
}
if (!result.html.empty()) result.html.pop_back();
if (!result.sitemap.empty()) result.sitemap.pop_back();
result.ok = true;
return result;
}
} // namespace cosmodev::hreflang
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →