first commit
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
# `fallback.ts` — unconditional fallback detector
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## Purpose
|
||||
|
||||
`fallbackDetector(locale)` builds a `LocaleDetector` that always
|
||||
returns the configured locale. The detector is the floor of every
|
||||
chain — when querystring, cookie, storage, header, navigator, and
|
||||
geo all miss, the fallback guarantees a deterministic response.
|
||||
|
||||
Because the detector never returns `null`, it MUST appear last in
|
||||
any chain — any detector after it would never run. The constructor
|
||||
validates the supplied locale up-front and throws
|
||||
`I18nError(I18N.INVALID_LOCALE)` on empty / whitespace-only input
|
||||
so a misconfiguration surfaces at chain-build time rather than at
|
||||
the first request.
|
||||
|
||||
## Features
|
||||
|
||||
- `environment: "both"` — eligible on every chain run.
|
||||
- Constructor-time validation: empty string / whitespace string /
|
||||
non-string locale all throw a typed `I18nError(INVALID_LOCALE)`.
|
||||
- Locale value is trimmed once at construction; subsequent
|
||||
`detect` calls reuse the cached value.
|
||||
- Read-only — no `cache()` because the fallback has no source to
|
||||
persist to.
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import { fallbackDetector } from "@suaveplan/i18n-detector/detectors/fallback";
|
||||
|
||||
const detector = fallbackDetector("en-GB");
|
||||
const locale = detector.detect?.({
|
||||
supportedLocales: ["en-GB", "fr-FR"],
|
||||
fallbackLocale: "en-GB",
|
||||
});
|
||||
// locale === "en-GB"
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import { I18nError } from "@suaveplan/i18n-shared";
|
||||
import { fallbackDetector } from "@suaveplan/i18n-detector/detectors/fallback";
|
||||
|
||||
try {
|
||||
fallbackDetector("");
|
||||
} catch (err) {
|
||||
if (err instanceof I18nError) {
|
||||
console.error("misconfigured fallback:", err.code, err.message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- `fallbackDetector(locale: string): LocaleDetector` —
|
||||
`environment: "both"`, `name: "fallback"`. Has only `detect`;
|
||||
no `detectAsync`, no `cache`.
|
||||
- Throws `I18nError(I18N.INVALID_LOCALE)` synchronously on
|
||||
empty / whitespace / non-string input.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
- Validation runs once at detector-build time, not on every
|
||||
`detect` call — the chain pays no per-request cost for the
|
||||
guard.
|
||||
- The trimmed locale is captured by closure so the returned
|
||||
detector is allocation-free per request.
|
||||
- The fallback's `name` is fixed at `"fallback"` so chain
|
||||
consumers can identify it deterministically (e.g. to render
|
||||
a "default locale" warning in dev tools).
|
||||
Reference in New Issue
Block a user