intor 2.4.6 → 2.4.8

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.
Files changed (70) hide show
  1. package/dist/core/export/server/index.js +2 -3
  2. package/dist/core/src/routing/pathname/localize-pathname.js +1 -1
  3. package/dist/core/src/server/helpers/get-translator.js +3 -2
  4. package/dist/core/src/server/intor/intor.js +1 -1
  5. package/dist/core/src/server/translator/init-translator.js +6 -3
  6. package/dist/express/src/adapters/express/get-translator.js +5 -4
  7. package/dist/express/src/routing/pathname/localize-pathname.js +1 -1
  8. package/dist/express/src/server/helpers/get-translator.js +3 -2
  9. package/dist/express/src/server/translator/init-translator.js +6 -3
  10. package/dist/fastify/src/adapters/fastify/get-translator.js +5 -4
  11. package/dist/fastify/src/routing/pathname/localize-pathname.js +1 -1
  12. package/dist/fastify/src/server/helpers/get-translator.js +3 -2
  13. package/dist/fastify/src/server/translator/init-translator.js +6 -3
  14. package/dist/hono/src/routing/pathname/localize-pathname.js +1 -1
  15. package/dist/next/src/adapters/next/server/get-translator.js +5 -4
  16. package/dist/next/src/routing/pathname/localize-pathname.js +1 -1
  17. package/dist/next/src/server/helpers/get-translator.js +3 -2
  18. package/dist/next/src/server/intor/intor.js +1 -1
  19. package/dist/next/src/server/translator/init-translator.js +6 -3
  20. package/dist/svelte-kit/export/svelte-kit/index.js +1 -0
  21. package/dist/svelte-kit/src/adapters/svelte-kit/{server/create-intor-handler.js → create-intor-handler.js} +4 -4
  22. package/dist/svelte-kit/src/core/utils/resolve-loader-options.js +1 -5
  23. package/dist/svelte-kit/src/policies/shoud-full-reload.js +1 -1
  24. package/dist/svelte-kit/src/routing/pathname/localize-pathname.js +1 -1
  25. package/dist/types/export/server/index.d.ts +1 -1
  26. package/dist/types/export/svelte-kit/index.d.ts +1 -1
  27. package/dist/types/src/adapters/next/server/get-translator.d.ts +1 -1
  28. package/dist/types/src/adapters/svelte-kit/{server/create-intor-handler.d.ts → create-intor-handler.d.ts} +1 -1
  29. package/dist/types/src/adapters/svelte-kit/index.d.ts +1 -0
  30. package/dist/types/src/client/react/helpers/use-intor.d.ts +1 -2
  31. package/dist/types/src/client/react/provider/intor-provider.d.ts +1 -2
  32. package/dist/types/src/client/react/provider/types.d.ts +10 -11
  33. package/dist/types/src/client/react/provider/use-intor-context.d.ts +1 -2
  34. package/dist/types/src/routing/index.d.ts +1 -1
  35. package/dist/types/src/routing/pathname/localize-pathname.d.ts +1 -1
  36. package/dist/types/src/server/helpers/get-translator.d.ts +2 -0
  37. package/dist/types/src/server/index.d.ts +2 -1
  38. package/dist/types/src/server/intor/intor.d.ts +2 -3
  39. package/dist/types/src/server/translator/index.d.ts +1 -0
  40. package/dist/types/src/server/translator/init-translator.d.ts +2 -0
  41. package/dist/types/src/server/translator/types.d.ts +9 -0
  42. package/package.json +1 -5
  43. package/dist/svelte-kit/export/svelte-kit/server/index.js +0 -2
  44. package/dist/svelte-kit/src/adapters/svelte-kit/server/intor.js +0 -24
  45. package/dist/svelte-kit/src/core/logger/get-logger.js +0 -39
  46. package/dist/svelte-kit/src/core/logger/global-logger-pool.js +0 -8
  47. package/dist/svelte-kit/src/core/messages/load-remote-messages/collect-remote-resources.js +0 -25
  48. package/dist/svelte-kit/src/core/messages/load-remote-messages/fetch-remote-resource.js +0 -47
  49. package/dist/svelte-kit/src/core/messages/load-remote-messages/load-remote-messages.js +0 -93
  50. package/dist/svelte-kit/src/core/messages/load-remote-messages/resolve-remote-resources.js +0 -24
  51. package/dist/svelte-kit/src/core/messages/merge-messages.js +0 -33
  52. package/dist/svelte-kit/src/core/messages/utils/is-valid-messages.js +0 -44
  53. package/dist/svelte-kit/src/core/messages/utils/nest-object-from-path.js +0 -21
  54. package/dist/svelte-kit/src/core/translator/create-translator.js +0 -30
  55. package/dist/svelte-kit/src/core/utils/deep-merge.js +0 -47
  56. package/dist/svelte-kit/src/core/utils/normalizers/normalize-cache-key.js +0 -45
  57. package/dist/svelte-kit/src/server/intor/intor.js +0 -32
  58. package/dist/svelte-kit/src/server/messages/load-local-messages/cache/messages-pool.js +0 -11
  59. package/dist/svelte-kit/src/server/messages/load-local-messages/load-local-messages.js +0 -108
  60. package/dist/svelte-kit/src/server/messages/load-local-messages/read-locale-messages/collect-file-entries/collect-file-entries.js +0 -91
  61. package/dist/svelte-kit/src/server/messages/load-local-messages/read-locale-messages/parse-file-entries/parse-file-entries.js +0 -103
  62. package/dist/svelte-kit/src/server/messages/load-local-messages/read-locale-messages/parse-file-entries/utils/json-reader.js +0 -12
  63. package/dist/svelte-kit/src/server/messages/load-local-messages/read-locale-messages/read-locale-messages.js +0 -42
  64. package/dist/svelte-kit/src/server/messages/load-messages.js +0 -78
  65. package/dist/svelte-kit/src/server/translator/init-translator.js +0 -36
  66. package/dist/types/export/svelte-kit/server/index.d.ts +0 -1
  67. package/dist/types/src/adapters/svelte-kit/server/index.d.ts +0 -2
  68. package/dist/types/src/adapters/svelte-kit/server/intor.d.ts +0 -20
  69. /package/dist/svelte-kit/src/adapters/svelte-kit/{server/utils → utils}/is-svelte-kit-ssg.js +0 -0
  70. /package/dist/types/src/adapters/svelte-kit/{server/utils → utils}/is-svelte-kit-ssg.d.ts +0 -0
