laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use laravel::http::{IntoResponse, Redirect, Request, Response};

use crate::registry::{Registry, Settings};

/// The localized fallback: a URL that matches no route but exists under another locale is
/// redirected there with a `301` instead of being a `404`, so `/servicios` reaches `/es/servicios`
/// and `/es/services` reaches `/services`.
///
/// Locales are tried with the default one first and then in the configured order, so the
/// destination depends only on the path and never on the visitor, which is what makes a permanent
/// redirect safe. The query string travels along. Anything that cannot be rescued, and any request
/// that is not a `GET` or a `HEAD`, is a `404`.
///
/// With every locale prefixed, nothing is registered at the root, so `/` goes to the visitor's
/// language with a `302`, `Vary: Accept-Language` and `no-store`: the destination depends on who
/// asks, so a `301` would pin one language for everyone behind a cache. The language is what
/// laralocale detected: the stored choice, then `Accept-Language`, then the default.
///
/// The provider registers it when `fallback` is on. To keep a fallback of your own, leave that off
/// and call this from yours, or register it with [`LocalizedRoute::fallback`](crate::LocalizedRoute::fallback),
/// since a later fallback replaces an earlier one.
///
/// # Errors
///
/// Fails with a `404` when there is nothing to rescue.
pub async fn localized_fallback(request: Request) -> laravel::Result<Response> {
    let registry = Registry::current();
    let settings = registry.settings();
    let path = request.path().trim_matches('/').to_owned();

    if path.is_empty() && !settings.prefix(&settings.default_locale).is_empty() {
        let preferred = preferred_locale(&settings);
        let target = laravel::url::to(&format!("/{}", settings.prefix(&preferred)));

        return Ok(Redirect::to(target)
            .status(302)
            .with_header("vary", "accept-language")
            .with_header("cache-control", "no-store, private")
            .into_response());
    }

    match resolve(&request, &registry, &settings) {
        Some(target) => Ok(Redirect::to(target)
            .permanent()
            .with_header("cache-control", format!("max-age={}", settings.redirect_max_age))
            .into_response()),
        None => Err(laravel::abort(404)),
    }
}

fn preferred_locale(settings: &Settings) -> String {
    let locale = laralocale::locale();

    if settings.has_locale(&locale) {
        locale
    } else {
        settings.default_locale.clone()
    }
}

/// The URL of the same path under another locale, if a localized route serves it.
fn resolve(request: &Request, registry: &Registry, settings: &Settings) -> Option<String> {
    if !matches!(request.method().as_str(), "GET" | "HEAD") {
        return None;
    }

    let path = request.path().trim_matches('/');

    if path.is_empty() {
        return None;
    }

    let prefixes = settings.prefixes();
    let bare = without_locale_prefix(path, &prefixes);
    let mut order = vec![settings.default_locale.clone()];

    order.extend(
        settings
            .locales
            .iter()
            .filter(|locale| **locale != settings.default_locale)
            .cloned(),
    );

    for locale in order {
        let Some((_, prefix)) = prefixes.iter().find(|(candidate, _)| *candidate == locale) else {
            continue;
        };
        let candidate = format!("{prefix}/{bare}").trim_matches('/').to_owned();

        if candidate == path {
            continue;
        }

        if registry.serves(&format!("/{candidate}")) {
            let url = laravel::url::to(&format!("/{candidate}"));

            return Some(match request.uri().query() {
                Some(query) if !query.is_empty() => format!("{url}?{query}"),
                _ => url,
            });
        }
    }

    None
}

fn without_locale_prefix(path: &str, prefixes: &[(String, String)]) -> String {
    for (_, prefix) in prefixes {
        if prefix.is_empty() {
            continue;
        }

        if path == prefix {
            return String::new();
        }

        if let Some(rest) = path.strip_prefix(&format!("{prefix}/")) {
            return rest.trim_matches('/').to_owned();
        }
    }

    path.to_owned()
}