@aureus-core/i18n 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/client.d.ts +9 -0
- package/dist/internal/types/index.d.ts +2 -0
- package/dist/internal/types/index.js +0 -0
- package/dist/internal/types/resources-contract-types.d.ts +38 -0
- package/dist/internal/types/resources-contract-types.js +0 -0
- package/dist/internal/utils/constants/hmr-event.d.ts +5 -0
- package/dist/internal/utils/constants/hmr-event.js +7 -0
- package/dist/internal/utils/constants/index.d.ts +4 -0
- package/dist/internal/utils/constants/index.js +4 -0
- package/dist/internal/utils/constants/is-dev.d.ts +5 -0
- package/dist/internal/utils/constants/is-dev.js +7 -0
- package/dist/internal/utils/constants/virtual-module-id.d.ts +4 -0
- package/dist/internal/utils/constants/virtual-module-id.js +6 -0
- package/dist/internal/utils/helpers/index.d.ts +2 -0
- package/dist/internal/utils/helpers/index.js +1 -0
- package/dist/internal/utils/helpers/warn-once.d.ts +7 -0
- package/dist/internal/utils/helpers/warn-once.js +18 -0
- package/dist/runtime/index.d.ts +5 -0
- package/dist/runtime/index.js +1 -0
- package/dist/runtime/runtime.d.ts +20 -0
- package/dist/runtime/runtime.js +54 -0
- package/dist/runtime/types/index.d.ts +3 -0
- package/dist/runtime/types/index.js +0 -0
- package/dist/runtime/types/runtime-types.d.ts +47 -0
- package/dist/runtime/types/runtime-types.js +0 -0
- package/dist/runtime/utils/helpers/index.d.ts +6 -0
- package/dist/runtime/utils/helpers/index.js +6 -0
- package/dist/runtime/utils/helpers/language-detector.d.ts +16 -0
- package/dist/runtime/utils/helpers/language-detector.js +46 -0
- package/dist/runtime/utils/helpers/managed-options.d.ts +5 -0
- package/dist/runtime/utils/helpers/managed-options.js +27 -0
- package/dist/runtime/utils/helpers/match-language.d.ts +6 -0
- package/dist/runtime/utils/helpers/match-language.js +17 -0
- package/dist/runtime/utils/helpers/resources-backend.d.ts +9 -0
- package/dist/runtime/utils/helpers/resources-backend.js +19 -0
- package/dist/runtime/utils/helpers/sync-document.d.ts +6 -0
- package/dist/runtime/utils/helpers/sync-document.js +17 -0
- package/dist/vite/index.d.ts +3 -0
- package/dist/vite/index.js +1 -0
- package/dist/vite/types/index.d.ts +2 -0
- package/dist/vite/types/index.js +0 -0
- package/dist/vite/types/vite-types.d.ts +47 -0
- package/dist/vite/types/vite-types.js +0 -0
- package/dist/vite/utils/helpers/check-key-parity.d.ts +32 -0
- package/dist/vite/utils/helpers/check-key-parity.js +53 -0
- package/dist/vite/utils/helpers/flatten-keys.d.ts +9 -0
- package/dist/vite/utils/helpers/flatten-keys.js +18 -0
- package/dist/vite/utils/helpers/format-parity-report.d.ts +14 -0
- package/dist/vite/utils/helpers/format-parity-report.js +36 -0
- package/dist/vite/utils/helpers/index.d.ts +11 -0
- package/dist/vite/utils/helpers/index.js +11 -0
- package/dist/vite/utils/helpers/load-locales.d.ts +12 -0
- package/dist/vite/utils/helpers/load-locales.js +25 -0
- package/dist/vite/utils/helpers/match-glob.d.ts +17 -0
- package/dist/vite/utils/helpers/match-glob.js +53 -0
- package/dist/vite/utils/helpers/read-locale-file.d.ts +9 -0
- package/dist/vite/utils/helpers/read-locale-file.js +35 -0
- package/dist/vite/utils/helpers/render-types-file.d.ts +18 -0
- package/dist/vite/utils/helpers/render-types-file.js +48 -0
- package/dist/vite/utils/helpers/render-virtual-module.d.ts +14 -0
- package/dist/vite/utils/helpers/render-virtual-module.js +38 -0
- package/dist/vite/utils/helpers/scan-namespaces.d.ts +35 -0
- package/dist/vite/utils/helpers/scan-namespaces.js +68 -0
- package/dist/vite/utils/helpers/write-if-changed.d.ts +5 -0
- package/dist/vite/utils/helpers/write-if-changed.js +14 -0
- package/dist/vite/vite.d.ts +26 -0
- package/dist/vite/vite.js +184 -0
- package/package.json +84 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eddy Javier Cabrera Rodriguez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aureus-core/i18n
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
i18next for Aureus apps (Vite + React), configured from the folder layout. Keep your texts in `locales` folders and declare the rules once. Every namespace and language is found automatically, loaded only when needed, and `t()` is typed from your JSON files. ESM only, no root import.
|
|
4
|
+
|
|
5
|
+
**Documentation:** <https://ing-eddy.github.io/aureus-frontend-core/> (section **i18n**), in English and Spanish, with a live demo and examples.
|
|
6
|
+
|
|
7
|
+
## Why
|
|
8
|
+
|
|
9
|
+
- **No registration.** Create `src/features/payments/locales/es.json` and the `payments` namespace exists.
|
|
10
|
+
- **Autocompletion and type errors.** Namespaces and keys of `useTranslation()` and `t()` are suggested, and a wrong one is a type error.
|
|
11
|
+
- **Typed interpolation.** `"Hola, {{name}}"` requires `{ name }`.
|
|
12
|
+
- **Any language code.** The file name is the language: `es.json`, `es-MX.json` or only `pt-BR.json`. A region without a file of its own (`es-ES`) uses its base language (`es`).
|
|
13
|
+
- **Lazy loading.** One chunk per language and namespace, downloaded the first time a screen needs it.
|
|
14
|
+
- **Keys kept in sync.** A key or file missing in a language is a warning in development and an error in `vite build`.
|
|
15
|
+
- **Instant text edits.** Edited texts update without a reload. A new or deleted module reloads the page by itself.
|
|
16
|
+
- **Remembered language.** The first visit uses the browser's language, and the user's choice is stored.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
pnpm add @aureus-core/i18n i18next react-i18next
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
| Entry point | What it is |
|
|
25
|
+
| --------------------------- | ---------------------------------------------------------------------- |
|
|
26
|
+
| `@aureus-core/i18n/vite` | `aureusI18n(options)`, the Vite plugin (runs in Node; needs `vite` 8) |
|
|
27
|
+
| `@aureus-core/i18n/runtime` | `createI18n(config)`, the app's i18next instance (runs in the browser) |
|
|
28
|
+
| `@aureus-core/i18n/client` | Types of `virtual:aureus-i18n`, for the `types` of your tsconfig |
|
|
29
|
+
|
|
30
|
+
The required peers are `i18next` 27, `react-i18next` 18 and `react` 19. `vite` 8 is an optional peer.
|
|
31
|
+
|
|
32
|
+
## Minimal setup
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// vite.config.ts
|
|
36
|
+
import { aureusI18n } from "@aureus-core/i18n/vite";
|
|
37
|
+
|
|
38
|
+
export default defineConfig({
|
|
39
|
+
plugins: [react(), aureusI18n({ typesFrom: "es", defaultNamespace: "common" })],
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```jsonc
|
|
44
|
+
// tsconfig.app.json
|
|
45
|
+
{ "compilerOptions": { "types": ["vite/client", "@aureus-core/i18n/client"] } }
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
// src/i18n.ts
|
|
50
|
+
import { createI18n } from "@aureus-core/i18n/runtime";
|
|
51
|
+
import resources from "virtual:aureus-i18n";
|
|
52
|
+
|
|
53
|
+
export const i18n = createI18n({ resources, fallbackLng: "es" });
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```tsx
|
|
57
|
+
// src/main.tsx
|
|
58
|
+
import "./i18n";
|
|
59
|
+
createRoot(root).render(
|
|
60
|
+
<Suspense fallback={null}>
|
|
61
|
+
<App />
|
|
62
|
+
</Suspense>,
|
|
63
|
+
);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The plugin writes `src/types/i18next.d.ts` on start and on every change. Commit it.
|
|
67
|
+
|
|
68
|
+
## Examples
|
|
69
|
+
|
|
70
|
+
**A. No configuration.** With `src/common/locales/{en,es}.json` and `src/features/{auth,companies}/locales/{en,es}.json`, the namespaces are `auth`, `common` and `companies`, and the languages are `en` and `es`. Each namespace is named after the folder that contains `locales`.
|
|
71
|
+
|
|
72
|
+
**B. A new module.** While `pnpm dev` runs, create `src/features/payments/locales/{es,en}.json`. The terminal logs `[aureusI18n] Locales changed (added namespace "payments")…` and the page reloads. `useTranslation("payments")` now works and autocompletes.
|
|
73
|
+
|
|
74
|
+
**C. Typed `t()`.**
|
|
75
|
+
|
|
76
|
+
```tsx
|
|
77
|
+
const { t } = useTranslation("auth");
|
|
78
|
+
t("login.title"); // ✅ autocompleted
|
|
79
|
+
t("login.titel"); // ❌ type error
|
|
80
|
+
t("welcome", { name: "Ana" }); // ✅ "Hola, {{name}}"
|
|
81
|
+
t("welcome"); // ❌ type error: { name } is required
|
|
82
|
+
|
|
83
|
+
const { t: tt } = useTranslation(["auth", "common"]);
|
|
84
|
+
tt("common:actions.save"); // ✅ another namespace, with its prefix
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Options
|
|
88
|
+
|
|
89
|
+
`aureusI18n({ typesFrom, defaultNamespace?, include?, exclude?, namespaces?, typesFile? })`:
|
|
90
|
+
|
|
91
|
+
- `include` defaults to `["src/**/locales"]`;
|
|
92
|
+
- `node_modules`, `dist` and hidden folders are never searched;
|
|
93
|
+
- `namespaces` maps a folder to an explicit name (`{ "src/shared/i18n": "shared" }`).
|
|
94
|
+
|
|
95
|
+
`createI18n({ resources, fallbackLng, lng?, detection?, syncDocument?, options? })`:
|
|
96
|
+
|
|
97
|
+
- `detection: false` turns off the browser and stored language;
|
|
98
|
+
- `detection: { storageKey }` changes the `localStorage` key;
|
|
99
|
+
- `syncDocument: true` keeps `<html lang dir>` in sync;
|
|
100
|
+
- `options` is passed to i18next as is.
|
|
101
|
+
|
|
102
|
+
The guide has the full reference, examples D–I (keys out of sync, narrowing the search, collisions, language selection and RTL, schema hooks, extra i18next options) and a FAQ.
|
package/client.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Types of the virtual module served by the `@aureus-core/i18n/vite` plugin. Add this file to the
|
|
2
|
+
// `types` of the app's tsconfig: `"types": ["vite/client", "@aureus-core/i18n/client"]`.
|
|
3
|
+
// It is a script (no top-level import or export), so the module declaration below is ambient.
|
|
4
|
+
|
|
5
|
+
declare module "virtual:aureus-i18n" {
|
|
6
|
+
/** The discovered languages, namespaces and lazy loaders. Pass it to `createI18n({ resources })`. */
|
|
7
|
+
const resources: import("@aureus-core/i18n/runtime").I18nResources;
|
|
8
|
+
export default resources;
|
|
9
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** The content of one language of one namespace: the parsed object of its JSON file. */
|
|
2
|
+
export type I18nResourceContent = Record<string, unknown>;
|
|
3
|
+
/** A change to one locale file, sent during development so the texts update without a reload. */
|
|
4
|
+
export interface I18nUpdate {
|
|
5
|
+
/** The language whose file changed (`"es"`). */
|
|
6
|
+
readonly language: string;
|
|
7
|
+
/** The namespace whose file changed (`"auth"`). */
|
|
8
|
+
readonly namespace: string;
|
|
9
|
+
/** The new content of the file. */
|
|
10
|
+
readonly content: I18nResourceContent;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The resources the `@aureus-core/i18n/vite` plugin discovered, as served by `virtual:aureus-i18n`.
|
|
14
|
+
* The plugin writes this object and `createI18n` consumes it; apps only pass it along:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* import resources from "virtual:aureus-i18n";
|
|
18
|
+
* export const i18n = createI18n({ resources, fallbackLng: "es" });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export interface I18nResources {
|
|
22
|
+
/** Every discovered language, sorted (`["en", "es"]`). */
|
|
23
|
+
readonly languages: readonly string[];
|
|
24
|
+
/** Every discovered namespace, sorted (`["auth", "common"]`). */
|
|
25
|
+
readonly namespaces: readonly string[];
|
|
26
|
+
/** The `defaultNamespace` configured in the plugin, if any. */
|
|
27
|
+
readonly defaultNamespace?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Loads the content of one language of one namespace, on demand. Resolves to an empty object
|
|
30
|
+
* when that file does not exist.
|
|
31
|
+
*/
|
|
32
|
+
load(language: string, namespace: string): Promise<I18nResourceContent>;
|
|
33
|
+
/**
|
|
34
|
+
* Subscribes to locale file changes during development. Returns the function that unsubscribes.
|
|
35
|
+
* Never called in production builds.
|
|
36
|
+
*/
|
|
37
|
+
onUpdate(listener: (update: I18nUpdate) => void): () => void;
|
|
38
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// src/internal/utils/constants/hmr-event.ts
|
|
2
|
+
/**
|
|
3
|
+
* The custom HMR event the plugin sends when the content of a locale file changes during
|
|
4
|
+
* development. Its payload is an `I18nUpdate`.
|
|
5
|
+
*/
|
|
6
|
+
const HMR_UPDATE_EVENT = "aureus-i18n:update";
|
|
7
|
+
export { HMR_UPDATE_EVENT };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// src/internal/utils/constants/is-dev.ts
|
|
2
|
+
/**
|
|
3
|
+
* True outside production builds. Bundlers replace `process.env.NODE_ENV` statically, as they do
|
|
4
|
+
* for React itself, so development-only warnings are removed from production bundles.
|
|
5
|
+
*/
|
|
6
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
7
|
+
export { isDev };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The id apps import: `import resources from "virtual:aureus-i18n"`. */
|
|
2
|
+
export declare const VIRTUAL_MODULE_ID = "virtual:aureus-i18n";
|
|
3
|
+
/** The resolved id. The `\0` prefix tells Vite and other plugins that it is not a file on disk. */
|
|
4
|
+
export declare const RESOLVED_VIRTUAL_MODULE_ID = "\0virtual:aureus-i18n";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// src/internal/utils/constants/virtual-module-id.ts
|
|
2
|
+
/** The id apps import: `import resources from "virtual:aureus-i18n"`. */
|
|
3
|
+
const VIRTUAL_MODULE_ID = "virtual:aureus-i18n";
|
|
4
|
+
/** The resolved id. The `\0` prefix tells Vite and other plugins that it is not a file on disk. */
|
|
5
|
+
const RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
|
|
6
|
+
export { RESOLVED_VIRTUAL_MODULE_ID, VIRTUAL_MODULE_ID };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { resetWarnings, warnOnce } from "./warn-once.js";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logs `message` with `console.warn` once per `key`, and only outside production builds. Messages
|
|
3
|
+
* start with the function name in brackets (`[createI18n] …`).
|
|
4
|
+
*/
|
|
5
|
+
export declare function warnOnce(key: string, message: string): void;
|
|
6
|
+
/** Forgets every warning already logged. For tests only; not part of any public module. */
|
|
7
|
+
export declare function resetWarnings(): void;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { isDev } from "../constants/is-dev.js";
|
|
2
|
+
// src/internal/utils/helpers/warn-once.ts
|
|
3
|
+
/** The keys already warned about, kept for the life of the page. */
|
|
4
|
+
const warned = /* @__PURE__ */ new Set();
|
|
5
|
+
/**
|
|
6
|
+
* Logs `message` with `console.warn` once per `key`, and only outside production builds. Messages
|
|
7
|
+
* start with the function name in brackets (`[createI18n] …`).
|
|
8
|
+
*/
|
|
9
|
+
function warnOnce(key, message) {
|
|
10
|
+
if (!isDev || warned.has(key)) return;
|
|
11
|
+
warned.add(key);
|
|
12
|
+
console.warn(message);
|
|
13
|
+
}
|
|
14
|
+
/** Forgets every warning already logged. For tests only; not part of any public module. */
|
|
15
|
+
function resetWarnings() {
|
|
16
|
+
warned.clear();
|
|
17
|
+
}
|
|
18
|
+
export { resetWarnings, warnOnce };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { I18nResourceContent, I18nResources, I18nUpdate } from "../internal/types/resources-contract-types.js";
|
|
2
|
+
import { CreateI18nConfig, I18nDetectionOptions } from "./types/runtime-types.js";
|
|
3
|
+
import { createI18n } from "./runtime.js";
|
|
4
|
+
import "./types/index.js";
|
|
5
|
+
export { type CreateI18nConfig, type I18nDetectionOptions, type I18nResourceContent, type I18nResources, type I18nUpdate, createI18n };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createI18n } from "./runtime.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CreateI18nConfig } from "./types/runtime-types.js";
|
|
2
|
+
import "./types/index.js";
|
|
3
|
+
import { i18n } from "i18next";
|
|
4
|
+
/**
|
|
5
|
+
* Creates the app's i18next instance from the resources of the `@aureus-core/i18n/vite` plugin,
|
|
6
|
+
* with React bindings attached. Each language and namespace is loaded the first time it is needed,
|
|
7
|
+
* so wrap the app in `Suspense`. Returns i18next's own instance, already initializing.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* // src/i18n.ts
|
|
11
|
+
* import { createI18n } from "@aureus-core/i18n/runtime";
|
|
12
|
+
* import resources from "virtual:aureus-i18n";
|
|
13
|
+
*
|
|
14
|
+
* export const i18n = createI18n({ resources, fallbackLng: "es" });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* The instance is isolated from i18next's global one: outside React, import it from this file
|
|
18
|
+
* instead of `"i18next"`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createI18n(config: CreateI18nConfig): i18n;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { isDev } from "../internal/utils/constants/is-dev.js";
|
|
2
|
+
import { createLanguageDetector } from "./utils/helpers/language-detector.js";
|
|
3
|
+
import { createResourcesBackend } from "./utils/helpers/resources-backend.js";
|
|
4
|
+
import { syncDocument } from "./utils/helpers/sync-document.js";
|
|
5
|
+
import { withoutManagedOptions } from "./utils/helpers/managed-options.js";
|
|
6
|
+
import i18next from "i18next";
|
|
7
|
+
import { initReactI18next } from "react-i18next";
|
|
8
|
+
// src/runtime/runtime.ts
|
|
9
|
+
/**
|
|
10
|
+
* Creates the app's i18next instance from the resources of the `@aureus-core/i18n/vite` plugin,
|
|
11
|
+
* with React bindings attached. Each language and namespace is loaded the first time it is needed,
|
|
12
|
+
* so wrap the app in `Suspense`. Returns i18next's own instance, already initializing.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* // src/i18n.ts
|
|
16
|
+
* import { createI18n } from "@aureus-core/i18n/runtime";
|
|
17
|
+
* import resources from "virtual:aureus-i18n";
|
|
18
|
+
*
|
|
19
|
+
* export const i18n = createI18n({ resources, fallbackLng: "es" });
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* The instance is isolated from i18next's global one: outside React, import it from this file
|
|
23
|
+
* instead of `"i18next"`.
|
|
24
|
+
*/
|
|
25
|
+
function createI18n(config) {
|
|
26
|
+
const { resources } = config;
|
|
27
|
+
const defaultNamespace = resources.defaultNamespace;
|
|
28
|
+
const instance = i18next.createInstance();
|
|
29
|
+
instance.use(createResourcesBackend(resources));
|
|
30
|
+
if (config.lng === void 0 && config.detection !== false) {
|
|
31
|
+
const storageKey = config.detection?.storageKey ?? "aureus-i18n-language";
|
|
32
|
+
instance.use(createLanguageDetector({
|
|
33
|
+
languages: resources.languages,
|
|
34
|
+
storageKey
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
instance.use(initReactI18next);
|
|
38
|
+
if (config.syncDocument) syncDocument(instance);
|
|
39
|
+
if (isDev) resources.onUpdate(({ language, namespace, content }) => {
|
|
40
|
+
const code = instance.services.languageUtils.formatLanguageCode(language);
|
|
41
|
+
instance.addResourceBundle(code, namespace, content, false, true);
|
|
42
|
+
instance.emit("languageChanged", instance.language);
|
|
43
|
+
});
|
|
44
|
+
instance.init({
|
|
45
|
+
...withoutManagedOptions(config.options),
|
|
46
|
+
fallbackLng: config.fallbackLng,
|
|
47
|
+
...config.lng === void 0 ? {} : { lng: config.lng },
|
|
48
|
+
supportedLngs: [...resources.languages],
|
|
49
|
+
ns: defaultNamespace === void 0 ? [] : [defaultNamespace],
|
|
50
|
+
defaultNS: defaultNamespace ?? false
|
|
51
|
+
});
|
|
52
|
+
return instance;
|
|
53
|
+
}
|
|
54
|
+
export { createI18n };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { I18nResourceContent, I18nResources, I18nUpdate } from "../../internal/types/resources-contract-types.js";
|
|
2
|
+
import { CreateI18nConfig, I18nDetectionOptions } from "./runtime-types.js";
|
|
3
|
+
export type { CreateI18nConfig, I18nDetectionOptions, I18nResourceContent, I18nResources, I18nUpdate };
|
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { I18nResourceContent, I18nResources, I18nUpdate } from "../../internal/types/resources-contract-types.js";
|
|
2
|
+
import { FallbackLng, InitOptions } from "i18next";
|
|
3
|
+
/** Language detection of `createI18n`. */
|
|
4
|
+
export interface I18nDetectionOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The `localStorage` key where the user's language is remembered.
|
|
7
|
+
*
|
|
8
|
+
* @default "aureus-i18n-language"
|
|
9
|
+
*/
|
|
10
|
+
storageKey?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Configuration of `createI18n`. Only `resources` and `fallbackLng` are required. */
|
|
13
|
+
export interface CreateI18nConfig {
|
|
14
|
+
/** The default export of `virtual:aureus-i18n`, served by the `@aureus-core/i18n/vite` plugin. */
|
|
15
|
+
resources: I18nResources;
|
|
16
|
+
/**
|
|
17
|
+
* The language used when the active one has no text for a key, or is not supported. It is
|
|
18
|
+
* required: the library never chooses a language for you.
|
|
19
|
+
*/
|
|
20
|
+
fallbackLng: FallbackLng;
|
|
21
|
+
/** Forces the initial language. Language detection is off when it is given. */
|
|
22
|
+
lng?: string;
|
|
23
|
+
/**
|
|
24
|
+
* How the initial language is chosen when `lng` is not given. By default (or with an object): the
|
|
25
|
+
* language stored by a previous visit if it is still supported, else the first of the browser's
|
|
26
|
+
* preferred languages that matches a discovered language (`es-MX` → `es`), else `fallbackLng`.
|
|
27
|
+
* Every language i18next sets is stored in `localStorage`, including the one detected on the
|
|
28
|
+
* first visit. `false` turns detection off: the initial language is `fallbackLng` and nothing is
|
|
29
|
+
* stored.
|
|
30
|
+
*/
|
|
31
|
+
detection?: false | I18nDetectionOptions;
|
|
32
|
+
/**
|
|
33
|
+
* Keeps the `lang` and `dir` attributes of `<html>` in sync with the active language (for
|
|
34
|
+
* example `dir="rtl"` for Arabic).
|
|
35
|
+
*
|
|
36
|
+
* @default false
|
|
37
|
+
*/
|
|
38
|
+
syncDocument?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Any other i18next init option, passed as is. The options `createI18n` manages itself
|
|
41
|
+
* (`supportedLngs`, `nonExplicitSupportedLngs`, `load`, `ns`, `defaultNS`, `backend`,
|
|
42
|
+
* `resources`, `partialBundledLanguages`, `lng` and `fallbackLng`) are ignored here, with a
|
|
43
|
+
* development warning.
|
|
44
|
+
*/
|
|
45
|
+
options?: InitOptions;
|
|
46
|
+
}
|
|
47
|
+
export type { I18nResourceContent, I18nResources, I18nUpdate };
|
|
File without changes
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DEFAULT_STORAGE_KEY, LanguageDetectorOptions, createLanguageDetector } from "./language-detector.js";
|
|
2
|
+
import { MANAGED_OPTIONS, withoutManagedOptions } from "./managed-options.js";
|
|
3
|
+
import { matchLanguage } from "./match-language.js";
|
|
4
|
+
import { createResourcesBackend } from "./resources-backend.js";
|
|
5
|
+
import { syncDocument } from "./sync-document.js";
|
|
6
|
+
export { DEFAULT_STORAGE_KEY, type LanguageDetectorOptions, MANAGED_OPTIONS, createLanguageDetector, createResourcesBackend, matchLanguage, syncDocument, withoutManagedOptions };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DEFAULT_STORAGE_KEY, createLanguageDetector } from "./language-detector.js";
|
|
2
|
+
import { MANAGED_OPTIONS, withoutManagedOptions } from "./managed-options.js";
|
|
3
|
+
import { matchLanguage } from "./match-language.js";
|
|
4
|
+
import { createResourcesBackend } from "./resources-backend.js";
|
|
5
|
+
import { syncDocument } from "./sync-document.js";
|
|
6
|
+
export { DEFAULT_STORAGE_KEY, MANAGED_OPTIONS, createLanguageDetector, createResourcesBackend, matchLanguage, syncDocument, withoutManagedOptions };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { LanguageDetectorModule } from "i18next";
|
|
2
|
+
/** The default `localStorage` key of the remembered language. */
|
|
3
|
+
export declare const DEFAULT_STORAGE_KEY = "aureus-i18n-language";
|
|
4
|
+
/** Configuration of `createLanguageDetector`. */
|
|
5
|
+
export interface LanguageDetectorOptions {
|
|
6
|
+
/** The discovered languages. */
|
|
7
|
+
readonly languages: readonly string[];
|
|
8
|
+
/** The `localStorage` key that holds the remembered language. */
|
|
9
|
+
readonly storageKey: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* An i18next language detector: the stored language if it is still supported, else the first
|
|
13
|
+
* browser language that matches a discovered one, else nothing (i18next then uses `fallbackLng`).
|
|
14
|
+
* Every language change is stored. A `localStorage` that is missing or throws is ignored.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createLanguageDetector({ languages, storageKey }: LanguageDetectorOptions): LanguageDetectorModule;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { matchLanguage } from "./match-language.js";
|
|
2
|
+
// src/runtime/utils/helpers/language-detector.ts
|
|
3
|
+
/** The default `localStorage` key of the remembered language. */
|
|
4
|
+
const DEFAULT_STORAGE_KEY = "aureus-i18n-language";
|
|
5
|
+
/** `localStorage`, or `undefined` where it does not exist or access to it throws. */
|
|
6
|
+
function storage() {
|
|
7
|
+
try {
|
|
8
|
+
return typeof localStorage === "undefined" ? void 0 : localStorage;
|
|
9
|
+
} catch {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** The remembered language, or `undefined` when there is none or storage cannot be read. */
|
|
14
|
+
function readStored(key) {
|
|
15
|
+
try {
|
|
16
|
+
return storage()?.getItem(key) ?? void 0;
|
|
17
|
+
} catch {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** The browser's preferred languages, best first; empty where there is no `navigator`. */
|
|
22
|
+
function browserLanguages() {
|
|
23
|
+
if (typeof navigator === "undefined") return [];
|
|
24
|
+
if (navigator.languages && navigator.languages.length > 0) return navigator.languages;
|
|
25
|
+
return navigator.language ? [navigator.language] : [];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* An i18next language detector: the stored language if it is still supported, else the first
|
|
29
|
+
* browser language that matches a discovered one, else nothing (i18next then uses `fallbackLng`).
|
|
30
|
+
* Every language change is stored. A `localStorage` that is missing or throws is ignored.
|
|
31
|
+
*/
|
|
32
|
+
function createLanguageDetector({ languages, storageKey }) {
|
|
33
|
+
return {
|
|
34
|
+
type: "languageDetector",
|
|
35
|
+
detect() {
|
|
36
|
+
const stored = readStored(storageKey);
|
|
37
|
+
return (stored ? matchLanguage([stored], languages) : void 0) ?? matchLanguage(browserLanguages(), languages);
|
|
38
|
+
},
|
|
39
|
+
cacheUserLanguage(language) {
|
|
40
|
+
try {
|
|
41
|
+
storage()?.setItem(storageKey, language);
|
|
42
|
+
} catch {}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export { DEFAULT_STORAGE_KEY, createLanguageDetector };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { InitOptions } from "i18next";
|
|
2
|
+
/** i18next options that `createI18n` sets itself. */
|
|
3
|
+
export declare const MANAGED_OPTIONS: readonly ["supportedLngs", "nonExplicitSupportedLngs", "load", "ns", "defaultNS", "backend", "resources", "partialBundledLanguages", "lng", "fallbackLng"];
|
|
4
|
+
/** `options` without the managed ones. Each managed option found is warned about once. */
|
|
5
|
+
export declare function withoutManagedOptions(options?: InitOptions): InitOptions;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { warnOnce } from "../../../internal/utils/helpers/warn-once.js";
|
|
2
|
+
// src/runtime/utils/helpers/managed-options.ts
|
|
3
|
+
/** i18next options that `createI18n` sets itself. */
|
|
4
|
+
const MANAGED_OPTIONS = [
|
|
5
|
+
"supportedLngs",
|
|
6
|
+
"nonExplicitSupportedLngs",
|
|
7
|
+
"load",
|
|
8
|
+
"ns",
|
|
9
|
+
"defaultNS",
|
|
10
|
+
"backend",
|
|
11
|
+
"resources",
|
|
12
|
+
"partialBundledLanguages",
|
|
13
|
+
"lng",
|
|
14
|
+
"fallbackLng"
|
|
15
|
+
];
|
|
16
|
+
/** `options` without the managed ones. Each managed option found is warned about once. */
|
|
17
|
+
function withoutManagedOptions(options = {}) {
|
|
18
|
+
const rest = { ...options };
|
|
19
|
+
for (const name of MANAGED_OPTIONS) {
|
|
20
|
+
if (!(name in rest)) continue;
|
|
21
|
+
delete rest[name];
|
|
22
|
+
const hint = name === "lng" || name === "fallbackLng" ? `pass it as createI18n({ ${name} }) instead` : "it is set from the resources of the Vite plugin";
|
|
23
|
+
warnOnce(`managed-option:${name}`, `[createI18n] "${name}" is managed by createI18n and was ignored: ${hint}.`);
|
|
24
|
+
}
|
|
25
|
+
return rest;
|
|
26
|
+
}
|
|
27
|
+
export { MANAGED_OPTIONS, withoutManagedOptions };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The first candidate that matches a supported language, as written in `supported`. Each
|
|
3
|
+
* candidate is tried in order: an exact match (ignoring case), then its base language
|
|
4
|
+
* (`es-MX` → `es`), then a supported language with the same base (`pt` → `pt-BR`).
|
|
5
|
+
*/
|
|
6
|
+
export declare function matchLanguage(candidates: readonly string[], supported: readonly string[]): string | undefined;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/runtime/utils/helpers/match-language.ts
|
|
2
|
+
/** The base language of a tag, in lower case (`"es-MX"` → `"es"`). */
|
|
3
|
+
const baseOf = (code) => code.toLowerCase().split(/[-_]/)[0] ?? "";
|
|
4
|
+
/**
|
|
5
|
+
* The first candidate that matches a supported language, as written in `supported`. Each
|
|
6
|
+
* candidate is tried in order: an exact match (ignoring case), then its base language
|
|
7
|
+
* (`es-MX` → `es`), then a supported language with the same base (`pt` → `pt-BR`).
|
|
8
|
+
*/
|
|
9
|
+
function matchLanguage(candidates, supported) {
|
|
10
|
+
for (const candidate of candidates) {
|
|
11
|
+
const lower = candidate.toLowerCase();
|
|
12
|
+
const base = baseOf(candidate);
|
|
13
|
+
const match = supported.find((language) => language.toLowerCase() === lower) ?? supported.find((language) => language.toLowerCase() === base) ?? supported.find((language) => baseOf(language) === base);
|
|
14
|
+
if (match) return match;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export { matchLanguage };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { I18nResources } from "../../../internal/types/resources-contract-types.js";
|
|
2
|
+
import { BackendModule } from "i18next";
|
|
3
|
+
/**
|
|
4
|
+
* An i18next backend that loads each language and namespace through the virtual module, on demand.
|
|
5
|
+
* i18next asks with the canonical code, so the language is matched to a discovered one ignoring
|
|
6
|
+
* case (`pt-BR` loads `pt-br.json`). A failed load is passed to i18next, which does not retry it: the keys come from the fallback
|
|
7
|
+
* language.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createResourcesBackend(resources: I18nResources): BackendModule;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// src/runtime/utils/helpers/resources-backend.ts
|
|
2
|
+
/**
|
|
3
|
+
* An i18next backend that loads each language and namespace through the virtual module, on demand.
|
|
4
|
+
* i18next asks with the canonical code, so the language is matched to a discovered one ignoring
|
|
5
|
+
* case (`pt-BR` loads `pt-br.json`). A failed load is passed to i18next, which does not retry it: the keys come from the fallback
|
|
6
|
+
* language.
|
|
7
|
+
*/
|
|
8
|
+
function createResourcesBackend(resources) {
|
|
9
|
+
const discovered = new Map(resources.languages.map((language) => [language.toLowerCase(), language]));
|
|
10
|
+
return {
|
|
11
|
+
type: "backend",
|
|
12
|
+
callbackApi: false,
|
|
13
|
+
init() {},
|
|
14
|
+
read(language, namespace) {
|
|
15
|
+
return resources.load(discovered.get(language.toLowerCase()) ?? language, namespace);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export { createResourcesBackend };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/runtime/utils/helpers/sync-document.ts
|
|
2
|
+
/**
|
|
3
|
+
* Keeps `<html lang dir>` in sync with the active language of `instance`, now and on every
|
|
4
|
+
* language change. Does nothing where there is no `document`.
|
|
5
|
+
*/
|
|
6
|
+
function syncDocument(instance) {
|
|
7
|
+
const apply = () => {
|
|
8
|
+
if (typeof document === "undefined") return;
|
|
9
|
+
const language = instance.resolvedLanguage ?? instance.language;
|
|
10
|
+
if (!language) return;
|
|
11
|
+
document.documentElement.lang = language;
|
|
12
|
+
document.documentElement.dir = instance.dir(language);
|
|
13
|
+
};
|
|
14
|
+
instance.on("languageChanged", apply);
|
|
15
|
+
if (instance.isInitialized) apply();
|
|
16
|
+
}
|
|
17
|
+
export { syncDocument };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { aureusI18n } from "./vite.js";
|