@appweaver/skill 0.0.0-stage → 3.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 +29 -2
- package/index.d.ts +39 -0
- package/index.js +105 -0
- package/package.json +41 -3
- package/skill/GUIDELINES.md +383 -0
- package/skill/SKILL.md +120 -0
- package/skill/references/ai.md +231 -0
- package/skill/references/audit.md +218 -0
- package/skill/references/cache.md +233 -0
- package/skill/references/cli.md +729 -0
- package/skill/references/client.md +884 -0
- package/skill/references/configuration.md +1159 -0
- package/skill/references/database.md +345 -0
- package/skill/references/dependency-injection.md +301 -0
- package/skill/references/errors.md +466 -0
- package/skill/references/events.md +203 -0
- package/skill/references/logging.md +156 -0
- package/skill/references/mailer.md +393 -0
- package/skill/references/mcp.md +245 -0
- package/skill/references/modules.md +500 -0
- package/skill/references/patterns.md +1216 -0
- package/skill/references/queue.md +281 -0
- package/skill/references/realtime.md +572 -0
- package/skill/references/resources.md +2228 -0
- package/skill/references/scheduler.md +228 -0
- package/skill/references/security.md +1185 -0
- package/skill/references/sms.md +143 -0
- package/skill/references/spatial.md +197 -0
- package/skill/references/storage.md +500 -0
- package/skill/references/telemetry.md +202 -0
- package/skill/references/templates.md +488 -0
- package/skill/references/timeseries.md +312 -0
- package/skill/references/workflow.md +223 -0
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
# Templates & Localization
|
|
2
|
+
|
|
3
|
+
Templates and localization are two independent features, each usable without the other:
|
|
4
|
+
|
|
5
|
+
- **Templates**: the template engine renders text of any format from template files: email bodies, HTML pages, XML
|
|
6
|
+
documents for external integrations, CSV or any other text. `TemplateEngine` is an optional infrastructure provider of
|
|
7
|
+
`@appweaver/common`, the default implementation is `HandlebarsTemplateEngine`
|
|
8
|
+
([Handlebars](https://handlebarsjs.com/guide/)) of the `@appweaver/handlebars` package, replaceable with
|
|
9
|
+
`TEMPLATE_PROVIDER`. The project installs the package with the `templates` module (`weaver upgrade` keeps it in
|
|
10
|
+
step).
|
|
11
|
+
- **Localization**: the locale service translates the keys of nested JSON files into a locale, anywhere in the
|
|
12
|
+
application and, with the `t` helper, inside the templates. `LocaleService` is a core service of `@appweaver/core`,
|
|
13
|
+
always available. Without a `locales/` directory it translates only the framework's own English `emails.*` keys.
|
|
14
|
+
|
|
15
|
+
The locale is always given by the application (a request parameter, a user field, ...), falling back to
|
|
16
|
+
`LOCALE_DEFAULT`. It also picks the localized template variants and the locale of the date and number helpers, so a
|
|
17
|
+
project without translation files can still render localized templates.
|
|
18
|
+
|
|
19
|
+
`@appweaver/create` scaffolds each one as a module, `templates` and `locales` (`--add templates locales`, or `--all`),
|
|
20
|
+
which `weaver module add` and `weaver module remove` add and remove later. With the `mailer` module the templates
|
|
21
|
+
include the account emails, and `en.json` their `emails` texts (it starts empty without the mailer):
|
|
22
|
+
|
|
23
|
+
| Modules | `templates/`, `@appweaver/handlebars` | `locales/` | Account emails (with `mailer`) |
|
|
24
|
+
| ------------------- | ---------------------------------------------- | ---------- | ------------------------------------- |
|
|
25
|
+
| `templates locales` | Scaffolded, the texts translated with `{{t}}` | `en.json` | Rendered from the localized templates |
|
|
26
|
+
| `templates` | Scaffolded, the English texts written in place | — | Rendered from the English templates |
|
|
27
|
+
| `locales` | —, `TEMPLATE_PROVIDER` is empty | `en.json` | Plain text of the `en.json` texts |
|
|
28
|
+
| (neither) | —, `TEMPLATE_PROVIDER` is empty | — | Plain text of the framework's texts |
|
|
29
|
+
|
|
30
|
+
Without `locales`, every `{{t "key" param=value}}` of the scaffolded templates is replaced by the English message of
|
|
31
|
+
the key, its parameters by the expressions (`{{@app.name}}`) and a plural by an `{{#if (eq count 1)}}` chain, so the
|
|
32
|
+
templates render the same text. `weaver module remove locales` does the same to every template of the project with the
|
|
33
|
+
texts of its `locales/en.json`, before deleting `locales/`. `weaver module add locales` restores the `t` calls of the
|
|
34
|
+
scaffolded templates that still hold the English texts, and leaves the edited ones as they are.
|
|
35
|
+
|
|
36
|
+
Both directories live in the project root next to `public/`, outside `src/`, so they are read the same way from the
|
|
37
|
+
Node build and the Bun sources. A Docker image copies each of them next to `dist/`. `weaver start --watch` restarts the
|
|
38
|
+
server when a file of either changes, and ignores a directory that does not exist.
|
|
39
|
+
|
|
40
|
+
## Templates
|
|
41
|
+
|
|
42
|
+
The template engine is selected only when its package is installed: `TEMPLATE_PROVIDER=auto` picks the `handlebars`
|
|
43
|
+
driver when `@appweaver/handlebars` is installed, otherwise the application starts without an engine, as with
|
|
44
|
+
`TEMPLATE_PROVIDER=none`. Injecting `TemplateEngine` then throws `CONTEXT_DEFINITION_MISSING`, sending a template email
|
|
45
|
+
fails with `CONFIGURATION_INVALID`, and the account emails are sent as plain text built from the `emails.*`
|
|
46
|
+
translations, as they are when the application has no template for them. `EmailService.sendEmail` sends an email the
|
|
47
|
+
application built itself, i.e. of an HTML body stored in the database, with or without the engine.
|
|
48
|
+
|
|
49
|
+
### Project layout
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
templates/ # TEMPLATE_PATH
|
|
53
|
+
├── layouts/
|
|
54
|
+
│ ├── email.html.hbs # the layout of the account emails, scaffolded
|
|
55
|
+
│ └── page.html.hbs
|
|
56
|
+
├── partials/
|
|
57
|
+
│ ├── tag-list.html.hbs
|
|
58
|
+
│ └── signature.txt.hbs
|
|
59
|
+
├── emails/
|
|
60
|
+
│ ├── password-reset.html.hbs # an account email, see mailer.md
|
|
61
|
+
│ ├── order-shipped.html.hbs
|
|
62
|
+
│ ├── order-shipped.txt.hbs
|
|
63
|
+
│ ├── order-shipped.subject.hbs
|
|
64
|
+
│ └── order-shipped.de.html.hbs # whole template localized for `de`
|
|
65
|
+
├── pages/invoice.html.hbs
|
|
66
|
+
└── exports/orders.xml.hbs
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Template names
|
|
70
|
+
|
|
71
|
+
A file `<path>/<name>[.<locale>].<format>.hbs` (or `.handlebars`) is the template **`<path>/<name>.<format>`**, i.e.
|
|
72
|
+
`emails/order-shipped.de.html.hbs` is the `de` variant of `emails/order-shipped.html`. The segment before the format is
|
|
73
|
+
a locale only when it is a locale tag, so `feeds/posts.rss.xml.hbs` is the template `feeds/posts.rss.xml`.
|
|
74
|
+
|
|
75
|
+
The format decides the escaping and the MIME type:
|
|
76
|
+
|
|
77
|
+
| Format | Values |
|
|
78
|
+
| --------------------------------------------------- | ------------------- |
|
|
79
|
+
| `html`, `htm`, `xhtml`, `xml`, `rss`, `atom`, `svg` | Escaped as markup |
|
|
80
|
+
| Any other, i.e. `txt`, `csv`, `json`, `subject` | Written as they are |
|
|
81
|
+
|
|
82
|
+
`templateMimeType(name)` of `@appweaver/common` returns the MIME type of a format (`text/html`, `application/xml`,
|
|
83
|
+
`text/csv`, ...), `text/plain` for a format it does not know.
|
|
84
|
+
|
|
85
|
+
Use `{{{value}}}` to write a value unescaped in a markup template.
|
|
86
|
+
|
|
87
|
+
### Locale variants and fallbacks
|
|
88
|
+
|
|
89
|
+
A render in `de-AT` looks a template up in `de-AT`, `de`, the default locale (and its language), then the template
|
|
90
|
+
without a locale. The same chain applies to the partials it includes and to the translations. A template only localized
|
|
91
|
+
to other locales is not found in the default one. The variants need no translation files.
|
|
92
|
+
|
|
93
|
+
### Rendering
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { inject } from '@appweaver/core';
|
|
97
|
+
import { TemplateEngine } from '@appweaver/common';
|
|
98
|
+
|
|
99
|
+
const templates = inject(TemplateEngine);
|
|
100
|
+
|
|
101
|
+
const html = await templates.render(
|
|
102
|
+
'pages/invoice.html',
|
|
103
|
+
{ invoice },
|
|
104
|
+
{ locale: 'de' }
|
|
105
|
+
);
|
|
106
|
+
const xml = await templates.render('exports/orders.xml', {
|
|
107
|
+
orders,
|
|
108
|
+
generatedAt: new Date()
|
|
109
|
+
});
|
|
110
|
+
const text = await templates.renderString(
|
|
111
|
+
'Hi {{name}}',
|
|
112
|
+
{ name },
|
|
113
|
+
{ format: 'txt' }
|
|
114
|
+
);
|
|
115
|
+
const exists = await templates.hasTemplate('emails/welcome.html', 'de');
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
| Method | Description |
|
|
119
|
+
| ----------------------------------------- | ----------------------------------------------------------------------------------- |
|
|
120
|
+
| `render(name, data?, { locale? })` | Renders a template, rejecting with `TEMPLATE_NOT_FOUND` or `TEMPLATE_RENDER_FAILED` |
|
|
121
|
+
| `renderString(source, data?, options?)` | Renders a source string, `format` (default `html`) decides the escaping |
|
|
122
|
+
| `hasTemplate(name, locale?)` | Whether the template exists in the locale or its fallbacks |
|
|
123
|
+
| `registerTemplate(name, source, locale?)` | Registers a template in code, taking precedence over the files |
|
|
124
|
+
| `registerHelper(name, helper)` | Registers a helper |
|
|
125
|
+
|
|
126
|
+
The templates are loaded when the application starts, failing with `TEMPLATE_LOAD_FAILED` on a template of an invalid
|
|
127
|
+
syntax. The line break ending a template file is dropped, so an included partial adds none. `TEMPLATE_CACHE: false`
|
|
128
|
+
(set for the `dev` environment of a scaffolded project) reloads the changed templates and translation files on every
|
|
129
|
+
render.
|
|
130
|
+
|
|
131
|
+
### Returning a rendered template from a route
|
|
132
|
+
|
|
133
|
+
`templateContentType(name)` returns the `Content-Type` of a template's format, i.e. `text/html; charset=utf-8`. Declare
|
|
134
|
+
a `Type.String()` response and the produced MIME type, so the OpenAPI document describes it.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { Type } from 'typebox';
|
|
138
|
+
import { TemplateEngine, templateContentType } from '@appweaver/common';
|
|
139
|
+
import { inject } from '@appweaver/core';
|
|
140
|
+
import { registerRoute } from '@appweaver/web';
|
|
141
|
+
|
|
142
|
+
registerRoute(
|
|
143
|
+
(router) => {
|
|
144
|
+
router.get(
|
|
145
|
+
'/orders/export/xml',
|
|
146
|
+
{
|
|
147
|
+
schema: {
|
|
148
|
+
querystring: Type.Object({ locale: Type.Optional(Type.String()) }),
|
|
149
|
+
produces: ['application/xml'],
|
|
150
|
+
response: { 200: Type.String() }
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
async (req, reply) => {
|
|
154
|
+
const name = 'exports/orders.xml';
|
|
155
|
+
const xml = await inject(TemplateEngine).render(
|
|
156
|
+
name,
|
|
157
|
+
{ orders: await findOrders(), generatedAt: new Date() },
|
|
158
|
+
{ locale: req.query.locale }
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
return reply
|
|
162
|
+
.type(templateContentType(name))
|
|
163
|
+
.header('Content-Disposition', 'attachment; filename="orders.xml"')
|
|
164
|
+
.send(xml);
|
|
165
|
+
}
|
|
166
|
+
);
|
|
167
|
+
},
|
|
168
|
+
{ roles: ['Admin'] }
|
|
169
|
+
);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### Layouts and components
|
|
173
|
+
|
|
174
|
+
Every template is also a partial, included by its name, or by its name without the format, which prefers the format of
|
|
175
|
+
the including template (`{{> partials/signature}}` includes `partials/signature.txt.hbs` from a `.txt` template). A
|
|
176
|
+
layout or a component with content wraps it with `{{> @partial-block}}`:
|
|
177
|
+
|
|
178
|
+
```hbs
|
|
179
|
+
{{!-- templates/layouts/page.html.hbs --}}
|
|
180
|
+
<!DOCTYPE html>
|
|
181
|
+
<html lang="{{@locale}}">
|
|
182
|
+
<head><title>{{title}} · {{@app.name}}</title></head>
|
|
183
|
+
<body>{{> @partial-block}}</body>
|
|
184
|
+
</html>
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
```hbs
|
|
188
|
+
{{!-- templates/pages/invoice.html.hbs --}}
|
|
189
|
+
{{#> layouts/page.html title=(t "invoice.title" number=invoice.number)}}
|
|
190
|
+
<h1>{{t "invoice.title" number=invoice.number}}</h1>
|
|
191
|
+
<p>{{t "invoice.issued" date=(formatDate invoice.issuedAt "long")}}</p>
|
|
192
|
+
{{#each invoice.lines}}
|
|
193
|
+
{{> partials/invoice-line line=this}}
|
|
194
|
+
{{/each}}
|
|
195
|
+
<p>{{formatCurrency invoice.total invoice.currency}}</p>
|
|
196
|
+
{{/layouts/page.html}}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
```hbs
|
|
200
|
+
{{!-- templates/exports/orders.xml.hbs --}}
|
|
201
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
202
|
+
<orders generatedAt="{{formatDate generatedAt "iso"}}">
|
|
203
|
+
{{#each orders}}
|
|
204
|
+
<order id="{{id}}"><customer>{{customer.name}}</customer><note>{{cdata note}}</note></order>
|
|
205
|
+
{{/each}}
|
|
206
|
+
</orders>
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### Data variables
|
|
210
|
+
|
|
211
|
+
| Variable | Value |
|
|
212
|
+
| ------------------ | ------------------------------------ |
|
|
213
|
+
| `@locale` | The locale rendered in, i.e. `de-AT` |
|
|
214
|
+
| `@app.name` | `APP_NAME` |
|
|
215
|
+
| `@app.description` | `APP_DESCRIPTION` |
|
|
216
|
+
| `@app.hostname` | `APP_HOSTNAME` |
|
|
217
|
+
| `@app.version` | `APP_VERSION` |
|
|
218
|
+
|
|
219
|
+
### Built-in helpers
|
|
220
|
+
|
|
221
|
+
The locale-aware helpers use `@locale`, the options of the `Intl` helpers are given as hash arguments. The `t` helper
|
|
222
|
+
translates with the locale service, see [Localization](#localization).
|
|
223
|
+
|
|
224
|
+
| Helper | Example |
|
|
225
|
+
| ----------------------------------------- | ---------------------------------------------------------------------------------- |
|
|
226
|
+
| `t key [locale] params...` | `{{t "cart.items" count=items.length}}` |
|
|
227
|
+
| `formatDate value [style\|"iso"] options` | `{{formatDate createdAt "long"}}`, `{{formatDate d month="short" timeZone="UTC"}}` |
|
|
228
|
+
| `formatNumber value options` | `{{formatNumber ratio style="percent"}}` |
|
|
229
|
+
| `formatCurrency value currency options` | `{{formatCurrency total "EUR"}}` |
|
|
230
|
+
| `eq`, `ne`, `lt`, `lte`, `gt`, `gte` | `{{#if (eq status "Paid")}}` |
|
|
231
|
+
| `and`, `or`, `not` | `{{#if (and active (not deleted))}}` |
|
|
232
|
+
| `default value fallback` | `{{default nickname "Guest"}}` |
|
|
233
|
+
| `includes`, `length` | `{{#if (includes roles "Admin")}}`, `{{length items}}` |
|
|
234
|
+
| `add`, `subtract`, `multiply`, `divide` | `{{multiply price quantity}}` |
|
|
235
|
+
| `uppercase`, `lowercase`, `trim` | `{{uppercase code}}` |
|
|
236
|
+
| `truncate value length [suffix]` | `{{truncate excerpt 100}}` |
|
|
237
|
+
| `join array [separator]`, `concat` | `{{join tags ", "}}`, `{{concat first " " last}}` |
|
|
238
|
+
| `json value [indent]` | `{{{json payload}}}` |
|
|
239
|
+
| `cdata value` | `<note>{{cdata note}}</note>` |
|
|
240
|
+
|
|
241
|
+
### Custom helpers and templates
|
|
242
|
+
|
|
243
|
+
Register them from a module the application loads, i.e. `src/features/index.ts`:
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
import {
|
|
247
|
+
registerTemplate,
|
|
248
|
+
registerTemplateHelper,
|
|
249
|
+
registerTemplateHelpers
|
|
250
|
+
} from '@appweaver/core';
|
|
251
|
+
|
|
252
|
+
registerTemplateHelper('initials', (name: string) =>
|
|
253
|
+
name
|
|
254
|
+
.split(' ')
|
|
255
|
+
.map((part) => part[0])
|
|
256
|
+
.join('')
|
|
257
|
+
);
|
|
258
|
+
|
|
259
|
+
// Several helpers at once, i.e. of a helper library the application installs
|
|
260
|
+
registerTemplateHelpers(myHelpers);
|
|
261
|
+
|
|
262
|
+
// A template defined in code, i.e. loaded from the database
|
|
263
|
+
registerTemplate('emails/promo.html', source, 'de');
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
A custom helper reads the rendered locale from `options.data.locale`, i.e. to format amounts kept in cents:
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
registerTemplateHelper(
|
|
270
|
+
'money',
|
|
271
|
+
(cents: number, options: { data?: { locale?: string } }) =>
|
|
272
|
+
new Intl.NumberFormat(options.data?.locale, {
|
|
273
|
+
style: 'currency',
|
|
274
|
+
currency: 'EUR'
|
|
275
|
+
}).format(cents / 100)
|
|
276
|
+
);
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### Previewing templates
|
|
280
|
+
|
|
281
|
+
The preview route renders a template as the application would, to check it in a browser while editing it. It is
|
|
282
|
+
disabled by default; enable it only in the `dev` environment of `appweaver.json`. It is open to anyone by default, set
|
|
283
|
+
`auth` to `true` to require authentication, i.e. on a shared development server:
|
|
284
|
+
|
|
285
|
+
```json
|
|
286
|
+
{
|
|
287
|
+
"environments": {
|
|
288
|
+
"dev": {
|
|
289
|
+
"template": {
|
|
290
|
+
"cache": false,
|
|
291
|
+
"preview": {
|
|
292
|
+
"enabled": true
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
The startup logs the route, i.e. `Template preview enabled on '/templates/*'`.
|
|
301
|
+
|
|
302
|
+
`GET <TEMPLATE_PREVIEW_ROUTE_PREFIX>/<template name>` (`/templates/...` by default) responds with the rendered template
|
|
303
|
+
and the content type of its format. The query parameters are the template data:
|
|
304
|
+
|
|
305
|
+
- a dotted name sets a nested value, and a numeric part an item of a list: `order.number=WS-1&order.items.0.name=Book`
|
|
306
|
+
- a repeated parameter sets a list of values: `tags=news&tags=sport`
|
|
307
|
+
- `true`, `false`, `null` and the numbers written the way they print (`12`, `-0.5`, not `012`) get their type, every
|
|
308
|
+
other value stays a string
|
|
309
|
+
- `_data` holds a JSON object the other parameters are merged over, for data the parameters cannot express
|
|
310
|
+
- `_locale` selects the locale, i.e. the localized variants and the translations
|
|
311
|
+
|
|
312
|
+
```
|
|
313
|
+
/templates/emails/order-confirmation.html?_locale=de&order.number=WS-1&order.items.0.name=Book&order.items.0.quantity=2
|
|
314
|
+
/templates/exports/posts.xml?_data={"posts":[{"title":"Hello","slug":"hello"}]}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
A missing template responds with `404 TEMPLATE_PREVIEW_NOT_FOUND`, and an invalid `_data` with `400 MALFORMED_REQUEST`.
|
|
318
|
+
The route requires authentication only when `TEMPLATE_PREVIEW_AUTH` is `true`, is left out of the OpenAPI document,
|
|
319
|
+
responds with `Content-Security-Policy: sandbox` so no script of a rendered page runs, and fails the startup when no
|
|
320
|
+
template engine is loaded (the `@appweaver/handlebars` package is not installed).
|
|
321
|
+
|
|
322
|
+
### Template configuration
|
|
323
|
+
|
|
324
|
+
| Key | Default | Description |
|
|
325
|
+
| ------------------------------- | --------------- | ------------------------------------------------------------------------------------------ |
|
|
326
|
+
| `TEMPLATE_PATH` | `'./templates'` | Directory of the template files |
|
|
327
|
+
| `TEMPLATE_CACHE` | `true` | Keep the templates in memory |
|
|
328
|
+
| `TEMPLATE_PREVIEW_ENABLED` | `false` | Enable the preview route |
|
|
329
|
+
| `TEMPLATE_PREVIEW_AUTH` | `false` | Require authentication for the preview route |
|
|
330
|
+
| `TEMPLATE_PREVIEW_ROUTE_PREFIX` | `'/templates'` | URL prefix of the preview route |
|
|
331
|
+
| `TEMPLATE_PROVIDER` | `'auto'` | `auto` (`handlebars` with `@appweaver/handlebars`), `handlebars`, `none`, or a module path |
|
|
332
|
+
|
|
333
|
+
### Template errors
|
|
334
|
+
|
|
335
|
+
| Code | Raised when |
|
|
336
|
+
| ---------------------------- | ------------------------------------------------------------- |
|
|
337
|
+
| `TEMPLATE_NOT_FOUND` | No template of the name exists in the locale or its fallbacks |
|
|
338
|
+
| `TEMPLATE_RENDER_FAILED` | A template fails to compile or render, i.e. a missing partial |
|
|
339
|
+
| `TEMPLATE_LOAD_FAILED` | A template cannot be read, or its syntax is invalid |
|
|
340
|
+
| `TEMPLATE_PREVIEW_NOT_FOUND` | The preview route is asked for a template that does not exist |
|
|
341
|
+
|
|
342
|
+
### Custom template engine
|
|
343
|
+
|
|
344
|
+
Extend `TemplateEngine` of `@appweaver/common` and point `TEMPLATE_PROVIDER` to the module. The account emails render
|
|
345
|
+
the templates listed in [mailer.md](./mailer.md#account-emails) when the engine has them, otherwise they are sent as
|
|
346
|
+
plain text.
|
|
347
|
+
|
|
348
|
+
## Localization
|
|
349
|
+
|
|
350
|
+
`LocaleService` needs no package and no template engine: it translates in services, hooks, jobs and routes as well as in
|
|
351
|
+
the templates. A missing `locales/` directory leaves only the framework's own English keys (`emails.*`), which
|
|
352
|
+
translate the plain text of the account emails.
|
|
353
|
+
|
|
354
|
+
### Project layout
|
|
355
|
+
|
|
356
|
+
```text
|
|
357
|
+
locales/ # LOCALE_PATH
|
|
358
|
+
├── en.json
|
|
359
|
+
├── de.json
|
|
360
|
+
└── de-AT.json # only the keys differing from de.json
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### Translations
|
|
364
|
+
|
|
365
|
+
A translation file is a JSON object of nested objects and string messages, named by its locale (`locales/de.json`).
|
|
366
|
+
A message is translated by its dotted key, the path of its object names: `inbox.unread` below. A value that is neither
|
|
367
|
+
a string nor an object is ignored with a warning. Every translation is an
|
|
368
|
+
[ICU MessageFormat](https://unicode-org.github.io/icu/userguide/format_parse/messages/) message, the syntax of FormatJS,
|
|
369
|
+
Angular, vue-i18n and Symfony, with the plural categories of the Unicode CLDR (`Intl.PluralRules`):
|
|
370
|
+
|
|
371
|
+
```json
|
|
372
|
+
{
|
|
373
|
+
"inbox": {
|
|
374
|
+
"greeting": "Hello {name}",
|
|
375
|
+
"unread": "You have {msg_cnt, plural, =0 {no unread messages} one {# unread message} other {# unread messages}}"
|
|
376
|
+
},
|
|
377
|
+
"race": {
|
|
378
|
+
"place": "You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}"
|
|
379
|
+
},
|
|
380
|
+
"comment": {
|
|
381
|
+
"replied": "{gender, select, female {She} male {He} other {They}} replied"
|
|
382
|
+
},
|
|
383
|
+
"order": {
|
|
384
|
+
"total": "Total: {total, number} items"
|
|
385
|
+
},
|
|
386
|
+
"help": {
|
|
387
|
+
"braces": "Write '{name}' to insert the name, it''s easy"
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
| Syntax | Writes |
|
|
393
|
+
| ------------------------------------------------------------- | ----------------------------------------------------------------- |
|
|
394
|
+
| `{name}` | The parameter as it is |
|
|
395
|
+
| `{n, plural, =0 {...} one {...} other {...}}` | The branch of the exact value, else of the plural category of `n` |
|
|
396
|
+
| `#` | The number of the enclosing plural, formatted in the locale |
|
|
397
|
+
| `{n, plural, offset:1 ...}` | The categories and `#` of `n - 1`, the exact values of `n` |
|
|
398
|
+
| `{n, selectordinal, one {#st} two {#nd} ... other {#th}}` | The branch of the ordinal category |
|
|
399
|
+
| `{value, select, a {...} b {...} other {...}}` | The branch of the value |
|
|
400
|
+
| `{n, number}`, `{n, number, integer}`, `{n, number, percent}` | The number formatted in the locale |
|
|
401
|
+
| `''`, `'{text}'` | An apostrophe, the quoted text as it is (a lone `'` stays as is) |
|
|
402
|
+
|
|
403
|
+
The categories differ by language: English and German have `one` and `other`, Spanish adds `many` (a million and more),
|
|
404
|
+
Arabic has all six (`zero`, `one`, `two`, `few`, `many`, `other`). Every `plural`, `selectordinal` and `select` needs an
|
|
405
|
+
`other` branch. A message is checked when its file loads, failing with `LOCALE_LOAD_FAILED` on an invalid one, and an
|
|
406
|
+
argument without a parameter is written as it is, i.e. `{name}`. The plural forms follow the locale of the file the
|
|
407
|
+
translation is found in.
|
|
408
|
+
|
|
409
|
+
```ts
|
|
410
|
+
import { inject, LocaleService, registerTranslations } from '@appweaver/core';
|
|
411
|
+
|
|
412
|
+
const locales = inject(LocaleService);
|
|
413
|
+
|
|
414
|
+
locales.translate('inbox.unread', 'en', { msg_cnt: 1 }); // 'You have 1 unread message'
|
|
415
|
+
locales.translate('inbox.unread', 'de', { msg_cnt: 3 }); // the `other` branch of de.json
|
|
416
|
+
locales.hasTranslation('inbox.unread', 'de');
|
|
417
|
+
locales.getLocales(); // ['de', 'en']
|
|
418
|
+
locales.resolveLocales('de-AT'); // ['de-AT', 'de', 'en']
|
|
419
|
+
|
|
420
|
+
// Translations defined in code, merged key by key over the file
|
|
421
|
+
registerTranslations('de', { cart: { checkout: 'Zur Kasse' } });
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
In a template, the hash arguments of `t` are the parameters: `{{t "inbox.unread" msg_cnt=user.unreadCount}}`.
|
|
425
|
+
|
|
426
|
+
A missing key returns the key itself. The framework's own keys (`emails.*`) fall back to their English text.
|
|
427
|
+
|
|
428
|
+
### Translating in a service hook
|
|
429
|
+
|
|
430
|
+
```ts
|
|
431
|
+
import { inject, LocaleService } from '@appweaver/core';
|
|
432
|
+
import { createService } from '@appweaver/data';
|
|
433
|
+
|
|
434
|
+
export default createService({
|
|
435
|
+
modelName: 'Category',
|
|
436
|
+
beforeCreate: (data) => {
|
|
437
|
+
data.description ??= inject(LocaleService).translate(
|
|
438
|
+
'category.defaultDescription',
|
|
439
|
+
undefined, // LOCALE_DEFAULT
|
|
440
|
+
{ name: data.name }
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
### Choosing the locale
|
|
447
|
+
|
|
448
|
+
The framework never guesses the locale, the application passes it where it knows it. A common pattern, used by the
|
|
449
|
+
`webshop-api` sample, is a `language` field on the auth model, the preferred language of the user, copied onto the
|
|
450
|
+
records whose emails are sent later, so an email is written in the language the record was made in:
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
// src/resources/user/model.ts
|
|
454
|
+
const config = {
|
|
455
|
+
language: {
|
|
456
|
+
type: 'string',
|
|
457
|
+
default: 'en',
|
|
458
|
+
pattern: '^[a-z]{2}(-[A-Z]{2})?$',
|
|
459
|
+
maxLength: 8
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
// At checkout: the language asked for, or the preferred one of the customer
|
|
464
|
+
const order = await tx.order.create({
|
|
465
|
+
data: { ...data, language: request.language ?? customer.language }
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
// Later, i.e. in a queue worker
|
|
469
|
+
await inject(EmailService).sendEmail({
|
|
470
|
+
to: order.customer.email,
|
|
471
|
+
template: 'emails/order-confirmed',
|
|
472
|
+
data: { order, customer: order.customer },
|
|
473
|
+
locale: order.language
|
|
474
|
+
});
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
### Locale configuration
|
|
478
|
+
|
|
479
|
+
| Key | Default | Description |
|
|
480
|
+
| ---------------- | ------------- | ---------------------------------- |
|
|
481
|
+
| `LOCALE_DEFAULT` | `'en'` | Locale used when none is given |
|
|
482
|
+
| `LOCALE_PATH` | `'./locales'` | Directory of the translation files |
|
|
483
|
+
|
|
484
|
+
### Locale errors
|
|
485
|
+
|
|
486
|
+
| Code | Raised when |
|
|
487
|
+
| -------------------- | ------------------------------------------------------------- |
|
|
488
|
+
| `LOCALE_LOAD_FAILED` | A translation file is not a JSON object, or a message invalid |
|