@zairakai/js-i18n 1.0.15 → 2.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 +50 -56
- package/dist/index.cjs +38 -28
- package/dist/index.d.cts +3 -13
- package/dist/index.d.ts +3 -13
- package/dist/index.js +38 -28
- package/package.json +29 -16
- package/src/index.ts +5 -2
- package/src/pluralization.ts +41 -16
- package/src/schemas.ts +18 -10
- package/src/translator.ts +36 -17
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Stanislas Poisson (Zairakai)
|
|
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,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://gitlab.com/zairakai/npm-packages/js-i18n/-/raw/main/assets/icon.png" alt="JS i18n" width="160">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
# JS i18n
|
|
2
6
|
|
|
3
7
|
[![Main][pipeline-main-badge]][pipeline-main-link]
|
|
4
8
|
[![Develop][pipeline-develop-badge]][pipeline-develop-link]
|
|
@@ -12,8 +16,10 @@
|
|
|
12
16
|
[![Node.js][node-badge]][node]
|
|
13
17
|
[![ESLint][eslint-badge]][eslint]
|
|
14
18
|
[![Prettier][prettier-badge]][prettier]
|
|
19
|
+
[![Vitest][vitest-badge]][vitest]
|
|
20
|
+
[![Knip][knip-badge]][knip]
|
|
15
21
|
|
|
16
|
-
|
|
22
|
+
Internationalization library for the web with Laravel-style translation, pluralization, dot-notation keys and multi-locale support. Translations are validated at runtime with `zod`.
|
|
17
23
|
|
|
18
24
|
**Documentation: [js-i18n-8f9736.gitlab.io][docs]**
|
|
19
25
|
|
|
@@ -21,11 +27,11 @@ Lightweight internationalization library with Laravel-style translation, plurali
|
|
|
21
27
|
|
|
22
28
|
## Features
|
|
23
29
|
|
|
24
|
-
- **Laravel-style `__()`**
|
|
25
|
-
- **Dot notation keys**
|
|
26
|
-
- **Multi-locale**
|
|
27
|
-
- **Runtime validation**
|
|
28
|
-
- **Type-safe**
|
|
30
|
+
- **Laravel-style `__()`** - familiar `:attribute` replacement and `{0} | {1} | [2,*] :count` pluralization
|
|
31
|
+
- **Dot notation keys** - navigate nested translation objects with `auth.login.title`
|
|
32
|
+
- **Multi-locale** - manage any number of locales, switch at runtime
|
|
33
|
+
- **Runtime validation** - translation data validated at runtime, invalid structures throw with a descriptive error message
|
|
34
|
+
- **Type-safe** - full TypeScript types for IDE support and static analysis
|
|
29
35
|
|
|
30
36
|
---
|
|
31
37
|
|
|
@@ -41,6 +47,12 @@ The documentation site has this guide and the reference of the API generated fro
|
|
|
41
47
|
npm install @zairakai/js-i18n
|
|
42
48
|
```
|
|
43
49
|
|
|
50
|
+
### In the browser
|
|
51
|
+
|
|
52
|
+
The library is made for the web: ESM and CommonJS builds, no Node.js built-ins, `"sideEffects": false`. A bundler keeps only what you import (the tests of this repository check it with esbuild): a project that imports `applyPluralization` alone gets a few hundred bytes. `createTranslator` validates the translations with `zod`, so it brings `zod` with it.
|
|
53
|
+
|
|
54
|
+
There is no minimum browser version.
|
|
55
|
+
|
|
44
56
|
---
|
|
45
57
|
|
|
46
58
|
## Usage
|
|
@@ -74,7 +86,8 @@ i18n.__('welcome', { name: 'Stan' }) // "Welcome, Stan!"
|
|
|
74
86
|
i18n.__('auth.login') // "Sign in"
|
|
75
87
|
```
|
|
76
88
|
|
|
77
|
-
|
|
89
|
+
<details>
|
|
90
|
+
<summary>Pluralization: singular, plural and ranges</summary>
|
|
78
91
|
|
|
79
92
|
```typescript
|
|
80
93
|
import { createI18n } from '@zairakai/js-i18n'
|
|
@@ -91,13 +104,19 @@ i18n.__('apples', 1) // "One apple"
|
|
|
91
104
|
i18n.__('apples', 5) // "5 apples"
|
|
92
105
|
```
|
|
93
106
|
|
|
94
|
-
|
|
107
|
+
</details>
|
|
108
|
+
|
|
109
|
+
<details>
|
|
110
|
+
<summary>Count and replacements together</summary>
|
|
95
111
|
|
|
96
112
|
```typescript
|
|
97
113
|
i18n.__('files', 3, { extra: 'info' }) // "3 files"
|
|
98
114
|
```
|
|
99
115
|
|
|
100
|
-
|
|
116
|
+
</details>
|
|
117
|
+
|
|
118
|
+
<details>
|
|
119
|
+
<summary>Managing locales at runtime</summary>
|
|
101
120
|
|
|
102
121
|
```typescript
|
|
103
122
|
i18n.setLocale('fr')
|
|
@@ -111,7 +130,10 @@ i18n.hasTranslation('auth.login', 'de') // true
|
|
|
111
130
|
i18n.hasTranslation('auth.logout', 'de') // false
|
|
112
131
|
```
|
|
113
132
|
|
|
114
|
-
|
|
133
|
+
</details>
|
|
134
|
+
|
|
135
|
+
<details>
|
|
136
|
+
<summary>Error handling: what throws and when</summary>
|
|
115
137
|
|
|
116
138
|
Translation data is validated at runtime. Invalid structures (e.g. loading from an API or external JSON) throw an `Error` with a descriptive message indicating exactly what is wrong.
|
|
117
139
|
|
|
@@ -129,20 +151,21 @@ try {
|
|
|
129
151
|
|
|
130
152
|
The same applies to `setTranslations()`, `addTranslations()`, and `translate()` when replacements are malformed.
|
|
131
153
|
|
|
132
|
-
|
|
154
|
+
</details>
|
|
133
155
|
|
|
134
|
-
|
|
156
|
+
<details>
|
|
157
|
+
<summary>Pluralization syntax: the forms a translation can take</summary>
|
|
135
158
|
|
|
136
159
|
The pluralization format follows Laravel's `trans_choice` pattern exactly.
|
|
137
160
|
|
|
138
|
-
| Pattern
|
|
139
|
-
|
|
|
140
|
-
| `{0}`
|
|
141
|
-
| `{1}`
|
|
142
|
-
| `{n}`
|
|
143
|
-
| `[2,*]`
|
|
144
|
-
| `[0,1]`
|
|
145
|
-
| `[1,10]`
|
|
161
|
+
| Pattern | Matches | Example |
|
|
162
|
+
| :--- | :--- | :--- |
|
|
163
|
+
| `{0}` | Exactly 0 | `{0} No items` |
|
|
164
|
+
| `{1}` | Exactly 1 | `{1} One item` |
|
|
165
|
+
| `{n}` | Exactly n | `{5} Exactly five` |
|
|
166
|
+
| `[2,*]` | 2 and above | `[2,*] :count items` |
|
|
167
|
+
| `[0,1]` | 0 or 1 | `[0,1] :count file` |
|
|
168
|
+
| `[1,10]` | Between 1 and 10 (inclusive) | `[1,10] a few items` |
|
|
146
169
|
|
|
147
170
|
Forms are separated by `|`. The `:count` placeholder is automatically replaced by the count value.
|
|
148
171
|
|
|
@@ -151,40 +174,7 @@ Forms are separated by `|`. The `:count` placeholder is automatically replaced b
|
|
|
151
174
|
'{0} No apples|{1} One apple|[2,*] :count apples'
|
|
152
175
|
```
|
|
153
176
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
## API Reference
|
|
157
|
-
|
|
158
|
-
### Factory functions
|
|
159
|
-
|
|
160
|
-
| Function | Description |
|
|
161
|
-
| --- | --- |
|
|
162
|
-
| `createI18n(translations?, locale?)` | Creates a translator instance (alias, preferred). |
|
|
163
|
-
| `createTranslator(translations?, locale?)` | Creates a translator instance (explicit name). |
|
|
164
|
-
|
|
165
|
-
Both return a `Translator` instance. Default locale is `'en'`.
|
|
166
|
-
|
|
167
|
-
### Translator methods
|
|
168
|
-
|
|
169
|
-
| Method | Description |
|
|
170
|
-
| --------------------------------------- | ------------------------------------------------------- |
|
|
171
|
-
| `__(path, replacements?)` | Translate a key with optional replacements. |
|
|
172
|
-
| `__(path, count, replacements?)` | Translate with pluralization count. |
|
|
173
|
-
| `translate(path, replacements?)` | Alias for `__`. |
|
|
174
|
-
| `translate(path, count, replacements?)` | Alias for `__` with count. |
|
|
175
|
-
| `setLocale(locale)` | Set the active locale. |
|
|
176
|
-
| `getLocale()` | Get the active locale. |
|
|
177
|
-
| `setTranslations(locale, translations)` | Replace all translations for a locale. |
|
|
178
|
-
| `addTranslations(locale, translations)` | Merge translations into an existing locale. |
|
|
179
|
-
| `hasTranslation(path, locale?)` | Check if a translation key exists (uses active locale). |
|
|
180
|
-
| `getAvailableLocales()` | Return all registered locale codes. |
|
|
181
|
-
|
|
182
|
-
### Pluralization utilities
|
|
183
|
-
|
|
184
|
-
| Function | Description |
|
|
185
|
-
| ---------------------------------- | ----------------------------------------------- |
|
|
186
|
-
| `applyPluralization(value, count)` | Apply pluralization to a raw string with count. |
|
|
187
|
-
| `selectPluralForm(forms, count)` | Select the correct form from a pre-split array. |
|
|
177
|
+
</details>
|
|
188
178
|
|
|
189
179
|
---
|
|
190
180
|
|
|
@@ -230,7 +220,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full development workflow.
|
|
|
230
220
|
[license]: ./LICENSE
|
|
231
221
|
[security-badge]: https://img.shields.io/badge/security-scanned-green.svg
|
|
232
222
|
[security]: ./SECURITY.md
|
|
233
|
-
[issues-badge]: https://img.shields.io/gitlab/issues/open-raw/zairakai%2Fnpm-packages%
|
|
223
|
+
[issues-badge]: https://img.shields.io/gitlab/issues/open-raw/zairakai%2Fnpm-packages%2Fjs-i18n?logo=gitlab&label=Issues
|
|
234
224
|
[issues]: https://gitlab.com/zairakai/npm-packages/js-i18n/-/issues
|
|
235
225
|
[node-badge]: https://img.shields.io/badge/node.js-%3E%3D24-green.svg?logo=node.js
|
|
236
226
|
[node]: https://nodejs.org
|
|
@@ -238,6 +228,10 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full development workflow.
|
|
|
238
228
|
[eslint]: https://eslint.org
|
|
239
229
|
[prettier-badge]: https://img.shields.io/badge/formatter-prettier-F7B93E.svg?logo=prettier
|
|
240
230
|
[prettier]: https://prettier.io
|
|
231
|
+
[vitest-badge]: https://img.shields.io/badge/test-vitest-6E9F18.svg?logo=vitest
|
|
232
|
+
[vitest]: https://vitest.dev
|
|
233
|
+
[knip-badge]: https://img.shields.io/badge/dead%20code-knip-EC4899.svg
|
|
234
|
+
[knip]: https://knip.dev
|
|
241
235
|
[ecosystem]: https://gitlab.com/zairakai
|
|
242
236
|
[docs]: https://js-i18n-8f9736.gitlab.io
|
|
243
237
|
[docs-badge]: https://img.shields.io/badge/docs-online-blue
|
package/dist/index.cjs
CHANGED
|
@@ -28,22 +28,26 @@ __export(src_exports, {
|
|
|
28
28
|
module.exports = __toCommonJS(src_exports);
|
|
29
29
|
|
|
30
30
|
// src/pluralization.ts
|
|
31
|
+
var group = (match, index) => match[index] ?? "";
|
|
32
|
+
var first = (part) => part?.trim() ?? "";
|
|
31
33
|
var selectPluralForm = (message, count) => {
|
|
32
34
|
const parts = message.split("|");
|
|
33
35
|
for (const part of parts) {
|
|
34
36
|
const trimmedPart = part.trim();
|
|
35
37
|
const exactMatch2 = trimmedPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
36
|
-
const rangeMatch2 = trimmedPart.match(
|
|
38
|
+
const rangeMatch2 = trimmedPart.match(
|
|
39
|
+
/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/
|
|
40
|
+
);
|
|
37
41
|
if (exactMatch2) {
|
|
38
|
-
const exactNumber = parseInt(exactMatch2
|
|
42
|
+
const exactNumber = parseInt(group(exactMatch2, 1), 10);
|
|
39
43
|
if (count === exactNumber) {
|
|
40
|
-
return exactMatch2
|
|
44
|
+
return group(exactMatch2, 2).trim();
|
|
41
45
|
}
|
|
42
46
|
} else if (rangeMatch2) {
|
|
43
|
-
const min =
|
|
44
|
-
const max =
|
|
47
|
+
const min = rangeMatch2[1] === "*" ? -Infinity : parseInt(group(rangeMatch2, 1), 10);
|
|
48
|
+
const max = rangeMatch2[2] === "*" ? Infinity : parseInt(group(rangeMatch2, 2), 10);
|
|
45
49
|
if (count >= min && count <= max) {
|
|
46
|
-
return rangeMatch2
|
|
50
|
+
return group(rangeMatch2, 3).trim();
|
|
47
51
|
}
|
|
48
52
|
}
|
|
49
53
|
}
|
|
@@ -51,23 +55,25 @@ var selectPluralForm = (message, count) => {
|
|
|
51
55
|
const trimmed = part.trim();
|
|
52
56
|
return !trimmed.match(/^[{\[]/);
|
|
53
57
|
});
|
|
54
|
-
if (
|
|
55
|
-
return
|
|
56
|
-
} else if (
|
|
57
|
-
return simpleParts[0]
|
|
58
|
+
if (simpleParts.length >= 2) {
|
|
59
|
+
return first(simpleParts[count === 1 ? 0 : 1]);
|
|
60
|
+
} else if (simpleParts.length === 1) {
|
|
61
|
+
return first(simpleParts[0]);
|
|
58
62
|
}
|
|
59
|
-
const firstPart = parts[0]
|
|
63
|
+
const firstPart = first(parts[0]);
|
|
60
64
|
const exactMatch = firstPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
61
|
-
const rangeMatch = firstPart.match(
|
|
65
|
+
const rangeMatch = firstPart.match(
|
|
66
|
+
/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/
|
|
67
|
+
);
|
|
62
68
|
if (exactMatch) {
|
|
63
|
-
return exactMatch
|
|
69
|
+
return group(exactMatch, 2).trim();
|
|
64
70
|
} else if (rangeMatch) {
|
|
65
|
-
return rangeMatch
|
|
71
|
+
return group(rangeMatch, 3).trim();
|
|
66
72
|
}
|
|
67
73
|
return firstPart;
|
|
68
74
|
};
|
|
69
75
|
var applyPluralization = (translation, count) => {
|
|
70
|
-
if ("string"
|
|
76
|
+
if (typeof translation === "string" && translation.includes("|") && count !== null) {
|
|
71
77
|
return selectPluralForm(translation, count);
|
|
72
78
|
}
|
|
73
79
|
return translation;
|
|
@@ -82,12 +88,15 @@ var TranslationObjectSchema = import_zod.z.record(
|
|
|
82
88
|
import_zod.z.string(),
|
|
83
89
|
TranslationValueSchema
|
|
84
90
|
);
|
|
85
|
-
var TranslationDataSchema = import_zod.z.record(
|
|
86
|
-
var ReplacementParametersSchema = import_zod.z.record(
|
|
91
|
+
var TranslationDataSchema = import_zod.z.record(
|
|
87
92
|
import_zod.z.string(),
|
|
88
|
-
|
|
93
|
+
TranslationObjectSchema
|
|
89
94
|
);
|
|
90
|
-
var
|
|
95
|
+
var ReplacementParametersSchema = import_zod.z.record(import_zod.z.string(), import_zod.z.union([import_zod.z.string(), import_zod.z.number()]));
|
|
96
|
+
var CountOrReplacementsSchema = import_zod.z.union([
|
|
97
|
+
import_zod.z.number(),
|
|
98
|
+
ReplacementParametersSchema
|
|
99
|
+
]);
|
|
91
100
|
|
|
92
101
|
// src/translator.ts
|
|
93
102
|
var createTranslator = (translations = {}, locale = "en") => {
|
|
@@ -98,7 +107,7 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
98
107
|
ReplacementParametersSchema.parse(replacements);
|
|
99
108
|
let count = null;
|
|
100
109
|
let actualReplacements = replacements;
|
|
101
|
-
if ("number"
|
|
110
|
+
if (typeof countOrReplacements === "number") {
|
|
102
111
|
count = countOrReplacements;
|
|
103
112
|
actualReplacements = { count: countOrReplacements, ...replacements };
|
|
104
113
|
} else {
|
|
@@ -110,13 +119,13 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
110
119
|
const segments = path.split(".");
|
|
111
120
|
let translation = currentTranslations[currentLocale];
|
|
112
121
|
for (const segment of segments) {
|
|
113
|
-
if (translation && "object"
|
|
122
|
+
if (translation && typeof translation === "object" && Object.prototype.hasOwnProperty.call(translation, segment)) {
|
|
114
123
|
translation = translation[segment];
|
|
115
124
|
} else {
|
|
116
125
|
return path;
|
|
117
126
|
}
|
|
118
127
|
}
|
|
119
|
-
if ("string"
|
|
128
|
+
if (typeof translation === "string") {
|
|
120
129
|
const pluralizedTranslation = applyPluralization(translation, count);
|
|
121
130
|
const result = pluralizedTranslation.replace(/:(\w+)/g, (match, key) => {
|
|
122
131
|
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match;
|
|
@@ -136,10 +145,11 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
136
145
|
};
|
|
137
146
|
const addTranslations = (locale2, translations2) => {
|
|
138
147
|
const validated = TranslationObjectSchema.parse(translations2);
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
148
|
+
currentTranslations[locale2] ??= {};
|
|
149
|
+
currentTranslations[locale2] = {
|
|
150
|
+
...currentTranslations[locale2],
|
|
151
|
+
...validated
|
|
152
|
+
};
|
|
143
153
|
};
|
|
144
154
|
const hasTranslation = (path, locale2 = null) => {
|
|
145
155
|
const checkLocale = locale2 ?? currentLocale;
|
|
@@ -149,13 +159,13 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
149
159
|
const segments = path.split(".");
|
|
150
160
|
let current = currentTranslations[checkLocale];
|
|
151
161
|
for (const segment of segments) {
|
|
152
|
-
if (current && "object"
|
|
162
|
+
if (current && typeof current === "object" && segment in current) {
|
|
153
163
|
current = current[segment];
|
|
154
164
|
} else {
|
|
155
165
|
return false;
|
|
156
166
|
}
|
|
157
167
|
}
|
|
158
|
-
return "string"
|
|
168
|
+
return typeof current === "string";
|
|
159
169
|
};
|
|
160
170
|
const getAvailableLocales = () => Object.keys(currentTranslations);
|
|
161
171
|
return {
|
package/dist/index.d.cts
CHANGED
|
@@ -2,17 +2,6 @@
|
|
|
2
2
|
* Pluralization utilities for Laravel-style translation strings
|
|
3
3
|
* Handles complex pluralization rules with conditions and ranges
|
|
4
4
|
*/
|
|
5
|
-
/**
|
|
6
|
-
* Selects the appropriate plural form based on count
|
|
7
|
-
* Supports Laravel formats:
|
|
8
|
-
* - Simple: "item|items"
|
|
9
|
-
* - With conditions: "{0} none|{1} one|[2,*] many"
|
|
10
|
-
* - With ranges: "[1,19] some|[20,*] many"
|
|
11
|
-
*
|
|
12
|
-
* @param message - Translation string with plural forms
|
|
13
|
-
* @param count - Count to determine plural form
|
|
14
|
-
* @returns Selected plural form
|
|
15
|
-
*/
|
|
16
5
|
declare const selectPluralForm: (message: string, count: number) => string;
|
|
17
6
|
/**
|
|
18
7
|
* Apply pluralization rules to a translation
|
|
@@ -74,7 +63,7 @@ declare const createTranslator: (translations?: TranslationData, locale?: string
|
|
|
74
63
|
|
|
75
64
|
/**
|
|
76
65
|
* @zairakai/npm-i18n
|
|
77
|
-
*
|
|
66
|
+
* Internationalization library with Laravel-style features
|
|
78
67
|
*/
|
|
79
68
|
|
|
80
69
|
/**
|
|
@@ -85,4 +74,5 @@ declare const createTranslator: (translations?: TranslationData, locale?: string
|
|
|
85
74
|
*/
|
|
86
75
|
declare const createI18n: (translations?: TranslationData, locale?: string) => Translator;
|
|
87
76
|
|
|
88
|
-
export {
|
|
77
|
+
export { applyPluralization, createI18n, createTranslator, selectPluralForm };
|
|
78
|
+
export type { ReplacementParameters, TranslateFunction, TranslationData, TranslationObject, Translator };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,17 +2,6 @@
|
|
|
2
2
|
* Pluralization utilities for Laravel-style translation strings
|
|
3
3
|
* Handles complex pluralization rules with conditions and ranges
|
|
4
4
|
*/
|
|
5
|
-
/**
|
|
6
|
-
* Selects the appropriate plural form based on count
|
|
7
|
-
* Supports Laravel formats:
|
|
8
|
-
* - Simple: "item|items"
|
|
9
|
-
* - With conditions: "{0} none|{1} one|[2,*] many"
|
|
10
|
-
* - With ranges: "[1,19] some|[20,*] many"
|
|
11
|
-
*
|
|
12
|
-
* @param message - Translation string with plural forms
|
|
13
|
-
* @param count - Count to determine plural form
|
|
14
|
-
* @returns Selected plural form
|
|
15
|
-
*/
|
|
16
5
|
declare const selectPluralForm: (message: string, count: number) => string;
|
|
17
6
|
/**
|
|
18
7
|
* Apply pluralization rules to a translation
|
|
@@ -74,7 +63,7 @@ declare const createTranslator: (translations?: TranslationData, locale?: string
|
|
|
74
63
|
|
|
75
64
|
/**
|
|
76
65
|
* @zairakai/npm-i18n
|
|
77
|
-
*
|
|
66
|
+
* Internationalization library with Laravel-style features
|
|
78
67
|
*/
|
|
79
68
|
|
|
80
69
|
/**
|
|
@@ -85,4 +74,5 @@ declare const createTranslator: (translations?: TranslationData, locale?: string
|
|
|
85
74
|
*/
|
|
86
75
|
declare const createI18n: (translations?: TranslationData, locale?: string) => Translator;
|
|
87
76
|
|
|
88
|
-
export {
|
|
77
|
+
export { applyPluralization, createI18n, createTranslator, selectPluralForm };
|
|
78
|
+
export type { ReplacementParameters, TranslateFunction, TranslationData, TranslationObject, Translator };
|
package/dist/index.js
CHANGED
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
// src/pluralization.ts
|
|
2
|
+
var group = (match, index) => match[index] ?? "";
|
|
3
|
+
var first = (part) => part?.trim() ?? "";
|
|
2
4
|
var selectPluralForm = (message, count) => {
|
|
3
5
|
const parts = message.split("|");
|
|
4
6
|
for (const part of parts) {
|
|
5
7
|
const trimmedPart = part.trim();
|
|
6
8
|
const exactMatch2 = trimmedPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
7
|
-
const rangeMatch2 = trimmedPart.match(
|
|
9
|
+
const rangeMatch2 = trimmedPart.match(
|
|
10
|
+
/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/
|
|
11
|
+
);
|
|
8
12
|
if (exactMatch2) {
|
|
9
|
-
const exactNumber = parseInt(exactMatch2
|
|
13
|
+
const exactNumber = parseInt(group(exactMatch2, 1), 10);
|
|
10
14
|
if (count === exactNumber) {
|
|
11
|
-
return exactMatch2
|
|
15
|
+
return group(exactMatch2, 2).trim();
|
|
12
16
|
}
|
|
13
17
|
} else if (rangeMatch2) {
|
|
14
|
-
const min =
|
|
15
|
-
const max =
|
|
18
|
+
const min = rangeMatch2[1] === "*" ? -Infinity : parseInt(group(rangeMatch2, 1), 10);
|
|
19
|
+
const max = rangeMatch2[2] === "*" ? Infinity : parseInt(group(rangeMatch2, 2), 10);
|
|
16
20
|
if (count >= min && count <= max) {
|
|
17
|
-
return rangeMatch2
|
|
21
|
+
return group(rangeMatch2, 3).trim();
|
|
18
22
|
}
|
|
19
23
|
}
|
|
20
24
|
}
|
|
@@ -22,23 +26,25 @@ var selectPluralForm = (message, count) => {
|
|
|
22
26
|
const trimmed = part.trim();
|
|
23
27
|
return !trimmed.match(/^[{\[]/);
|
|
24
28
|
});
|
|
25
|
-
if (
|
|
26
|
-
return
|
|
27
|
-
} else if (
|
|
28
|
-
return simpleParts[0]
|
|
29
|
+
if (simpleParts.length >= 2) {
|
|
30
|
+
return first(simpleParts[count === 1 ? 0 : 1]);
|
|
31
|
+
} else if (simpleParts.length === 1) {
|
|
32
|
+
return first(simpleParts[0]);
|
|
29
33
|
}
|
|
30
|
-
const firstPart = parts[0]
|
|
34
|
+
const firstPart = first(parts[0]);
|
|
31
35
|
const exactMatch = firstPart.match(/^{\s*(\d+)\s*}\s*(.*)$/);
|
|
32
|
-
const rangeMatch = firstPart.match(
|
|
36
|
+
const rangeMatch = firstPart.match(
|
|
37
|
+
/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/
|
|
38
|
+
);
|
|
33
39
|
if (exactMatch) {
|
|
34
|
-
return exactMatch
|
|
40
|
+
return group(exactMatch, 2).trim();
|
|
35
41
|
} else if (rangeMatch) {
|
|
36
|
-
return rangeMatch
|
|
42
|
+
return group(rangeMatch, 3).trim();
|
|
37
43
|
}
|
|
38
44
|
return firstPart;
|
|
39
45
|
};
|
|
40
46
|
var applyPluralization = (translation, count) => {
|
|
41
|
-
if ("string"
|
|
47
|
+
if (typeof translation === "string" && translation.includes("|") && count !== null) {
|
|
42
48
|
return selectPluralForm(translation, count);
|
|
43
49
|
}
|
|
44
50
|
return translation;
|
|
@@ -53,12 +59,15 @@ var TranslationObjectSchema = z.record(
|
|
|
53
59
|
z.string(),
|
|
54
60
|
TranslationValueSchema
|
|
55
61
|
);
|
|
56
|
-
var TranslationDataSchema = z.record(
|
|
57
|
-
var ReplacementParametersSchema = z.record(
|
|
62
|
+
var TranslationDataSchema = z.record(
|
|
58
63
|
z.string(),
|
|
59
|
-
|
|
64
|
+
TranslationObjectSchema
|
|
60
65
|
);
|
|
61
|
-
var
|
|
66
|
+
var ReplacementParametersSchema = z.record(z.string(), z.union([z.string(), z.number()]));
|
|
67
|
+
var CountOrReplacementsSchema = z.union([
|
|
68
|
+
z.number(),
|
|
69
|
+
ReplacementParametersSchema
|
|
70
|
+
]);
|
|
62
71
|
|
|
63
72
|
// src/translator.ts
|
|
64
73
|
var createTranslator = (translations = {}, locale = "en") => {
|
|
@@ -69,7 +78,7 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
69
78
|
ReplacementParametersSchema.parse(replacements);
|
|
70
79
|
let count = null;
|
|
71
80
|
let actualReplacements = replacements;
|
|
72
|
-
if ("number"
|
|
81
|
+
if (typeof countOrReplacements === "number") {
|
|
73
82
|
count = countOrReplacements;
|
|
74
83
|
actualReplacements = { count: countOrReplacements, ...replacements };
|
|
75
84
|
} else {
|
|
@@ -81,13 +90,13 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
81
90
|
const segments = path.split(".");
|
|
82
91
|
let translation = currentTranslations[currentLocale];
|
|
83
92
|
for (const segment of segments) {
|
|
84
|
-
if (translation && "object"
|
|
93
|
+
if (translation && typeof translation === "object" && Object.prototype.hasOwnProperty.call(translation, segment)) {
|
|
85
94
|
translation = translation[segment];
|
|
86
95
|
} else {
|
|
87
96
|
return path;
|
|
88
97
|
}
|
|
89
98
|
}
|
|
90
|
-
if ("string"
|
|
99
|
+
if (typeof translation === "string") {
|
|
91
100
|
const pluralizedTranslation = applyPluralization(translation, count);
|
|
92
101
|
const result = pluralizedTranslation.replace(/:(\w+)/g, (match, key) => {
|
|
93
102
|
return Object.prototype.hasOwnProperty.call(actualReplacements, key) ? String(actualReplacements[key]) : match;
|
|
@@ -107,10 +116,11 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
107
116
|
};
|
|
108
117
|
const addTranslations = (locale2, translations2) => {
|
|
109
118
|
const validated = TranslationObjectSchema.parse(translations2);
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
119
|
+
currentTranslations[locale2] ??= {};
|
|
120
|
+
currentTranslations[locale2] = {
|
|
121
|
+
...currentTranslations[locale2],
|
|
122
|
+
...validated
|
|
123
|
+
};
|
|
114
124
|
};
|
|
115
125
|
const hasTranslation = (path, locale2 = null) => {
|
|
116
126
|
const checkLocale = locale2 ?? currentLocale;
|
|
@@ -120,13 +130,13 @@ var createTranslator = (translations = {}, locale = "en") => {
|
|
|
120
130
|
const segments = path.split(".");
|
|
121
131
|
let current = currentTranslations[checkLocale];
|
|
122
132
|
for (const segment of segments) {
|
|
123
|
-
if (current && "object"
|
|
133
|
+
if (current && typeof current === "object" && segment in current) {
|
|
124
134
|
current = current[segment];
|
|
125
135
|
} else {
|
|
126
136
|
return false;
|
|
127
137
|
}
|
|
128
138
|
}
|
|
129
|
-
return "string"
|
|
139
|
+
return typeof current === "string";
|
|
130
140
|
};
|
|
131
141
|
const getAvailableLocales = () => Object.keys(currentTranslations);
|
|
132
142
|
return {
|
package/package.json
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zairakai/js-i18n",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Internationalization library for the web with Laravel-style translation, pluralization, dot-notation keys and multi-locale support, validated at runtime with zod",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"i18n",
|
|
7
7
|
"internationalization",
|
|
8
8
|
"localization",
|
|
9
|
-
"pluralization",
|
|
10
9
|
"translations",
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
10
|
+
"pluralization",
|
|
11
|
+
"laravel",
|
|
12
|
+
"dot-notation",
|
|
13
|
+
"zod",
|
|
14
|
+
"typescript",
|
|
15
|
+
"browser"
|
|
14
16
|
],
|
|
15
17
|
"homepage": "https://js-i18n-8f9736.gitlab.io",
|
|
16
18
|
"bugs": {
|
|
@@ -40,6 +42,7 @@
|
|
|
40
42
|
"role": "Maintainer"
|
|
41
43
|
}
|
|
42
44
|
],
|
|
45
|
+
"sideEffects": false,
|
|
43
46
|
"type": "module",
|
|
44
47
|
"exports": {
|
|
45
48
|
".": {
|
|
@@ -74,24 +77,34 @@
|
|
|
74
77
|
"validate": "make quality"
|
|
75
78
|
},
|
|
76
79
|
"overrides": {
|
|
77
|
-
"
|
|
80
|
+
"brace-expansion": "5.0.12",
|
|
81
|
+
"colord": "2.9.7",
|
|
82
|
+
"esbuild": "^0.28.2",
|
|
83
|
+
"fast-uri": "3.1.9",
|
|
84
|
+
"js-yaml": {
|
|
85
|
+
".": "4.3.2"
|
|
86
|
+
},
|
|
87
|
+
"katex": "0.18.11",
|
|
88
|
+
"markdown-it": "14.3.3",
|
|
89
|
+
"minimatch": "11.0.6",
|
|
90
|
+
"nanoid": "3.3.20",
|
|
91
|
+
"re2js": "2.9.1",
|
|
92
|
+
"smol-toml": "1.9.0"
|
|
78
93
|
},
|
|
79
94
|
"dependencies": {
|
|
80
95
|
"zod": "^4.6.7"
|
|
81
96
|
},
|
|
82
97
|
"devDependencies": {
|
|
83
|
-
"@types/node": "^26.6.
|
|
84
|
-
"@vitest/coverage-v8": "^5.0
|
|
85
|
-
"@zairakai/js-dev-tools": "^
|
|
86
|
-
"
|
|
98
|
+
"@types/node": "^26.6.6",
|
|
99
|
+
"@vitest/coverage-v8": "^5.1.0",
|
|
100
|
+
"@zairakai/js-dev-tools": "^4.1.0",
|
|
101
|
+
"esbuild": "^0.28.2",
|
|
102
|
+
"knip": "^6.45.1",
|
|
87
103
|
"sort-package-json": "^4.1.0",
|
|
88
|
-
"tsup": "^
|
|
104
|
+
"tsup": "^9.0.0",
|
|
89
105
|
"typedoc": "^0.28.20",
|
|
90
106
|
"typescript": "^6.0.3",
|
|
91
|
-
"vitest": "^5.0
|
|
92
|
-
},
|
|
93
|
-
"engines": {
|
|
94
|
-
"node": ">=24.0.0"
|
|
107
|
+
"vitest": "^5.1.0"
|
|
95
108
|
},
|
|
96
109
|
"publishConfig": {
|
|
97
110
|
"access": "public"
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @zairakai/npm-i18n
|
|
3
|
-
*
|
|
3
|
+
* Internationalization library with Laravel-style features
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
export { applyPluralization, selectPluralForm } from './pluralization.js'
|
|
@@ -22,6 +22,9 @@ import type { TranslationData, Translator } from './types.js'
|
|
|
22
22
|
* @param locale - Default locale
|
|
23
23
|
* @returns Translator instance with __ function
|
|
24
24
|
*/
|
|
25
|
-
export const createI18n = (
|
|
25
|
+
export const createI18n = (
|
|
26
|
+
translations: TranslationData = {},
|
|
27
|
+
locale = 'en',
|
|
28
|
+
): Translator => {
|
|
26
29
|
return createTranslator(translations, locale)
|
|
27
30
|
}
|
package/src/pluralization.ts
CHANGED
|
@@ -14,6 +14,18 @@
|
|
|
14
14
|
* @param count - Count to determine plural form
|
|
15
15
|
* @returns Selected plural form
|
|
16
16
|
*/
|
|
17
|
+
/**
|
|
18
|
+
* Group of a regular expression match. The groups of the patterns used here
|
|
19
|
+
* always take part in the match: the empty string is only for the type.
|
|
20
|
+
*/
|
|
21
|
+
const group = (match: RegExpMatchArray, index: number): string =>
|
|
22
|
+
match[index] ?? ''
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Trimmed text of a part, empty when there is none
|
|
26
|
+
*/
|
|
27
|
+
const first = (part: string | undefined): string => part?.trim() ?? ''
|
|
28
|
+
|
|
17
29
|
export const selectPluralForm = (message: string, count: number): string => {
|
|
18
30
|
const parts = message.split('|')
|
|
19
31
|
|
|
@@ -24,21 +36,25 @@ export const selectPluralForm = (message: string, count: number): string => {
|
|
|
24
36
|
// Look for exact match conditions {n}
|
|
25
37
|
const exactMatch = trimmedPart.match(/^{\s*(\d+)\s*}\s*(.*)$/)
|
|
26
38
|
// Look for range conditions [n,m]
|
|
27
|
-
const rangeMatch = trimmedPart.match(
|
|
39
|
+
const rangeMatch = trimmedPart.match(
|
|
40
|
+
/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/,
|
|
41
|
+
)
|
|
28
42
|
|
|
29
43
|
if (exactMatch) {
|
|
30
44
|
// Exact number match {5}
|
|
31
|
-
const exactNumber = parseInt(exactMatch
|
|
45
|
+
const exactNumber = parseInt(group(exactMatch, 1), 10)
|
|
32
46
|
if (count === exactNumber) {
|
|
33
|
-
return exactMatch
|
|
47
|
+
return group(exactMatch, 2).trim()
|
|
34
48
|
}
|
|
35
49
|
} else if (rangeMatch) {
|
|
36
50
|
// Range match [1,5] or [20,*]
|
|
37
|
-
const min =
|
|
38
|
-
|
|
51
|
+
const min =
|
|
52
|
+
rangeMatch[1] === '*' ? -Infinity : parseInt(group(rangeMatch, 1), 10)
|
|
53
|
+
const max =
|
|
54
|
+
rangeMatch[2] === '*' ? Infinity : parseInt(group(rangeMatch, 2), 10)
|
|
39
55
|
|
|
40
56
|
if (count >= min && count <= max) {
|
|
41
|
-
return rangeMatch
|
|
57
|
+
return group(rangeMatch, 3).trim()
|
|
42
58
|
}
|
|
43
59
|
}
|
|
44
60
|
}
|
|
@@ -50,24 +66,26 @@ export const selectPluralForm = (message: string, count: number): string => {
|
|
|
50
66
|
return !trimmed.match(/^[{\[]/) // No special condition markers
|
|
51
67
|
})
|
|
52
68
|
|
|
53
|
-
if (
|
|
69
|
+
if (simpleParts.length >= 2) {
|
|
54
70
|
// English pluralization: only 1 = singular, others (including 0) = plural
|
|
55
|
-
return
|
|
56
|
-
} else if (
|
|
57
|
-
return simpleParts[0]
|
|
71
|
+
return first(simpleParts[count === 1 ? 0 : 1])
|
|
72
|
+
} else if (simpleParts.length === 1) {
|
|
73
|
+
return first(simpleParts[0])
|
|
58
74
|
}
|
|
59
75
|
|
|
60
76
|
// Last resort: return first part, extracting content from patterns
|
|
61
|
-
const firstPart = parts[0]
|
|
77
|
+
const firstPart = first(parts[0])
|
|
62
78
|
|
|
63
79
|
// Try to extract content from patterns
|
|
64
80
|
const exactMatch = firstPart.match(/^{\s*(\d+)\s*}\s*(.*)$/)
|
|
65
|
-
const rangeMatch = firstPart.match(
|
|
81
|
+
const rangeMatch = firstPart.match(
|
|
82
|
+
/^\[\s*(\d+|\*)\s*,\s*(\d+|\*)\s*\]\s*(.*)$/,
|
|
83
|
+
)
|
|
66
84
|
|
|
67
85
|
if (exactMatch) {
|
|
68
|
-
return exactMatch
|
|
86
|
+
return group(exactMatch, 2).trim()
|
|
69
87
|
} else if (rangeMatch) {
|
|
70
|
-
return rangeMatch
|
|
88
|
+
return group(rangeMatch, 3).trim()
|
|
71
89
|
}
|
|
72
90
|
|
|
73
91
|
return firstPart
|
|
@@ -79,8 +97,15 @@ export const selectPluralForm = (message: string, count: number): string => {
|
|
|
79
97
|
* @param count - Count for pluralization
|
|
80
98
|
* @returns Pluralized translation
|
|
81
99
|
*/
|
|
82
|
-
export const applyPluralization = (
|
|
83
|
-
|
|
100
|
+
export const applyPluralization = (
|
|
101
|
+
translation: string,
|
|
102
|
+
count: number | null,
|
|
103
|
+
): string => {
|
|
104
|
+
if (
|
|
105
|
+
typeof translation === 'string' &&
|
|
106
|
+
translation.includes('|') &&
|
|
107
|
+
count !== null
|
|
108
|
+
) {
|
|
84
109
|
return selectPluralForm(translation, count)
|
|
85
110
|
}
|
|
86
111
|
return translation
|
package/src/schemas.ts
CHANGED
|
@@ -3,13 +3,17 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { z } from 'zod'
|
|
6
|
-
import type {
|
|
6
|
+
import type {
|
|
7
|
+
ReplacementParameters,
|
|
8
|
+
TranslationData,
|
|
9
|
+
TranslationObject,
|
|
10
|
+
} from './types.js'
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
13
|
* Recursive schema for a translation value (string or nested TranslationObject)
|
|
10
14
|
*/
|
|
11
|
-
const TranslationValueSchema: z.ZodType<string | TranslationObject> = z.lazy(
|
|
12
|
-
z.union([z.string(), z.record(z.string(), TranslationValueSchema)])
|
|
15
|
+
const TranslationValueSchema: z.ZodType<string | TranslationObject> = z.lazy(
|
|
16
|
+
() => z.union([z.string(), z.record(z.string(), TranslationValueSchema)]),
|
|
13
17
|
) as z.ZodType<string | TranslationObject>
|
|
14
18
|
|
|
15
19
|
/**
|
|
@@ -17,24 +21,28 @@ const TranslationValueSchema: z.ZodType<string | TranslationObject> = z.lazy(()
|
|
|
17
21
|
*/
|
|
18
22
|
export const TranslationObjectSchema: z.ZodType<TranslationObject> = z.record(
|
|
19
23
|
z.string(),
|
|
20
|
-
TranslationValueSchema
|
|
24
|
+
TranslationValueSchema,
|
|
21
25
|
) as z.ZodType<TranslationObject>
|
|
22
26
|
|
|
23
27
|
/**
|
|
24
28
|
* Schema for the full translation data map (locale → TranslationObject)
|
|
25
29
|
*/
|
|
26
|
-
export const TranslationDataSchema: z.ZodType<TranslationData> = z.record(
|
|
30
|
+
export const TranslationDataSchema: z.ZodType<TranslationData> = z.record(
|
|
31
|
+
z.string(),
|
|
32
|
+
TranslationObjectSchema,
|
|
33
|
+
)
|
|
27
34
|
|
|
28
35
|
/**
|
|
29
36
|
* Schema for placeholder replacement parameters
|
|
30
37
|
*/
|
|
31
|
-
export const ReplacementParametersSchema: z.ZodType<ReplacementParameters> =
|
|
32
|
-
z.string(),
|
|
33
|
-
z.union([z.string(), z.number()])
|
|
34
|
-
)
|
|
38
|
+
export const ReplacementParametersSchema: z.ZodType<ReplacementParameters> =
|
|
39
|
+
z.record(z.string(), z.union([z.string(), z.number()]))
|
|
35
40
|
|
|
36
41
|
/**
|
|
37
42
|
* Schema for the second parameter of translate():
|
|
38
43
|
* either a count (number) for pluralization or a replacements object
|
|
39
44
|
*/
|
|
40
|
-
export const CountOrReplacementsSchema = z.union([
|
|
45
|
+
export const CountOrReplacementsSchema = z.union([
|
|
46
|
+
z.number(),
|
|
47
|
+
ReplacementParametersSchema,
|
|
48
|
+
])
|
package/src/translator.ts
CHANGED
|
@@ -23,7 +23,10 @@ import type {
|
|
|
23
23
|
* @param locale - Current locale
|
|
24
24
|
* @returns Translator instance
|
|
25
25
|
*/
|
|
26
|
-
export const createTranslator = (
|
|
26
|
+
export const createTranslator = (
|
|
27
|
+
translations: TranslationData = {},
|
|
28
|
+
locale = 'en',
|
|
29
|
+
): Translator => {
|
|
27
30
|
const currentTranslations = TranslationDataSchema.parse(translations)
|
|
28
31
|
let currentLocale = locale
|
|
29
32
|
|
|
@@ -37,7 +40,7 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
37
40
|
const translate: TranslateFunction = (
|
|
38
41
|
path: string,
|
|
39
42
|
countOrReplacements: number | ReplacementParameters = {},
|
|
40
|
-
replacements: ReplacementParameters = {}
|
|
43
|
+
replacements: ReplacementParameters = {},
|
|
41
44
|
): string => {
|
|
42
45
|
CountOrReplacementsSchema.parse(countOrReplacements)
|
|
43
46
|
ReplacementParametersSchema.parse(replacements)
|
|
@@ -46,7 +49,7 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
46
49
|
let actualReplacements = replacements
|
|
47
50
|
|
|
48
51
|
// Handle parameter overloading
|
|
49
|
-
if ('number'
|
|
52
|
+
if (typeof countOrReplacements === 'number') {
|
|
50
53
|
count = countOrReplacements
|
|
51
54
|
// Automatically add count to replacements
|
|
52
55
|
actualReplacements = { count: countOrReplacements, ...replacements }
|
|
@@ -61,12 +64,13 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
61
64
|
|
|
62
65
|
// Navigate through translation object using dot notation
|
|
63
66
|
const segments = path.split('.')
|
|
64
|
-
let translation: string | TranslationObject =
|
|
67
|
+
let translation: string | TranslationObject | undefined =
|
|
68
|
+
currentTranslations[currentLocale]
|
|
65
69
|
|
|
66
70
|
for (const segment of segments) {
|
|
67
71
|
if (
|
|
68
72
|
translation &&
|
|
69
|
-
'object'
|
|
73
|
+
typeof translation === 'object' &&
|
|
70
74
|
Object.prototype.hasOwnProperty.call(translation, segment)
|
|
71
75
|
) {
|
|
72
76
|
translation = translation[segment]
|
|
@@ -75,17 +79,21 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
75
79
|
}
|
|
76
80
|
}
|
|
77
81
|
|
|
78
|
-
if ('string'
|
|
82
|
+
if (typeof translation === 'string') {
|
|
79
83
|
// Apply pluralization if count provided
|
|
80
84
|
const pluralizedTranslation = applyPluralization(translation, count)
|
|
81
85
|
|
|
82
86
|
// Replace placeholders (:key and {key} formats)
|
|
83
87
|
const result = pluralizedTranslation
|
|
84
88
|
.replace(/:(\w+)/g, (match, key) => {
|
|
85
|
-
return Object.prototype.hasOwnProperty.call(actualReplacements, key)
|
|
89
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key)
|
|
90
|
+
? String(actualReplacements[key])
|
|
91
|
+
: match
|
|
86
92
|
})
|
|
87
93
|
.replace(/{(\w+)}/g, (match, key) => {
|
|
88
|
-
return Object.prototype.hasOwnProperty.call(actualReplacements, key)
|
|
94
|
+
return Object.prototype.hasOwnProperty.call(actualReplacements, key)
|
|
95
|
+
? String(actualReplacements[key])
|
|
96
|
+
: match
|
|
89
97
|
})
|
|
90
98
|
|
|
91
99
|
return result
|
|
@@ -114,7 +122,10 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
114
122
|
* @param locale - Locale code
|
|
115
123
|
* @param translations - Translation object
|
|
116
124
|
*/
|
|
117
|
-
const setTranslations = (
|
|
125
|
+
const setTranslations = (
|
|
126
|
+
locale: string,
|
|
127
|
+
translations: TranslationObject,
|
|
128
|
+
): void => {
|
|
118
129
|
currentTranslations[locale] = TranslationObjectSchema.parse(translations)
|
|
119
130
|
}
|
|
120
131
|
|
|
@@ -123,12 +134,16 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
123
134
|
* @param locale - Locale code
|
|
124
135
|
* @param translations - Translation object to merge
|
|
125
136
|
*/
|
|
126
|
-
const addTranslations = (
|
|
137
|
+
const addTranslations = (
|
|
138
|
+
locale: string,
|
|
139
|
+
translations: TranslationObject,
|
|
140
|
+
): void => {
|
|
127
141
|
const validated = TranslationObjectSchema.parse(translations)
|
|
128
|
-
|
|
129
|
-
|
|
142
|
+
currentTranslations[locale] ??= {}
|
|
143
|
+
currentTranslations[locale] = {
|
|
144
|
+
...currentTranslations[locale],
|
|
145
|
+
...validated,
|
|
130
146
|
}
|
|
131
|
-
currentTranslations[locale] = { ...currentTranslations[locale], ...validated }
|
|
132
147
|
}
|
|
133
148
|
|
|
134
149
|
/**
|
|
@@ -137,7 +152,10 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
137
152
|
* @param locale - Locale to check (optional, uses current if not provided)
|
|
138
153
|
* @returns True if key exists
|
|
139
154
|
*/
|
|
140
|
-
const hasTranslation = (
|
|
155
|
+
const hasTranslation = (
|
|
156
|
+
path: string,
|
|
157
|
+
locale: string | null = null,
|
|
158
|
+
): boolean => {
|
|
141
159
|
const checkLocale = locale ?? currentLocale
|
|
142
160
|
|
|
143
161
|
// Check if locale exists
|
|
@@ -146,11 +164,12 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
146
164
|
}
|
|
147
165
|
|
|
148
166
|
const segments = path.split('.')
|
|
149
|
-
let current: Record<string, unknown> | string =
|
|
167
|
+
let current: Record<string, unknown> | string =
|
|
168
|
+
currentTranslations[checkLocale]
|
|
150
169
|
|
|
151
170
|
// Navigate through the path
|
|
152
171
|
for (const segment of segments) {
|
|
153
|
-
if (current && 'object'
|
|
172
|
+
if (current && typeof current === 'object' && segment in current) {
|
|
154
173
|
current = current[segment] as Record<string, unknown> | string
|
|
155
174
|
} else {
|
|
156
175
|
return false
|
|
@@ -158,7 +177,7 @@ export const createTranslator = (translations: TranslationData = {}, locale = 'e
|
|
|
158
177
|
}
|
|
159
178
|
|
|
160
179
|
// Check if final value is a string
|
|
161
|
-
return 'string'
|
|
180
|
+
return typeof current === 'string'
|
|
162
181
|
}
|
|
163
182
|
|
|
164
183
|
/**
|