intor 2.2.4 → 2.2.6
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/dist/config/index.cjs +12 -10
- package/dist/config/index.js +12 -10
- package/dist/index.cjs +21 -583
- package/dist/index.d.cts +28 -260
- package/dist/index.d.ts +28 -260
- package/dist/index.js +20 -574
- package/dist/next/index.cjs +255 -265
- package/dist/next/index.d.cts +102 -92
- package/dist/next/index.d.ts +102 -92
- package/dist/next/index.js +254 -263
- package/dist/next/server/index.cjs +13 -13
- package/dist/next/server/index.js +13 -13
- package/dist/react/index.cjs +650 -0
- package/dist/react/index.d.cts +213 -0
- package/dist/react/index.d.ts +213 -0
- package/dist/react/index.js +622 -0
- package/dist/server/index.cjs +698 -0
- package/dist/server/index.d.cts +372 -0
- package/dist/server/index.d.ts +372 -0
- package/dist/server/index.js +682 -0
- package/package.json +21 -11
package/dist/index.js
CHANGED
|
@@ -1,248 +1,8 @@
|
|
|
1
|
-
import path from 'path';
|
|
2
|
-
import { performance as performance$1 } from 'perf_hooks';
|
|
3
|
-
import pLimit from 'p-limit';
|
|
4
|
-
import fs from 'fs/promises';
|
|
5
|
-
import { logry } from 'logry';
|
|
6
1
|
import merge from 'lodash.merge';
|
|
7
|
-
import Keyv from 'keyv';
|
|
8
|
-
import { Translator } from 'intor-translator';
|
|
9
2
|
export { Translator } from 'intor-translator';
|
|
10
3
|
|
|
11
|
-
// src/
|
|
12
|
-
var
|
|
13
|
-
if (!loader) return false;
|
|
14
|
-
const { type, lazyLoad } = loader;
|
|
15
|
-
if (type === "local") return true;
|
|
16
|
-
if (lazyLoad) return false;
|
|
17
|
-
return true;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
// src/modules/config/constants/cache.constants.ts
|
|
21
|
-
var DEFAULT_CACHE_OPTIONS = {
|
|
22
|
-
enabled: process.env.NODE_ENV === "production",
|
|
23
|
-
ttl: 60 * 60 * 1e3
|
|
24
|
-
// 1 hour
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
// src/shared/logger/global-logger-pool.ts
|
|
28
|
-
function getGlobalLoggerPool() {
|
|
29
|
-
if (!globalThis.__INTOR_LOGGER_POOL__) {
|
|
30
|
-
globalThis.__INTOR_LOGGER_POOL__ = /* @__PURE__ */ new Map();
|
|
31
|
-
}
|
|
32
|
-
return globalThis.__INTOR_LOGGER_POOL__;
|
|
33
|
-
}
|
|
34
|
-
function clearLoggerPool() {
|
|
35
|
-
const pool = getGlobalLoggerPool();
|
|
36
|
-
pool.clear();
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// src/shared/logger/get-logger.ts
|
|
40
|
-
var DEFAULT_FORMATTER_CONFIG = {
|
|
41
|
-
node: { meta: { compact: true }, lineBreaksAfter: 1 }
|
|
42
|
-
};
|
|
43
|
-
function getLogger({
|
|
44
|
-
id = "default",
|
|
45
|
-
formatterConfig,
|
|
46
|
-
preset,
|
|
47
|
-
...options
|
|
48
|
-
}) {
|
|
49
|
-
const pool = getGlobalLoggerPool();
|
|
50
|
-
let logger = pool.get(id);
|
|
51
|
-
const useDefault = !formatterConfig && !preset;
|
|
52
|
-
if (!logger) {
|
|
53
|
-
logger = logry({
|
|
54
|
-
id,
|
|
55
|
-
formatterConfig: useDefault ? DEFAULT_FORMATTER_CONFIG : formatterConfig,
|
|
56
|
-
preset,
|
|
57
|
-
...options
|
|
58
|
-
});
|
|
59
|
-
pool.set(id, logger);
|
|
60
|
-
if (pool.size > 1e3) {
|
|
61
|
-
const keys = [...pool.keys()];
|
|
62
|
-
for (const key of keys.slice(0, 200)) pool.delete(key);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return logger;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// src/modules/messages/load-local-messages/read-locale-messages/collect-file-entries/collect-file-entries.ts
|
|
69
|
-
async function collectFileEntries({
|
|
70
|
-
readdir = fs.readdir,
|
|
71
|
-
limit,
|
|
72
|
-
rootDir,
|
|
73
|
-
namespaces,
|
|
74
|
-
extraOptions: { exts = [".json"], loggerOptions } = {}
|
|
75
|
-
}) {
|
|
76
|
-
const baseLogger = getLogger({ ...loggerOptions });
|
|
77
|
-
const logger = baseLogger.child({ scope: "collect-file-entries" });
|
|
78
|
-
const results = [];
|
|
79
|
-
const walk = async (currentDir) => {
|
|
80
|
-
let entries = [];
|
|
81
|
-
try {
|
|
82
|
-
entries = await readdir(currentDir, { withFileTypes: true });
|
|
83
|
-
} catch (error) {
|
|
84
|
-
logger.error(`Error reading directory: ${currentDir}`, { error });
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
const tasks = entries.map(
|
|
88
|
-
(entry) => limit(async () => {
|
|
89
|
-
const fullPath = path.join(currentDir, entry.name);
|
|
90
|
-
if (entry.isDirectory()) {
|
|
91
|
-
await walk(fullPath);
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
if (!exts.some((ext2) => entry.name.endsWith(ext2))) return;
|
|
95
|
-
const relativePath = path.relative(rootDir, fullPath);
|
|
96
|
-
const ext = path.extname(relativePath);
|
|
97
|
-
const withoutExt = relativePath.slice(0, -ext.length);
|
|
98
|
-
const segments = withoutExt.split(path.sep).filter(Boolean);
|
|
99
|
-
const namespace = segments.at(0);
|
|
100
|
-
if (!namespace) return;
|
|
101
|
-
if (namespaces && namespace !== "index") {
|
|
102
|
-
if (!namespaces.includes(namespace)) return;
|
|
103
|
-
}
|
|
104
|
-
results.push({
|
|
105
|
-
namespace,
|
|
106
|
-
fullPath,
|
|
107
|
-
relativePath,
|
|
108
|
-
segments,
|
|
109
|
-
basename: path.basename(entry.name, ext)
|
|
110
|
-
});
|
|
111
|
-
})
|
|
112
|
-
);
|
|
113
|
-
await Promise.all(tasks);
|
|
114
|
-
};
|
|
115
|
-
await walk(rootDir);
|
|
116
|
-
if (logger.core.level === "debug") {
|
|
117
|
-
logger.debug("Local message files collected.", {
|
|
118
|
-
count: results.length
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
logger.trace("Local message files collected.", {
|
|
122
|
-
count: results.length,
|
|
123
|
-
fileEntries: results.map(({ namespace, relativePath }) => ({
|
|
124
|
-
namespace: namespace === "index" ? null : namespace,
|
|
125
|
-
relativePath
|
|
126
|
-
}))
|
|
127
|
-
});
|
|
128
|
-
return results;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// src/modules/messages/shared/utils/is-valid-messages.ts
|
|
132
|
-
function isPlainObject(value) {
|
|
133
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
134
|
-
}
|
|
135
|
-
function isValidMessages(value) {
|
|
136
|
-
if (!isPlainObject(value)) return false;
|
|
137
|
-
const stack = [value];
|
|
138
|
-
while (stack.length > 0) {
|
|
139
|
-
const current = stack.pop();
|
|
140
|
-
for (const v of Object.values(current)) {
|
|
141
|
-
if (typeof v === "string") continue;
|
|
142
|
-
if (isPlainObject(v)) {
|
|
143
|
-
stack.push(v);
|
|
144
|
-
} else {
|
|
145
|
-
return false;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
return true;
|
|
150
|
-
}
|
|
151
|
-
async function jsonReader(filePath, readFile = fs.readFile) {
|
|
152
|
-
const raw = await readFile(filePath, "utf8");
|
|
153
|
-
const parsed = JSON.parse(raw);
|
|
154
|
-
return parsed;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// src/modules/messages/load-local-messages/read-locale-messages/parse-file-entries/utils/nest-object-from-path.ts
|
|
158
|
-
function nestObjectFromPath(path5, value) {
|
|
159
|
-
let obj = value;
|
|
160
|
-
for (let i = path5.length - 1; i >= 0; i--) {
|
|
161
|
-
obj = { [path5[i]]: obj };
|
|
162
|
-
}
|
|
163
|
-
return obj;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// src/modules/messages/load-local-messages/read-locale-messages/parse-file-entries/parse-file-entries.ts
|
|
167
|
-
async function parseFileEntries({
|
|
168
|
-
fileEntries,
|
|
169
|
-
limit,
|
|
170
|
-
extraOptions: { messagesReader, loggerOptions } = {}
|
|
171
|
-
}) {
|
|
172
|
-
const baseLogger = getLogger({ ...loggerOptions });
|
|
173
|
-
const logger = baseLogger.child({ scope: "parse-file-entries" });
|
|
174
|
-
const parsedFileEntries = [];
|
|
175
|
-
const tasks = fileEntries.map(
|
|
176
|
-
({ namespace, segments, basename, fullPath }) => limit(async () => {
|
|
177
|
-
try {
|
|
178
|
-
const segsWithoutNs = segments.slice(1);
|
|
179
|
-
const ext = path.extname(fullPath);
|
|
180
|
-
const json = ext !== ".json" && messagesReader ? await messagesReader(fullPath) : await jsonReader(fullPath);
|
|
181
|
-
if (!isValidMessages(json)) {
|
|
182
|
-
throw new Error(
|
|
183
|
-
"JSON file does not match NamespaceMessages structure"
|
|
184
|
-
);
|
|
185
|
-
}
|
|
186
|
-
const isIndex = basename === "index";
|
|
187
|
-
const keyPath = isIndex ? segsWithoutNs.slice(0, -1) : segsWithoutNs;
|
|
188
|
-
const nested = nestObjectFromPath(keyPath, json);
|
|
189
|
-
parsedFileEntries.push({ namespace, messages: nested });
|
|
190
|
-
logger.trace("Parsed file.", { path: fullPath });
|
|
191
|
-
} catch (error) {
|
|
192
|
-
logger.error("Failed to read or parse file.", {
|
|
193
|
-
path: fullPath,
|
|
194
|
-
error
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
})
|
|
198
|
-
);
|
|
199
|
-
await Promise.all(tasks);
|
|
200
|
-
const result = {};
|
|
201
|
-
for (const { namespace, messages } of parsedFileEntries) {
|
|
202
|
-
if (namespace === "index") {
|
|
203
|
-
merge(result, messages);
|
|
204
|
-
} else {
|
|
205
|
-
result[namespace] = merge(
|
|
206
|
-
result[namespace] ?? {},
|
|
207
|
-
messages
|
|
208
|
-
);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
return result;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// src/modules/messages/load-local-messages/read-locale-messages/read-locale-messages.ts
|
|
215
|
-
var readLocaleMessages = async ({
|
|
216
|
-
limit,
|
|
217
|
-
rootDir = "messages",
|
|
218
|
-
locale,
|
|
219
|
-
namespaces,
|
|
220
|
-
extraOptions: { exts, messagesReader, loggerOptions } = {}
|
|
221
|
-
}) => {
|
|
222
|
-
const fileEntries = await collectFileEntries({
|
|
223
|
-
rootDir: path.resolve(process.cwd(), rootDir, locale),
|
|
224
|
-
namespaces,
|
|
225
|
-
limit,
|
|
226
|
-
extraOptions: { exts, loggerOptions }
|
|
227
|
-
});
|
|
228
|
-
const namespaceMessages = await parseFileEntries({
|
|
229
|
-
fileEntries,
|
|
230
|
-
limit,
|
|
231
|
-
extraOptions: { messagesReader, loggerOptions }
|
|
232
|
-
});
|
|
233
|
-
const localeMessages = { [locale]: namespaceMessages };
|
|
234
|
-
return localeMessages;
|
|
235
|
-
};
|
|
236
|
-
function getGlobalMessagesPool() {
|
|
237
|
-
if (!globalThis.__INTOR_MESSAGES_POOL__) {
|
|
238
|
-
globalThis.__INTOR_MESSAGES_POOL__ = new Keyv();
|
|
239
|
-
}
|
|
240
|
-
return globalThis.__INTOR_MESSAGES_POOL__;
|
|
241
|
-
}
|
|
242
|
-
function clearMessagesPool() {
|
|
243
|
-
const pool = getGlobalMessagesPool();
|
|
244
|
-
pool.clear();
|
|
245
|
-
}
|
|
4
|
+
// src/shared/constants/prefix-placeholder.ts
|
|
5
|
+
var PREFIX_PLACEHOLDER = "{locale}";
|
|
246
6
|
var mergeMessages = (staticMessages = {}, loadedMessages = {}) => {
|
|
247
7
|
if (!loadedMessages) return { ...staticMessages };
|
|
248
8
|
return merge({}, staticMessages, loadedMessages);
|
|
@@ -267,9 +27,6 @@ var normalizeCacheKey = (key, delimiter = CACHE_KEY_DELIMITER) => {
|
|
|
267
27
|
return String(key);
|
|
268
28
|
};
|
|
269
29
|
|
|
270
|
-
// src/shared/constants/prefix-placeholder.ts
|
|
271
|
-
var PREFIX_PLACEHOLDER = "{locale}";
|
|
272
|
-
|
|
273
30
|
// src/shared/utils/resolve-namespaces.ts
|
|
274
31
|
var resolveNamespaces = ({
|
|
275
32
|
config,
|
|
@@ -434,335 +191,24 @@ var standardizePathname = ({
|
|
|
434
191
|
return normalizePathname(standardizedPathname);
|
|
435
192
|
};
|
|
436
193
|
|
|
437
|
-
// src/
|
|
438
|
-
var
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
exts,
|
|
449
|
-
messagesReader
|
|
450
|
-
} = {},
|
|
451
|
-
allowCacheWrite = false
|
|
452
|
-
}) => {
|
|
453
|
-
const baseLogger = getLogger({ ...loggerOptions });
|
|
454
|
-
const logger = baseLogger.child({ scope: "load-local-messages" });
|
|
455
|
-
const start = performance$1.now();
|
|
456
|
-
logger.debug("Loading local messages from directory.", {
|
|
457
|
-
rootDir,
|
|
458
|
-
resolvedRootDir: path.resolve(process.cwd(), rootDir)
|
|
459
|
-
});
|
|
460
|
-
const key = normalizeCacheKey([
|
|
461
|
-
loggerOptions.id,
|
|
462
|
-
"loaderType:local",
|
|
463
|
-
rootDir,
|
|
464
|
-
locale,
|
|
465
|
-
(fallbackLocales || []).toSorted().join(","),
|
|
466
|
-
(namespaces || []).toSorted().join(",")
|
|
467
|
-
]);
|
|
468
|
-
if (cacheOptions.enabled && key) {
|
|
469
|
-
const cached = await pool?.get(key);
|
|
470
|
-
if (cached) {
|
|
471
|
-
logger.debug("Messages cache hit.", { key });
|
|
472
|
-
return cached;
|
|
473
|
-
}
|
|
194
|
+
// src/shared/error/intor-error.ts
|
|
195
|
+
var IntorError = class extends Error {
|
|
196
|
+
code;
|
|
197
|
+
id;
|
|
198
|
+
constructor({ message, code, id }) {
|
|
199
|
+
const fullMessage = id ? `[${id}] ${message}` : message;
|
|
200
|
+
super(fullMessage);
|
|
201
|
+
this.name = "IntorError";
|
|
202
|
+
this.id = id;
|
|
203
|
+
this.code = code;
|
|
204
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
474
205
|
}
|
|
475
|
-
const limit = pLimit(concurrency);
|
|
476
|
-
const candidateLocales = [locale, ...fallbackLocales || []];
|
|
477
|
-
let messages;
|
|
478
|
-
for (const candidateLocale of candidateLocales) {
|
|
479
|
-
try {
|
|
480
|
-
const result = await readLocaleMessages({
|
|
481
|
-
limit,
|
|
482
|
-
rootDir,
|
|
483
|
-
locale: candidateLocale,
|
|
484
|
-
namespaces,
|
|
485
|
-
extraOptions: { loggerOptions, exts, messagesReader }
|
|
486
|
-
});
|
|
487
|
-
if (result && Object.values(result[candidateLocale] || {}).length > 0) {
|
|
488
|
-
messages = result;
|
|
489
|
-
break;
|
|
490
|
-
}
|
|
491
|
-
} catch (error) {
|
|
492
|
-
logger.error("Failed to read locale messages", {
|
|
493
|
-
locale: candidateLocale,
|
|
494
|
-
error
|
|
495
|
-
});
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
if (allowCacheWrite && cacheOptions.enabled && key && messages) {
|
|
499
|
-
await pool?.set(key, messages, cacheOptions.ttl);
|
|
500
|
-
}
|
|
501
|
-
const end = performance$1.now();
|
|
502
|
-
const duration = Math.round(end - start);
|
|
503
|
-
logger.trace("Finished loading local messages.", {
|
|
504
|
-
loadedLocale: messages ? Object.keys(messages)[0] : void 0,
|
|
505
|
-
duration: `${duration} ms`
|
|
506
|
-
});
|
|
507
|
-
return messages;
|
|
508
206
|
};
|
|
207
|
+
var IntorErrorCode = /* @__PURE__ */ ((IntorErrorCode2) => {
|
|
208
|
+
IntorErrorCode2["MISSING_SUPPORTED_LOCALES"] = "INTOR_MISSING_SUPPORTED_LOCALES";
|
|
209
|
+
IntorErrorCode2["MISSING_DEFAULT_LOCALE"] = "INTOR_MISSING_DEFAULT_LOCALE";
|
|
210
|
+
IntorErrorCode2["UNSUPPORTED_DEFAULT_LOCALE"] = "INTOR_UNSUPPORTED_DEFAULT_LOCALE";
|
|
211
|
+
return IntorErrorCode2;
|
|
212
|
+
})(IntorErrorCode || {});
|
|
509
213
|
|
|
510
|
-
|
|
511
|
-
var fetchLocaleMessages = async ({
|
|
512
|
-
remoteUrl,
|
|
513
|
-
remoteHeaders,
|
|
514
|
-
searchParams,
|
|
515
|
-
locale,
|
|
516
|
-
extraOptions: { loggerOptions } = {}
|
|
517
|
-
}) => {
|
|
518
|
-
const baseLogger = getLogger({ ...loggerOptions });
|
|
519
|
-
const logger = baseLogger.child({ scope: "fetch-locale-messages" });
|
|
520
|
-
try {
|
|
521
|
-
const params = new URLSearchParams(searchParams);
|
|
522
|
-
params.append("locale", locale);
|
|
523
|
-
const url = `${remoteUrl}?${params.toString()}`;
|
|
524
|
-
const headers = {
|
|
525
|
-
"Content-Type": "application/json",
|
|
526
|
-
...remoteHeaders
|
|
527
|
-
};
|
|
528
|
-
const response = await fetch(url, {
|
|
529
|
-
method: "GET",
|
|
530
|
-
headers,
|
|
531
|
-
cache: "no-store"
|
|
532
|
-
});
|
|
533
|
-
if (!response.ok) {
|
|
534
|
-
throw new Error(`HTTP error ${response.status} ${response.statusText}`);
|
|
535
|
-
}
|
|
536
|
-
const data = await response.json();
|
|
537
|
-
if (!isValidMessages(data[locale])) {
|
|
538
|
-
throw new Error("JSON file does not match NamespaceMessages structure");
|
|
539
|
-
}
|
|
540
|
-
return data;
|
|
541
|
-
} catch (error) {
|
|
542
|
-
logger.warn("Fetching locale messages failed.", {
|
|
543
|
-
locale,
|
|
544
|
-
remoteUrl,
|
|
545
|
-
searchParams: decodeURIComponent(searchParams.toString()),
|
|
546
|
-
error
|
|
547
|
-
});
|
|
548
|
-
return;
|
|
549
|
-
}
|
|
550
|
-
};
|
|
551
|
-
|
|
552
|
-
// src/modules/messages/load-remote-messages/fetch-locale-messages/utils/build-search-params.ts
|
|
553
|
-
var buildSearchParams = (params) => {
|
|
554
|
-
const searchParams = new URLSearchParams();
|
|
555
|
-
const appendParam = (key, value) => {
|
|
556
|
-
if (value === void 0 || value === null) return;
|
|
557
|
-
if (Array.isArray(value) && value.length === 0) return;
|
|
558
|
-
if (Array.isArray(value)) {
|
|
559
|
-
value.forEach((v) => v && searchParams.append(key, v));
|
|
560
|
-
} else {
|
|
561
|
-
searchParams.append(key, value);
|
|
562
|
-
}
|
|
563
|
-
};
|
|
564
|
-
Object.entries(params).forEach(([key, value]) => {
|
|
565
|
-
appendParam(key, value);
|
|
566
|
-
});
|
|
567
|
-
return searchParams;
|
|
568
|
-
};
|
|
569
|
-
|
|
570
|
-
// src/modules/messages/load-remote-messages/load-remote-messages.ts
|
|
571
|
-
var loadRemoteMessages = async ({
|
|
572
|
-
pool = getGlobalMessagesPool(),
|
|
573
|
-
rootDir,
|
|
574
|
-
remoteUrl,
|
|
575
|
-
remoteHeaders,
|
|
576
|
-
locale,
|
|
577
|
-
fallbackLocales = [],
|
|
578
|
-
namespaces = [],
|
|
579
|
-
extraOptions: {
|
|
580
|
-
cacheOptions = DEFAULT_CACHE_OPTIONS,
|
|
581
|
-
loggerOptions = { id: "default" }
|
|
582
|
-
} = {},
|
|
583
|
-
allowCacheWrite
|
|
584
|
-
}) => {
|
|
585
|
-
const baseLogger = getLogger({ ...loggerOptions });
|
|
586
|
-
const logger = baseLogger.child({ scope: "load-remote-messages" });
|
|
587
|
-
const start = performance.now();
|
|
588
|
-
logger.debug("Loading remote messages from api.", { remoteUrl });
|
|
589
|
-
const key = normalizeCacheKey([
|
|
590
|
-
loggerOptions.id,
|
|
591
|
-
"loaderType:remote",
|
|
592
|
-
rootDir,
|
|
593
|
-
locale,
|
|
594
|
-
(fallbackLocales ?? []).toSorted().join(","),
|
|
595
|
-
(namespaces ?? []).toSorted().join(",")
|
|
596
|
-
]);
|
|
597
|
-
if (cacheOptions.enabled && key) {
|
|
598
|
-
const cached = await pool?.get(key);
|
|
599
|
-
if (cached) {
|
|
600
|
-
logger.debug("Messages cache hit.", { key });
|
|
601
|
-
return cached;
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
const searchParams = buildSearchParams({ rootDir, namespaces });
|
|
605
|
-
const candidateLocales = [locale, ...fallbackLocales || []];
|
|
606
|
-
let messages;
|
|
607
|
-
for (const candidateLocale of candidateLocales) {
|
|
608
|
-
try {
|
|
609
|
-
const result = await fetchLocaleMessages({
|
|
610
|
-
remoteUrl,
|
|
611
|
-
remoteHeaders,
|
|
612
|
-
searchParams,
|
|
613
|
-
locale: candidateLocale,
|
|
614
|
-
extraOptions: { loggerOptions }
|
|
615
|
-
});
|
|
616
|
-
if (result && Object.values(result[candidateLocale] || {}).length > 0) {
|
|
617
|
-
messages = result;
|
|
618
|
-
break;
|
|
619
|
-
}
|
|
620
|
-
} catch (error) {
|
|
621
|
-
logger.error("Failed to fetch locale messages.", {
|
|
622
|
-
locale: candidateLocale,
|
|
623
|
-
error
|
|
624
|
-
});
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
if (allowCacheWrite && cacheOptions.enabled && key && messages) {
|
|
628
|
-
await pool?.set(key, messages, cacheOptions.ttl);
|
|
629
|
-
}
|
|
630
|
-
const end = performance.now();
|
|
631
|
-
const duration = Math.round(end - start);
|
|
632
|
-
logger.trace("Finished loading remote messages.", {
|
|
633
|
-
loadedLocale: messages ? Object.keys(messages)[0] : void 0,
|
|
634
|
-
duration: `${duration} ms`
|
|
635
|
-
});
|
|
636
|
-
return messages;
|
|
637
|
-
};
|
|
638
|
-
|
|
639
|
-
// src/modules/messages/load-messages.ts
|
|
640
|
-
var loadMessages = async ({
|
|
641
|
-
config,
|
|
642
|
-
locale,
|
|
643
|
-
pathname = "",
|
|
644
|
-
extraOptions: { exts, messagesReader } = {},
|
|
645
|
-
allowCacheWrite = false
|
|
646
|
-
}) => {
|
|
647
|
-
const baseLogger = getLogger({ id: config.id, ...config.logger });
|
|
648
|
-
const logger = baseLogger.child({ scope: "load-messages" });
|
|
649
|
-
if (!config.loader) {
|
|
650
|
-
logger.warn(
|
|
651
|
-
"No loader options have been configured in the current config."
|
|
652
|
-
);
|
|
653
|
-
return;
|
|
654
|
-
}
|
|
655
|
-
const { type, concurrency, rootDir } = config.loader;
|
|
656
|
-
const fallbackLocales = config.fallbackLocales[locale] || [];
|
|
657
|
-
const namespaces = resolveNamespaces({ config, pathname });
|
|
658
|
-
if (logger.core.level === "debug") {
|
|
659
|
-
logger.debug("Starting to load messages.", { locale });
|
|
660
|
-
}
|
|
661
|
-
logger.trace("Starting to load messages with runtime context.", {
|
|
662
|
-
loaderType: type,
|
|
663
|
-
locale,
|
|
664
|
-
fallbackLocales,
|
|
665
|
-
namespaces: namespaces && namespaces.length > 0 ? [...namespaces] : "[ALL]",
|
|
666
|
-
cache: config.cache,
|
|
667
|
-
concurrency: concurrency ?? 10
|
|
668
|
-
});
|
|
669
|
-
let loadedMessages;
|
|
670
|
-
if (type === "local") {
|
|
671
|
-
loadedMessages = await loadLocalMessages({
|
|
672
|
-
rootDir,
|
|
673
|
-
locale,
|
|
674
|
-
fallbackLocales,
|
|
675
|
-
namespaces,
|
|
676
|
-
extraOptions: {
|
|
677
|
-
concurrency,
|
|
678
|
-
cacheOptions: config.cache,
|
|
679
|
-
loggerOptions: { id: config.id, ...config.logger },
|
|
680
|
-
exts,
|
|
681
|
-
messagesReader
|
|
682
|
-
},
|
|
683
|
-
allowCacheWrite
|
|
684
|
-
});
|
|
685
|
-
} else if (type === "remote") {
|
|
686
|
-
loadedMessages = await loadRemoteMessages({
|
|
687
|
-
rootDir,
|
|
688
|
-
remoteUrl: config.loader.remoteUrl,
|
|
689
|
-
remoteHeaders: config.loader.remoteHeaders,
|
|
690
|
-
locale,
|
|
691
|
-
fallbackLocales,
|
|
692
|
-
namespaces,
|
|
693
|
-
extraOptions: {
|
|
694
|
-
cacheOptions: config.cache,
|
|
695
|
-
loggerOptions: { id: config.id, ...config.logger }
|
|
696
|
-
}
|
|
697
|
-
});
|
|
698
|
-
}
|
|
699
|
-
if (!loadedMessages || Object.keys(loadedMessages).length === 0) {
|
|
700
|
-
logger.warn("No messages found.", { locale, namespaces });
|
|
701
|
-
}
|
|
702
|
-
return loadedMessages;
|
|
703
|
-
};
|
|
704
|
-
|
|
705
|
-
// src/modules/intor/intor.ts
|
|
706
|
-
var intor = async (config, i18nContext, loadMessagesOptions = {}) => {
|
|
707
|
-
const baseLogger = getLogger({ id: config.id, ...config.logger });
|
|
708
|
-
const logger = baseLogger.child({ scope: "intor" });
|
|
709
|
-
logger.info("Start Intor initialization.");
|
|
710
|
-
const { messages, loader } = config;
|
|
711
|
-
const isI18nContextFunction = typeof i18nContext === "function";
|
|
712
|
-
const context = isI18nContextFunction ? await i18nContext(config) : {
|
|
713
|
-
locale: i18nContext?.locale || config.defaultLocale,
|
|
714
|
-
pathname: i18nContext?.pathname || ""
|
|
715
|
-
};
|
|
716
|
-
const { locale, pathname } = context;
|
|
717
|
-
const source = isI18nContextFunction ? i18nContext.name : "static fallback";
|
|
718
|
-
logger.debug(`I18n context resolved via ${source}.`, context);
|
|
719
|
-
let loadedMessages;
|
|
720
|
-
if (shouldLoadMessages(loader)) {
|
|
721
|
-
loadedMessages = await loadMessages({
|
|
722
|
-
config,
|
|
723
|
-
locale,
|
|
724
|
-
pathname,
|
|
725
|
-
extraOptions: {
|
|
726
|
-
exts: loadMessagesOptions.exts,
|
|
727
|
-
messagesReader: loadMessagesOptions.messagesReader
|
|
728
|
-
},
|
|
729
|
-
allowCacheWrite: true
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
|
-
const mergedMessages = mergeMessages(messages, loadedMessages);
|
|
733
|
-
logger.info("Messages successfully initialized.", {
|
|
734
|
-
static: { enabled: !!messages },
|
|
735
|
-
loaded: {
|
|
736
|
-
enabled: !!loadedMessages,
|
|
737
|
-
...loader ? { loaderType: loader.type, lazyLoad: !!loader.lazyLoad } : null
|
|
738
|
-
},
|
|
739
|
-
merged: mergedMessages
|
|
740
|
-
});
|
|
741
|
-
return {
|
|
742
|
-
config,
|
|
743
|
-
initialLocale: locale,
|
|
744
|
-
pathname,
|
|
745
|
-
messages: mergedMessages
|
|
746
|
-
};
|
|
747
|
-
};
|
|
748
|
-
async function getTranslator(opts) {
|
|
749
|
-
const { config, locale, pathname = "", preKey, handlers } = opts;
|
|
750
|
-
const messages = await loadMessages({ config, locale, pathname });
|
|
751
|
-
const translator = new Translator({
|
|
752
|
-
locale,
|
|
753
|
-
messages,
|
|
754
|
-
fallbackLocales: config.fallbackLocales,
|
|
755
|
-
loadingMessage: config.translator?.loadingMessage,
|
|
756
|
-
placeholder: config.translator?.placeholder,
|
|
757
|
-
handlers
|
|
758
|
-
});
|
|
759
|
-
const props = { messages, locale };
|
|
760
|
-
const scoped = translator.scoped(preKey);
|
|
761
|
-
return {
|
|
762
|
-
...props,
|
|
763
|
-
hasKey: preKey ? scoped.hasKey : translator.hasKey,
|
|
764
|
-
t: preKey ? scoped.t : translator.t
|
|
765
|
-
};
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
export { PREFIX_PLACEHOLDER, clearLoggerPool, clearMessagesPool, extractPathname, getTranslator, intor, loadLocalMessages, loadMessages, loadRemoteMessages, mergeMessages, normalizeCacheKey, normalizeLocale, normalizePathname, resolveNamespaces, resolvePreferredLocale, standardizePathname };
|
|
214
|
+
export { IntorError, IntorErrorCode, PREFIX_PLACEHOLDER, extractPathname, mergeMessages, normalizeCacheKey, normalizeLocale, normalizePathname, resolveNamespaces, resolvePreferredLocale, standardizePathname };
|