@dokebi/i18n 0.0.0-stage → 0.2.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/AI.md +236 -0
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/dist/calendar.d.ts +78 -0
- package/dist/calendar.js +318 -0
- package/dist/catalogs.d.ts +33 -0
- package/dist/catalogs.js +165 -0
- package/dist/contract.d.ts +47 -0
- package/dist/contract.js +1 -0
- package/dist/dependency.d.ts +3 -0
- package/dist/dependency.js +8 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +17 -0
- package/dist/http.d.ts +31 -0
- package/dist/http.js +206 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/install.d.ts +31 -0
- package/dist/install.js +29 -0
- package/dist/layers.d.ts +19 -0
- package/dist/layers.js +57 -0
- package/dist/message.d.ts +23 -0
- package/dist/message.js +103 -0
- package/dist/negotiation.d.ts +23 -0
- package/dist/negotiation.js +165 -0
- package/dist/options.d.ts +42 -0
- package/dist/options.js +211 -0
- package/dist/page.d.ts +93 -0
- package/dist/page.js +572 -0
- package/dist/plugin.d.ts +15 -0
- package/dist/plugin.js +92 -0
- package/dist/service.d.ts +27 -0
- package/dist/service.js +359 -0
- package/dist/values.d.ts +12 -0
- package/dist/values.js +65 -0
- package/options.schema.json +250 -0
- package/package.json +100 -4
- package/templates/extension.ts +7 -0
- package/templates/locales/en/common.json +7 -0
- package/templates/upgrade-extension.ts +12 -0
package/dist/http.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { I18nError } from './errors.js';
|
|
2
|
+
import { Negotiator } from './negotiation.js';
|
|
3
|
+
import { COOKIE_CLAIMED } from './page.js';
|
|
4
|
+
const VARY_NAMES = ['Accept-Language', 'Cookie'];
|
|
5
|
+
const VARY = VARY_NAMES.join(', ');
|
|
6
|
+
const COOKIE_VARY = ['Cookie'];
|
|
7
|
+
/** @dokebi/web's mark of a sealed JSON answer (its `SEALED_PATH_HEADER`; web is optional here). */
|
|
8
|
+
const SEALED_PATH = 'x-dokebi-sealed-path';
|
|
9
|
+
/** A JSON media type: `application/json`, `application/problem+json`, `application/vnd.api+json`. */
|
|
10
|
+
const JSON_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/;
|
|
11
|
+
/**
|
|
12
|
+
* True for a document whose words depend on the request's language: HTML or any JSON type
|
|
13
|
+
* (media type compared without case and without its parameters).
|
|
14
|
+
*/
|
|
15
|
+
function translatable(contentType) {
|
|
16
|
+
const type = String(contentType ?? '')
|
|
17
|
+
.split(';', 1)[0]
|
|
18
|
+
?.trim()
|
|
19
|
+
.toLowerCase();
|
|
20
|
+
return type === 'text/html' || (type !== undefined && JSON_TYPE.test(type));
|
|
21
|
+
}
|
|
22
|
+
/** Set on a reply while the Content-Language it holds is the one this adapter wrote. */
|
|
23
|
+
const OWN = Symbol('dokebi.i18n.own-content-language');
|
|
24
|
+
/**
|
|
25
|
+
* Fastify's reply.header for a reply this adapter labelled: a Content-Language set after it is
|
|
26
|
+
* the answer's own (its body's real language), so it is never removed as ours. One shared
|
|
27
|
+
* function: a request costs one property, not a closure.
|
|
28
|
+
*/
|
|
29
|
+
function labelledHeader(key, ...rest) {
|
|
30
|
+
if (this[OWN] &&
|
|
31
|
+
typeof key === 'string' &&
|
|
32
|
+
key.length === 16 &&
|
|
33
|
+
key.toLowerCase() === 'content-language')
|
|
34
|
+
this[OWN] = false;
|
|
35
|
+
const prototype = Object.getPrototypeOf(this);
|
|
36
|
+
return prototype.header.call(this, key, ...rest);
|
|
37
|
+
}
|
|
38
|
+
/** Set on a request whose locale its URL names (http.pathLocale, useUrlLocale). */
|
|
39
|
+
const FROM_URL = Symbol('dokebi.i18n.url-locale');
|
|
40
|
+
/** The adapter of a request (one shared object per plugin, never a closure per request). */
|
|
41
|
+
const ADAPTER = Symbol('dokebi.i18n.adapter');
|
|
42
|
+
/**
|
|
43
|
+
* The locale this answer's URL names (a route parameter such as `/:lang/products/:id`): the
|
|
44
|
+
* request translates in it, the answer says it (`Content-Language`, unless the answer set its
|
|
45
|
+
* own), and the answer does not vary by Accept-Language or Cookie (only by its URL), so a
|
|
46
|
+
* shared cache or CDN can keep it. Call before rendering. `locale` must be a configured locale
|
|
47
|
+
* (case does not matter): anything else is INVALID_LOCALE (answer 404 for it). Needs
|
|
48
|
+
* `http.enabled`; `http.pathLocale` does the same for a first path segment by itself.
|
|
49
|
+
*/
|
|
50
|
+
export function useUrlLocale(request, reply, locale) {
|
|
51
|
+
const adapter = request[ADAPTER];
|
|
52
|
+
if (!adapter)
|
|
53
|
+
throw new I18nError('HTTP_UNAVAILABLE', 'useUrlLocale needs options.dokebi-i18n.http.enabled');
|
|
54
|
+
const translator = typeof locale === 'string' ? adapter.translators.get(locale.toLowerCase()) : undefined;
|
|
55
|
+
if (!translator)
|
|
56
|
+
throw new I18nError('INVALID_LOCALE', 'The URL names a locale that has no catalog');
|
|
57
|
+
urlTranslator(request, reply, translator);
|
|
58
|
+
return translator;
|
|
59
|
+
}
|
|
60
|
+
function urlTranslator(request, reply, translator) {
|
|
61
|
+
request.i18n = translator;
|
|
62
|
+
request[FROM_URL] = true;
|
|
63
|
+
// Still this adapter's label: it follows the URL (an answer's own Content-Language stays).
|
|
64
|
+
if (reply[OWN] !== false) {
|
|
65
|
+
const prototype = Object.getPrototypeOf(reply);
|
|
66
|
+
prototype.header.call(reply, 'Content-Language', translator.locale);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** The configured locale a first path segment names (`/ja/p/1` → ja), or undefined. */
|
|
70
|
+
function pathTranslator(url, translators, longest) {
|
|
71
|
+
if (url.charCodeAt(0) !== 47)
|
|
72
|
+
return undefined;
|
|
73
|
+
// A segment longer than the longest configured locale is no locale: stop looking there.
|
|
74
|
+
let end = 1;
|
|
75
|
+
for (; end < url.length && end <= longest + 1; end++) {
|
|
76
|
+
const code = url.charCodeAt(end);
|
|
77
|
+
if (code === 47 || code === 63 || code === 35)
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
return end > 1 && end <= longest + 1
|
|
81
|
+
? translators.get(url.slice(1, end).toLowerCase())
|
|
82
|
+
: undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Application-scoped immutable translators; no global current locale or per-request catalog work. */
|
|
85
|
+
export function translationHttp(api, cookieName, logger, limits, pageHeader) {
|
|
86
|
+
// D-0099: an Inertia visit's `i18n` prop depends on what the browser runtime says it holds.
|
|
87
|
+
const varyNames = pageHeader ? [...VARY_NAMES, pageHeader] : VARY_NAMES;
|
|
88
|
+
const inertiaVary = varyNames.join(', ');
|
|
89
|
+
// D-0181: the translators of each scope (the base, and each app with a layer), made once.
|
|
90
|
+
const scoped = new Map(['', ...api.apps].map((app) => {
|
|
91
|
+
const options = app ? { app } : undefined;
|
|
92
|
+
const translators = new Map(api.locales.map((locale) => [locale.toLowerCase(), api.forLocale(locale, options)]));
|
|
93
|
+
const scope = {
|
|
94
|
+
options,
|
|
95
|
+
translators,
|
|
96
|
+
adapter: Object.freeze({ translators }),
|
|
97
|
+
fallback: api.forLocale(api.defaultLocale, options),
|
|
98
|
+
};
|
|
99
|
+
return [app, scope];
|
|
100
|
+
}));
|
|
101
|
+
const base = scoped.get('');
|
|
102
|
+
const appOf = api.apps.length ? limits.appOf : undefined;
|
|
103
|
+
const longest = Math.max(...api.locales.map((locale) => locale.length));
|
|
104
|
+
// A URL-decided answer varies by its URL only; an Inertia visit still by what the page holds.
|
|
105
|
+
const urlVary = pageHeader ? [pageHeader] : [];
|
|
106
|
+
const negotiator = new Negotiator(api.locales, api.defaultLocale, limits.negotiation);
|
|
107
|
+
// cookieName has already passed the options schema's token pattern.
|
|
108
|
+
const cookie = new RegExp(`(?:^|;\\s*)${cookieName}=([^;]*)`);
|
|
109
|
+
const attach = (server, _options, done) => {
|
|
110
|
+
server.decorateRequest('i18n');
|
|
111
|
+
server.addHook('onRequest', (request, reply, next) => {
|
|
112
|
+
const app = appOf?.(request);
|
|
113
|
+
const { translators, adapter, fallback, options } = (app !== undefined && scoped.get(app)) || base;
|
|
114
|
+
request[ADAPTER] = adapter;
|
|
115
|
+
const fromPath = limits.pathLocale
|
|
116
|
+
? pathTranslator(request.url, translators, longest)
|
|
117
|
+
: undefined;
|
|
118
|
+
if (fromPath) {
|
|
119
|
+
request.i18n = fromPath;
|
|
120
|
+
request[FROM_URL] = true;
|
|
121
|
+
reply.header('Content-Language', fromPath.locale);
|
|
122
|
+
reply[OWN] = true;
|
|
123
|
+
reply.header = labelledHeader;
|
|
124
|
+
next();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const header = request.headers.cookie;
|
|
128
|
+
const saved = header && header.length <= limits.maxCookieHeaderBytes
|
|
129
|
+
? cookie.exec(header)?.[1]
|
|
130
|
+
: undefined;
|
|
131
|
+
let translator = saved ? translators.get(saved.toLowerCase()) : undefined;
|
|
132
|
+
if (!translator) {
|
|
133
|
+
const locale = negotiator.prefer(request.headers['accept-language']);
|
|
134
|
+
// A header past the negotiation limits is client input, not a server failure.
|
|
135
|
+
if (locale === undefined && logger.isEnabled('debug'))
|
|
136
|
+
logger.log('debug', 'Oversized Accept-Language ignored', {
|
|
137
|
+
code: 'I18N_HTTP_HEADER_IGNORED',
|
|
138
|
+
});
|
|
139
|
+
translator = locale === undefined ? fallback : api.forLocale(locale, options);
|
|
140
|
+
}
|
|
141
|
+
request.i18n = translator;
|
|
142
|
+
// Renderers can use the representation language before serialization; do not rewrite HTML.
|
|
143
|
+
reply.header('Content-Language', translator.locale);
|
|
144
|
+
reply[OWN] = true;
|
|
145
|
+
reply.header = labelledHeader;
|
|
146
|
+
if (logger.isEnabled('debug'))
|
|
147
|
+
logger.log('debug', 'Request translation selected', {
|
|
148
|
+
code: 'I18N_HTTP_LOCALE',
|
|
149
|
+
locale: translator.locale,
|
|
150
|
+
});
|
|
151
|
+
next();
|
|
152
|
+
});
|
|
153
|
+
server.addHook('onSend', (request, reply, payload, next) => {
|
|
154
|
+
if (!translatable(reply.getHeader('content-type')) &&
|
|
155
|
+
reply.getHeader('x-inertia') !== 'true' &&
|
|
156
|
+
// A JSON answer @dokebi/web sealed before this hook (seal host, D-0062): its type is
|
|
157
|
+
// application/vnd.dokebi-seal, the opened body is the translated JSON.
|
|
158
|
+
reply.getHeader(SEALED_PATH) === undefined) {
|
|
159
|
+
// Only the label this adapter wrote: one the answer set itself (also the same value) stays.
|
|
160
|
+
if (reply[OWN])
|
|
161
|
+
reply.removeHeader('Content-Language');
|
|
162
|
+
next(null, payload);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const inertia = pageHeader !== undefined && reply.getHeader('x-inertia') === 'true';
|
|
166
|
+
const fromUrl = request[FROM_URL] === true;
|
|
167
|
+
// A URL-decided page that left bundles out for the pageCache cookie is that browser's own.
|
|
168
|
+
const claimed = request[COOKIE_CLAIMED] === true;
|
|
169
|
+
const names = fromUrl
|
|
170
|
+
? inertia
|
|
171
|
+
? urlVary
|
|
172
|
+
: claimed
|
|
173
|
+
? COOKIE_VARY
|
|
174
|
+
: []
|
|
175
|
+
: inertia
|
|
176
|
+
? varyNames
|
|
177
|
+
: VARY_NAMES;
|
|
178
|
+
if (!names.length) {
|
|
179
|
+
next(null, payload);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const existing = reply.getHeader('vary');
|
|
183
|
+
if (existing === undefined || existing === '') {
|
|
184
|
+
reply.header('Vary', fromUrl ? names.join(', ') : inertia ? inertiaVary : VARY);
|
|
185
|
+
next(null, payload);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const parts = (Array.isArray(existing) ? existing.join(',') : String(existing))
|
|
189
|
+
.split(',')
|
|
190
|
+
.map((part) => part.trim())
|
|
191
|
+
.filter(Boolean);
|
|
192
|
+
const seen = new Set(parts.map((part) => part.toLowerCase()));
|
|
193
|
+
if (!seen.has('*')) {
|
|
194
|
+
for (const name of names)
|
|
195
|
+
if (!seen.has(name.toLowerCase()))
|
|
196
|
+
parts.push(name);
|
|
197
|
+
reply.header('Vary', parts.join(', '));
|
|
198
|
+
}
|
|
199
|
+
next(null, payload);
|
|
200
|
+
});
|
|
201
|
+
done();
|
|
202
|
+
};
|
|
203
|
+
// The same non-encapsulated plugin registration used by session/auth/CSRF, owned by the plugin.
|
|
204
|
+
Object.defineProperty(attach, Symbol.for('skip-override'), { value: true });
|
|
205
|
+
return attach;
|
|
206
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type { Catalogs, I18nApi, I18nEntry, Message, Parameters, PluralMessage, Translator, } from './contract.js';
|
|
2
|
+
export { dependency } from './dependency.js';
|
|
3
|
+
export { I18nError, type I18nErrorCode } from './errors.js';
|
|
4
|
+
export { type I18nHttpRequest, useUrlLocale } from './http.js';
|
|
5
|
+
export { type I18nOptions, options } from './options.js';
|
|
6
|
+
export { PAGE_HEADER, type PageI18nCache, type PageI18nPayload, type PageI18nSettings, pageMessages, } from './page.js';
|
|
7
|
+
export { createPlugin } from './plugin.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { dependency } from './dependency.js';
|
|
2
|
+
export { I18nError } from './errors.js';
|
|
3
|
+
export { useUrlLocale } from './http.js';
|
|
4
|
+
export { options } from './options.js';
|
|
5
|
+
export { PAGE_HEADER, pageMessages, } from './page.js';
|
|
6
|
+
export { createPlugin } from './plugin.js';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
interface InstallContext {
|
|
2
|
+
readonly options: Readonly<Record<string, unknown>>;
|
|
3
|
+
}
|
|
4
|
+
export declare function planInstall(context: InstallContext): {
|
|
5
|
+
requires: string[];
|
|
6
|
+
entry: {
|
|
7
|
+
source: string;
|
|
8
|
+
target: string;
|
|
9
|
+
};
|
|
10
|
+
files: {
|
|
11
|
+
source: string;
|
|
12
|
+
target: string;
|
|
13
|
+
owner: 'user';
|
|
14
|
+
}[];
|
|
15
|
+
};
|
|
16
|
+
export declare function planUpgrade(context: InstallContext): {
|
|
17
|
+
requires: string[];
|
|
18
|
+
entry: {
|
|
19
|
+
source: string;
|
|
20
|
+
target: string;
|
|
21
|
+
};
|
|
22
|
+
files: {
|
|
23
|
+
source: string;
|
|
24
|
+
target: string;
|
|
25
|
+
owner: 'user';
|
|
26
|
+
}[];
|
|
27
|
+
};
|
|
28
|
+
export declare function check(context: InstallContext): {
|
|
29
|
+
requires: string[];
|
|
30
|
+
};
|
|
31
|
+
export {};
|
package/dist/install.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const target = 'src/infra/i18n/extension.ts';
|
|
2
|
+
const files = [
|
|
3
|
+
{
|
|
4
|
+
source: 'templates/locales/en/common.json',
|
|
5
|
+
target: 'src/shared/locales/en/common.json',
|
|
6
|
+
owner: 'user',
|
|
7
|
+
},
|
|
8
|
+
];
|
|
9
|
+
function requires(context) {
|
|
10
|
+
return context.options.http?.enabled ? ['dokebi-web'] : [];
|
|
11
|
+
}
|
|
12
|
+
export function planInstall(context) {
|
|
13
|
+
return {
|
|
14
|
+
requires: requires(context),
|
|
15
|
+
entry: { source: 'templates/extension.ts', target },
|
|
16
|
+
files,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function planUpgrade(context) {
|
|
20
|
+
// CLI >=0.4.6 preserves retired user-owned files. No user translation is overwritten or deleted.
|
|
21
|
+
return {
|
|
22
|
+
requires: requires(context),
|
|
23
|
+
entry: { source: 'templates/upgrade-extension.ts', target },
|
|
24
|
+
files,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function check(context) {
|
|
28
|
+
return { requires: requires(context) };
|
|
29
|
+
}
|
package/dist/layers.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Message } from './contract.js';
|
|
2
|
+
/** One layer: its catalogs by canonical locale. */
|
|
3
|
+
export interface Layer<T> {
|
|
4
|
+
readonly kind: 'app' | 'module' | 'shared';
|
|
5
|
+
readonly name: string;
|
|
6
|
+
readonly catalogs: ReadonlyMap<string, ReadonlyMap<string, T>>;
|
|
7
|
+
}
|
|
8
|
+
/** The base scope (no app). */
|
|
9
|
+
export declare const BASE = "";
|
|
10
|
+
/** The raw messages of an entry: the shared layer, the module layers and the app layers. */
|
|
11
|
+
export declare function entryLayers(entry: Record<string, unknown>): {
|
|
12
|
+
shared: Layer<Message>;
|
|
13
|
+
modules: Layer<Message>[];
|
|
14
|
+
apps: Layer<Message>[];
|
|
15
|
+
};
|
|
16
|
+
/** Every locale any layer has. */
|
|
17
|
+
export declare function localesOf<T>(layers: Iterable<Layer<T>>): string[];
|
|
18
|
+
/** One scope's catalogs by locale: per locale, the first layer with a key gives it. */
|
|
19
|
+
export declare function merge<T>(layers: readonly Layer<T>[], locales: Iterable<string>): Map<string, Map<string, T>>;
|
package/dist/layers.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { I18nError } from './errors.js';
|
|
2
|
+
import { canonical, record } from './values.js';
|
|
3
|
+
/** The base scope (no app). */
|
|
4
|
+
export const BASE = '';
|
|
5
|
+
const LAYER_NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
|
6
|
+
/** The raw messages of an entry: the shared layer, the module layers and the app layers. */
|
|
7
|
+
export function entryLayers(entry) {
|
|
8
|
+
const catalogsOf = (input) => {
|
|
9
|
+
const out = new Map();
|
|
10
|
+
for (const [name, messages] of Object.entries(record(input))) {
|
|
11
|
+
const locale = canonical(name);
|
|
12
|
+
if (out.has(locale))
|
|
13
|
+
throw new I18nError('INVALID_CATALOG', 'Duplicate canonical locale');
|
|
14
|
+
const map = new Map();
|
|
15
|
+
for (const [key, value] of Object.entries(record(messages)))
|
|
16
|
+
map.set(key, value);
|
|
17
|
+
out.set(locale, map);
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
};
|
|
21
|
+
const layers = entry.layers === undefined ? {} : record(entry.layers);
|
|
22
|
+
if (Object.keys(layers).some((key) => key !== 'apps' && key !== 'modules'))
|
|
23
|
+
throw new I18nError('INVALID_CATALOG', 'layers holds apps and modules (loadLayers)');
|
|
24
|
+
const named = (kind, input) => Object.entries(input === undefined ? {} : record(input))
|
|
25
|
+
.map(([name, catalogs]) => {
|
|
26
|
+
if (!LAYER_NAME.test(name))
|
|
27
|
+
throw new I18nError('INVALID_CATALOG', `The ${kind} layer ${JSON.stringify(name)} is not a ${kind} name`);
|
|
28
|
+
return { kind, name, catalogs: catalogsOf(catalogs) };
|
|
29
|
+
})
|
|
30
|
+
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
31
|
+
return {
|
|
32
|
+
shared: { kind: 'shared', name: 'shared', catalogs: catalogsOf(entry.catalogs) },
|
|
33
|
+
modules: named('module', layers.modules),
|
|
34
|
+
apps: named('app', layers.apps),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Every locale any layer has. */
|
|
38
|
+
export function localesOf(layers) {
|
|
39
|
+
const out = new Set();
|
|
40
|
+
for (const layer of layers)
|
|
41
|
+
for (const locale of layer.catalogs.keys())
|
|
42
|
+
out.add(locale);
|
|
43
|
+
return [...out];
|
|
44
|
+
}
|
|
45
|
+
/** One scope's catalogs by locale: per locale, the first layer with a key gives it. */
|
|
46
|
+
export function merge(layers, locales) {
|
|
47
|
+
const out = new Map();
|
|
48
|
+
for (const locale of locales) {
|
|
49
|
+
const merged = new Map();
|
|
50
|
+
for (const layer of layers)
|
|
51
|
+
for (const [key, value] of layer.catalogs.get(locale) ?? [])
|
|
52
|
+
if (!merged.has(key))
|
|
53
|
+
merged.set(key, value);
|
|
54
|
+
out.set(locale, merged);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Parameters } from './contract.js';
|
|
2
|
+
type Part = string | {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
};
|
|
5
|
+
type Template = readonly Part[];
|
|
6
|
+
export interface CompiledMessage {
|
|
7
|
+
readonly branches: ReadonlyMap<string, Template>;
|
|
8
|
+
readonly plural: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** The option default of maxBranchLength. */
|
|
11
|
+
export declare const MAX_BRANCH_LENGTH = 16384;
|
|
12
|
+
export declare function compileMessage(input: unknown, maxBranchLength?: number): CompiledMessage;
|
|
13
|
+
/**
|
|
14
|
+
* One locale's cardinal rules. Intl selection costs a few hundred nanoseconds; the category of a
|
|
15
|
+
* whole count below 1024 never changes, so it is remembered in a fixed 1 KiB table.
|
|
16
|
+
*/
|
|
17
|
+
export declare class PluralRules {
|
|
18
|
+
#private;
|
|
19
|
+
constructor(locale: string);
|
|
20
|
+
select(count: number): Intl.LDMLPluralRule;
|
|
21
|
+
}
|
|
22
|
+
export declare function render(message: CompiledMessage, rules: PluralRules, parameters: Parameters | undefined, limit: number): string;
|
|
23
|
+
export {};
|
package/dist/message.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { types } from 'node:util';
|
|
2
|
+
import { I18nError } from './errors.js';
|
|
3
|
+
import { record } from './values.js';
|
|
4
|
+
/** The option default of maxBranchLength. */
|
|
5
|
+
export const MAX_BRANCH_LENGTH = 16384;
|
|
6
|
+
function compile(text, maxLength) {
|
|
7
|
+
if (typeof text !== 'string' || text.length > maxLength)
|
|
8
|
+
throw new I18nError('INVALID_CATALOG', `Message branches must be strings of at most ${maxLength} characters (maxBranchLength)`);
|
|
9
|
+
const parts = [];
|
|
10
|
+
let literal = '';
|
|
11
|
+
for (let index = 0; index < text.length;) {
|
|
12
|
+
const char = text[index];
|
|
13
|
+
if ((char === '{' || char === '}') && text[index + 1] === char) {
|
|
14
|
+
literal += char;
|
|
15
|
+
index += 2;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (char === '{') {
|
|
19
|
+
const end = text.indexOf('}', index + 1);
|
|
20
|
+
const name = text.slice(index + 1, end);
|
|
21
|
+
if (end < 0 || !/^[a-zA-Z_][a-zA-Z0-9_]{0,63}$/.test(name))
|
|
22
|
+
throw new I18nError('INVALID_CATALOG', 'Invalid named placeholder');
|
|
23
|
+
if (literal) {
|
|
24
|
+
parts.push(literal);
|
|
25
|
+
literal = '';
|
|
26
|
+
}
|
|
27
|
+
parts.push({ name });
|
|
28
|
+
index = end + 1;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
if (char === '}')
|
|
32
|
+
throw new I18nError('INVALID_CATALOG', 'Unescaped closing brace');
|
|
33
|
+
literal += char;
|
|
34
|
+
index++;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (literal)
|
|
38
|
+
parts.push(literal);
|
|
39
|
+
return parts;
|
|
40
|
+
}
|
|
41
|
+
export function compileMessage(input, maxBranchLength = MAX_BRANCH_LENGTH) {
|
|
42
|
+
if (typeof input === 'string')
|
|
43
|
+
return { plural: false, branches: new Map([['other', compile(input, maxBranchLength)]]) };
|
|
44
|
+
const values = record(input);
|
|
45
|
+
if (typeof values.other !== 'string' ||
|
|
46
|
+
Object.keys(values).some((key) => !['zero', 'one', 'two', 'few', 'many', 'other'].includes(key)))
|
|
47
|
+
throw new I18nError('INVALID_CATALOG', 'Plural messages require other and only cardinal categories');
|
|
48
|
+
return {
|
|
49
|
+
plural: true,
|
|
50
|
+
branches: new Map(Object.entries(values).map(([key, value]) => [key, compile(value, maxBranchLength)])),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function parameter(parameters, name) {
|
|
54
|
+
if (!parameters || typeof parameters !== 'object' || types.isProxy(parameters))
|
|
55
|
+
throw new I18nError('INVALID_PARAMETER', 'Missing or invalid message parameters');
|
|
56
|
+
const descriptor = Object.getOwnPropertyDescriptor(parameters, name);
|
|
57
|
+
const value = descriptor && 'value' in descriptor ? descriptor.value : undefined;
|
|
58
|
+
if (typeof value !== 'string' && (typeof value !== 'number' || !Number.isFinite(value)))
|
|
59
|
+
throw new I18nError('INVALID_PARAMETER', 'Message parameters must be own strings or finite numbers');
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
const REMEMBERED_COUNTS = 1024;
|
|
63
|
+
const CATEGORIES = ['zero', 'one', 'two', 'few', 'many', 'other'];
|
|
64
|
+
/**
|
|
65
|
+
* One locale's cardinal rules. Intl selection costs a few hundred nanoseconds; the category of a
|
|
66
|
+
* whole count below 1024 never changes, so it is remembered in a fixed 1 KiB table.
|
|
67
|
+
*/
|
|
68
|
+
export class PluralRules {
|
|
69
|
+
#rules;
|
|
70
|
+
/** Category index + 1 per whole count; 0 = not selected yet. */
|
|
71
|
+
#small = new Uint8Array(REMEMBERED_COUNTS);
|
|
72
|
+
constructor(locale) {
|
|
73
|
+
this.#rules = new Intl.PluralRules(locale);
|
|
74
|
+
}
|
|
75
|
+
select(count) {
|
|
76
|
+
if (!Number.isInteger(count) || count < 0 || count >= REMEMBERED_COUNTS)
|
|
77
|
+
return this.#rules.select(count);
|
|
78
|
+
const known = this.#small[count];
|
|
79
|
+
if (known !== 0)
|
|
80
|
+
return CATEGORIES[known - 1];
|
|
81
|
+
const category = this.#rules.select(count);
|
|
82
|
+
this.#small[count] = CATEGORIES.indexOf(category) + 1;
|
|
83
|
+
return category;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function render(message, rules, parameters, limit) {
|
|
87
|
+
let category = 'other';
|
|
88
|
+
if (message.plural) {
|
|
89
|
+
const count = parameter(parameters, 'count');
|
|
90
|
+
if (typeof count !== 'number')
|
|
91
|
+
throw new I18nError('INVALID_PARAMETER', 'Plural count must be a finite number');
|
|
92
|
+
category = rules.select(count);
|
|
93
|
+
}
|
|
94
|
+
const parts = message.branches.get(category) ?? message.branches.get('other');
|
|
95
|
+
let output = '';
|
|
96
|
+
for (const part of parts ?? []) {
|
|
97
|
+
const value = typeof part === 'string' ? part : String(parameter(parameters, part.name));
|
|
98
|
+
if (output.length + value.length > limit)
|
|
99
|
+
throw new I18nError('OUTPUT_LIMIT', 'Rendered message exceeds maxOutputLength');
|
|
100
|
+
output += value;
|
|
101
|
+
}
|
|
102
|
+
return output;
|
|
103
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The input limits of negotiate() (options maxAcceptLanguageLength, maxAcceptLanguageRanges). */
|
|
2
|
+
export interface NegotiationLimits {
|
|
3
|
+
readonly maxLength: number;
|
|
4
|
+
readonly maxRanges: number;
|
|
5
|
+
}
|
|
6
|
+
/** The option defaults, for a Negotiator made without options. */
|
|
7
|
+
export declare const NEGOTIATION_LIMITS: NegotiationLimits;
|
|
8
|
+
/**
|
|
9
|
+
* Accept-Language negotiation over one fixed locale list. Lowercased tags are prepared once; a call
|
|
10
|
+
* allocates only its parsed ranges. Calls are synchronous, so the per-locale scratch is reused.
|
|
11
|
+
*/
|
|
12
|
+
export declare class Negotiator {
|
|
13
|
+
#private;
|
|
14
|
+
constructor(locales: readonly string[], fallback: string, limits?: NegotiationLimits);
|
|
15
|
+
/** The public contract: input past the limits is a coded error; undefined when all are excluded. */
|
|
16
|
+
negotiate(header: string | undefined): string | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* For the automatic HTTP adapter, where a page always gets a language: an all-excluded header
|
|
19
|
+
* selects the fallback. undefined means the client-controlled header is past the limits and
|
|
20
|
+
* carries no usable preference; the caller decides (and logs) what to use instead.
|
|
21
|
+
*/
|
|
22
|
+
prefer(header: string | undefined): string | undefined;
|
|
23
|
+
}
|