@@ -1,39 +0,0 @@
1
- import { logry } from 'logry';
2
- import { getGlobalLoggerPool } from './global-logger-pool.js';
3
-
4
- const DEFAULT_FORMAT_CONFIG = {
5
- timestamp: { withDate: false },
6
- };
7
- const DEFAULT_RENDER_CONFIG = {
8
- timestamp: {},
9
- id: { visible: true, prefix: "<", suffix: ">" },
10
- meta: { lineBreaksAfter: 1 },
11
- };
12
- /**
13
- * Get a shared logger instance by id.
14
- * - Safe across hot reloads
15
- * - Prevents unbounded memory usage via soft LRU
16
- */
17
- function getLogger({ id = "default", formatConfig, renderConfig, preset, ...options }) {
18
- const pool = getGlobalLoggerPool();
19
- let logger = pool.get(id);
20
- if (!logger) {
21
- logger = logry({
22
- id,
23
- formatConfig: !formatConfig && !preset ? DEFAULT_FORMAT_CONFIG : formatConfig,
24
- renderConfig: !renderConfig && !preset ? DEFAULT_RENDER_CONFIG : renderConfig,
25
- preset,
26
- ...options,
27
- });
28
- pool.set(id, logger);
29
- // Soft LRU: keep pool size under control
30
- if (pool.size > 1000) {
31
- const keys = [...pool.keys()];
32
- for (const key of keys.slice(0, 200))
33
- pool.delete(key);
34
- }
35
- }
36
- return logger;
37
- }
38
-
39
- export { getLogger };
@@ -1,8 +0,0 @@
1
- function getGlobalLoggerPool() {
2
- if (!globalThis.__INTOR_LOGGER_POOL__) {
3
- globalThis.__INTOR_LOGGER_POOL__ = new Map();
4
- }
5
- return globalThis.__INTOR_LOGGER_POOL__;
6
- }
7
-
8
- export { getGlobalLoggerPool };
@@ -1,25 +0,0 @@
1
- /**
2
- * Collect remote message resources for a given locale.
3
- *
4
- * - Always includes the root `index.json`
5
- * - Optionally includes namespace-specific resources
6
- * - Produces semantic paths for later message nesting
7
- *
8
- * This function performs no I/O and does not validate resource existence.
9
- */
10
- function collectRemoteResources({ locale, baseUrl, namespaces, }) {
11
- const basePath = `${baseUrl}/${locale}`;
12
- // Root translation resource (always loaded)
13
- const indexResource = { url: `${basePath}/index.json`, path: [] };
14
- // When no namespaces are provided, the locale domain consists of index only
15
- if (!namespaces || namespaces.length === 0)
16
- return [indexResource];
17
- // Namespace-specific resources are nested under their namespace key
18
- const nsResources = namespaces.map((ns) => ({
19
- url: `${basePath}/${ns}.json`,
20
- path: [ns],
21
- }));
22
- return [indexResource, ...nsResources];
23
- }
24
-
25
- export { collectRemoteResources };
@@ -1,47 +0,0 @@
1
- import { getLogger } from '../../logger/get-logger.js';
2
- import { isValidMessages } from '../utils/is-valid-messages.js';
3
-
4
- /**
5
- * Fetch a single remote messages resource.
6
- *
7
- * This function performs a single HTTP request to retrieve
8
- * a remote translation messages payload.
9
- *
10
- * It is responsible for:
11
- * - Issuing the network request
12
- * - Validating the returned message structure
13
- * - Handling abort and network errors
14
- */
15
- async function fetchRemoteResource({ fetch, url, headers, signal, loggerOptions, }) {
16
- const baseLogger = getLogger(loggerOptions);
17
- const logger = baseLogger.child({ scope: "fetch-locale-messages" });
18
- try {
19
- // Fetch
20
- const response = await fetch(url, {
21
- method: "GET",
22
- headers: { "Content-Type": "application/json", ...headers },
23
- cache: "no-store",
24
- signal,
25
- });
26
- if (!response.ok) {
27
- throw new Error(`HTTP ${response.status} ${response.statusText}`);
28
- }
29
- // Parse JSON body
30
- const data = await response.json();
31
- // Validate messages structure
32
- if (!isValidMessages(data)) {
33
- throw new Error("Invalid messages structure");
34
- }
35
- return data;
36
- }
37
- catch (error) {
38
- if (error instanceof Error && error.name === "AbortError") {
39
- logger.debug("Remote fetch aborted.", { url });
40
- return;
41
- }
42
- logger.warn("Failed to fetch remote messages.", { url, error });
43
- return;
44
- }
45
- }
46
-
47
- export { fetchRemoteResource };
@@ -1,93 +0,0 @@
1
- import pLimit from 'p-limit';
2
- import { getLogger } from '../../logger/get-logger.js';
3
- import { collectRemoteResources } from './collect-remote-resources.js';
4
- import { fetchRemoteResource } from './fetch-remote-resource.js';
5
- import { resolveRemoteResources } from './resolve-remote-resources.js';
6
-
7
- /**
8
- * Load locale messages from a remote source.
9
- *
10
- * This function serves as the orchestration layer for remote message loading.
11
- * It coordinates:
12
- *
13
- * - Locale resolution with fallbacks
14
- * - Concurrency control for network requests
15
- * - Remote resource fetching and message merging
16
- *
17
- * Remote messages are fetched on demand and are not memoized at the process level.
18
- *
19
- * Network requests and response validation are delegated to lower-level utilities.
20
- */
21
- const loadRemoteMessages = async ({ locale, fallbackLocales, namespaces, concurrency, fetch, url: baseUrl, headers, signal, loggerOptions, }) => {
22
- const baseLogger = getLogger(loggerOptions);
23
- const logger = baseLogger.child({ scope: "load-remote-messages" });
24
- // Abort early if the request has already been cancelled
25
- if (signal?.aborted) {
26
- logger.debug("Remote message loading aborted before fetch.");
27
- return;
28
- }
29
- const start = performance.now();
30
- logger.debug("Loading remote messages.", { baseUrl });
31
- // ----------------------------------------------------------------
32
- // Resolve locale messages with ordered fallback strategy
33
- // ----------------------------------------------------------------
34
- const limit = concurrency ? pLimit(concurrency) : undefined;
35
- const candidateLocales = [locale, ...(fallbackLocales || [])];
36
- let messages;
37
- for (let i = 0; i < candidateLocales.length; i++) {
38
- const candidateLocale = candidateLocales[i];
39
- const isLast = i === candidateLocales.length - 1;
40
- try {
41
- // -----------------------------------------------------------------
42
- // Collect remote message resources for the locale
43
- // -----------------------------------------------------------------
44
- const resources = collectRemoteResources({
45
- locale: candidateLocale,
46
- baseUrl,
47
- namespaces,
48
- });
49
- // -----------------------------------------------------------------
50
- // Fetch all message chunks in parallel
51
- // -----------------------------------------------------------------
52
- const fetchUrl = (url) => fetchRemoteResource({ url, headers, signal, loggerOptions, fetch });
53
- const results = await Promise.all(resources.map(({ url }) => limit ? limit(() => fetchUrl(url)) : fetchUrl(url)));
54
- // Guard: no valid remote resources
55
- if (!results.some(Boolean))
56
- continue;
57
- // -----------------------------------------------------------------
58
- // Resolve and merge remote message resources
59
- // -----------------------------------------------------------------
60
- const resolved = resolveRemoteResources(resources.map((res, i) => ({ path: res.path, data: results[i] })));
61
- // -----------------------------------------------------------------
62
- // Wrap resolved messages into locale-scoped LocaleMessages
63
- // -----------------------------------------------------------------
64
- messages = { [candidateLocale]: resolved };
65
- break;
66
- }
67
- catch {
68
- if (signal?.aborted) {
69
- logger.debug("Remote message loading aborted.");
70
- return;
71
- }
72
- if (isLast) {
73
- logger.warn("Failed to load messages for all candidate locales.", {
74
- locale,
75
- fallbackLocales,
76
- });
77
- }
78
- else {
79
- logger.warn(`Failed to load locale messages for "${candidateLocale}", trying next fallback.`);
80
- }
81
- }
82
- }
83
- // Final success log with resolved locale and timing
84
- if (messages) {
85
- logger.trace("Finished loading remote messages.", {
86
- loadedLocale: Object.keys(messages)[0],
87
- duration: `${Math.round(performance.now() - start)} ms`,
88
- });
89
- }
90
- return messages;
91
- };
92
-
93
- export { loadRemoteMessages };
@@ -1,24 +0,0 @@
1
- import { deepMerge } from '../../utils/deep-merge.js';
2
- import { nestObjectFromPath } from '../utils/nest-object-from-path.js';
3
-
4
- /**
5
- * Resolve remote message resources into a single MessageObject.
6
- *
7
- * - Applies semantic nesting based on resource path
8
- * - Merges all resolved message chunks
9
- *
10
- * Always returns a MessageObject.
11
- * An empty object represents an empty translation domain.
12
- */
13
- function resolveRemoteResources(resources) {
14
- let result = {};
15
- for (const { path, data } of resources) {
16
- if (!data)
17
- continue;
18
- const resolved = path.length > 0 ? nestObjectFromPath(path, data) : data;
19
- result = deepMerge(result, resolved);
20
- }
21
- return result;
22
- }
23
-
24
- export { resolveRemoteResources };
@@ -1,33 +0,0 @@
1
- import { getLogger } from '../logger/get-logger.js';
2
- import { deepMerge } from '../utils/deep-merge.js';
3
-
4
- /**
5
- * Merge locale-specific messages with runtime overrides.
6
- *
7
- * - Only merges messages under the given locale
8
- * - Emits debug logs for add / override events
9
- */
10
- function mergeMessages(a, b, { config, locale, onEvent }) {
11
- const baseLogger = getLogger({ ...config.logger, id: config.id });
12
- const logger = baseLogger.child({ scope: "merge-messages" });
13
- // Merge messages for the active locale only
14
- const merged = deepMerge(a?.[locale] ?? {}, b?.[locale] ?? {}, {
15
- onOverride: (event) => {
16
- if (onEvent) {
17
- onEvent(event);
18
- return;
19
- }
20
- const { kind, path, next, prev } = event;
21
- if (kind === "add")
22
- return;
23
- logger.debug(`Override | ${locale}: "${path}"`, { prev, next });
24
- },
25
- });
26
- // Preserve other locales, update only the target one
27
- return {
28
- ...a,
29
- [locale]: merged,
30
- };
31
- }
32
-
33
- export { mergeMessages };
@@ -1,44 +0,0 @@
1
- /** Check if a value is a plain object (not null, not array) */
2
- function isPlainObject(value) {
3
- return typeof value === "object" && value !== null && !Array.isArray(value);
4
- }
5
- /**
6
- * Check if a value is a valid MessageObject.
7
- *
8
- * - Supports all MessageValue variants (primitive, array, object).
9
- * - Uses an iterative approach to avoid stack overflow.
10
- */
11
- function isValidMessages(value) {
12
- if (!isPlainObject(value))
13
- return false;
14
- const stack = [value];
15
- while (stack.length > 0) {
16
- const current = stack.pop();
17
- // primitives are always valid
18
- if (current === null ||
19
- typeof current === "string" ||
20
- typeof current === "number" ||
21
- typeof current === "boolean") {
22
- continue;
23
- }
24
- // array → validate each item
25
- if (Array.isArray(current)) {
26
- for (const item of current) {
27
- stack.push(item);
28
- }
29
- continue;
30
- }
31
- // object → validate each value
32
- if (isPlainObject(current)) {
33
- for (const v of Object.values(current)) {
34
- stack.push(v);
35
- }
36
- continue;
37
- }
38
- // everything else is invalid
39
- return false;
40
- }
41
- return true;
42
- }
43
-
44
- export { isPlainObject, isValidMessages };
@@ -1,21 +0,0 @@
1
- /**
2
- * Wraps a value inside nested objects according to a given path.
3
- *
4
- * @example
5
- * ```ts
6
- * const value = { a: "A" };
7
- *
8
- * nestObjectFromPath(["auth", "verify"], value); // → { auth: { verify: { a: "A" } } }
9
- *
10
- * nestObjectFromPath([], value); // → { a: "A" }
11
- * ```
12
- */
13
- function nestObjectFromPath(path, value) {
14
- let obj = value;
15
- for (let i = path.length - 1; i >= 0; i--) {
16
- obj = { [path[i]]: obj };
17
- }
18
- return obj;
19
- }
20
-
21
- export { nestObjectFromPath };
@@ -1,30 +0,0 @@
1
- import { Translator } from 'intor-translator';
2
- import { mergeMessages } from '../messages/merge-messages.js';
3
-
4
- /**
5
- * Create a server-side Translator instance for a fixed locale.
6
- *
7
- * - Merges static config messages with runtime-loaded messages
8
- * - Initializes a Translator bound to a specific locale
9
- * - Injects fallback rules, handlers, and plugins from config
10
- */
11
- function createTranslator(params) {
12
- const { config, locale, messages, handlers, plugins } = params;
13
- // Merge static config messages with runtime-loaded messages
14
- const finalMessages = mergeMessages(config.messages, messages, {
15
- config,
16
- locale,
17
- });
18
- const translator = new Translator({
19
- locale,
20
- messages: finalMessages,
21
- fallbackLocales: config.fallbackLocales,
22
- loadingMessage: config.translator?.loadingMessage,
23
- missingMessage: config.translator?.missingMessage,
24
- handlers,
25
- plugins,
26
- });
27
- return translator;
28
- }
29
-
30
- export { createTranslator };
@@ -1,47 +0,0 @@
1
- /**
2
- * Deeply merges two plain objects.
3
- *
4
- * - Nested plain objects → merged recursively
5
- * - Arrays / primitives → `b` overwrites `a`
6
- *
7
- * Debug behavior (optional):
8
- * - Emits override events via `onOverride`
9
- * - Zero overhead when no options are provided
10
- *
11
- * This function always returns a new plain object.
12
- */
13
- const deepMerge = (a = {}, b = {}, options) => {
14
- const result = { ...a };
15
- const basePath = options?._path ?? [];
16
- // Iterate only over b's own enumerable properties
17
- for (const key in b) {
18
- if (!Object.prototype.hasOwnProperty.call(b, key))
19
- continue;
20
- const aValue = a[key];
21
- const bValue = b[key];
22
- const nextPath = [...basePath, key];
23
- // Recursively merge when both sides are plain objects
24
- if (aValue &&
25
- bValue &&
26
- typeof aValue === "object" &&
27
- typeof bValue === "object" &&
28
- !Array.isArray(aValue) &&
29
- !Array.isArray(bValue)) {
30
- result[key] = deepMerge(aValue, bValue, options ? { ...options, _path: nextPath } : undefined);
31
- }
32
- else {
33
- // Emit override event only when debugging is enabled
34
- const isAdd = aValue === undefined;
35
- options?.onOverride?.({
36
- path: nextPath.join("."),
37
- prev: aValue,
38
- next: bValue,
39
- kind: isAdd ? "add" : "override",
40
- });
41
- result[key] = bValue;
42
- }
43
- }
44
- return result;
45
- };
46
-
47
- export { deepMerge };
@@ -1,45 +0,0 @@
1
- const CACHE_KEY_DELIMITER = "|";
2
- const sanitize = (k) => k
3
- .replaceAll(/[\u200B-\u200D\uFEFF]/g, "")
4
- .replaceAll(/[\r\n]/g, "")
5
- .trim();
6
- /**
7
- * Normalizes a value into a stable cache key string.
8
- *
9
- * - Supports primitive values and structured array keys.
10
- * - Produces deterministic output suitable for cache identifiers.
11
- *
12
- * Notes:
13
- * - `null`, `undefined`, or empty arrays return `null`.
14
- * - Special tokens are used for boolean, null, and undefined values
15
- * to preserve semantic differences.
16
- */
17
- const normalizeCacheKey = (key, delimiter = CACHE_KEY_DELIMITER) => {
18
- // Treat nullish values as "no cache key"
19
- if (key === null || key === undefined)
20
- return null;
21
- if (Array.isArray(key)) {
22
- // Empty array produces no meaningful cache key
23
- if (key.length === 0)
24
- return null;
25
- const normalized = key.map((k) => {
26
- // Preserve semantic differences for special values
27
- if (k === null)
28
- return "__null";
29
- if (k === undefined)
30
- return "__undefined";
31
- if (typeof k === "boolean")
32
- return k ? "__true" : "__false";
33
- return sanitize(String(k));
34
- });
35
- // Join segments into a single deterministic cache key
36
- return normalized.join(delimiter);
37
- }
38
- // Normalize boolean primitives explicitly
39
- if (typeof key === "boolean")
40
- return key ? "__true" : "__false";
41
- // Fallback: stringify primitive values
42
- return String(key);
43
- };
44
-
45
- export { normalizeCacheKey };
@@ -1,32 +0,0 @@
1
- import '../../core/error/intor-error.js';
2
- import { getLogger } from '../../core/logger/get-logger.js';
3
- import 'p-limit';
4
- import 'intor-translator';
5
- import { initTranslator } from '../translator/init-translator.js';
6
-
7
- /**
8
- * Initializes Intor for the current execution context.
9
- *
10
- * Produces a server-side snapshot for SSR and
11
- * full-stack rendering environments.
12
- */
13
- async function intor(config, locale, options) {
14
- const baseLogger = getLogger(config.logger);
15
- const logger = baseLogger.child({ scope: "intor" });
16
- logger.info("Start Intor initialization.");
17
- logger.debug(`Initializing Intor with locale "${locale}".`);
18
- // Initialize a locale-bound translator snapshot with messages loaded
19
- const translator = await initTranslator(config, locale, {
20
- readers: options?.readers,
21
- allowCacheWrite: options?.allowCacheWrite,
22
- fetch: options?.fetch || globalThis.fetch,
23
- });
24
- logger.info("Intor initialized.");
25
- return {
26
- config,
27
- locale: translator.locale,
28
- messages: translator.messages,
29
- };
30
- }
31
-
32
- export { intor };
@@ -1,11 +0,0 @@
1
- /**
2
- * Get the messages pool.
3
- */
4
- function getMessagesPool() {
5
- if (!globalThis.__INTOR_MESSAGES_POOL__) {
6
- globalThis.__INTOR_MESSAGES_POOL__ = new Map();
7
- }
8
- return globalThis.__INTOR_MESSAGES_POOL__;
9
- }
10
-
11
- export { getMessagesPool };
@@ -1,108 +0,0 @@
1
- import path from 'node:path';
2
- import pLimit from 'p-limit';
3
- import '../../../core/error/intor-error.js';
4
- import { normalizeCacheKey } from '../../../core/utils/normalizers/normalize-cache-key.js';
5
- import { getLogger } from '../../../core/logger/get-logger.js';
6
- import 'intor-translator';
7
- import { getMessagesPool } from './cache/messages-pool.js';
8
- import { readLocaleMessages } from './read-locale-messages/read-locale-messages.js';
9
-
10
- /**
11
- * Load locale messages from the local file system.
12
- *
13
- * This function serves as the orchestration layer for local message loading.
14
- * It coordinates:
15
- *
16
- * - Locale resolution with fallbacks
17
- * - Concurrency control for file system access
18
- * - Process-level memoization (read by default, write by ownership)
19
- *
20
- * Local messages are cached for the lifetime of the process.
21
- * Cache writes are restricted to the primary initialization flow.
22
- *
23
- * File traversal, parsing, and validation are delegated to lower-level utilities.
24
- */
25
- const loadLocalMessages = async ({ id, locale, fallbackLocales, namespaces, rootDir = "messages", concurrency = 10, readers, pool = getMessagesPool(), allowCacheWrite = false, loggerOptions, }) => {
26
- const baseLogger = getLogger(loggerOptions);
27
- const logger = baseLogger.child({ scope: "load-local-messages" });
28
- const start = performance.now();
29
- logger.debug("Loading local messages.", {
30
- rootDir,
31
- resolvedRootDir: path.resolve(rootDir),
32
- });
33
- // ---------------------------------------------------------------------------
34
- // Cache key resolution
35
- // ---------------------------------------------------------------------------
36
- const cacheKey = normalizeCacheKey([
37
- id,
38
- "loaderType:local",
39
- rootDir,
40
- locale,
41
- fallbackLocales?.toSorted().join(","),
42
- namespaces?.toSorted().join(","),
43
- ].filter(Boolean));
44
- // ---------------------------------------------------------------------------
45
- // Cache read
46
- // ---------------------------------------------------------------------------
47
- if (cacheKey) {
48
- const cached = pool.get(cacheKey);
49
- if (cached) {
50
- logger.debug("Messages cache hit.", { key: cacheKey });
51
- return cached;
52
- }
53
- }
54
- // ---------------------------------------------------------------------------
55
- // Resolve locale messages with ordered fallback strategy
56
- // ---------------------------------------------------------------------------
57
- const limit = pLimit(concurrency);
58
- const candidateLocales = [locale, ...(fallbackLocales || [])];
59
- let messages;
60
- for (let i = 0; i < candidateLocales.length; i++) {
61
- const candidateLocale = candidateLocales[i];
62
- const isLast = i === candidateLocales.length - 1;
63
- try {
64
- const result = await readLocaleMessages({
65
- locale: candidateLocale,
66
- namespaces,
67
- rootDir,
68
- limit,
69
- readers,
70
- loggerOptions,
71
- });
72
- // Stop at the first locale that yields non-empty messages
73
- if (Object.values(result[candidateLocale] || {}).length > 0) {
74
- messages = result;
75
- break;
76
- }
77
- }
78
- catch {
79
- if (isLast) {
80
- logger.warn("Failed to load messages for all candidate locales.", {
81
- locale,
82
- fallbackLocales,
83
- });
84
- }
85
- else {
86
- logger.warn(`Failed to load locale messages for "${candidateLocale}", trying next fallback.`);
87
- }
88
- }
89
- }
90
- // ---------------------------------------------------------------------------
91
- // Cache write (explicitly permitted)
92
- // ---------------------------------------------------------------------------
93
- const isProd = process.env.NODE_ENV === "production";
94
- const canWriteCache = isProd && allowCacheWrite;
95
- if (canWriteCache && cacheKey && messages) {
96
- pool.set(cacheKey, messages);
97
- }
98
- // Final success log with resolved locale and timing
99
- if (messages) {
100
- logger.trace("Finished loading local messages.", {
101
- loadedLocale: Object.keys(messages)[0],
102
- duration: `${Math.round(performance.now() - start)} ms`,
103
- });
104
- }
105
- return messages;
106
- };
107
-
108
- export { loadLocalMessages };