@hazeljs/i18n 0.2.0-alpha.1
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 +192 -0
- package/README.md +292 -0
- package/dist/decorators/lang.decorator.d.ts +33 -0
- package/dist/decorators/lang.decorator.d.ts.map +1 -0
- package/dist/decorators/lang.decorator.js +53 -0
- package/dist/decorators/lang.decorator.test.d.ts +2 -0
- package/dist/decorators/lang.decorator.test.d.ts.map +1 -0
- package/dist/decorators/lang.decorator.test.js +61 -0
- package/dist/i18n.interceptor.d.ts +29 -0
- package/dist/i18n.interceptor.d.ts.map +1 -0
- package/dist/i18n.interceptor.js +52 -0
- package/dist/i18n.interceptor.test.d.ts +2 -0
- package/dist/i18n.interceptor.test.d.ts.map +1 -0
- package/dist/i18n.interceptor.test.js +126 -0
- package/dist/i18n.middleware.d.ts +59 -0
- package/dist/i18n.middleware.d.ts.map +1 -0
- package/dist/i18n.middleware.js +126 -0
- package/dist/i18n.middleware.test.d.ts +2 -0
- package/dist/i18n.middleware.test.d.ts.map +1 -0
- package/dist/i18n.middleware.test.js +239 -0
- package/dist/i18n.module.d.ts +73 -0
- package/dist/i18n.module.d.ts.map +1 -0
- package/dist/i18n.module.js +154 -0
- package/dist/i18n.module.test.d.ts +2 -0
- package/dist/i18n.module.test.d.ts.map +1 -0
- package/dist/i18n.module.test.js +162 -0
- package/dist/i18n.service.d.ts +112 -0
- package/dist/i18n.service.d.ts.map +1 -0
- package/dist/i18n.service.js +228 -0
- package/dist/i18n.service.test.d.ts +2 -0
- package/dist/i18n.service.test.d.ts.map +1 -0
- package/dist/i18n.service.test.js +297 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +39 -0
- package/dist/translation.loader.d.ts +20 -0
- package/dist/translation.loader.d.ts.map +1 -0
- package/dist/translation.loader.js +51 -0
- package/dist/translation.loader.test.d.ts +2 -0
- package/dist/translation.loader.test.d.ts.map +1 -0
- package/dist/translation.loader.test.js +89 -0
- package/dist/types.d.ts +86 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2024 HazelJS Team
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
22
|
+
|
|
23
|
+
1. Definitions.
|
|
24
|
+
|
|
25
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
26
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
27
|
+
|
|
28
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
29
|
+
the copyright owner that is granting the License.
|
|
30
|
+
|
|
31
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
32
|
+
other entities that control, are controlled by, or are under common
|
|
33
|
+
control with that entity. For the purposes of this definition,
|
|
34
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
35
|
+
direction or management of such entity, whether by contract or
|
|
36
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
37
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
38
|
+
|
|
39
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
40
|
+
exercising permissions granted by this License.
|
|
41
|
+
|
|
42
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
43
|
+
including but not limited to software source code, documentation
|
|
44
|
+
source, and configuration files.
|
|
45
|
+
|
|
46
|
+
"Object" form shall mean any form resulting from mechanical
|
|
47
|
+
transformation or translation of a Source form, including but
|
|
48
|
+
not limited to compiled object code, generated documentation,
|
|
49
|
+
and conversions to other media types.
|
|
50
|
+
|
|
51
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
52
|
+
Object form, made available under the License, as indicated by a
|
|
53
|
+
copyright notice that is included in or attached to the work
|
|
54
|
+
(an example is provided in the Appendix below).
|
|
55
|
+
|
|
56
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
57
|
+
form, that is based on (or derived from) the Work and for which the
|
|
58
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
59
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
60
|
+
of this License, Derivative Works shall not include works that remain
|
|
61
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
62
|
+
the Work and Derivative Works thereof.
|
|
63
|
+
|
|
64
|
+
"Contribution" shall mean any work of authorship, including
|
|
65
|
+
the original version of the Work and any modifications or additions
|
|
66
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
67
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
68
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
69
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
70
|
+
means any form of electronic, verbal, or written communication sent
|
|
71
|
+
to the Licensor or its representatives, including but not limited to
|
|
72
|
+
communication on electronic mailing lists, source code control systems,
|
|
73
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
74
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
75
|
+
excluding communication that is conspicuously marked or otherwise
|
|
76
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
77
|
+
|
|
78
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
79
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
80
|
+
subsequently incorporated within the Work.
|
|
81
|
+
|
|
82
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
83
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
84
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
85
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
86
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
87
|
+
Work and such Derivative Works in Source or Object form.
|
|
88
|
+
|
|
89
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
90
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
91
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
92
|
+
(except as stated in this section) patent license to make, have made,
|
|
93
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
94
|
+
where such license applies only to those patent claims licensable
|
|
95
|
+
by such Contributor that are necessarily infringed by their
|
|
96
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
97
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
98
|
+
institute patent litigation against any entity (including a
|
|
99
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
100
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
101
|
+
or contributory patent infringement, then any patent licenses
|
|
102
|
+
granted to You under this License for that Work shall terminate
|
|
103
|
+
as of the date such litigation is filed.
|
|
104
|
+
|
|
105
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
106
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
107
|
+
modifications, and in Source or Object form, provided that You
|
|
108
|
+
meet the following conditions:
|
|
109
|
+
|
|
110
|
+
(a) You must give any other recipients of the Work or
|
|
111
|
+
Derivative Works a copy of this License; and
|
|
112
|
+
|
|
113
|
+
(b) You must cause any modified files to carry prominent notices
|
|
114
|
+
stating that You changed the files; and
|
|
115
|
+
|
|
116
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
117
|
+
that You distribute, all copyright, patent, trademark, and
|
|
118
|
+
attribution notices from the Source form of the Work,
|
|
119
|
+
excluding those notices that do not pertain to any part of
|
|
120
|
+
the Derivative Works; and
|
|
121
|
+
|
|
122
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
123
|
+
distribution, then any Derivative Works that You distribute must
|
|
124
|
+
include a readable copy of the attribution notices contained
|
|
125
|
+
within such NOTICE file, excluding those notices that do not
|
|
126
|
+
pertain to any part of the Derivative Works, in at least one
|
|
127
|
+
of the following places: within a NOTICE text file distributed
|
|
128
|
+
as part of the Derivative Works; within the Source form or
|
|
129
|
+
documentation, if provided along with the Derivative Works; or,
|
|
130
|
+
within a display generated by the Derivative Works, if and
|
|
131
|
+
wherever such third-party notices normally appear. The contents
|
|
132
|
+
of the NOTICE file are for informational purposes only and
|
|
133
|
+
do not modify the License. You may add Your own attribution
|
|
134
|
+
notices within Derivative Works that You distribute, alongside
|
|
135
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
136
|
+
that such additional attribution notices cannot be construed
|
|
137
|
+
as modifying the License.
|
|
138
|
+
|
|
139
|
+
You may add Your own copyright statement to Your modifications and
|
|
140
|
+
may provide additional or different license terms and conditions
|
|
141
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
142
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
143
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
144
|
+
the conditions stated in this License.
|
|
145
|
+
|
|
146
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
147
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
148
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
149
|
+
this License, without any additional terms or conditions.
|
|
150
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
151
|
+
the terms of any separate license agreement you may have executed
|
|
152
|
+
with Licensor regarding such Contributions.
|
|
153
|
+
|
|
154
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
155
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
156
|
+
except as required for reasonable and customary use in describing the
|
|
157
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
158
|
+
|
|
159
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
160
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
161
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
162
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
163
|
+
implied, including, without limitation, any warranties or conditions
|
|
164
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
165
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
166
|
+
appropriateness of using or redistributing the Work and assume any
|
|
167
|
+
risks associated with Your exercise of permissions under this License.
|
|
168
|
+
|
|
169
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
170
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
171
|
+
unless required by applicable law (such as deliberate and grossly
|
|
172
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
173
|
+
liable to You for damages, including any direct, indirect, special,
|
|
174
|
+
incidental, or consequential damages of any character arising as a
|
|
175
|
+
result of this License or out of the use or inability to use the
|
|
176
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
177
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
178
|
+
other commercial damages or losses), even if such Contributor
|
|
179
|
+
has been advised of the possibility of such damages.
|
|
180
|
+
|
|
181
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
182
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
183
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
184
|
+
or other liability obligations and/or rights consistent with this
|
|
185
|
+
License. However, in accepting such obligations, You may act only
|
|
186
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
187
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
188
|
+
defend, and hold each Contributor harmless for any liability
|
|
189
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
190
|
+
of your accepting any such warranty or additional liability.
|
|
191
|
+
|
|
192
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
# @hazeljs/i18n
|
|
2
|
+
|
|
3
|
+
**Internationalization (i18n) Module for HazelJS - Translate, Format, and Detect Locales**
|
|
4
|
+
|
|
5
|
+
Zero-dependency i18n for HazelJS with JSON translation files, interpolation, pluralization, and native `Intl.*` formatting.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@hazeljs/i18n)
|
|
8
|
+
[](https://www.npmjs.com/package/@hazeljs/i18n)
|
|
9
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **Zero heavy dependencies** — uses only Node.js built-ins (`fs/promises`, native `Intl` API)
|
|
14
|
+
- **Translation** - JSON-based translation files with dot-notation key lookup
|
|
15
|
+
- **Interpolation** - Variable substitution via `{placeholder}` tokens
|
|
16
|
+
- **Pluralization** - Native `Intl.PluralRules` for all CLDR plural categories
|
|
17
|
+
- **Locale Detection** - Query parameter, cookie, or `Accept-Language` header strategies
|
|
18
|
+
- **Formatting** - Number, date, currency, and relative-time via native `Intl.*` APIs
|
|
19
|
+
- **`@Lang()` Decorator** - Inject detected locale into controller method parameters
|
|
20
|
+
- **`I18nInterceptor`** - Automatic response message translation
|
|
21
|
+
- **Async Configuration** - `forRootAsync()` for container-resolved options
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install @hazeljs/i18n
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
### 1. Create translation files
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
my-app/
|
|
35
|
+
└── translations/
|
|
36
|
+
├── en.json
|
|
37
|
+
└── fr.json
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
**`translations/en.json`**
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"welcome": "Welcome, {name}!",
|
|
45
|
+
"goodbye": "Goodbye!",
|
|
46
|
+
"items": {
|
|
47
|
+
"one": "1 item",
|
|
48
|
+
"other": "{count} items"
|
|
49
|
+
},
|
|
50
|
+
"errors": {
|
|
51
|
+
"notFound": "Resource not found.",
|
|
52
|
+
"unauthorized": "You are not authorized."
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**`translations/fr.json`**
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"welcome": "Bienvenue, {name} !",
|
|
62
|
+
"goodbye": "Au revoir !",
|
|
63
|
+
"items": {
|
|
64
|
+
"one": "1 élément",
|
|
65
|
+
"other": "{count} éléments"
|
|
66
|
+
},
|
|
67
|
+
"errors": {
|
|
68
|
+
"notFound": "Ressource introuvable.",
|
|
69
|
+
"unauthorized": "Vous n'êtes pas autorisé."
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 2. Register the module
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { HazelModule } from '@hazeljs/core';
|
|
78
|
+
import { I18nModule } from '@hazeljs/i18n';
|
|
79
|
+
import { AppController } from './app.controller';
|
|
80
|
+
|
|
81
|
+
@HazelModule({
|
|
82
|
+
imports: [
|
|
83
|
+
I18nModule.forRoot({
|
|
84
|
+
defaultLocale: 'en',
|
|
85
|
+
fallbackLocale: 'en',
|
|
86
|
+
translationsPath: './translations',
|
|
87
|
+
detection: ['query', 'cookie', 'header'],
|
|
88
|
+
}),
|
|
89
|
+
],
|
|
90
|
+
controllers: [AppController],
|
|
91
|
+
})
|
|
92
|
+
export class AppModule {}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### 3. Apply locale middleware
|
|
96
|
+
|
|
97
|
+
Add `LocaleMiddleware` before your routes so every request has a locale attached before controllers execute:
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { HazelApp } from '@hazeljs/core';
|
|
101
|
+
import { LocaleMiddleware } from '@hazeljs/i18n';
|
|
102
|
+
|
|
103
|
+
const app = new HazelApp(AppModule);
|
|
104
|
+
|
|
105
|
+
const localeMw = app.get(LocaleMiddleware);
|
|
106
|
+
app.use((req, res, next) => localeMw.handle(req, res, next));
|
|
107
|
+
|
|
108
|
+
await app.listen(3000);
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### 4. Use in a controller
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import { Controller, Get } from '@hazeljs/core';
|
|
115
|
+
import { I18nService, Lang } from '@hazeljs/i18n';
|
|
116
|
+
|
|
117
|
+
@Controller('/greet')
|
|
118
|
+
export class AppController {
|
|
119
|
+
constructor(private readonly i18n: I18nService) {}
|
|
120
|
+
|
|
121
|
+
@Get('/')
|
|
122
|
+
hello(@Lang() locale: string) {
|
|
123
|
+
return {
|
|
124
|
+
message: this.i18n.t('welcome', { locale, vars: { name: 'Alice' } }),
|
|
125
|
+
};
|
|
126
|
+
// GET /greet?lang=fr → { message: "Bienvenue, Alice !" }
|
|
127
|
+
// GET /greet → { message: "Welcome, Alice!" }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
@Get('/items')
|
|
131
|
+
items(@Lang() locale: string) {
|
|
132
|
+
const count = 5;
|
|
133
|
+
return {
|
|
134
|
+
message: this.i18n.t('items', { locale, count, vars: { count: String(count) } }),
|
|
135
|
+
};
|
|
136
|
+
// → { message: "5 items" }
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Async Configuration
|
|
142
|
+
|
|
143
|
+
Use `forRootAsync` with `ConfigService`:
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
import { ConfigService } from '@hazeljs/config';
|
|
147
|
+
import { I18nModule } from '@hazeljs/i18n';
|
|
148
|
+
|
|
149
|
+
I18nModule.forRootAsync({
|
|
150
|
+
useFactory: async (config: ConfigService) => ({
|
|
151
|
+
defaultLocale: config.get('LOCALE', 'en'),
|
|
152
|
+
translationsPath: config.get('TRANSLATIONS_PATH', './translations'),
|
|
153
|
+
}),
|
|
154
|
+
inject: [ConfigService],
|
|
155
|
+
})
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## API Reference
|
|
159
|
+
|
|
160
|
+
### I18nModule.forRoot(options)
|
|
161
|
+
|
|
162
|
+
| Option | Type | Default | Description |
|
|
163
|
+
|--------------------|-----------------------------|------------------------------|-------------------------------------------------|
|
|
164
|
+
| `defaultLocale` | `string` | `'en'` | Locale used when none is detected. |
|
|
165
|
+
| `fallbackLocale` | `string` | same as `defaultLocale` | Locale used when a key is missing. |
|
|
166
|
+
| `translationsPath` | `string` | `'./translations'` | Path to the directory of `<locale>.json` files. |
|
|
167
|
+
| `detection` | `LocaleDetectionStrategy[]` | `['query','cookie','header']`| Ordered locale detection strategies. |
|
|
168
|
+
| `queryParam` | `string` | `'lang'` | Query-string parameter name. |
|
|
169
|
+
| `cookieName` | `string` | `'locale'` | Cookie name. |
|
|
170
|
+
| `isGlobal` | `boolean` | `true` | Register as a global module. |
|
|
171
|
+
|
|
172
|
+
### I18nService
|
|
173
|
+
|
|
174
|
+
- `t(key, opts?)` - Translate a dot-notation key; supports `vars`, `count`, and `locale` override
|
|
175
|
+
- `has(key, locale?)` - Check whether a translation key exists
|
|
176
|
+
- `getLocales()` - Return all loaded locale codes
|
|
177
|
+
- `getKeys(locale?)` - Return all flattened dot-notation keys for a locale
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
i18n.t('errors.notFound')
|
|
181
|
+
// → "Resource not found."
|
|
182
|
+
|
|
183
|
+
i18n.t('welcome', { vars: { name: 'Bob' } })
|
|
184
|
+
// → "Welcome, Bob!"
|
|
185
|
+
|
|
186
|
+
i18n.t('items', { count: 3, vars: { count: '3' } })
|
|
187
|
+
// → "3 items"
|
|
188
|
+
|
|
189
|
+
i18n.t('welcome', { locale: 'fr', vars: { name: 'Bob' } })
|
|
190
|
+
// → "Bienvenue, Bob !"
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### I18nFormatter (`i18n.format.*`)
|
|
194
|
+
|
|
195
|
+
- `number(value, locale?, opts?)` - Format a number via `Intl.NumberFormat`
|
|
196
|
+
- `date(value, locale?, opts?)` - Format a date via `Intl.DateTimeFormat`
|
|
197
|
+
- `currency(value, locale?, currency?)` - Format a monetary value
|
|
198
|
+
- `relative(value, unit, locale?, opts?)` - Format a relative time via `Intl.RelativeTimeFormat`
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
i18n.format.number(1234567.89, 'de', { maximumFractionDigits: 2 })
|
|
202
|
+
// → "1.234.567,89"
|
|
203
|
+
|
|
204
|
+
i18n.format.date(new Date(), 'fr', { dateStyle: 'long' })
|
|
205
|
+
// → "4 mars 2026"
|
|
206
|
+
|
|
207
|
+
i18n.format.currency(49.99, 'en', 'USD')
|
|
208
|
+
// → "$49.99"
|
|
209
|
+
|
|
210
|
+
i18n.format.relative(-3, 'day', 'en')
|
|
211
|
+
// → "3 days ago"
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Decorators
|
|
215
|
+
|
|
216
|
+
- `@Lang()` - Inject the request locale into a controller method parameter
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
@Get('/hello')
|
|
220
|
+
greet(@Lang() locale: string) {
|
|
221
|
+
return this.i18n.t('welcome', { locale, vars: { name: 'World' } });
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### LocaleMiddleware
|
|
226
|
+
|
|
227
|
+
Detects the request locale and stores it on the request object. Sets the `Content-Language` response header.
|
|
228
|
+
|
|
229
|
+
**Detection order (configurable):**
|
|
230
|
+
|
|
231
|
+
1. Query parameter (`?lang=fr`)
|
|
232
|
+
2. Cookie (`locale=fr`)
|
|
233
|
+
3. `Accept-Language` header (`Accept-Language: fr-FR,fr;q=0.9,en;q=0.8`)
|
|
234
|
+
4. `defaultLocale` fallback
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// Manual registration
|
|
238
|
+
app.use((req, res, next) => localeMw.handle(req, res, next));
|
|
239
|
+
|
|
240
|
+
// Or use the static factory
|
|
241
|
+
app.use(LocaleMiddleware.create(resolvedOptions));
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### I18nInterceptor
|
|
245
|
+
|
|
246
|
+
Optional interceptor that automatically translates a `message` field in the response when the value matches an i18n key.
|
|
247
|
+
|
|
248
|
+
```typescript
|
|
249
|
+
import { UseInterceptors } from '@hazeljs/core';
|
|
250
|
+
import { I18nInterceptor } from '@hazeljs/i18n';
|
|
251
|
+
|
|
252
|
+
@Controller('/users')
|
|
253
|
+
@UseInterceptors(I18nInterceptor)
|
|
254
|
+
export class UserController {
|
|
255
|
+
@Post('/')
|
|
256
|
+
create() {
|
|
257
|
+
return { message: 'user.created', data: { id: 1 } };
|
|
258
|
+
// → { message: 'User created successfully.', data: { id: 1 } }
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Translation File Format
|
|
264
|
+
|
|
265
|
+
Files must be valid JSON named `<locale>.json`. Keys can be nested to create namespaces. Leaf values are plain strings or **plural objects**:
|
|
266
|
+
|
|
267
|
+
```json
|
|
268
|
+
{
|
|
269
|
+
"flat_key": "A simple string.",
|
|
270
|
+
"interpolated": "Hello, {name}!",
|
|
271
|
+
"namespace": {
|
|
272
|
+
"nested_key": "Nested value."
|
|
273
|
+
},
|
|
274
|
+
"plural": {
|
|
275
|
+
"one": "One apple",
|
|
276
|
+
"other": "{count} apples"
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Dot-notation resolves nested keys: `i18n.t('namespace.nested_key')`.
|
|
282
|
+
|
|
283
|
+
Plural objects support any CLDR plural category (`zero`, `one`, `two`, `few`, `many`, `other`) as determined by `Intl.PluralRules` for the active locale.
|
|
284
|
+
|
|
285
|
+
## Requirements
|
|
286
|
+
|
|
287
|
+
- Node.js >= 14
|
|
288
|
+
- `@hazeljs/core` >= 0.2.0-beta.0
|
|
289
|
+
|
|
290
|
+
## License
|
|
291
|
+
|
|
292
|
+
Apache-2.0 © [HazelJS](https://hazeljs.com)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
/**
|
|
3
|
+
* Internal query key used to pass the resolved locale through the HazelJS
|
|
4
|
+
* request context so the router can inject it via @Lang().
|
|
5
|
+
*
|
|
6
|
+
* The proxy handler in main.ts writes this key into context.query before
|
|
7
|
+
* route matching; @Lang() reads it back using the standard 'query' injection
|
|
8
|
+
* type that the router already handles.
|
|
9
|
+
*/
|
|
10
|
+
export declare const LANG_QUERY_KEY = "__hazel_i18n_locale__";
|
|
11
|
+
/**
|
|
12
|
+
* Parameter decorator that injects the detected locale string into a
|
|
13
|
+
* controller method parameter.
|
|
14
|
+
*
|
|
15
|
+
* Requires LocaleMiddleware (via addProxyHandler) to run before routing so
|
|
16
|
+
* the locale is resolved and stored in context.query[LANG_QUERY_KEY].
|
|
17
|
+
* When the middleware is not applied, the parameter will be undefined.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* @Get('/hello')
|
|
22
|
+
* greet(@Lang() locale: string) {
|
|
23
|
+
* return this.i18n.t('welcome', { locale, vars: { name: 'World' } });
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function Lang(): ParameterDecorator;
|
|
28
|
+
/**
|
|
29
|
+
* Reads the locale injected by LocaleMiddleware from the raw request object.
|
|
30
|
+
* Useful outside of controller parameters (e.g. in exception filters).
|
|
31
|
+
*/
|
|
32
|
+
export declare function extractLang(req: Record<string, unknown>): string | undefined;
|
|
33
|
+
//# sourceMappingURL=lang.decorator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lang.decorator.d.ts","sourceRoot":"","sources":["../../src/decorators/lang.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAK1B;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,0BAA0B,CAAC;AAEtD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,IAAI,IAAI,kBAAkB,CAiBzC;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS,CAE5E"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LANG_QUERY_KEY = void 0;
|
|
4
|
+
exports.Lang = Lang;
|
|
5
|
+
exports.extractLang = extractLang;
|
|
6
|
+
require("reflect-metadata");
|
|
7
|
+
const i18n_middleware_1 = require("../i18n.middleware");
|
|
8
|
+
const INJECT_METADATA_KEY = 'hazel:inject';
|
|
9
|
+
/**
|
|
10
|
+
* Internal query key used to pass the resolved locale through the HazelJS
|
|
11
|
+
* request context so the router can inject it via @Lang().
|
|
12
|
+
*
|
|
13
|
+
* The proxy handler in main.ts writes this key into context.query before
|
|
14
|
+
* route matching; @Lang() reads it back using the standard 'query' injection
|
|
15
|
+
* type that the router already handles.
|
|
16
|
+
*/
|
|
17
|
+
exports.LANG_QUERY_KEY = '__hazel_i18n_locale__';
|
|
18
|
+
/**
|
|
19
|
+
* Parameter decorator that injects the detected locale string into a
|
|
20
|
+
* controller method parameter.
|
|
21
|
+
*
|
|
22
|
+
* Requires LocaleMiddleware (via addProxyHandler) to run before routing so
|
|
23
|
+
* the locale is resolved and stored in context.query[LANG_QUERY_KEY].
|
|
24
|
+
* When the middleware is not applied, the parameter will be undefined.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* @Get('/hello')
|
|
29
|
+
* greet(@Lang() locale: string) {
|
|
30
|
+
* return this.i18n.t('welcome', { locale, vars: { name: 'World' } });
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
function Lang() {
|
|
35
|
+
return (target, propertyKey, parameterIndex) => {
|
|
36
|
+
if (!propertyKey) {
|
|
37
|
+
throw new Error('@Lang() must be used on a method parameter');
|
|
38
|
+
}
|
|
39
|
+
const constructor = target.constructor;
|
|
40
|
+
const injections = Reflect.getMetadata(INJECT_METADATA_KEY, constructor, propertyKey) ?? [];
|
|
41
|
+
// Use the router's built-in 'query' injection — the proxy handler seeds
|
|
42
|
+
// context.query[LANG_QUERY_KEY] with the detected locale before routing.
|
|
43
|
+
injections[parameterIndex] = { type: 'query', name: exports.LANG_QUERY_KEY };
|
|
44
|
+
Reflect.defineMetadata(INJECT_METADATA_KEY, injections, constructor, propertyKey);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Reads the locale injected by LocaleMiddleware from the raw request object.
|
|
49
|
+
* Useful outside of controller parameters (e.g. in exception filters).
|
|
50
|
+
*/
|
|
51
|
+
function extractLang(req) {
|
|
52
|
+
return req[i18n_middleware_1.LOCALE_KEY];
|
|
53
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lang.decorator.test.d.ts","sourceRoot":"","sources":["../../src/decorators/lang.decorator.test.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
require("reflect-metadata");
|
|
4
|
+
const lang_decorator_1 = require("./lang.decorator");
|
|
5
|
+
const i18n_middleware_1 = require("../i18n.middleware");
|
|
6
|
+
jest.mock('../i18n.middleware', () => ({
|
|
7
|
+
LOCALE_KEY: '__hazel_locale__',
|
|
8
|
+
}));
|
|
9
|
+
const INJECT_METADATA_KEY = 'hazel:inject';
|
|
10
|
+
class TestController {
|
|
11
|
+
greet(_locale) {
|
|
12
|
+
return `Hello, ${_locale}`;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
describe('Lang() decorator', () => {
|
|
16
|
+
it('defines inject metadata on the class method', () => {
|
|
17
|
+
const decorator = (0, lang_decorator_1.Lang)();
|
|
18
|
+
const target = TestController.prototype;
|
|
19
|
+
decorator(target, 'greet', 0);
|
|
20
|
+
const metadata = Reflect.getMetadata(INJECT_METADATA_KEY, TestController, 'greet');
|
|
21
|
+
expect(metadata).toBeDefined();
|
|
22
|
+
expect(metadata[0]).toEqual({ type: 'query', name: lang_decorator_1.LANG_QUERY_KEY });
|
|
23
|
+
});
|
|
24
|
+
it('stores metadata at the correct parameter index', () => {
|
|
25
|
+
class TwoParamController {
|
|
26
|
+
doSomething(_id, _locale) { }
|
|
27
|
+
}
|
|
28
|
+
const decorator = (0, lang_decorator_1.Lang)();
|
|
29
|
+
decorator(TwoParamController.prototype, 'doSomething', 1);
|
|
30
|
+
const metadata = Reflect.getMetadata(INJECT_METADATA_KEY, TwoParamController, 'doSomething');
|
|
31
|
+
expect(metadata[1]).toEqual({ type: 'query', name: lang_decorator_1.LANG_QUERY_KEY });
|
|
32
|
+
expect(metadata[0]).toBeUndefined();
|
|
33
|
+
});
|
|
34
|
+
it('merges with existing metadata at other indices', () => {
|
|
35
|
+
class MultiController {
|
|
36
|
+
action(_a, _b, _c) { }
|
|
37
|
+
}
|
|
38
|
+
const existingMeta = [{ type: 'body' }];
|
|
39
|
+
Reflect.defineMetadata(INJECT_METADATA_KEY, existingMeta, MultiController, 'action');
|
|
40
|
+
const decorator = (0, lang_decorator_1.Lang)();
|
|
41
|
+
decorator(MultiController.prototype, 'action', 2);
|
|
42
|
+
const metadata = Reflect.getMetadata(INJECT_METADATA_KEY, MultiController, 'action');
|
|
43
|
+
expect(metadata[0]).toEqual({ type: 'body' });
|
|
44
|
+
expect(metadata[2]).toEqual({ type: 'query', name: lang_decorator_1.LANG_QUERY_KEY });
|
|
45
|
+
});
|
|
46
|
+
it('throws when propertyKey is undefined (constructor usage)', () => {
|
|
47
|
+
const decorator = (0, lang_decorator_1.Lang)();
|
|
48
|
+
expect(() => {
|
|
49
|
+
decorator(TestController.prototype, undefined, 0);
|
|
50
|
+
}).toThrow('@Lang() must be used on a method parameter');
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
describe('extractLang()', () => {
|
|
54
|
+
it('returns the locale value from the request', () => {
|
|
55
|
+
const req = { [i18n_middleware_1.LOCALE_KEY]: 'fr' };
|
|
56
|
+
expect((0, lang_decorator_1.extractLang)(req)).toBe('fr');
|
|
57
|
+
});
|
|
58
|
+
it('returns undefined when locale key is not set', () => {
|
|
59
|
+
expect((0, lang_decorator_1.extractLang)({})).toBeUndefined();
|
|
60
|
+
});
|
|
61
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Interceptor } from '@hazeljs/core';
|
|
2
|
+
import { RequestContext } from '@hazeljs/core';
|
|
3
|
+
import { I18nService } from './i18n.service';
|
|
4
|
+
/**
|
|
5
|
+
* Optional interceptor that automatically translates a `message` field found
|
|
6
|
+
* in the response object.
|
|
7
|
+
*
|
|
8
|
+
* The `message` value is treated as an i18n key. If the key exists in the
|
|
9
|
+
* translation store for the request locale, it is replaced in-place; otherwise
|
|
10
|
+
* the original value is preserved.
|
|
11
|
+
*
|
|
12
|
+
* Register it per-controller with @UseInterceptors(I18nInterceptor) or
|
|
13
|
+
* globally via the HazelApp interceptor API.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* // Returning from a controller:
|
|
17
|
+
* return { message: 'user.created', data: user };
|
|
18
|
+
* // → { message: 'User created successfully.', data: user } (if key exists)
|
|
19
|
+
*/
|
|
20
|
+
export declare class I18nInterceptor implements Interceptor {
|
|
21
|
+
private readonly i18n;
|
|
22
|
+
constructor(i18n: I18nService);
|
|
23
|
+
intercept(context: RequestContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
24
|
+
/**
|
|
25
|
+
* Reads the locale attached by LocaleMiddleware from the raw request object.
|
|
26
|
+
*/
|
|
27
|
+
private extractLocale;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=i18n.interceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"i18n.interceptor.d.ts","sourceRoot":"","sources":["../src/i18n.interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAa7C;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,eAAgB,YAAW,WAAW;IACrC,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,WAAW;IAExC,SAAS,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IAuBxF;;OAEG;IACH,OAAO,CAAC,aAAa;CAKtB"}
|