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.
@@ -0,0 +1,682 @@
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
+ import merge from 'lodash.merge';
7
+ import Keyv from 'keyv';
8
+ import { Translator } from 'intor-translator';
9
+
10
+ // src/server/intor/utils/should-load-messages.ts
11
+ var shouldLoadMessages = (loader) => {
12
+ if (!loader) return false;
13
+ const { type, lazyLoad } = loader;
14
+ if (type === "local") return true;
15
+ if (lazyLoad) return false;
16
+ return true;
17
+ };
18
+
19
+ // src/config/constants/cache.constants.ts
20
+ var DEFAULT_CACHE_OPTIONS = {
21
+ enabled: process.env.NODE_ENV === "production",
22
+ ttl: 60 * 60 * 1e3
23
+ // 1 hour
24
+ };
25
+
26
+ // src/server/shared/logger/global-logger-pool.ts
27
+ function getGlobalLoggerPool() {
28
+ if (!globalThis.__INTOR_LOGGER_POOL__) {
29
+ globalThis.__INTOR_LOGGER_POOL__ = /* @__PURE__ */ new Map();
30
+ }
31
+ return globalThis.__INTOR_LOGGER_POOL__;
32
+ }
33
+ function clearLoggerPool() {
34
+ const pool = getGlobalLoggerPool();
35
+ pool.clear();
36
+ }
37
+
38
+ // src/server/shared/logger/get-logger.ts
39
+ var DEFAULT_FORMATTER_CONFIG = {
40
+ node: { meta: { compact: true }, lineBreaksAfter: 1 }
41
+ };
42
+ function getLogger({
43
+ id = "default",
44
+ formatterConfig,
45
+ preset,
46
+ ...options
47
+ }) {
48
+ const pool = getGlobalLoggerPool();
49
+ let logger = pool.get(id);
50
+ const useDefault = !formatterConfig && !preset;
51
+ if (!logger) {
52
+ logger = logry({
53
+ id,
54
+ formatterConfig: useDefault ? DEFAULT_FORMATTER_CONFIG : formatterConfig,
55
+ preset,
56
+ ...options
57
+ });
58
+ pool.set(id, logger);
59
+ if (pool.size > 1e3) {
60
+ const keys = [...pool.keys()];
61
+ for (const key of keys.slice(0, 200)) pool.delete(key);
62
+ }
63
+ }
64
+ return logger;
65
+ }
66
+
67
+ // src/server/messages/load-local-messages/read-locale-messages/collect-file-entries/collect-file-entries.ts
68
+ async function collectFileEntries({
69
+ readdir = fs.readdir,
70
+ limit,
71
+ rootDir,
72
+ namespaces,
73
+ extraOptions: { exts = [".json"], loggerOptions } = {}
74
+ }) {
75
+ const baseLogger = getLogger({ ...loggerOptions });
76
+ const logger = baseLogger.child({ scope: "collect-file-entries" });
77
+ const results = [];
78
+ const walk = async (currentDir) => {
79
+ let entries = [];
80
+ try {
81
+ entries = await readdir(currentDir, { withFileTypes: true });
82
+ } catch (error) {
83
+ logger.error(`Error reading directory: ${currentDir}`, { error });
84
+ return;
85
+ }
86
+ const tasks = entries.map(
87
+ (entry) => limit(async () => {
88
+ const fullPath = path.join(currentDir, entry.name);
89
+ if (entry.isDirectory()) {
90
+ await walk(fullPath);
91
+ return;
92
+ }
93
+ if (!exts.some((ext2) => entry.name.endsWith(ext2))) return;
94
+ const relativePath = path.relative(rootDir, fullPath);
95
+ const ext = path.extname(relativePath);
96
+ const withoutExt = relativePath.slice(0, -ext.length);
97
+ const segments = withoutExt.split(path.sep).filter(Boolean);
98
+ const namespace = segments.at(0);
99
+ if (!namespace) return;
100
+ if (namespaces && namespace !== "index") {
101
+ if (!namespaces.includes(namespace)) return;
102
+ }
103
+ results.push({
104
+ namespace,
105
+ fullPath,
106
+ relativePath,
107
+ segments,
108
+ basename: path.basename(entry.name, ext)
109
+ });
110
+ })
111
+ );
112
+ await Promise.all(tasks);
113
+ };
114
+ await walk(rootDir);
115
+ if (logger.core.level === "debug") {
116
+ logger.debug("Local message files collected.", {
117
+ count: results.length
118
+ });
119
+ }
120
+ logger.trace("Local message files collected.", {
121
+ count: results.length,
122
+ fileEntries: results.map(({ namespace, relativePath }) => ({
123
+ namespace: namespace === "index" ? null : namespace,
124
+ relativePath
125
+ }))
126
+ });
127
+ return results;
128
+ }
129
+
130
+ // src/server/messages/shared/utils/is-valid-messages.ts
131
+ function isPlainObject(value) {
132
+ return typeof value === "object" && value !== null && !Array.isArray(value);
133
+ }
134
+ function isValidMessages(value) {
135
+ if (!isPlainObject(value)) return false;
136
+ const stack = [value];
137
+ while (stack.length > 0) {
138
+ const current = stack.pop();
139
+ for (const v of Object.values(current)) {
140
+ if (typeof v === "string") continue;
141
+ if (isPlainObject(v)) {
142
+ stack.push(v);
143
+ } else {
144
+ return false;
145
+ }
146
+ }
147
+ }
148
+ return true;
149
+ }
150
+ async function jsonReader(filePath, readFile = fs.readFile) {
151
+ const raw = await readFile(filePath, "utf8");
152
+ const parsed = JSON.parse(raw);
153
+ return parsed;
154
+ }
155
+
156
+ // src/server/messages/load-local-messages/read-locale-messages/parse-file-entries/utils/nest-object-from-path.ts
157
+ function nestObjectFromPath(path5, value) {
158
+ let obj = value;
159
+ for (let i = path5.length - 1; i >= 0; i--) {
160
+ obj = { [path5[i]]: obj };
161
+ }
162
+ return obj;
163
+ }
164
+
165
+ // src/server/messages/load-local-messages/read-locale-messages/parse-file-entries/parse-file-entries.ts
166
+ async function parseFileEntries({
167
+ fileEntries,
168
+ limit,
169
+ extraOptions: { messagesReader, loggerOptions } = {}
170
+ }) {
171
+ const baseLogger = getLogger({ ...loggerOptions });
172
+ const logger = baseLogger.child({ scope: "parse-file-entries" });
173
+ const parsedFileEntries = [];
174
+ const tasks = fileEntries.map(
175
+ ({ namespace, segments, basename, fullPath }) => limit(async () => {
176
+ try {
177
+ const segsWithoutNs = segments.slice(1);
178
+ const ext = path.extname(fullPath);
179
+ const json = ext !== ".json" && messagesReader ? await messagesReader(fullPath) : await jsonReader(fullPath);
180
+ if (!isValidMessages(json)) {
181
+ throw new Error(
182
+ "JSON file does not match NamespaceMessages structure"
183
+ );
184
+ }
185
+ const isIndex = basename === "index";
186
+ const keyPath = isIndex ? segsWithoutNs.slice(0, -1) : segsWithoutNs;
187
+ const nested = nestObjectFromPath(keyPath, json);
188
+ parsedFileEntries.push({ namespace, messages: nested });
189
+ logger.trace("Parsed file.", { path: fullPath });
190
+ } catch (error) {
191
+ logger.error("Failed to read or parse file.", {
192
+ path: fullPath,
193
+ error
194
+ });
195
+ }
196
+ })
197
+ );
198
+ await Promise.all(tasks);
199
+ const result = {};
200
+ for (const { namespace, messages } of parsedFileEntries) {
201
+ if (namespace === "index") {
202
+ merge(result, messages);
203
+ } else {
204
+ result[namespace] = merge(
205
+ result[namespace] ?? {},
206
+ messages
207
+ );
208
+ }
209
+ }
210
+ return result;
211
+ }
212
+
213
+ // src/server/messages/load-local-messages/read-locale-messages/read-locale-messages.ts
214
+ var readLocaleMessages = async ({
215
+ limit,
216
+ rootDir = "messages",
217
+ locale,
218
+ namespaces,
219
+ extraOptions: { exts, messagesReader, loggerOptions } = {}
220
+ }) => {
221
+ const fileEntries = await collectFileEntries({
222
+ rootDir: path.resolve(process.cwd(), rootDir, locale),
223
+ namespaces,
224
+ limit,
225
+ extraOptions: { exts, loggerOptions }
226
+ });
227
+ const namespaceMessages = await parseFileEntries({
228
+ fileEntries,
229
+ limit,
230
+ extraOptions: { messagesReader, loggerOptions }
231
+ });
232
+ const localeMessages = { [locale]: namespaceMessages };
233
+ return localeMessages;
234
+ };
235
+ function getGlobalMessagesPool() {
236
+ if (!globalThis.__INTOR_MESSAGES_POOL__) {
237
+ globalThis.__INTOR_MESSAGES_POOL__ = new Keyv();
238
+ }
239
+ return globalThis.__INTOR_MESSAGES_POOL__;
240
+ }
241
+ function clearMessagesPool() {
242
+ const pool = getGlobalMessagesPool();
243
+ pool.clear();
244
+ }
245
+ var mergeMessages = (staticMessages = {}, loadedMessages = {}) => {
246
+ if (!loadedMessages) return { ...staticMessages };
247
+ return merge({}, staticMessages, loadedMessages);
248
+ };
249
+
250
+ // src/shared/utils/normalize-cache-key.ts
251
+ var CACHE_KEY_DELIMITER = "|";
252
+ var sanitize = (k) => k.replaceAll(/[\u200B-\u200D\uFEFF]/g, "").replaceAll(/[\r\n]/g, "").trim();
253
+ var normalizeCacheKey = (key, delimiter = CACHE_KEY_DELIMITER) => {
254
+ if (key === null || key === void 0) return null;
255
+ if (Array.isArray(key)) {
256
+ if (key.length === 0) return null;
257
+ const normalized = key.map((k) => {
258
+ if (k === null) return "__null";
259
+ if (k === void 0) return "__undefined";
260
+ if (typeof k === "boolean") return k ? "__true" : "__false";
261
+ return sanitize(String(k));
262
+ });
263
+ return normalized.join(delimiter);
264
+ }
265
+ if (typeof key === "boolean") return key ? "__true" : "__false";
266
+ return String(key);
267
+ };
268
+
269
+ // src/shared/constants/prefix-placeholder.ts
270
+ var PREFIX_PLACEHOLDER = "{locale}";
271
+
272
+ // src/shared/utils/resolve-namespaces.ts
273
+ var resolveNamespaces = ({
274
+ config,
275
+ pathname
276
+ }) => {
277
+ const { loader } = config;
278
+ const { routeNamespaces = {}, namespaces } = loader || {};
279
+ if (Object.keys(routeNamespaces).length === 0 && !namespaces)
280
+ return void 0;
281
+ const standardizedPathname = standardizePathname({ config, pathname });
282
+ const placeholderRemovedPathname = standardizedPathname.replace(
283
+ `/${PREFIX_PLACEHOLDER}`,
284
+ ""
285
+ );
286
+ const collected = [
287
+ ...routeNamespaces.default || [],
288
+ // default
289
+ ...namespaces || [],
290
+ // default
291
+ ...routeNamespaces[standardizedPathname] || [],
292
+ // exact match
293
+ ...routeNamespaces[placeholderRemovedPathname] || []
294
+ // exact match
295
+ ];
296
+ const prefixPatterns = Object.keys(routeNamespaces).filter(
297
+ (pattern) => pattern.endsWith("/*")
298
+ );
299
+ for (const pattern of prefixPatterns) {
300
+ const basePath = pattern.replace(/\/\*$/, "");
301
+ if (standardizedPathname.startsWith(basePath) || placeholderRemovedPathname.startsWith(basePath)) {
302
+ collected.push(...routeNamespaces[pattern] || []);
303
+ }
304
+ }
305
+ return [...new Set(collected)];
306
+ };
307
+
308
+ // src/shared/utils/pathname/normalize-pathname.ts
309
+ var normalizePathname = (rawPathname, options = {}) => {
310
+ const length = rawPathname.length;
311
+ let start = 0;
312
+ let end = length - 1;
313
+ while (start <= end && (rawPathname.codePointAt(start) ?? 0) <= 32) start++;
314
+ while (end >= start && (rawPathname.codePointAt(end) ?? 0) <= 32) end--;
315
+ if (start > end) return "/";
316
+ let result = "";
317
+ let hasSlash = false;
318
+ for (let i = start; i <= end; i++) {
319
+ const char = rawPathname[i];
320
+ if (char === "/") {
321
+ if (!hasSlash) {
322
+ hasSlash = true;
323
+ }
324
+ } else {
325
+ result += hasSlash || result === "" ? "/" + char : char;
326
+ hasSlash = false;
327
+ }
328
+ }
329
+ if (options.removeLeadingSlash && result.startsWith("/")) {
330
+ result = result.slice(1);
331
+ }
332
+ return result || "/";
333
+ };
334
+
335
+ // src/shared/utils/pathname/standardize-pathname.ts
336
+ var standardizePathname = ({
337
+ config,
338
+ pathname
339
+ }) => {
340
+ const { routing } = config;
341
+ const { basePath } = routing;
342
+ const parts = [
343
+ normalizePathname(basePath),
344
+ PREFIX_PLACEHOLDER,
345
+ normalizePathname(pathname)
346
+ ];
347
+ const standardizedPathname = parts.join("/").replaceAll(/\/{2,}/g, "/");
348
+ return normalizePathname(standardizedPathname);
349
+ };
350
+
351
+ // src/server/messages/load-local-messages/load-local-messages.ts
352
+ var loadLocalMessages = async ({
353
+ pool = getGlobalMessagesPool(),
354
+ rootDir = "messages",
355
+ locale,
356
+ fallbackLocales,
357
+ namespaces,
358
+ extraOptions: {
359
+ concurrency = 10,
360
+ cacheOptions = DEFAULT_CACHE_OPTIONS,
361
+ loggerOptions = { id: "default" },
362
+ exts,
363
+ messagesReader
364
+ } = {},
365
+ allowCacheWrite = false
366
+ }) => {
367
+ const baseLogger = getLogger({ ...loggerOptions });
368
+ const logger = baseLogger.child({ scope: "load-local-messages" });
369
+ const start = performance$1.now();
370
+ logger.debug("Loading local messages from directory.", {
371
+ rootDir,
372
+ resolvedRootDir: path.resolve(process.cwd(), rootDir)
373
+ });
374
+ const key = normalizeCacheKey([
375
+ loggerOptions.id,
376
+ "loaderType:local",
377
+ rootDir,
378
+ locale,
379
+ (fallbackLocales || []).toSorted().join(","),
380
+ (namespaces || []).toSorted().join(",")
381
+ ]);
382
+ if (cacheOptions.enabled && key) {
383
+ const cached = await pool?.get(key);
384
+ if (cached) {
385
+ logger.debug("Messages cache hit.", { key });
386
+ return cached;
387
+ }
388
+ }
389
+ const limit = pLimit(concurrency);
390
+ const candidateLocales = [locale, ...fallbackLocales || []];
391
+ let messages;
392
+ for (const candidateLocale of candidateLocales) {
393
+ try {
394
+ const result = await readLocaleMessages({
395
+ limit,
396
+ rootDir,
397
+ locale: candidateLocale,
398
+ namespaces,
399
+ extraOptions: { loggerOptions, exts, messagesReader }
400
+ });
401
+ if (result && Object.values(result[candidateLocale] || {}).length > 0) {
402
+ messages = result;
403
+ break;
404
+ }
405
+ } catch (error) {
406
+ logger.error("Failed to read locale messages", {
407
+ locale: candidateLocale,
408
+ error
409
+ });
410
+ }
411
+ }
412
+ if (allowCacheWrite && cacheOptions.enabled && key && messages) {
413
+ await pool?.set(key, messages, cacheOptions.ttl);
414
+ }
415
+ const end = performance$1.now();
416
+ const duration = Math.round(end - start);
417
+ logger.trace("Finished loading local messages.", {
418
+ loadedLocale: messages ? Object.keys(messages)[0] : void 0,
419
+ duration: `${duration} ms`
420
+ });
421
+ return messages;
422
+ };
423
+
424
+ // src/server/messages/load-remote-messages/fetch-locale-messages/fetch-locale-messages.ts
425
+ var fetchLocaleMessages = async ({
426
+ remoteUrl,
427
+ remoteHeaders,
428
+ searchParams,
429
+ locale,
430
+ extraOptions: { loggerOptions } = {}
431
+ }) => {
432
+ const baseLogger = getLogger({ ...loggerOptions });
433
+ const logger = baseLogger.child({ scope: "fetch-locale-messages" });
434
+ try {
435
+ const params = new URLSearchParams(searchParams);
436
+ params.append("locale", locale);
437
+ const url = `${remoteUrl}?${params.toString()}`;
438
+ const headers = {
439
+ "Content-Type": "application/json",
440
+ ...remoteHeaders
441
+ };
442
+ const response = await fetch(url, {
443
+ method: "GET",
444
+ headers,
445
+ cache: "no-store"
446
+ });
447
+ if (!response.ok) {
448
+ throw new Error(`HTTP error ${response.status} ${response.statusText}`);
449
+ }
450
+ const data = await response.json();
451
+ if (!isValidMessages(data[locale])) {
452
+ throw new Error("JSON file does not match NamespaceMessages structure");
453
+ }
454
+ return data;
455
+ } catch (error) {
456
+ logger.warn("Fetching locale messages failed.", {
457
+ locale,
458
+ remoteUrl,
459
+ searchParams: decodeURIComponent(searchParams.toString()),
460
+ error
461
+ });
462
+ return;
463
+ }
464
+ };
465
+
466
+ // src/server/messages/load-remote-messages/fetch-locale-messages/utils/build-search-params.ts
467
+ var buildSearchParams = (params) => {
468
+ const searchParams = new URLSearchParams();
469
+ const appendParam = (key, value) => {
470
+ if (value === void 0 || value === null) return;
471
+ if (Array.isArray(value) && value.length === 0) return;
472
+ if (Array.isArray(value)) {
473
+ value.forEach((v) => v && searchParams.append(key, v));
474
+ } else {
475
+ searchParams.append(key, value);
476
+ }
477
+ };
478
+ Object.entries(params).forEach(([key, value]) => {
479
+ appendParam(key, value);
480
+ });
481
+ return searchParams;
482
+ };
483
+
484
+ // src/server/messages/load-remote-messages/load-remote-messages.ts
485
+ var loadRemoteMessages = async ({
486
+ pool = getGlobalMessagesPool(),
487
+ rootDir,
488
+ remoteUrl,
489
+ remoteHeaders,
490
+ locale,
491
+ fallbackLocales = [],
492
+ namespaces = [],
493
+ extraOptions: {
494
+ cacheOptions = DEFAULT_CACHE_OPTIONS,
495
+ loggerOptions = { id: "default" }
496
+ } = {},
497
+ allowCacheWrite
498
+ }) => {
499
+ const baseLogger = getLogger({ ...loggerOptions });
500
+ const logger = baseLogger.child({ scope: "load-remote-messages" });
501
+ const start = performance.now();
502
+ logger.debug("Loading remote messages from api.", { remoteUrl });
503
+ const key = normalizeCacheKey([
504
+ loggerOptions.id,
505
+ "loaderType:remote",
506
+ rootDir,
507
+ locale,
508
+ (fallbackLocales ?? []).toSorted().join(","),
509
+ (namespaces ?? []).toSorted().join(",")
510
+ ]);
511
+ if (cacheOptions.enabled && key) {
512
+ const cached = await pool?.get(key);
513
+ if (cached) {
514
+ logger.debug("Messages cache hit.", { key });
515
+ return cached;
516
+ }
517
+ }
518
+ const searchParams = buildSearchParams({ rootDir, namespaces });
519
+ const candidateLocales = [locale, ...fallbackLocales || []];
520
+ let messages;
521
+ for (const candidateLocale of candidateLocales) {
522
+ try {
523
+ const result = await fetchLocaleMessages({
524
+ remoteUrl,
525
+ remoteHeaders,
526
+ searchParams,
527
+ locale: candidateLocale,
528
+ extraOptions: { loggerOptions }
529
+ });
530
+ if (result && Object.values(result[candidateLocale] || {}).length > 0) {
531
+ messages = result;
532
+ break;
533
+ }
534
+ } catch (error) {
535
+ logger.error("Failed to fetch locale messages.", {
536
+ locale: candidateLocale,
537
+ error
538
+ });
539
+ }
540
+ }
541
+ if (allowCacheWrite && cacheOptions.enabled && key && messages) {
542
+ await pool?.set(key, messages, cacheOptions.ttl);
543
+ }
544
+ const end = performance.now();
545
+ const duration = Math.round(end - start);
546
+ logger.trace("Finished loading remote messages.", {
547
+ loadedLocale: messages ? Object.keys(messages)[0] : void 0,
548
+ duration: `${duration} ms`
549
+ });
550
+ return messages;
551
+ };
552
+
553
+ // src/server/messages/load-messages.ts
554
+ var loadMessages = async ({
555
+ config,
556
+ locale,
557
+ pathname = "",
558
+ extraOptions: { exts, messagesReader } = {},
559
+ allowCacheWrite = false
560
+ }) => {
561
+ const baseLogger = getLogger({ id: config.id, ...config.logger });
562
+ const logger = baseLogger.child({ scope: "load-messages" });
563
+ if (!config.loader) {
564
+ logger.warn(
565
+ "No loader options have been configured in the current config."
566
+ );
567
+ return;
568
+ }
569
+ const { type, concurrency, rootDir } = config.loader;
570
+ const fallbackLocales = config.fallbackLocales[locale] || [];
571
+ const namespaces = resolveNamespaces({ config, pathname });
572
+ if (logger.core.level === "debug") {
573
+ logger.debug("Starting to load messages.", { locale });
574
+ }
575
+ logger.trace("Starting to load messages with runtime context.", {
576
+ loaderType: type,
577
+ locale,
578
+ fallbackLocales,
579
+ namespaces: namespaces && namespaces.length > 0 ? [...namespaces] : "[ALL]",
580
+ cache: config.cache,
581
+ concurrency: concurrency ?? 10
582
+ });
583
+ let loadedMessages;
584
+ if (type === "local") {
585
+ loadedMessages = await loadLocalMessages({
586
+ rootDir,
587
+ locale,
588
+ fallbackLocales,
589
+ namespaces,
590
+ extraOptions: {
591
+ concurrency,
592
+ cacheOptions: config.cache,
593
+ loggerOptions: { id: config.id, ...config.logger },
594
+ exts,
595
+ messagesReader
596
+ },
597
+ allowCacheWrite
598
+ });
599
+ } else if (type === "remote") {
600
+ loadedMessages = await loadRemoteMessages({
601
+ rootDir,
602
+ remoteUrl: config.loader.remoteUrl,
603
+ remoteHeaders: config.loader.remoteHeaders,
604
+ locale,
605
+ fallbackLocales,
606
+ namespaces,
607
+ extraOptions: {
608
+ cacheOptions: config.cache,
609
+ loggerOptions: { id: config.id, ...config.logger }
610
+ }
611
+ });
612
+ }
613
+ if (!loadedMessages || Object.keys(loadedMessages).length === 0) {
614
+ logger.warn("No messages found.", { locale, namespaces });
615
+ }
616
+ return loadedMessages;
617
+ };
618
+
619
+ // src/server/intor/intor.ts
620
+ var intor = async (config, i18nContext, loadMessagesOptions = {}) => {
621
+ const baseLogger = getLogger({ id: config.id, ...config.logger });
622
+ const logger = baseLogger.child({ scope: "intor" });
623
+ logger.info("Start Intor initialization.");
624
+ const { messages, loader } = config;
625
+ const isI18nContextFunction = typeof i18nContext === "function";
626
+ const context = isI18nContextFunction ? await i18nContext(config) : {
627
+ locale: i18nContext?.locale || config.defaultLocale,
628
+ pathname: i18nContext?.pathname || ""
629
+ };
630
+ const { locale, pathname } = context;
631
+ const source = isI18nContextFunction ? i18nContext.name : "static fallback";
632
+ logger.debug(`I18n context resolved via ${source}.`, context);
633
+ let loadedMessages;
634
+ if (shouldLoadMessages(loader)) {
635
+ loadedMessages = await loadMessages({
636
+ config,
637
+ locale,
638
+ pathname,
639
+ extraOptions: {
640
+ exts: loadMessagesOptions.exts,
641
+ messagesReader: loadMessagesOptions.messagesReader
642
+ },
643
+ allowCacheWrite: true
644
+ });
645
+ }
646
+ const mergedMessages = mergeMessages(messages, loadedMessages);
647
+ logger.info("Messages successfully initialized.", {
648
+ static: { enabled: !!messages },
649
+ loaded: {
650
+ enabled: !!loadedMessages,
651
+ ...loader ? { loaderType: loader.type, lazyLoad: !!loader.lazyLoad } : null
652
+ },
653
+ merged: mergedMessages
654
+ });
655
+ return {
656
+ config,
657
+ initialLocale: locale,
658
+ pathname,
659
+ messages: mergedMessages
660
+ };
661
+ };
662
+ async function getTranslator(opts) {
663
+ const { config, locale, pathname = "", preKey, handlers } = opts;
664
+ const messages = await loadMessages({ config, locale, pathname });
665
+ const translator = new Translator({
666
+ locale,
667
+ messages,
668
+ fallbackLocales: config.fallbackLocales,
669
+ loadingMessage: config.translator?.loadingMessage,
670
+ placeholder: config.translator?.placeholder,
671
+ handlers
672
+ });
673
+ const props = { messages, locale };
674
+ const scoped = translator.scoped(preKey);
675
+ return {
676
+ ...props,
677
+ hasKey: preKey ? scoped.hasKey : translator.hasKey,
678
+ t: preKey ? scoped.t : translator.t
679
+ };
680
+ }
681
+
682
+ export { clearLoggerPool, clearMessagesPool, getTranslator, intor, loadLocalMessages, loadMessages, loadRemoteMessages };