@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/calendar.js
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Day boundaries in a time zone, the same on the server and in the browser (D-0178 §3): this
|
|
3
|
+
* module imports nothing, so a page bundles it as it is. Every function takes the zone; days are
|
|
4
|
+
* `YYYY-MM-DD`, months `YYYY-MM`, wall-clock times `YYYY-MM-DDTHH:mm`, instants epoch ms (UTC).
|
|
5
|
+
*/
|
|
6
|
+
export const HOUR = 3_600_000;
|
|
7
|
+
export const DAY = 86_400_000;
|
|
8
|
+
/** A refused day, month, time or zone: 400 through @dokebi/web (a Dokebi error shape). */
|
|
9
|
+
export class CalendarError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
status = 400;
|
|
12
|
+
plugin = 'dokebi-i18n';
|
|
13
|
+
data;
|
|
14
|
+
constructor(code, message, field, options) {
|
|
15
|
+
super(message, options);
|
|
16
|
+
this.name = 'CalendarError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.data = { field };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Zones whose offset from UTC is a whole number of hours at every time, summer time included,
|
|
23
|
+
* east to west (a site's choices when its reports count UTC hours into site days). Names only:
|
|
24
|
+
* the labels belong to the application's catalogs.
|
|
25
|
+
*/
|
|
26
|
+
export const WHOLE_HOUR_ZONES = Object.freeze([
|
|
27
|
+
'Pacific/Auckland',
|
|
28
|
+
'Australia/Sydney',
|
|
29
|
+
'Australia/Brisbane',
|
|
30
|
+
'Asia/Vladivostok',
|
|
31
|
+
'Asia/Seoul',
|
|
32
|
+
'Asia/Tokyo',
|
|
33
|
+
'Asia/Shanghai',
|
|
34
|
+
'Asia/Hong_Kong',
|
|
35
|
+
'Asia/Taipei',
|
|
36
|
+
'Asia/Singapore',
|
|
37
|
+
'Asia/Manila',
|
|
38
|
+
'Australia/Perth',
|
|
39
|
+
'Asia/Ulaanbaatar',
|
|
40
|
+
'Asia/Bangkok',
|
|
41
|
+
'Asia/Ho_Chi_Minh',
|
|
42
|
+
'Asia/Jakarta',
|
|
43
|
+
'Asia/Dhaka',
|
|
44
|
+
'Asia/Tashkent',
|
|
45
|
+
'Asia/Karachi',
|
|
46
|
+
'Asia/Dubai',
|
|
47
|
+
'Europe/Moscow',
|
|
48
|
+
'Europe/Istanbul',
|
|
49
|
+
'Asia/Riyadh',
|
|
50
|
+
'Europe/Athens',
|
|
51
|
+
'Africa/Cairo',
|
|
52
|
+
'Africa/Johannesburg',
|
|
53
|
+
'Europe/Berlin',
|
|
54
|
+
'Europe/Paris',
|
|
55
|
+
'Africa/Lagos',
|
|
56
|
+
'Europe/London',
|
|
57
|
+
'UTC',
|
|
58
|
+
'Atlantic/Azores',
|
|
59
|
+
'America/Sao_Paulo',
|
|
60
|
+
'America/Argentina/Buenos_Aires',
|
|
61
|
+
'America/Halifax',
|
|
62
|
+
'America/New_York',
|
|
63
|
+
'America/Chicago',
|
|
64
|
+
'America/Mexico_City',
|
|
65
|
+
'America/Denver',
|
|
66
|
+
'America/Phoenix',
|
|
67
|
+
'America/Los_Angeles',
|
|
68
|
+
'America/Anchorage',
|
|
69
|
+
'Pacific/Honolulu',
|
|
70
|
+
]);
|
|
71
|
+
const MAX_FORMATS = 512;
|
|
72
|
+
const formats = new Map();
|
|
73
|
+
function formatOf(zone) {
|
|
74
|
+
let format = formats.get(zone);
|
|
75
|
+
if (format)
|
|
76
|
+
return format;
|
|
77
|
+
try {
|
|
78
|
+
format = new Intl.DateTimeFormat('en-US', {
|
|
79
|
+
timeZone: zone,
|
|
80
|
+
hourCycle: 'h23',
|
|
81
|
+
year: 'numeric',
|
|
82
|
+
month: '2-digit',
|
|
83
|
+
day: '2-digit',
|
|
84
|
+
hour: '2-digit',
|
|
85
|
+
minute: '2-digit',
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
catch (cause) {
|
|
89
|
+
throw new CalendarError('INVALID_ZONE', 'Not a time zone such as Asia/Seoul', 'zone', {
|
|
90
|
+
cause,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (formats.size >= MAX_FORMATS)
|
|
94
|
+
formats.delete(formats.keys().next().value);
|
|
95
|
+
formats.set(zone, format);
|
|
96
|
+
return format;
|
|
97
|
+
}
|
|
98
|
+
function wall(zone, ms) {
|
|
99
|
+
// An instant from a request (`Number(query.at)`) that is no time: a coded 400, not Intl's
|
|
100
|
+
// RangeError (a 500).
|
|
101
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms) || Math.abs(ms) > 8.64e15)
|
|
102
|
+
throw new CalendarError('INVALID_DATE', 'An instant is epoch milliseconds', 'ms');
|
|
103
|
+
const out = {};
|
|
104
|
+
for (const part of formatOf(zone).formatToParts(ms))
|
|
105
|
+
if (part.type !== 'literal')
|
|
106
|
+
out[part.type] = Number(part.value);
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
const pad = (value, size = 2) => String(value).padStart(size, '0');
|
|
110
|
+
const dayText = (w) => `${pad(w.year, 4)}-${pad(w.month)}-${pad(w.day)}`;
|
|
111
|
+
function zoneName(zone) {
|
|
112
|
+
if (typeof zone !== 'string' || !zone.length || zone.length > 64)
|
|
113
|
+
throw new CalendarError('INVALID_ZONE', 'A zone is an IANA name such as Asia/Seoul', 'zone');
|
|
114
|
+
formatOf(zone);
|
|
115
|
+
return zone;
|
|
116
|
+
}
|
|
117
|
+
/** The zone's offset from UTC at `ms`, in minutes (+540 for Seoul). */
|
|
118
|
+
export function offsetMinutes(zone, ms) {
|
|
119
|
+
zoneName(zone);
|
|
120
|
+
const w = wall(zone, ms);
|
|
121
|
+
const local = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute);
|
|
122
|
+
return Math.round((local - Math.floor(ms / 60_000) * 60_000) / 60_000);
|
|
123
|
+
}
|
|
124
|
+
const DAY_TEXT = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
125
|
+
const MONTH_TEXT = /^(\d{4})-(\d{2})$/;
|
|
126
|
+
const WALL_TEXT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/;
|
|
127
|
+
/** Midnight UTC of a day that exists (1000-01-01 to 9999-12-31). */
|
|
128
|
+
function dayMs(day, field = 'day') {
|
|
129
|
+
const match = typeof day === 'string' ? DAY_TEXT.exec(day) : null;
|
|
130
|
+
const ms = match
|
|
131
|
+
? Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))
|
|
132
|
+
: Number.NaN;
|
|
133
|
+
if (!match || Number(match[1]) < 1000 || new Date(ms).toISOString().slice(0, 10) !== day)
|
|
134
|
+
throw new CalendarError('INVALID_DATE', `${field} is a day YYYY-MM-DD`, field);
|
|
135
|
+
return ms;
|
|
136
|
+
}
|
|
137
|
+
function monthDay(month, field = 'month') {
|
|
138
|
+
const match = typeof month === 'string' ? MONTH_TEXT.exec(month) : null;
|
|
139
|
+
if (!match || Number(match[1]) < 1000 || Number(match[2]) < 1 || Number(match[2]) > 12)
|
|
140
|
+
throw new CalendarError('INVALID_DATE', `${field} is a month YYYY-MM`, field);
|
|
141
|
+
return `${month}-01`;
|
|
142
|
+
}
|
|
143
|
+
const isoDay = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
144
|
+
/** The day `ms` falls on in `zone`. */
|
|
145
|
+
export function dayOf(zone, ms) {
|
|
146
|
+
return dayText(wall(zoneName(zone), ms));
|
|
147
|
+
}
|
|
148
|
+
/** The month `ms` falls on in `zone`. */
|
|
149
|
+
export function monthOf(zone, ms) {
|
|
150
|
+
return dayOf(zone, ms).slice(0, 7);
|
|
151
|
+
}
|
|
152
|
+
/** The wall-clock time of `ms` in `zone`, to the minute. */
|
|
153
|
+
export function wallTimeOf(zone, ms) {
|
|
154
|
+
const w = wall(zoneName(zone), ms);
|
|
155
|
+
return `${dayText(w)}T${pad(w.hour)}:${pad(w.minute)}`;
|
|
156
|
+
}
|
|
157
|
+
/** The instants whose wall-clock time in `zone` could be `local` (ms of that time as if UTC). */
|
|
158
|
+
function candidates(zone, local) {
|
|
159
|
+
const offsets = new Set([
|
|
160
|
+
offsetMinutes(zone, local - 14 * HOUR),
|
|
161
|
+
offsetMinutes(zone, local + 14 * HOUR),
|
|
162
|
+
]);
|
|
163
|
+
return [...offsets].map((offset) => local - offset * 60_000).sort((a, b) => a - b);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The first instant of `day` in `zone`: its midnight, or the end of a summer-time gap when the
|
|
167
|
+
* zone skips midnight that day.
|
|
168
|
+
*/
|
|
169
|
+
export function dayStart(zone, day) {
|
|
170
|
+
zoneName(zone);
|
|
171
|
+
const local = dayMs(day);
|
|
172
|
+
for (const instant of candidates(zone, local))
|
|
173
|
+
if (dayOf(zone, instant) === day)
|
|
174
|
+
return instant;
|
|
175
|
+
// Unreachable for a real zone: one of the two offsets around the day maps midnight into it.
|
|
176
|
+
throw new CalendarError('INVALID_DATE', `${day} has no start in ${zone}`, 'day');
|
|
177
|
+
}
|
|
178
|
+
/** The instants of the days `from` to `to` (both counted) in `zone`: `start <= t < end`. */
|
|
179
|
+
export function dayRange(zone, from, to) {
|
|
180
|
+
if (dayMs(to, 'to') < dayMs(from, 'from'))
|
|
181
|
+
throw new CalendarError('INVALID_DATE', 'to is before from', 'to');
|
|
182
|
+
return { start: dayStart(zone, from), end: dayStart(zone, addDays(to, 1)) };
|
|
183
|
+
}
|
|
184
|
+
/** The instants of `month` in `zone`: `start <= t < end`. */
|
|
185
|
+
export function monthRange(zone, month) {
|
|
186
|
+
const first = monthDay(month);
|
|
187
|
+
return { start: dayStart(zone, first), end: dayStart(zone, `${addMonths(month, 1)}-01`) };
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The instant a wall-clock time `YYYY-MM-DDTHH:mm` is in `zone`. A time a summer-time change
|
|
191
|
+
* skips is taken after the gap (02:30 → 03:30); a time it repeats is the earlier one.
|
|
192
|
+
*/
|
|
193
|
+
export function fromWallTime(zone, text) {
|
|
194
|
+
zoneName(zone);
|
|
195
|
+
const match = typeof text === 'string' ? WALL_TEXT.exec(text) : null;
|
|
196
|
+
if (!match || Number(match[4]) > 23 || Number(match[5]) > 59)
|
|
197
|
+
throw new CalendarError('INVALID_DATE', 'A time is YYYY-MM-DDTHH:mm', 'time');
|
|
198
|
+
const local = dayMs(text.slice(0, 10), 'time') + Number(match[4]) * HOUR + Number(match[5]) * 60_000;
|
|
199
|
+
const found = candidates(zone, local);
|
|
200
|
+
for (const instant of found)
|
|
201
|
+
if (wallTimeOf(zone, instant) === text)
|
|
202
|
+
return instant;
|
|
203
|
+
// In a gap: the offset before the change carries the time past the gap.
|
|
204
|
+
return local - offsetMinutes(zone, local - 14 * HOUR) * 60_000;
|
|
205
|
+
}
|
|
206
|
+
/** `day` moved by `count` days. */
|
|
207
|
+
export function addDays(day, count) {
|
|
208
|
+
if (!Number.isSafeInteger(count))
|
|
209
|
+
throw new CalendarError('INVALID_DATE', 'count is an integer', 'count');
|
|
210
|
+
const moved = dayMs(day) + count * DAY;
|
|
211
|
+
if (!Number.isFinite(moved) || Math.abs(moved) > 8.64e15)
|
|
212
|
+
throw new CalendarError('INVALID_DATE', 'The day moves out of range', 'count');
|
|
213
|
+
const out = isoDay(moved);
|
|
214
|
+
dayMs(out, 'count');
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
217
|
+
/** `month` moved by `count` months. */
|
|
218
|
+
export function addMonths(month, count) {
|
|
219
|
+
const first = monthDay(month);
|
|
220
|
+
if (!Number.isSafeInteger(count) || Math.abs(count) > 120_000)
|
|
221
|
+
throw new CalendarError('INVALID_DATE', 'count is an integer', 'count');
|
|
222
|
+
const total = Number(first.slice(0, 4)) * 12 + Number(first.slice(5, 7)) - 1 + count;
|
|
223
|
+
const out = `${pad(Math.floor(total / 12), 4)}-${pad((total % 12) + 1)}`;
|
|
224
|
+
monthDay(out, 'count');
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
/** Days from `from` to `to`, both counted (1 for the same day; 0 or less when `to` is before). */
|
|
228
|
+
export function daysBetween(from, to) {
|
|
229
|
+
return Math.round((dayMs(to, 'to') - dayMs(from, 'from')) / DAY) + 1;
|
|
230
|
+
}
|
|
231
|
+
/** The first day of the week `day` is in; `firstDay` 0 Sunday … 6 Saturday (default Monday). */
|
|
232
|
+
export function weekStart(day, firstDay = 1) {
|
|
233
|
+
if (!Number.isInteger(firstDay) || firstDay < 0 || firstDay > 6)
|
|
234
|
+
throw new CalendarError('INVALID_DATE', 'firstDay is 0 (Sunday) to 6', 'firstDay');
|
|
235
|
+
const weekday = new Date(dayMs(day)).getUTCDay();
|
|
236
|
+
return addDays(day, -((weekday - firstDay + 7) % 7));
|
|
237
|
+
}
|
|
238
|
+
export const DATE_PRESETS = [
|
|
239
|
+
'today',
|
|
240
|
+
'yesterday',
|
|
241
|
+
'last7',
|
|
242
|
+
'last30',
|
|
243
|
+
'thisWeek',
|
|
244
|
+
'thisMonth',
|
|
245
|
+
'lastMonth',
|
|
246
|
+
];
|
|
247
|
+
/** The days of a preset in `zone` at `now` (for a filter; `dayRange` makes its instants). */
|
|
248
|
+
export function presetRange(zone, preset, now = Date.now(), firstDay = 1) {
|
|
249
|
+
const today = dayOf(zone, now);
|
|
250
|
+
switch (preset) {
|
|
251
|
+
case 'today':
|
|
252
|
+
return { from: today, to: today };
|
|
253
|
+
case 'yesterday': {
|
|
254
|
+
const day = addDays(today, -1);
|
|
255
|
+
return { from: day, to: day };
|
|
256
|
+
}
|
|
257
|
+
case 'last7':
|
|
258
|
+
return { from: addDays(today, -6), to: today };
|
|
259
|
+
case 'last30':
|
|
260
|
+
return { from: addDays(today, -29), to: today };
|
|
261
|
+
case 'thisWeek':
|
|
262
|
+
return { from: weekStart(today, firstDay), to: today };
|
|
263
|
+
case 'thisMonth':
|
|
264
|
+
return { from: `${today.slice(0, 7)}-01`, to: today };
|
|
265
|
+
case 'lastMonth': {
|
|
266
|
+
const first = `${addMonths(today.slice(0, 7), -1)}-01`;
|
|
267
|
+
return { from: first, to: addDays(`${today.slice(0, 7)}-01`, -1) };
|
|
268
|
+
}
|
|
269
|
+
default:
|
|
270
|
+
throw new CalendarError('INVALID_DATE', `preset is one of ${DATE_PRESETS.join(', ')}`, 'preset');
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const wholeHours = new Map();
|
|
274
|
+
/**
|
|
275
|
+
* Whether `zone`'s offset is whole hours at every time from two years back to two years ahead
|
|
276
|
+
* (sampled every 6 hours; kept per zone).
|
|
277
|
+
*/
|
|
278
|
+
export function isWholeHourZone(zone) {
|
|
279
|
+
zoneName(zone);
|
|
280
|
+
const known = wholeHours.get(zone);
|
|
281
|
+
if (known !== undefined)
|
|
282
|
+
return known;
|
|
283
|
+
const now = Date.now();
|
|
284
|
+
let whole = true;
|
|
285
|
+
for (let at = now - 2 * 365 * DAY; at <= now + 2 * 365 * DAY && whole; at += 6 * HOUR)
|
|
286
|
+
if (offsetMinutes(zone, at) % 60 !== 0)
|
|
287
|
+
whole = false;
|
|
288
|
+
if (wholeHours.size < MAX_FORMATS)
|
|
289
|
+
wholeHours.set(zone, whole);
|
|
290
|
+
return whole;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* `zone` checked (INVALID_ZONE otherwise) and in its canonical spelling; with `wholeHours`, only
|
|
294
|
+
* a zone whose offset is always whole hours.
|
|
295
|
+
*/
|
|
296
|
+
export function checkZone(zone, options = {}) {
|
|
297
|
+
const name = zoneName(zone);
|
|
298
|
+
const canonical = formatOf(name).resolvedOptions().timeZone;
|
|
299
|
+
if (options.wholeHours && !isWholeHourZone(canonical))
|
|
300
|
+
throw new CalendarError('INVALID_ZONE', `${canonical} is not whole hours from UTC at every time`, 'zone');
|
|
301
|
+
return canonical;
|
|
302
|
+
}
|
|
303
|
+
/** The offsets `zone` uses in `year`, smallest first: `['+9']`, `['+1', '+2']`, `['-5', '-4']`, `['+5:30']`. */
|
|
304
|
+
export function zoneOffsets(zone, year) {
|
|
305
|
+
zoneName(zone);
|
|
306
|
+
if (!Number.isInteger(year) || year < 1000 || year > 9999)
|
|
307
|
+
throw new CalendarError('INVALID_DATE', 'year is 1000 to 9999', 'year');
|
|
308
|
+
const seen = new Set();
|
|
309
|
+
for (let at = Date.UTC(year, 0, 1); at < Date.UTC(year + 1, 0, 1); at += 6 * HOUR)
|
|
310
|
+
seen.add(offsetMinutes(zone, at));
|
|
311
|
+
return [...seen]
|
|
312
|
+
.sort((a, b) => a - b)
|
|
313
|
+
.map((minutes) => {
|
|
314
|
+
const sign = minutes < 0 ? '-' : '+';
|
|
315
|
+
const size = Math.abs(minutes);
|
|
316
|
+
return `${sign}${Math.floor(size / 60)}${size % 60 ? `:${pad(size % 60)}` : ''}`;
|
|
317
|
+
});
|
|
318
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CatalogLayers, Catalogs } from './contract.js';
|
|
2
|
+
/**
|
|
3
|
+
* Early bounds of `loadCatalogs` (optional). Without them (D-0118) the entry only reads and
|
|
4
|
+
* flattens the files, and the plugin applies its options `maxLocales`, `maxMessages`,
|
|
5
|
+
* `maxCatalogBytes` and `maxCatalogCharacters` at setup — one setting in dokebi.yaml. Pass a
|
|
6
|
+
* bound here only to refuse earlier, before the plugin starts (a test that loads by itself).
|
|
7
|
+
*/
|
|
8
|
+
export interface CatalogLimits {
|
|
9
|
+
readonly maxMessages?: number;
|
|
10
|
+
readonly maxLocales?: number;
|
|
11
|
+
readonly maxBytes?: number;
|
|
12
|
+
/** Key paths longer than this are refused while loading (the plugin's maxKeyLength applies at setup). */
|
|
13
|
+
readonly maxKeyLength?: number;
|
|
14
|
+
/** Nesting of a namespace file, default 16: it bounds the recursion of the loader itself. */
|
|
15
|
+
readonly maxDepth?: number;
|
|
16
|
+
}
|
|
17
|
+
/** What `loadCatalogs` read, for the plugin's setup checks (D-0118). */
|
|
18
|
+
export interface CatalogSource {
|
|
19
|
+
/** Bytes of every namespace file together. */
|
|
20
|
+
readonly bytes: number;
|
|
21
|
+
readonly files: number;
|
|
22
|
+
}
|
|
23
|
+
/** The files behind catalogs made by `loadCatalogs` (undefined for inline catalogs). */
|
|
24
|
+
export declare function catalogSource(catalogs: unknown): CatalogSource | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* D-0181: the app and module layers under `src` (`src/apps/<app>/locales/` and
|
|
27
|
+
* `src/shared/modules/<module>/locales/`, each read like `loadCatalogs`). An entry exports it as
|
|
28
|
+
* `layers` next to `catalogs` (the shared layer, `src/shared/locales/`). Folders without a
|
|
29
|
+
* `locales` folder are skipped.
|
|
30
|
+
*/
|
|
31
|
+
export declare function loadLayers(src: string | URL, limits?: CatalogLimits): Promise<CatalogLayers>;
|
|
32
|
+
/** Load once in an entry: locales/<locale>/<namespace>.json -> namespace.nested.key. */
|
|
33
|
+
export declare function loadCatalogs(directory: string | URL, limits?: CatalogLimits): Promise<Catalogs>;
|
package/dist/catalogs.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { I18nError } from './errors.js';
|
|
5
|
+
import { canonical, record } from './values.js';
|
|
6
|
+
const SOURCES = new WeakMap();
|
|
7
|
+
/** A key path inside a namespace (`title`, `nav.home`): the `$overrides` entries (D-0181). */
|
|
8
|
+
const KEY_PATH = /^[a-zA-Z][a-zA-Z0-9_-]*(?:\.[a-zA-Z][a-zA-Z0-9_-]*)*$/;
|
|
9
|
+
const MAX_OVERRIDES = 10_000;
|
|
10
|
+
const CATEGORIES = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
|
|
11
|
+
/**
|
|
12
|
+
* A plural message: `other` and only cardinal categories, each a string. An object with any other
|
|
13
|
+
* key is nested, even with an `other` key ("etc", community request A1: it failed the start).
|
|
14
|
+
*/
|
|
15
|
+
function pluralObject(value) {
|
|
16
|
+
if (value === null || typeof value !== 'object' || !Object.hasOwn(value, 'other'))
|
|
17
|
+
return false;
|
|
18
|
+
return Object.entries(value).every(([key, branch]) => CATEGORIES.has(key) && typeof branch === 'string');
|
|
19
|
+
}
|
|
20
|
+
/** The files behind catalogs made by `loadCatalogs` (undefined for inline catalogs). */
|
|
21
|
+
export function catalogSource(catalogs) {
|
|
22
|
+
return catalogs !== null && typeof catalogs === 'object' ? SOURCES.get(catalogs) : undefined;
|
|
23
|
+
}
|
|
24
|
+
/** App and module names: the folders of src/apps and src/shared/modules (D-0181). */
|
|
25
|
+
const LAYER_NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
|
26
|
+
/**
|
|
27
|
+
* D-0181: the app and module layers under `src` (`src/apps/<app>/locales/` and
|
|
28
|
+
* `src/shared/modules/<module>/locales/`, each read like `loadCatalogs`). An entry exports it as
|
|
29
|
+
* `layers` next to `catalogs` (the shared layer, `src/shared/locales/`). Folders without a
|
|
30
|
+
* `locales` folder are skipped.
|
|
31
|
+
*/
|
|
32
|
+
export async function loadLayers(src, limits = {}) {
|
|
33
|
+
const root = src instanceof URL ? fileURLToPath(src) : src;
|
|
34
|
+
let bytes = 0;
|
|
35
|
+
let files = 0;
|
|
36
|
+
const read = async (parent, kind) => {
|
|
37
|
+
const out = Object.create(null);
|
|
38
|
+
let entries;
|
|
39
|
+
try {
|
|
40
|
+
entries = await readdir(join(root, parent), { withFileTypes: true });
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
// No apps or modules folder: that layer is empty.
|
|
44
|
+
if (error.code === 'ENOENT')
|
|
45
|
+
return out;
|
|
46
|
+
throw new I18nError('INVALID_CATALOG', `Cannot read ${parent}`, error);
|
|
47
|
+
}
|
|
48
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
49
|
+
if (!entry.isDirectory())
|
|
50
|
+
continue;
|
|
51
|
+
const folder = join(root, parent, entry.name, 'locales');
|
|
52
|
+
try {
|
|
53
|
+
if (!(await stat(folder)).isDirectory())
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
// This app or module has no translations of its own.
|
|
58
|
+
if (error.code === 'ENOENT')
|
|
59
|
+
continue;
|
|
60
|
+
throw new I18nError('INVALID_CATALOG', `Cannot read ${parent}/${entry.name}/locales`, error);
|
|
61
|
+
}
|
|
62
|
+
if (!LAYER_NAME.test(entry.name))
|
|
63
|
+
throw new I18nError('INVALID_CATALOG', `The ${kind} folder ${JSON.stringify(entry.name)} is not a ${kind} name`);
|
|
64
|
+
let catalogs;
|
|
65
|
+
try {
|
|
66
|
+
catalogs = await loadCatalogs(folder, {
|
|
67
|
+
...limits,
|
|
68
|
+
...(limits.maxBytes === undefined ? {} : { maxBytes: limits.maxBytes - bytes }),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw new I18nError('INVALID_CATALOG', `Cannot load the ${kind} layer ${parent}/${entry.name}/locales`, error);
|
|
73
|
+
}
|
|
74
|
+
const source = SOURCES.get(catalogs);
|
|
75
|
+
bytes += source.bytes;
|
|
76
|
+
files += source.files;
|
|
77
|
+
out[entry.name] = catalogs;
|
|
78
|
+
}
|
|
79
|
+
return Object.freeze(out);
|
|
80
|
+
};
|
|
81
|
+
const layers = Object.freeze({
|
|
82
|
+
apps: await read('apps', 'app'),
|
|
83
|
+
modules: await read('shared/modules', 'module'),
|
|
84
|
+
});
|
|
85
|
+
SOURCES.set(layers, Object.freeze({ bytes, files }));
|
|
86
|
+
return layers;
|
|
87
|
+
}
|
|
88
|
+
/** Load once in an entry: locales/<locale>/<namespace>.json -> namespace.nested.key. */
|
|
89
|
+
export async function loadCatalogs(directory, limits = {}) {
|
|
90
|
+
const maxMessages = limits.maxMessages ?? Number.POSITIVE_INFINITY;
|
|
91
|
+
const maxLocales = limits.maxLocales ?? Number.POSITIVE_INFINITY;
|
|
92
|
+
const maxBytes = limits.maxBytes ?? Number.POSITIVE_INFINITY;
|
|
93
|
+
const maxKeyLength = limits.maxKeyLength ?? Number.POSITIVE_INFINITY;
|
|
94
|
+
const maxDepth = limits.maxDepth ?? 16;
|
|
95
|
+
let files = 0;
|
|
96
|
+
const root = directory instanceof URL ? fileURLToPath(directory) : directory;
|
|
97
|
+
const catalogs = Object.create(null);
|
|
98
|
+
let bytes = 0;
|
|
99
|
+
let messages = 0;
|
|
100
|
+
const flatten = (input, prefix, target, depth) => {
|
|
101
|
+
if (depth > maxDepth)
|
|
102
|
+
throw new I18nError('INVALID_CATALOG', `Catalog nesting exceeds ${maxDepth} levels (maxDepth)`);
|
|
103
|
+
const values = record(input);
|
|
104
|
+
for (const [key, value] of Object.entries(values)) {
|
|
105
|
+
// D-0181: the keys this file overrides on purpose (read by dokebi check, not a message).
|
|
106
|
+
if (key === '$overrides' && depth === 0) {
|
|
107
|
+
if (!Array.isArray(value) ||
|
|
108
|
+
value.length > MAX_OVERRIDES ||
|
|
109
|
+
!value.every((entry) => typeof entry === 'string' && KEY_PATH.test(entry)))
|
|
110
|
+
throw new I18nError('INVALID_CATALOG', '$overrides is a list of key paths inside the namespace (["title", "nav.home"])');
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(key) ||
|
|
114
|
+
['__proto__', 'constructor', 'prototype'].includes(key))
|
|
115
|
+
throw new I18nError('INVALID_CATALOG', 'Catalog keys must be safe path segments');
|
|
116
|
+
const path = `${prefix}.${key}`;
|
|
117
|
+
if (typeof value === 'string' || pluralObject(value)) {
|
|
118
|
+
if (++messages > maxMessages || path.length > maxKeyLength)
|
|
119
|
+
throw new I18nError('INVALID_CATALOG', 'Catalog message count or key length exceeded');
|
|
120
|
+
target[path] = value; // Message syntax is validated by provider setup.
|
|
121
|
+
}
|
|
122
|
+
else
|
|
123
|
+
flatten(value, path, target, depth + 1);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
// The folder or file being read, named in the error: a large tree is otherwise hard to search.
|
|
127
|
+
let current = '';
|
|
128
|
+
try {
|
|
129
|
+
const locales = await readdir(root, { withFileTypes: true });
|
|
130
|
+
for (const locale of locales.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
131
|
+
if (!locale.isDirectory())
|
|
132
|
+
continue;
|
|
133
|
+
current = locale.name;
|
|
134
|
+
const name = canonical(locale.name);
|
|
135
|
+
if (catalogs[name] || Object.keys(catalogs).length >= maxLocales)
|
|
136
|
+
throw new I18nError('INVALID_CATALOG', `Duplicate locale or more than ${maxLocales} locales (maxLocales)`);
|
|
137
|
+
const target = Object.create(null);
|
|
138
|
+
catalogs[name] = target;
|
|
139
|
+
const folder = join(root, locale.name);
|
|
140
|
+
for (const file of (await readdir(folder, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
141
|
+
if (!file.name.endsWith('.json'))
|
|
142
|
+
continue;
|
|
143
|
+
current = `${locale.name}/${file.name}`;
|
|
144
|
+
if (!file.isFile() || !/^[a-zA-Z][a-zA-Z0-9_-]*\.json$/.test(file.name))
|
|
145
|
+
throw new I18nError('INVALID_CATALOG', 'Catalog namespaces must be regular JSON files');
|
|
146
|
+
const path = join(folder, file.name);
|
|
147
|
+
const size = (await stat(path)).size;
|
|
148
|
+
bytes += size;
|
|
149
|
+
files++;
|
|
150
|
+
if (bytes > maxBytes)
|
|
151
|
+
throw new I18nError('INVALID_CATALOG', `Catalog files exceed ${maxBytes} bytes (maxBytes)`);
|
|
152
|
+
flatten(JSON.parse(await readFile(path, 'utf8')), file.name.slice(0, -5), target, 0);
|
|
153
|
+
}
|
|
154
|
+
Object.freeze(target);
|
|
155
|
+
}
|
|
156
|
+
const loaded = Object.freeze(catalogs);
|
|
157
|
+
SOURCES.set(loaded, Object.freeze({ bytes, files }));
|
|
158
|
+
return loaded;
|
|
159
|
+
}
|
|
160
|
+
catch (cause) {
|
|
161
|
+
throw new I18nError('INVALID_CATALOG', current
|
|
162
|
+
? `Cannot load locale namespace files (at ${JSON.stringify(current)})`
|
|
163
|
+
: 'Cannot load locale namespace files', cause);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type PluralMessage = Readonly<Partial<Record<Intl.LDMLPluralRule, string>> & {
|
|
2
|
+
other: string;
|
|
3
|
+
}>;
|
|
4
|
+
export type Message = string | PluralMessage;
|
|
5
|
+
export type Catalogs = Readonly<Record<string, Readonly<Record<string, Message>>>>;
|
|
6
|
+
/** D-0181: the app and module layers (`loadLayers`), above the shared `catalogs`. */
|
|
7
|
+
export interface CatalogLayers {
|
|
8
|
+
readonly apps?: Readonly<Record<string, Catalogs>>;
|
|
9
|
+
readonly modules?: Readonly<Record<string, Catalogs>>;
|
|
10
|
+
}
|
|
11
|
+
export interface I18nEntry {
|
|
12
|
+
readonly catalogs: Catalogs;
|
|
13
|
+
readonly layers?: CatalogLayers;
|
|
14
|
+
readonly numberFormats?: Readonly<Record<string, Intl.NumberFormatOptions>>;
|
|
15
|
+
readonly dateFormats?: Readonly<Record<string, Intl.DateTimeFormatOptions>>;
|
|
16
|
+
}
|
|
17
|
+
export type Parameters = Readonly<Record<string, string | number>>;
|
|
18
|
+
export interface Translator {
|
|
19
|
+
readonly locale: string;
|
|
20
|
+
t(key: string, parameters?: Parameters): string;
|
|
21
|
+
t(key: string, defaultValue: string, parameters?: Parameters): string;
|
|
22
|
+
number(value: number, format?: string): string;
|
|
23
|
+
date(value: Date | number, format?: string): string;
|
|
24
|
+
}
|
|
25
|
+
export interface I18nApi {
|
|
26
|
+
readonly locales: readonly string[];
|
|
27
|
+
readonly defaultLocale: string;
|
|
28
|
+
/**
|
|
29
|
+
* The translator of a locale; with `app`, of that app's scope (its layer, the modules, the
|
|
30
|
+
* shared catalogs; D-0181). An app without a layer, or none, gets the modules and shared ones.
|
|
31
|
+
*/
|
|
32
|
+
forLocale(locale?: string, options?: {
|
|
33
|
+
readonly app?: string;
|
|
34
|
+
}): Translator;
|
|
35
|
+
/** The apps that have a layer of their own (D-0181). */
|
|
36
|
+
readonly apps: readonly string[];
|
|
37
|
+
/** undefined means every configured locale was explicitly excluded. */
|
|
38
|
+
negotiate(acceptLanguage?: string): string | undefined;
|
|
39
|
+
/** The application's time zone now (options.timeZone until setTimeZone; D-0178). */
|
|
40
|
+
readonly timeZone: string;
|
|
41
|
+
/**
|
|
42
|
+
* Changes the application's time zone in this worker: server date formats, the page settings
|
|
43
|
+
* and their version (the browser takes the new zone on its next page). INVALID_FORMAT for a name
|
|
44
|
+
* that is not a time zone. Call it in every worker (runtime-settings onChange).
|
|
45
|
+
*/
|
|
46
|
+
setTimeZone(zone: string): void;
|
|
47
|
+
}
|
package/dist/contract.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { DokebiError } from '@dokebi/core';
|
|
2
|
+
export type I18nErrorCode = 'HTTP_UNAVAILABLE' | 'INVALID_CATALOG' | 'INVALID_LOCALE' | 'INVALID_FORMAT' | 'MISSING_MESSAGE' | 'INVALID_PARAMETER' | 'OUTPUT_LIMIT' | 'INVALID_HEADER' | 'UNKNOWN_NAMESPACE' | 'INVALID_OPTIONS';
|
|
3
|
+
export declare class I18nError extends DokebiError<I18nErrorCode> {
|
|
4
|
+
constructor(code: I18nErrorCode, message: string, cause?: unknown);
|
|
5
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { DokebiError } from '@dokebi/core';
|
|
2
|
+
export class I18nError extends DokebiError {
|
|
3
|
+
constructor(code, message, cause) {
|
|
4
|
+
super(code, message, {
|
|
5
|
+
plugin: 'dokebi-i18n',
|
|
6
|
+
cause,
|
|
7
|
+
fix: code === 'HTTP_UNAVAILABLE'
|
|
8
|
+
? 'Install and register @dokebi/web, or disable options.dokebi-i18n.http.enabled.'
|
|
9
|
+
: code === 'UNKNOWN_NAMESPACE'
|
|
10
|
+
? 'Name a namespace that a catalog has (locales/<locale>/<namespace>.json) in http.pageMessages or pageMessages(request, ...).'
|
|
11
|
+
: code === 'INVALID_OPTIONS'
|
|
12
|
+
? 'Give options.dokebi-i18n.http.pageCache.cookieName a name other than http.cookieName.'
|
|
13
|
+
: 'Check the i18n entry catalogs, supported locales, named formats and message parameters.',
|
|
14
|
+
});
|
|
15
|
+
this.name = 'I18nError';
|
|
16
|
+
}
|
|
17
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Logger } from '@dokebi/core';
|
|
2
|
+
import type { FastifyPluginCallback, FastifyReply, FastifyRequest } from 'fastify';
|
|
3
|
+
import type { I18nApi, Translator } from './contract.js';
|
|
4
|
+
import { type NegotiationLimits } from './negotiation.js';
|
|
5
|
+
export interface I18nHttpRequest {
|
|
6
|
+
readonly i18n: Translator;
|
|
7
|
+
}
|
|
8
|
+
declare module 'fastify' {
|
|
9
|
+
interface FastifyRequest {
|
|
10
|
+
/** Present only when dokebi-i18n HTTP integration is enabled. */
|
|
11
|
+
i18n: Translator;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The locale this answer's URL names (a route parameter such as `/:lang/products/:id`): the
|
|
16
|
+
* request translates in it, the answer says it (`Content-Language`, unless the answer set its
|
|
17
|
+
* own), and the answer does not vary by Accept-Language or Cookie (only by its URL), so a
|
|
18
|
+
* shared cache or CDN can keep it. Call before rendering. `locale` must be a configured locale
|
|
19
|
+
* (case does not matter): anything else is INVALID_LOCALE (answer 404 for it). Needs
|
|
20
|
+
* `http.enabled`; `http.pathLocale` does the same for a first path segment by itself.
|
|
21
|
+
*/
|
|
22
|
+
export declare function useUrlLocale(request: FastifyRequest, reply: FastifyReply, locale: string): Translator;
|
|
23
|
+
/** Application-scoped immutable translators; no global current locale or per-request catalog work. */
|
|
24
|
+
export declare function translationHttp(api: I18nApi, cookieName: string, logger: Logger, limits: {
|
|
25
|
+
readonly maxCookieHeaderBytes: number;
|
|
26
|
+
readonly negotiation: NegotiationLimits;
|
|
27
|
+
/** http.pathLocale: a first path segment that is a configured locale decides. */
|
|
28
|
+
readonly pathLocale?: boolean;
|
|
29
|
+
/** D-0181: the request's app (@dokebi/app); an app with a layer translates in its scope. */
|
|
30
|
+
readonly appOf?: (request: FastifyRequest) => string | undefined;
|
|
31
|
+
}, pageHeader?: string): FastifyPluginCallback;
|