vite-bundled-i18n 0.1.1 → 0.2.0
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/cli/index.js +1 -1
- package/dist/core/fetcher.d.ts +2 -2
- package/dist/core/types.d.ts +30 -0
- package/dist/{data-Trz4mxne.js → data-DctljUuI.js} +35 -12
- package/dist/data-DctljUuI.js.map +1 -0
- package/dist/extractor/dictionary-ownership.d.ts +1 -0
- package/dist/extractor/reports.d.ts +4 -0
- package/dist/extractor/type-generator.d.ts +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/plugin/buildPlugin.d.ts +1 -0
- package/dist/plugin.js +32 -5
- package/dist/plugin.js.map +1 -1
- package/dist/react/I18nBoundary.d.ts +22 -0
- package/dist/react/useI18n.d.ts +2 -2
- package/dist/react.d.ts +2 -0
- package/dist/react.js +24 -2
- package/dist/react.js.map +1 -1
- package/dist/{server-BpEocC73.js → server-Ckj2GFmZ.js} +2 -2
- package/dist/{server-BpEocC73.js.map → server-Ckj2GFmZ.js.map} +1 -1
- package/dist/server.js +2 -2
- package/dist/vanilla.js +2 -2
- package/dist/vue.js +1 -1
- package/dist/{walker-DqlV3VrX.js → walker-Bf9fpAPX.js} +70 -10
- package/dist/walker-Bf9fpAPX.js.map +1 -0
- package/package.json +1 -1
- package/dist/data-Trz4mxne.js.map +0 -1
- package/dist/walker-DqlV3VrX.js.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-
|
|
2
|
+
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-Bf9fpAPX.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
package/dist/core/fetcher.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { NestedTranslations } from './types';
|
|
2
2
|
export declare function buildLoadPath(localesDir: string, locale: string, namespace: string): string;
|
|
3
|
-
export declare function buildBundlePath(locale: string, bundleName: string): string;
|
|
3
|
+
export declare function buildBundlePath(base: string, locale: string, bundleName: string): string;
|
|
4
4
|
export declare function fetchNamespace(localesDir: string, locale: string, namespace: string, requestInit?: RequestInit): Promise<NestedTranslations>;
|
|
5
|
-
export declare function fetchBundle(locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
|
|
5
|
+
export declare function fetchBundle(base: string, locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
|
package/dist/core/types.d.ts
CHANGED
|
@@ -47,6 +47,24 @@ export interface I18nKeyMap {
|
|
|
47
47
|
*/
|
|
48
48
|
export interface I18nParamsMap {
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Augmentable interface for nested key structure.
|
|
52
|
+
* Enables progressive autocomplete: typing `t('feedback.` suggests
|
|
53
|
+
* `pages`, `actions`, etc. as next segments.
|
|
54
|
+
*/
|
|
55
|
+
export interface I18nNestedKeys {
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Augmentable interface for valid scope identifiers.
|
|
59
|
+
* When populated by the type generator, constrains `useI18n(scope)` to valid scopes.
|
|
60
|
+
*/
|
|
61
|
+
export interface I18nScopeMap {
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Resolves to the union of registered scope identifiers when `I18nScopeMap`
|
|
65
|
+
* has entries, or falls back to `string` when it's empty.
|
|
66
|
+
*/
|
|
67
|
+
export type ValidScope = keyof I18nScopeMap extends never ? string : keyof I18nScopeMap & string;
|
|
50
68
|
/**
|
|
51
69
|
* Resolves to the union of registered translation keys when `I18nKeyMap`
|
|
52
70
|
* has entries, or falls back to `string` when it's empty (no generated types).
|
|
@@ -179,6 +197,12 @@ export interface DictionaryConfig {
|
|
|
179
197
|
* - `admin*` (namespace prefix)
|
|
180
198
|
*/
|
|
181
199
|
include?: string[];
|
|
200
|
+
/**
|
|
201
|
+
* Key patterns to exclude from this dictionary, applied after `include`.
|
|
202
|
+
* Same pattern syntax as `include`. Use to carve out sub-namespaces
|
|
203
|
+
* that shouldn't be preloaded (e.g., large validation keys).
|
|
204
|
+
*/
|
|
205
|
+
exclude?: string[];
|
|
182
206
|
/** Higher priority dictionaries claim matching keys first. */
|
|
183
207
|
priority?: number;
|
|
184
208
|
/** Whether this dictionary should be pinned in the runtime cache. */
|
|
@@ -265,6 +289,12 @@ export interface I18nConfig {
|
|
|
265
289
|
* - Function: called before each request, may be async (e.g., for refreshing auth tokens)
|
|
266
290
|
*/
|
|
267
291
|
requestInit?: RequestInit | (() => RequestInit | Promise<RequestInit>);
|
|
292
|
+
/**
|
|
293
|
+
* Overrides the build-injected base path for translation bundle fetches.
|
|
294
|
+
* Useful for CDN or reverse proxy deployments where the runtime fetch URL
|
|
295
|
+
* differs from the Vite build `base`.
|
|
296
|
+
*/
|
|
297
|
+
publicBase?: string;
|
|
268
298
|
}
|
|
269
299
|
/**
|
|
270
300
|
* The i18n instance returned by `createI18n()`.
|
|
@@ -185,8 +185,8 @@ function interpolate$1(text, params) {
|
|
|
185
185
|
function buildLoadPath(localesDir, locale, namespace) {
|
|
186
186
|
return `${localesDir.endsWith("/") ? localesDir.slice(0, -1) : localesDir}/${locale}/${namespace}.json`;
|
|
187
187
|
}
|
|
188
|
-
function buildBundlePath(locale, bundleName) {
|
|
189
|
-
return
|
|
188
|
+
function buildBundlePath(base, locale, bundleName) {
|
|
189
|
+
return (base.endsWith("/") ? base : base + "/") + locale + "/" + bundleName + ".json";
|
|
190
190
|
}
|
|
191
191
|
async function fetchNamespace(localesDir, locale, namespace, requestInit) {
|
|
192
192
|
const url = buildLoadPath(localesDir, locale, namespace);
|
|
@@ -194,8 +194,8 @@ async function fetchNamespace(localesDir, locale, namespace, requestInit) {
|
|
|
194
194
|
if (!response.ok) throw new Error(`Failed to load translations: ${url} (${response.status} ${response.statusText})`);
|
|
195
195
|
return response.json();
|
|
196
196
|
}
|
|
197
|
-
async function fetchBundle(locale, bundleName, requestInit) {
|
|
198
|
-
const url = buildBundlePath(locale, bundleName);
|
|
197
|
+
async function fetchBundle(base, locale, bundleName, requestInit) {
|
|
198
|
+
const url = buildBundlePath(base, locale, bundleName);
|
|
199
199
|
const response = requestInit ? await fetch(url, requestInit) : await fetch(url);
|
|
200
200
|
if (!response.ok) throw new Error(`Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`);
|
|
201
201
|
return response.json();
|
|
@@ -341,6 +341,16 @@ function resolveRuntimeCache(config) {
|
|
|
341
341
|
pinDictionaries: runtime.pinDictionaries ?? true
|
|
342
342
|
};
|
|
343
343
|
}
|
|
344
|
+
function getInjectedI18nBase() {
|
|
345
|
+
return typeof __VITE_I18N_BASE__ !== "undefined" ? __VITE_I18N_BASE__ : void 0;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Resolves the base path for bundle fetches.
|
|
349
|
+
* Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'
|
|
350
|
+
*/
|
|
351
|
+
function resolveI18nBase(config) {
|
|
352
|
+
return config.publicBase ?? getInjectedI18nBase() ?? "/__i18n";
|
|
353
|
+
}
|
|
344
354
|
function getInjectedCompiledManifestUrl() {
|
|
345
355
|
return typeof __VITE_I18N_COMPILED_MANIFEST__ !== "undefined" ? __VITE_I18N_COMPILED_MANIFEST__ : void 0;
|
|
346
356
|
}
|
|
@@ -390,6 +400,7 @@ function createI18n(config) {
|
|
|
390
400
|
if (!config.supportedLocales.includes(config.defaultLocale)) throw new Error(`vite-bundled-i18n: defaultLocale "${config.defaultLocale}" must be included in supportedLocales`);
|
|
391
401
|
const store = createStore();
|
|
392
402
|
const frozenConfig = Object.freeze({ ...config });
|
|
403
|
+
const i18nBase = resolveI18nBase(config);
|
|
393
404
|
const runtimeCache = resolveRuntimeCache(config);
|
|
394
405
|
const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();
|
|
395
406
|
const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);
|
|
@@ -404,6 +415,14 @@ function createI18n(config) {
|
|
|
404
415
|
const keyUsage = [];
|
|
405
416
|
/** The current scope set by useI18n, used for key tracking. */
|
|
406
417
|
let activeScope;
|
|
418
|
+
/** Tracks whether a consolidated fetch error has been emitted. */
|
|
419
|
+
let fetchErrorEmitted = false;
|
|
420
|
+
function handleFetchError() {
|
|
421
|
+
if (!fetchErrorEmitted) {
|
|
422
|
+
fetchErrorEmitted = true;
|
|
423
|
+
console.error("vite-bundled-i18n: Cannot load translations. Ensure __i18n assets are accessible at the configured base path. Are you running the Vite dev server, or have you built with the i18n plugin?");
|
|
424
|
+
}
|
|
425
|
+
}
|
|
407
426
|
let compiledManifestPromise = null;
|
|
408
427
|
const compiledLocaleMaps = /* @__PURE__ */ new Map();
|
|
409
428
|
function getCompiledLocaleMap(locale) {
|
|
@@ -570,15 +589,15 @@ function createI18n(config) {
|
|
|
570
589
|
}
|
|
571
590
|
}
|
|
572
591
|
const reqInit = await resolveRequestInit(config.requestInit);
|
|
573
|
-
const bundle = await fetchBundle(locale, `_dict/${name}`, reqInit);
|
|
592
|
+
const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);
|
|
574
593
|
for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
|
|
575
594
|
source: "dictionary",
|
|
576
595
|
pinned: runtimeCache.pinDictionaries
|
|
577
596
|
});
|
|
578
597
|
loadedDicts.add(dictKey);
|
|
579
598
|
evictUnused();
|
|
580
|
-
} catch
|
|
581
|
-
|
|
599
|
+
} catch {
|
|
600
|
+
handleFetchError();
|
|
582
601
|
}
|
|
583
602
|
}
|
|
584
603
|
/**
|
|
@@ -604,7 +623,7 @@ function createI18n(config) {
|
|
|
604
623
|
return;
|
|
605
624
|
}
|
|
606
625
|
}
|
|
607
|
-
const bundle = await fetchBundle(locale, scope, await resolveRequestInit(config.requestInit));
|
|
626
|
+
const bundle = await fetchBundle(i18nBase, locale, scope, await resolveRequestInit(config.requestInit));
|
|
608
627
|
for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
|
|
609
628
|
source: "scope",
|
|
610
629
|
pinned: false
|
|
@@ -612,7 +631,11 @@ function createI18n(config) {
|
|
|
612
631
|
loadedScopes.add(scopeKey);
|
|
613
632
|
evictUnused();
|
|
614
633
|
} catch (error) {
|
|
615
|
-
|
|
634
|
+
if (error instanceof Error && error.message.includes("404")) {
|
|
635
|
+
loadedScopes.add(scopeKey);
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
handleFetchError();
|
|
616
639
|
}
|
|
617
640
|
}
|
|
618
641
|
/**
|
|
@@ -627,8 +650,8 @@ function createI18n(config) {
|
|
|
627
650
|
pinned: false
|
|
628
651
|
});
|
|
629
652
|
evictUnused();
|
|
630
|
-
} catch
|
|
631
|
-
|
|
653
|
+
} catch {
|
|
654
|
+
handleFetchError();
|
|
632
655
|
}
|
|
633
656
|
}
|
|
634
657
|
function addResources(locale, namespace, data) {
|
|
@@ -891,4 +914,4 @@ function i18nKey(key) {
|
|
|
891
914
|
//#endregion
|
|
892
915
|
export { clearTranslations as a, mergeTranslations as c, createI18n as i, setTranslations as l, i18nKey as n, compiledHasKey as o, defineI18nConfig as r, compiledTranslate as s, defineI18nData as t };
|
|
893
916
|
|
|
894
|
-
//# sourceMappingURL=data-
|
|
917
|
+
//# sourceMappingURL=data-DctljUuI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-DctljUuI.js","names":[],"sources":["../src/core/store.ts","../src/core/resolver.ts","../src/core/interpolator.ts","../src/core/fetcher.ts","../src/core/compiled-runtime.ts","../src/core/createI18n.ts","../src/core/config.ts","../src/core/data.ts"],"sourcesContent":["import type { NestedTranslations } from './types';\n\ntype StoreSource = 'dictionary' | 'scope' | 'manual';\n\ninterface StoreEntry {\n locale: string;\n namespace: string;\n data: NestedTranslations;\n source: StoreSource;\n pinned: boolean;\n lastAccessedAt: number;\n approxSize: number;\n}\n\ninterface StoreStats {\n totalLocales: number;\n totalNamespaces: number;\n approxTotalBytes: number;\n pinnedNamespaces: number;\n}\n\n/**\n * The resource store's public interface.\n * Manages an in-memory map of `locale → namespace → translations`.\n */\nexport interface ResourceStore {\n /** Stores translation data for a locale and namespace. Overwrites if already present. */\n addResources: (\n locale: string,\n namespace: string,\n data: NestedTranslations,\n options?: { source?: StoreSource; pinned?: boolean },\n ) => void;\n /** Retrieves translation data for a locale and namespace. Returns undefined if not loaded. */\n getResource: (locale: string, namespace: string) => NestedTranslations | undefined;\n /** Checks whether a namespace has been loaded for a locale. */\n hasNamespace: (locale: string, namespace: string) => boolean;\n /** Removes a namespace from a locale. */\n removeNamespace: (locale: string, namespace: string) => void;\n /** Removes an entire locale from the store. */\n removeLocale: (locale: string) => void;\n /** Returns cache metadata for all entries. */\n getEntries: () => StoreEntry[];\n /** Returns store-level stats. */\n getStats: () => StoreStats;\n /** Removes all stored translation data. */\n clear: () => void;\n}\n\n/**\n * Creates a new in-memory resource store.\n *\n * The store holds loaded translation data in a two-level map:\n * `locale → namespace → NestedTranslations`. It provides no fetching logic —\n * data is added externally via `addResources` after being loaded by the fetcher.\n *\n * @returns A {@link ResourceStore} instance\n *\n * @example\n * ```ts\n * const store = createStore();\n * store.addResources('en', 'shared', { ok: 'OK', cancel: 'Cancel' });\n * store.getResource('en', 'shared'); // { ok: 'OK', cancel: 'Cancel' }\n * store.hasNamespace('en', 'shared'); // true\n * ```\n */\nexport function createStore(): ResourceStore {\n const data = new Map<string, Map<string, StoreEntry>>();\n\n const now = () => Date.now();\n const approxSizeOf = (resources: NestedTranslations) =>\n JSON.stringify(resources).length;\n\n return {\n addResources(locale, namespace, resources, options) {\n let localeMap = data.get(locale);\n if (!localeMap) {\n localeMap = new Map();\n data.set(locale, localeMap);\n }\n localeMap.set(namespace, {\n locale,\n namespace,\n data: resources,\n source: options?.source ?? 'manual',\n pinned: options?.pinned ?? false,\n lastAccessedAt: now(),\n approxSize: approxSizeOf(resources),\n });\n },\n\n getResource(locale, namespace) {\n const entry = data.get(locale)?.get(namespace);\n if (!entry) return undefined;\n entry.lastAccessedAt = now();\n return entry.data;\n },\n\n hasNamespace(locale, namespace) {\n return data.get(locale)?.has(namespace) ?? false;\n },\n\n removeNamespace(locale, namespace) {\n const localeMap = data.get(locale);\n if (!localeMap) return;\n localeMap.delete(namespace);\n if (localeMap.size === 0) {\n data.delete(locale);\n }\n },\n\n removeLocale(locale) {\n data.delete(locale);\n },\n\n getEntries() {\n return [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n },\n\n getStats() {\n const entries = [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n return {\n totalLocales: data.size,\n totalNamespaces: entries.length,\n approxTotalBytes: entries.reduce((sum, entry) => sum + entry.approxSize, 0),\n pinnedNamespaces: entries.filter((entry) => entry.pinned).length,\n };\n },\n\n clear() {\n data.clear();\n },\n };\n}\n","import type { NestedTranslations } from './types';\n\n/**\n * Extracts the namespace from a fully qualified key.\n *\n * The namespace is the first dot-separated segment. This determines\n * which JSON file to load (e.g., `'products'` loads `products.json`).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The namespace name (e.g., `'products'`)\n *\n * @example\n * ```ts\n * inferNamespace('products.show.title'); // 'products'\n * inferNamespace('shared.ok'); // 'shared'\n * inferNamespace('checkout'); // 'checkout'\n * ```\n */\nexport function inferNamespace(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? key : key.slice(0, dotIndex);\n}\n\n/**\n * Extracts the subkey path from a fully qualified key (everything after the namespace).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The subkey path (e.g., `'show.title'`), or empty string if no subkey\n *\n * @example\n * ```ts\n * extractSubkey('products.show.title'); // 'show.title'\n * extractSubkey('shared.ok'); // 'ok'\n * extractSubkey('checkout'); // ''\n * ```\n */\nexport function extractSubkey(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? '' : key.slice(dotIndex + 1);\n}\n\n/**\n * Resolves a dot-separated key path against a nested translations object.\n *\n * Traverses the object tree following each segment of the key path.\n * Returns the string value at the leaf, or `undefined` if the path\n * doesn't exist or resolves to a non-string (branch node).\n *\n * @param data - The nested translations object to search\n * @param keyPath - Dot-separated path (e.g., `'show.title'`)\n * @returns The translated string, or `undefined` if not found\n *\n * @example\n * ```ts\n * const data = { show: { title: 'Product Details' } };\n * resolveKey(data, 'show.title'); // 'Product Details'\n * resolveKey(data, 'show.missing'); // undefined\n * ```\n */\nexport function resolveKey(\n data: NestedTranslations,\n keyPath: string,\n): string | undefined {\n if (!keyPath) return undefined;\n\n const segments = keyPath.split('.');\n let current: NestedTranslations | string = data;\n\n for (const segment of segments) {\n if (typeof current !== 'object' || current === null) {\n return undefined;\n }\n current = current[segment];\n if (current === undefined) {\n return undefined;\n }\n }\n\n return typeof current === 'string' ? current : undefined;\n}\n","/**\n * Pattern matching `{{paramName}}` placeholders in translation strings.\n * Allows optional whitespace around the parameter name: `{{ name }}` works.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Replaces `{{paramName}}` placeholders in a translation string with\n * values from the provided params object.\n *\n * Rules:\n * - `{{param}}` and `{{ param }}` both resolve to the `param` key\n * - Missing params leave the placeholder as-is (aids debugging)\n * - Values are converted to strings via `String(value)`\n * - If no params are provided, the string is returned unchanged\n *\n * @param text - The translation string containing `{{placeholders}}`\n * @param params - Optional object mapping parameter names to values\n * @returns The interpolated string\n *\n * @example\n * ```ts\n * interpolate('Hello {{name}}', { name: 'Alice' });\n * // 'Hello Alice'\n *\n * interpolate('Price: {{amount}}', { amount: 29.99 });\n * // 'Price: 29.99'\n *\n * interpolate('Hello {{name}}', {});\n * // 'Hello {{name}}' — missing param left as-is\n * ```\n */\nexport function interpolate(\n text: string,\n params?: Record<string, unknown>,\n): string {\n if (!params) return text;\n\n return text.replace(PLACEHOLDER_PATTERN, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { NestedTranslations } from './types';\n\nexport function buildLoadPath(\n localesDir: string,\n locale: string,\n namespace: string,\n): string {\n const base = localesDir.endsWith('/') ? localesDir.slice(0, -1) : localesDir;\n return `${base}/${locale}/${namespace}.json`;\n}\n\nexport function buildBundlePath(base: string, locale: string, bundleName: string): string {\n const normalized = base.endsWith('/') ? base : base + '/';\n return normalized + locale + '/' + bundleName + '.json';\n}\n\nexport async function fetchNamespace(\n localesDir: string,\n locale: string,\n namespace: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n const url = buildLoadPath(localesDir, locale, namespace);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translations: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<NestedTranslations>;\n}\n\nexport async function fetchBundle(\n base: string,\n locale: string,\n bundleName: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\n const url = buildBundlePath(base, locale, bundleName);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<Record<string, NestedTranslations>>;\n}\n","/**\n * Compiled runtime for i18n production mode.\n *\n * Replaces the full store + resolver + fetcher stack with a single flat\n * `Map<string, string>` that is populated at build time. Lookups are O(1)\n * — no namespace inference, no dot-path traversal, no fallback chain.\n */\n\n/** Matches `{{key}}` and `{{ key }}` placeholders (whitespace-tolerant). */\nconst PLACEHOLDER = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\nlet currentMap: Map<string, string> = new Map();\n\nexport type CompiledTranslationMap = Map<string, string>;\nexport type CompiledModuleLoader = () => Promise<{ default: CompiledTranslationMap }>;\n\nexport interface CompiledManifestModule {\n scopes: Record<string, Record<string, CompiledModuleLoader>>;\n dictionaries?: Record<string, Record<string, CompiledModuleLoader>>;\n}\n\n/**\n * Replaces the active translation map entirely.\n *\n * Intended to be called once per locale load (e.g. on app boot or locale\n * switch). The map is copied so that mutations to the original do not\n * affect the runtime state.\n *\n * @param map - A flat `Map` of dot-path translation keys to their string values.\n */\nexport function setTranslations(map: Map<string, string>): void {\n currentMap = new Map(map);\n}\n\n/**\n * Merges additional translations into the current map.\n *\n * Existing keys are overwritten if they appear in the incoming map. This\n * is used when loading scope bundles (e.g. lazy-loaded route namespaces)\n * on top of a base dictionary that was set via {@link setTranslations}.\n *\n * @param map - A flat `Map` of dot-path translation keys to merge in.\n */\nexport function mergeTranslations(map: Map<string, string>): void {\n for (const [k, v] of map) {\n currentMap.set(k, v);\n }\n}\n\n/**\n * Clears all translations from the runtime map.\n *\n * Resets state to an empty map. Primarily intended for use in tests via\n * `beforeEach` to ensure isolation between test cases.\n */\nexport function clearTranslations(): void {\n currentMap = new Map();\n}\n\n/**\n * Returns `true` if the given key exists in the compiled translation map.\n *\n * Useful for conditional rendering or feature detection without triggering\n * a full translation lookup.\n *\n * @param key - The dot-path translation key to check.\n */\nexport function compiledHasKey(key: string): boolean {\n return currentMap.has(key);\n}\n\nexport function compiledTryTranslate(\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n return compiledTryTranslateFromMap(currentMap, key, params);\n}\n\nexport function compiledHasKeyInMap(\n map: CompiledTranslationMap,\n key: string,\n): boolean {\n return map.has(key);\n}\n\nexport function compiledTryTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n const value = map.get(key);\n if (value === undefined) return undefined;\n return params ? interpolate(value, params) : value;\n}\n\n/**\n * Resolves a translation key from the compiled flat map.\n *\n * Lookup is O(1) — no namespace inference, no dot-path traversal, no\n * fallback chain. If the key is found, its value is returned (with\n * optional `{{param}}` interpolation). If not found, `fallback` is used\n * (also interpolated if provided). If neither is available, the raw `key`\n * string is returned so the UI degrades gracefully.\n *\n * @param key - The dot-path translation key to look up.\n * @param params - Optional map of placeholder names to replacement values.\n * Placeholders are written as `{{name}}` or `{{ name }}`.\n * Placeholders whose name is absent from `params` are left\n * untouched in the output.\n * @param fallback - Optional string to use when `key` is not in the map.\n * Subject to the same `params` interpolation as a found value.\n * @returns The resolved (and optionally interpolated) string.\n */\nexport function compiledTranslate(\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n return compiledTranslateFromMap(currentMap, key, params, fallback);\n}\n\nexport function compiledTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n const value = map.get(key);\n\n if (value !== undefined) {\n return params ? interpolate(value, params) : value;\n }\n\n if (fallback !== undefined) {\n return params ? interpolate(fallback, params) : fallback;\n }\n\n return key;\n}\n\nexport async function loadCompiledManifest(\n url: string,\n): Promise<CompiledManifestModule> {\n const dynamicImport = new Function('u', 'return import(u)') as (\n specifier: string,\n ) => Promise<CompiledManifestModule>;\n return dynamicImport(url);\n}\n\n/**\n * Replaces all `{{placeholder}}` tokens in `text` with values from `params`.\n *\n * Tokens whose name is absent from `params` are left as-is. Matched values\n * are coerced to strings via `String()`.\n *\n * @param text - The template string containing zero or more placeholders.\n * @param params - The parameter map supplying replacement values.\n */\nfunction interpolate(text: string, params: Record<string, unknown>): string {\n return text.replace(PLACEHOLDER, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { I18nConfig, I18nInstance, NestedTranslations, KeyUsageEntry } from './types';\nimport { createStore } from './store';\nimport { resolveKey, inferNamespace, extractSubkey } from './resolver';\nimport { interpolate } from './interpolator';\nimport { fetchBundle, fetchNamespace } from './fetcher';\nimport {\n compiledHasKeyInMap,\n compiledTranslateFromMap,\n compiledTryTranslateFromMap,\n loadCompiledManifest,\n type CompiledManifestModule,\n type CompiledTranslationMap,\n} from './compiled-runtime';\n\n/**\n * Resolves the requestInit config value to a concrete RequestInit object.\n * Handles static objects, sync functions, and async functions.\n */\nexport async function resolveRequestInit(\n requestInit: RequestInit | (() => RequestInit | Promise<RequestInit>) | undefined,\n): Promise<RequestInit | undefined> {\n if (requestInit === undefined) return undefined;\n if (typeof requestInit === 'function') return requestInit();\n return requestInit;\n}\n\nfunction resolveRuntimeCache(config: I18nConfig) {\n const runtime = config.cache?.runtime;\n\n if (runtime === 'none') {\n return { strategy: 'none', eviction: 'none', pinDictionaries: false } as const;\n }\n\n if (runtime === 'memory' || runtime == null) {\n return { strategy: 'memory', eviction: 'none', pinDictionaries: true } as const;\n }\n\n return {\n strategy: runtime.strategy ?? 'memory',\n eviction: runtime.eviction ?? 'none',\n maxLocales: runtime.maxLocales,\n maxNamespaces: runtime.maxNamespaces,\n maxBytes: runtime.maxBytes,\n pinDictionaries: runtime.pinDictionaries ?? true,\n } as const;\n}\n\nfunction getInjectedI18nBase(): string | undefined {\n return typeof __VITE_I18N_BASE__ !== 'undefined'\n ? __VITE_I18N_BASE__\n : undefined;\n}\n\n/**\n * Resolves the base path for bundle fetches.\n * Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'\n */\nfunction resolveI18nBase(config: I18nConfig): string {\n return config.publicBase ?? getInjectedI18nBase() ?? '/__i18n';\n}\n\nfunction getInjectedCompiledManifestUrl(): string | undefined {\n return typeof __VITE_I18N_COMPILED_MANIFEST__ !== 'undefined'\n ? __VITE_I18N_COMPILED_MANIFEST__\n : undefined;\n}\n\nfunction shouldUseCompiledRuntime(config: I18nConfig, manifestUrl?: string): boolean {\n if (config.compiled?.enabled === false) return false;\n if (config.compiled?.enabled === true) return true;\n if (config.compiled?.enabled === 'auto') return !!manifestUrl;\n return !!manifestUrl;\n}\n\n/**\n * Creates and configures an i18n instance.\n *\n * This is the main entry point for setting up translations. It assembles\n * the resource store, key resolver, interpolator, and fetcher into a\n * single {@link I18nInstance} with a unified API.\n *\n * Translation loading uses bundles:\n * - **Named dictionaries** — one HTTP request per dictionary name\n * (`/__i18n/{locale}/_dict/{name}.json`), loaded in declaration order.\n * - **Scope bundles** — one HTTP request per page scope\n * (`/__i18n/{locale}/{scope}.json`).\n *\n * The dev plugin (`i18nDevPlugin`) serves these by combining individual\n * namespace JSON files on the fly.\n *\n * @param config - The i18n configuration\n * @returns A configured {@link I18nInstance}\n *\n * @example\n * ```ts\n * const i18n = createI18n({\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * localesDir: '/locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * });\n * ```\n */\nexport function createI18n(config: I18nConfig): I18nInstance {\n if (!config.locale || typeof config.locale !== 'string') {\n throw new Error('vite-bundled-i18n: locale must be a non-empty string');\n }\n if (!config.defaultLocale || typeof config.defaultLocale !== 'string') {\n throw new Error('vite-bundled-i18n: defaultLocale must be a non-empty string');\n }\n if (!Array.isArray(config.supportedLocales) || config.supportedLocales.length === 0) {\n throw new Error('vite-bundled-i18n: supportedLocales must be a non-empty array');\n }\n if (!config.supportedLocales.includes(config.defaultLocale)) {\n throw new Error(\n `vite-bundled-i18n: defaultLocale \"${config.defaultLocale}\" must be included in supportedLocales`,\n );\n }\n\n const store = createStore();\n const frozenConfig = Object.freeze({ ...config });\n const i18nBase = resolveI18nBase(config);\n const runtimeCache = resolveRuntimeCache(config);\n const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();\n const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);\n let compiledRuntimeActive = useCompiledRuntime;\n\n let currentLocale = config.locale;\n const localeListeners = new Set<(locale: string) => void>();\n\n /** Tracks which scopes have been loaded per locale. */\n const loadedScopes = new Set<string>();\n\n /** Tracks which named dictionaries have been loaded per locale. */\n const loadedDicts = new Set<string>();\n\n /** Key usage log for dev diagnostics. */\n const keyUsage: KeyUsageEntry[] = [];\n\n /** The current scope set by useI18n, used for key tracking. */\n let activeScope: string | undefined;\n /** Tracks whether a consolidated fetch error has been emitted. */\n let fetchErrorEmitted = false;\n\n /** Dedup set for dev-mode missing key warnings. */\n const warnedMissingKeys = new Set<string>();\n\n function handleFetchError(): void {\n if (!fetchErrorEmitted) {\n fetchErrorEmitted = true;\n console.error(\n 'vite-bundled-i18n: Cannot load translations. ' +\n 'Ensure __i18n assets are accessible at the configured base path. ' +\n 'Are you running the Vite dev server, or have you built with the i18n plugin?'\n );\n }\n }\n\n let compiledManifestPromise: Promise<CompiledManifestModule | null> | null = null;\n const compiledLocaleMaps = new Map<string, CompiledTranslationMap>();\n\n function getCompiledLocaleMap(locale: string): CompiledTranslationMap {\n const existing = compiledLocaleMaps.get(locale);\n if (existing) return existing;\n const created = new Map<string, string>();\n compiledLocaleMaps.set(locale, created);\n return created;\n }\n\n async function getCompiledManifest(): Promise<CompiledManifestModule | null> {\n if (!useCompiledRuntime) return null;\n if (!compiledManifestUrl && !config.compiled?.loadManifest) return null;\n if (!compiledManifestPromise) {\n const manifestLoader = config.compiled?.loadManifest\n ? config.compiled.loadManifest\n : () => loadCompiledManifest(compiledManifestUrl!);\n compiledManifestPromise = manifestLoader().catch((error) => {\n compiledRuntimeActive = false;\n console.warn(\n `vite-bundled-i18n: Failed to load compiled manifest from \"${compiledManifestUrl}\". Falling back to JSON bundles.`,\n error,\n );\n return null;\n });\n }\n return compiledManifestPromise;\n }\n\n async function loadCompiledModule(\n locale: string,\n loader: (() => Promise<{ default: CompiledTranslationMap }>) | undefined,\n ): Promise<boolean> {\n if (!loader) return false;\n const module = await loader();\n const localeMap = getCompiledLocaleMap(locale);\n for (const [key, value] of module.default) {\n localeMap.set(key, value);\n }\n return true;\n }\n\n function clearLoadMarkersForNamespace(locale: string, namespace: string): void {\n for (const scopeKey of [...loadedScopes]) {\n const [scopeLocale, scope] = scopeKey.split(':');\n if (scopeLocale !== locale || !scope) continue;\n const scopeNamespace = scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n if (scopeNamespace === namespace) {\n loadedScopes.delete(scopeKey);\n }\n }\n\n for (const dictKey of [...loadedDicts]) {\n const [dictLocale, dictName] = dictKey.split(':');\n if (dictLocale !== locale || !dictName) continue;\n const dict = config.dictionaries?.[dictName];\n if ((dict?.keys ?? []).includes(namespace)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function clearLoadMarkersForLocale(locale: string): void {\n for (const scopeKey of [...loadedScopes]) {\n if (scopeKey.startsWith(`${locale}:`)) {\n loadedScopes.delete(scopeKey);\n }\n }\n for (const dictKey of [...loadedDicts]) {\n if (dictKey.startsWith(`${locale}:`)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function evictUnused(): void {\n if (runtimeCache.strategy === 'none' || runtimeCache.eviction === 'none') {\n return;\n }\n\n const entries = store.getEntries();\n const nonPinned = entries\n .filter((entry) => !entry.pinned)\n .sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);\n\n const evictOne = () => {\n const candidate = nonPinned.shift();\n if (!candidate) return false;\n store.removeNamespace(candidate.locale, candidate.namespace);\n clearLoadMarkersForNamespace(candidate.locale, candidate.namespace);\n return true;\n };\n\n if (runtimeCache.maxLocales !== undefined) {\n while (store.getStats().totalLocales > runtimeCache.maxLocales) {\n const localeCandidates = new Map<string, number>();\n for (const entry of nonPinned) {\n const previous = localeCandidates.get(entry.locale) ?? Number.POSITIVE_INFINITY;\n localeCandidates.set(entry.locale, Math.min(previous, entry.lastAccessedAt));\n }\n\n const localeToEvict = [...localeCandidates.entries()]\n .filter(([locale]) => locale !== currentLocale)\n .sort((a, b) => a[1] - b[1])[0]?.[0];\n\n if (!localeToEvict) break;\n store.removeLocale(localeToEvict);\n clearLoadMarkersForLocale(localeToEvict);\n for (let i = nonPinned.length - 1; i >= 0; i--) {\n if (nonPinned[i].locale === localeToEvict) {\n nonPinned.splice(i, 1);\n }\n }\n }\n }\n\n if (runtimeCache.maxNamespaces !== undefined) {\n while (store.getStats().totalNamespaces > runtimeCache.maxNamespaces) {\n if (!evictOne()) break;\n }\n }\n\n if (runtimeCache.maxBytes !== undefined) {\n while (store.getStats().approxTotalBytes > runtimeCache.maxBytes) {\n if (!evictOne()) break;\n }\n }\n }\n\n /**\n * Resolves a fully qualified key against the store, with fallback chain.\n * Records the resolution in the key usage log for dev diagnostics.\n */\n function translate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n ): string {\n if (compiledRuntimeActive) {\n recordUsage(key, inferNamespace(key), locale, 'primary');\n return compiledTranslateFromMap(getCompiledLocaleMap(locale), key, params, fallback);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n\n if (!subkey) {\n recordUsage(key, namespace, locale, 'fallback-string');\n if (fallback !== undefined) return interpolate(fallback, params);\n return key;\n }\n\n // Try requested locale\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'primary');\n return interpolate(value, params);\n }\n }\n\n // Fallback to default locale\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-locale');\n return interpolate(value, params);\n }\n }\n }\n\n // Return fallback string or key\n if (fallback !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n\n recordUsage(key, namespace, locale, 'key-as-value');\n if (import.meta.env?.DEV && !warnedMissingKeys.has(key)) {\n warnedMissingKeys.add(key);\n console.warn(\n `vite-bundled-i18n: Missing translation for \"${key}\" in locale \"${locale}\". Returning key as fallback.`\n );\n }\n return key;\n }\n\n /** Records a key lookup for dev diagnostics. */\n function recordUsage(\n key: string,\n namespace: string,\n locale: string,\n resolvedFrom: KeyUsageEntry['resolvedFrom'],\n ): void {\n keyUsage.push({ key, namespace, locale, resolvedFrom, scope: activeScope });\n }\n\n function hasKey(locale: string, key: string): boolean {\n if (compiledRuntimeActive) {\n return compiledHasKeyInMap(getCompiledLocaleMap(locale), key);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return false;\n\n const data = store.getResource(locale, namespace);\n if (!data) return false;\n return resolveKey(data, subkey) !== undefined;\n }\n\n function tryTranslate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n ): string | undefined {\n if (compiledRuntimeActive) {\n return compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return undefined;\n\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Loads a single named dictionary bundle for a locale.\n * Fetches `/__i18n/{locale}/_dict/{name}.json` — one HTTP request\n * containing all namespaces for that dictionary.\n */\n async function loadDictionary(locale: string, name: string): Promise<void> {\n const dictKey = `${locale}:${name}`;\n if (loadedDicts.has(dictKey)) return;\n\n const dictConfig = config.dictionaries?.[name];\n if (!dictConfig) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.dictionaries?.[name]?.[locale]);\n if (loaded) {\n loadedDicts.add(dictKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'dictionary',\n pinned: runtimeCache.pinDictionaries,\n });\n }\n loadedDicts.add(dictKey);\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n\n /**\n * Loads all configured dictionaries for a locale, in declaration order.\n * Each dictionary is one HTTP request.\n */\n async function loadAllDictionaries(locale: string): Promise<void> {\n if (!config.dictionaries) return;\n\n // Load in declaration order, sequentially (priority matters)\n for (const name of Object.keys(config.dictionaries)) {\n await loadDictionary(locale, name);\n }\n }\n\n /**\n * Loads a page/scope bundle for a locale.\n * Fetches `/__i18n/{locale}/{scope}.json` — one HTTP request\n * containing all namespaces needed by that page.\n */\n async function loadScope(locale: string, scope: string): Promise<void> {\n const scopeKey = `${locale}:${scope}`;\n if (loadedScopes.has(scopeKey)) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.scopes?.[scope]?.[locale]);\n if (loaded) {\n loadedScopes.add(scopeKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, scope, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'scope',\n pinned: false,\n });\n }\n loadedScopes.add(scopeKey);\n evictUnused();\n } catch (error) {\n if (error instanceof Error && error.message.includes('404')) {\n loadedScopes.add(scopeKey);\n return;\n }\n handleFetchError();\n }\n }\n\n /**\n * Loads namespace files individually. Kept for testing and non-plugin usage.\n */\n async function loadNamespaces(\n locale: string,\n namespaces: string[],\n ): Promise<void> {\n for (const ns of namespaces) {\n if (!store.hasNamespace(locale, ns)) {\n try {\n const reqInit = await resolveRequestInit(config.requestInit);\n const data = await fetchNamespace(\n config.localesDir,\n locale,\n ns,\n reqInit,\n );\n store.addResources(locale, ns, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n }\n }\n\n function addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n ): void {\n store.addResources(locale, namespace, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n }\n\n function getResource(locale: string, namespace: string): NestedTranslations | undefined {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return undefined;\n const prefix = `${namespace}.`;\n const nested: NestedTranslations = {};\n let found = false;\n\n for (const [key, value] of localeMap.entries()) {\n if (!key.startsWith(prefix)) continue;\n found = true;\n const parts = key.slice(prefix.length).split('.');\n let current: NestedTranslations = nested;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const next = current[part];\n if (!next || typeof next === 'string') {\n current[part] = {};\n }\n current = current[part] as NestedTranslations;\n }\n current[parts[parts.length - 1]] = value;\n }\n\n return found ? nested : undefined;\n }\n\n return store.getResource(locale, namespace);\n }\n\n function getLoadedNamespaces(locale: string): string[] {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return [];\n return [...new Set([...localeMap.keys()].map((key) => inferNamespace(key)))];\n }\n\n return store.getEntries()\n .filter((entry) => entry.locale === locale)\n .map((entry) => entry.namespace);\n }\n\n function isNamespaceLoaded(locale: string, namespace: string): boolean {\n if (compiledRuntimeActive) {\n return getLoadedNamespaces(locale).includes(namespace);\n }\n return store.hasNamespace(locale, namespace);\n }\n\n function isScopeLoaded(locale: string, scope: string): boolean {\n return loadedScopes.has(`${locale}:${scope}`);\n }\n\n function getCacheStats() {\n if (compiledRuntimeActive) {\n const totalLocales = compiledLocaleMaps.size;\n const totalNamespaces = new Set(\n [...compiledLocaleMaps.values()].flatMap((map) =>\n [...map.keys()].map((key) => inferNamespace(key)),\n ),\n ).size;\n const approxTotalBytes = [...compiledLocaleMaps.values()].reduce(\n (sum, map) =>\n sum + [...map.entries()].reduce((inner, [key, value]) => inner + key.length + value.length, 0),\n 0,\n );\n\n return {\n totalLocales,\n totalNamespaces,\n approxTotalBytes,\n pinnedNamespaces: 0,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n const stats = store.getStats();\n return {\n ...stats,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n function unloadLocale(locale: string): void {\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n clearLoadMarkersForLocale(locale);\n return;\n }\n store.removeLocale(locale);\n clearLoadMarkersForLocale(locale);\n }\n\n function unloadNamespace(locale: string, namespace: string): void {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (localeMap) {\n for (const key of [...localeMap.keys()]) {\n if (key === namespace || key.startsWith(`${namespace}.`)) {\n localeMap.delete(key);\n }\n }\n }\n clearLoadMarkersForNamespace(locale, namespace);\n return;\n }\n store.removeNamespace(locale, namespace);\n clearLoadMarkersForNamespace(locale, namespace);\n }\n\n function getDictionaryNamespaces(): string[] {\n if (!config.dictionaries) return [];\n const seen = new Set<string>();\n const result: string[] = [];\n for (const dict of Object.values(config.dictionaries)) {\n const patterns = [\n ...(dict.keys ?? []),\n ...((dict.include ?? []).map((pattern) => {\n const namespacePart = pattern.split('.')[0];\n return namespacePart.endsWith('*') ? namespacePart.slice(0, -1) : namespacePart;\n })),\n ];\n for (const ns of patterns) {\n if (!seen.has(ns)) {\n seen.add(ns);\n result.push(ns);\n }\n }\n }\n return result;\n }\n\n function getDictionaryNames(): string[] {\n if (!config.dictionaries) return [];\n return Object.keys(config.dictionaries);\n }\n\n function getLocale(): string {\n return currentLocale;\n }\n\n /**\n * Switches the active locale. Loads all dictionaries and previously\n * loaded scopes for the new locale before notifying listeners.\n */\n async function changeLocale(locale: string): Promise<void> {\n if (locale === currentLocale) return;\n\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n }\n\n // Load all dictionaries for the new locale (one request per dictionary)\n await loadAllDictionaries(locale);\n\n // Reload all previously loaded scopes for the new locale\n const uniqueScopes = new Set<string>();\n for (const scopeKey of loadedScopes) {\n const colonIdx = scopeKey.indexOf(':');\n if (colonIdx !== -1) {\n uniqueScopes.add(scopeKey.slice(colonIdx + 1));\n }\n }\n await Promise.all(\n [...uniqueScopes].map((scope) => loadScope(locale, scope)),\n );\n\n currentLocale = locale;\n for (const listener of localeListeners) {\n listener(locale);\n }\n }\n\n function onLocaleChange(callback: (locale: string) => void): () => void {\n localeListeners.add(callback);\n return () => {\n localeListeners.delete(callback);\n };\n }\n\n function getKeyUsage(): KeyUsageEntry[] {\n return keyUsage;\n }\n\n return {\n config: frozenConfig,\n translate,\n tryTranslate,\n hasKey,\n loadNamespaces,\n loadDictionary,\n loadAllDictionaries,\n loadScope,\n addResources,\n getResource,\n getLoadedNamespaces,\n isNamespaceLoaded,\n isScopeLoaded,\n getCacheStats,\n unloadLocale,\n unloadNamespace,\n evictUnused,\n getDictionaryNamespaces,\n getDictionaryNames,\n getLocale,\n changeLocale,\n onLocaleChange,\n getKeyUsage,\n };\n}\n","import type { DictionaryConfig } from './types';\n\n/**\n * Shared i18n configuration used by both the runtime (`createI18n`) and\n * the Vite dev plugin (`i18nDevPlugin`). Define this once in a shared\n * file and import it in both places to prevent config drift.\n *\n * This is the subset of config that must be identical between the\n * runtime and the plugin. Runtime-only fields (like `locale`) are\n * not included here.\n */\nexport interface I18nSharedConfig {\n /** Path to the locales directory. Relative to project root for the plugin, URL path for the runtime. */\n localesDir: string;\n /** Named groups of namespaces. Must be identical between runtime and plugin. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Extraction configuration shared between the plugin and CLI. */\n extraction?: {\n /** Additional property names to scan as translation key fields. */\n keyFields?: string[];\n };\n}\n\n/**\n * Defines the shared i18n configuration.\n *\n * Use this to create a config object that is imported by both `createI18n()`\n * and `i18nDevPlugin()`, ensuring they stay in sync.\n *\n * @param config - The shared configuration\n * @returns The same config object (identity function for type safety and readability)\n *\n * @example\n * ```ts\n * // src/i18n.config.ts\n * import { defineI18nConfig } from 'vite-bundled-i18n';\n *\n * export const i18nConfig = defineI18nConfig({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * },\n * });\n * ```\n *\n * ```ts\n * // src/i18n.ts — runtime\n * import { createI18n } from 'vite-bundled-i18n';\n * import { i18nConfig } from './i18n.config';\n *\n * export const i18n = createI18n({\n * ...i18nConfig,\n * localesDir: '/' + i18nConfig.localesDir, // URL path for browser\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * });\n * ```\n *\n * ```ts\n * // vite.config.ts — plugin\n * import { i18nConfig } from './src/i18n.config';\n *\n * i18nDevPlugin(i18nConfig)\n * ```\n */\nexport function defineI18nConfig(config: I18nSharedConfig): I18nSharedConfig {\n validateConfig(config);\n return config;\n}\n\nfunction getDictionaryPatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nfunction isValidPattern(pattern: string): boolean {\n if (!pattern || typeof pattern !== 'string') return false;\n if (pattern.includes('*')) {\n return pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1;\n }\n return true;\n}\n\nfunction validateConfig(config: I18nSharedConfig): void {\n if (!config.localesDir || typeof config.localesDir !== 'string') {\n throw new Error('vite-bundled-i18n: localesDir must be a non-empty string');\n }\n\n if (config.dictionaries) {\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n const hasKeys = dict.keys !== undefined;\n const hasInclude = dict.include !== undefined;\n\n if (hasKeys && !Array.isArray(dict.keys)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have a keys array`);\n }\n if (hasInclude && !Array.isArray(dict.include)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have an include array`);\n }\n if (hasKeys && (dict.keys?.length ?? 0) === 0 && !hasInclude) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" has an empty keys array`);\n }\n if (hasKeys) {\n for (const key of dict.keys ?? []) {\n if (!key || typeof key !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key: ${JSON.stringify(key)}`);\n }\n }\n }\n if (hasInclude) {\n for (const pattern of dict.include ?? []) {\n if (!pattern || typeof pattern !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(pattern)}`);\n }\n }\n }\n\n const patterns = getDictionaryPatterns(dict);\n if (patterns.length === 0) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must define keys or include patterns`);\n }\n\n if (dict.priority !== undefined && typeof dict.priority !== 'number') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" priority must be a number`);\n }\n\n for (const key of patterns) {\n if (!isValidPattern(key)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(key)}`);\n }\n }\n }\n\n // Warn about duplicate patterns across dictionaries\n const seen = new Map<string, string>(); // pattern → first dictionary name\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n for (const pattern of getDictionaryPatterns(dict)) {\n const existing = seen.get(pattern);\n if (existing) {\n console.warn(\n `vite-bundled-i18n: pattern \"${pattern}\" appears in both dictionary \"${existing}\" and \"${name}\". This is allowed but may cause unexpected loading order.`,\n );\n } else {\n seen.set(pattern, name);\n }\n }\n }\n }\n}\n","import type { TranslationKey } from './types';\n\n/**\n * Marks a serializable data structure as i18n-owned without changing it.\n * Useful for navigation configs, tables, and other shared data files.\n */\nexport function defineI18nData<const T>(data: T): T {\n return data;\n}\n\n/**\n * Typed identity helper for translation keys in arbitrary field names.\n */\nexport function i18nKey<K extends TranslationKey>(key: K): K {\n return key;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkEA,SAAgB,cAA6B;CAC3C,MAAM,uBAAO,IAAI,KAAsC;CAEvD,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,gBAAgB,cACpB,KAAK,UAAU,UAAU,CAAC;AAE5B,QAAO;EACL,aAAa,QAAQ,WAAW,WAAW,SAAS;GAClD,IAAI,YAAY,KAAK,IAAI,OAAO;AAChC,OAAI,CAAC,WAAW;AACd,gCAAY,IAAI,KAAK;AACrB,SAAK,IAAI,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,qCAAqC,KAAK,UAAU,QAAQ,GAAG;;GAK5H,MAAM,WAAW,sBAAsB,KAAK;AAC5C,OAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,kCAAkC,KAAK,wCAAwC;AAGjG,OAAI,KAAK,aAAa,KAAA,KAAa,OAAO,KAAK,aAAa,SAC1D,OAAM,IAAI,MAAM,kCAAkC,KAAK,6BAA6B;AAGtF,QAAK,MAAM,OAAO,SAChB,KAAI,CAAC,eAAe,IAAI,CACtB,OAAM,IAAI,MAAM,kCAAkC,KAAK,qCAAqC,KAAK,UAAU,IAAI,GAAG;;EAMxH,MAAM,uBAAO,IAAI,KAAqB;AACtC,OAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,aAAa,CAC5D,MAAK,MAAM,WAAW,sBAAsB,KAAK,EAAE;GACjD,MAAM,WAAW,KAAK,IAAI,QAAQ;AAClC,OAAI,SACF,SAAQ,KACN,+BAA+B,QAAQ,gCAAgC,SAAS,SAAS,KAAK,4DAC/F;OAED,MAAK,IAAI,SAAS,KAAK;;;;;;;;;;AC1IjC,SAAgB,eAAwB,MAAY;AAClD,QAAO;;;;;AAMT,SAAgB,QAAkC,KAAW;AAC3D,QAAO"}
|
|
@@ -22,6 +22,10 @@ export interface MissingKeyEntry {
|
|
|
22
22
|
* translation files.
|
|
23
23
|
*/
|
|
24
24
|
export declare function generateMissing(analysis: ProjectAnalysis, availableKeys: Map<string, string[]>): {
|
|
25
|
+
summary?: {
|
|
26
|
+
total: number;
|
|
27
|
+
hint: string;
|
|
28
|
+
};
|
|
25
29
|
keys: MissingKeyEntry[];
|
|
26
30
|
};
|
|
27
31
|
/**
|
|
@@ -27,8 +27,8 @@ export declare function extractPlaceholders(text: string): string[];
|
|
|
27
27
|
* When this file is present in the project, `t('shar...')` autocompletes to
|
|
28
28
|
* `t('shared.ok')`. Without it, `t()` accepts any string.
|
|
29
29
|
*/
|
|
30
|
-
export declare function generateTypes(localesDir: string, defaultLocale: string): string;
|
|
30
|
+
export declare function generateTypes(localesDir: string, defaultLocale: string, scopes?: string[]): string;
|
|
31
31
|
/**
|
|
32
32
|
* Calls {@link generateTypes} and writes the result to `outPath`.
|
|
33
33
|
*/
|
|
34
|
-
export declare function writeTypes(localesDir: string, defaultLocale: string, outPath: string): void;
|
|
34
|
+
export declare function writeTypes(localesDir: string, defaultLocale: string, outPath: string, scopes?: string[]): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -17,4 +17,4 @@ export { defineI18nData, i18nKey } from './core/data';
|
|
|
17
17
|
export { t, hasKey, scopedT, setGlobalInstance, getGlobalTranslations } from './core/t';
|
|
18
18
|
export { initServerI18n } from './server';
|
|
19
19
|
export type { I18nSharedConfig, } from './core/config';
|
|
20
|
-
export type { NestedTranslations, I18nConfig, I18nInstance, DictionaryConfig, CacheConfig, RuntimeCacheConfig, CacheStats, CompiledConfig, I18nKeyMap, I18nParamsMap, Primitive, ParamsOf, TranslationKey, TFunction, TryTFunction, RequireTFunction, Translations, NamespacedTranslations, ScopedTFunction, UseI18nResult, KeyUsageEntry, } from './core/types';
|
|
20
|
+
export type { NestedTranslations, I18nConfig, I18nInstance, DictionaryConfig, CacheConfig, RuntimeCacheConfig, CacheStats, CompiledConfig, I18nKeyMap, I18nParamsMap, Primitive, ParamsOf, TranslationKey, TFunction, TryTFunction, RequireTFunction, Translations, NamespacedTranslations, ScopedTFunction, UseI18nResult, KeyUsageEntry, I18nScopeMap, ValidScope, } from './core/types';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-
|
|
1
|
+
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-DctljUuI.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
3
|
import { a as t, i as setGlobalInstance, n as hasKey, r as scopedT, t as getGlobalTranslations } from "./t-Bfb3ut7N.js";
|
|
4
|
-
import { n as initServerI18n } from "./server-
|
|
4
|
+
import { n as initServerI18n } from "./server-Ckj2GFmZ.js";
|
|
5
5
|
export { createI18n, createTranslations, defineI18nConfig, defineI18nData, getGlobalTranslations, getTranslations, hasKey, i18nKey, initServerI18n, scopedT, setGlobalInstance, t };
|
|
@@ -34,6 +34,7 @@ export interface EmitI18nBuildArtifactsResult {
|
|
|
34
34
|
generatedOutDir: string;
|
|
35
35
|
compiledOutDir?: string;
|
|
36
36
|
typesOutPath?: string;
|
|
37
|
+
warnings: string[];
|
|
37
38
|
}
|
|
38
39
|
export declare function emitI18nBuildArtifacts(options: EmitI18nBuildArtifactsOptions): EmitI18nBuildArtifactsResult;
|
|
39
40
|
export declare function i18nBuildPlugin(sharedConfig: I18nSharedConfig, buildConfig: I18nBuildPluginConfig): Plugin;
|
package/dist/plugin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-
|
|
1
|
+
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-Bf9fpAPX.js";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
//#region src/plugin/devPlugin.ts
|
|
@@ -107,6 +107,11 @@ function i18nDevPlugin(config) {
|
|
|
107
107
|
projectRoot = resolvedConfig.root;
|
|
108
108
|
},
|
|
109
109
|
configureServer(server) {
|
|
110
|
+
const localesPath = path.join(projectRoot, config.localesDir);
|
|
111
|
+
server.watcher.add(localesPath);
|
|
112
|
+
server.watcher.on("change", (filePath) => {
|
|
113
|
+
if (filePath.startsWith(localesPath) && filePath.endsWith(".json")) server.ws.send({ type: "full-reload" });
|
|
114
|
+
});
|
|
110
115
|
server.middlewares.use((req, res, next) => {
|
|
111
116
|
if (!req.url?.startsWith("/__i18n/")) return next();
|
|
112
117
|
const dictMatch = req.url.match(/^\/__i18n\/([^/]+)\/_dict\/([^/]+)\.json$/);
|
|
@@ -165,7 +170,10 @@ function emitI18nBuildArtifacts(options) {
|
|
|
165
170
|
outDir: assetsOutDir,
|
|
166
171
|
dictionaries: sharedConfig.dictionaries
|
|
167
172
|
});
|
|
168
|
-
if (buildConfig.emitTypes !== false)
|
|
173
|
+
if (buildConfig.emitTypes !== false) {
|
|
174
|
+
const scopeNames = analysis.routes.map((r) => r.routeId);
|
|
175
|
+
writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);
|
|
176
|
+
}
|
|
169
177
|
let compiledOutDir;
|
|
170
178
|
if (buildConfig.emitCompiled !== false) {
|
|
171
179
|
compiledOutDir = path.join(assetsOutDir, "compiled");
|
|
@@ -178,12 +186,25 @@ function emitI18nBuildArtifacts(options) {
|
|
|
178
186
|
});
|
|
179
187
|
}
|
|
180
188
|
if (buildConfig.emitReports !== false) generateReports(analysis, localesDir, buildConfig.defaultLocale, generatedOutDir, sharedConfig.dictionaries);
|
|
189
|
+
const warnings = [];
|
|
190
|
+
const totalExtractedKeys = analysis.allKeys.filter((k) => !k.dynamic).length;
|
|
191
|
+
const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);
|
|
192
|
+
if (totalExtractedKeys > 0 && totalBundledKeys === 0) {
|
|
193
|
+
const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);
|
|
194
|
+
let foundFiles = [];
|
|
195
|
+
try {
|
|
196
|
+
foundFiles = fs.readdirSync(localeCheckDir).filter((f) => f.endsWith(".json"));
|
|
197
|
+
} catch {}
|
|
198
|
+
const hint = foundFiles.length === 0 ? `No JSON files found in ${localeCheckDir}` : `Found ${foundFiles.length} file(s) but 0 keys matched`;
|
|
199
|
+
warnings.push(`vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\n Expected structure: ${localesDir}/{locale}/{namespace}.json\n ${hint}\n Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`);
|
|
200
|
+
}
|
|
181
201
|
return {
|
|
182
202
|
assetBundles: bundles.length,
|
|
183
203
|
assetsOutDir,
|
|
184
204
|
generatedOutDir,
|
|
185
205
|
compiledOutDir,
|
|
186
|
-
typesOutPath: buildConfig.emitTypes === false ? void 0 : typesOutPath
|
|
206
|
+
typesOutPath: buildConfig.emitTypes === false ? void 0 : typesOutPath,
|
|
207
|
+
warnings
|
|
187
208
|
};
|
|
188
209
|
}
|
|
189
210
|
function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
@@ -193,8 +214,13 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
193
214
|
name: "vite-bundled-i18n-build",
|
|
194
215
|
apply: "build",
|
|
195
216
|
config(config) {
|
|
196
|
-
const
|
|
197
|
-
|
|
217
|
+
const base = config.base ?? "/";
|
|
218
|
+
const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);
|
|
219
|
+
const i18nBase = joinPublicPath(base, assetsDir).replace(/\/$/, "");
|
|
220
|
+
return { define: {
|
|
221
|
+
__VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),
|
|
222
|
+
__VITE_I18N_BASE__: JSON.stringify(i18nBase)
|
|
223
|
+
} };
|
|
198
224
|
},
|
|
199
225
|
configResolved(config) {
|
|
200
226
|
resolvedConfig = config;
|
|
@@ -207,6 +233,7 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
207
233
|
sharedConfig,
|
|
208
234
|
buildConfig
|
|
209
235
|
});
|
|
236
|
+
for (const warning of result.warnings) resolvedConfig.logger.warn(warning);
|
|
210
237
|
resolvedConfig.logger.info(`vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`);
|
|
211
238
|
if (result.compiledOutDir) resolvedConfig.logger.info(`vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`);
|
|
212
239
|
if (result.typesOutPath) resolvedConfig.logger.info(`vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`);
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport type { I18nSharedConfig } from '../core/config';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function i18nDevPlugin(config: I18nDevPluginConfig): Plugin {\n let projectRoot = '';\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n projectRoot,\n config.localesDir,\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n */\n function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith('/__i18n/')) {\n return next();\n }\n\n // Named dictionary: /__i18n/{locale}/_dict/{name}.json\n const dictMatch = req.url.match(\n /^\\/__i18n\\/([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: /__i18n/{locale}/{scope}.json\n const scopeMatch = req.url.match(\n /^\\/__i18n\\/([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n}\n\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(rootDir, 'src', 'i18n-types.d.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath);\n }\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n return {\n assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n config(config) {\n const base = config.base ?? '/';\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [i18nDevPlugin(sharedConfig)];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,cAAc,QAAqC;CACjE,IAAI,cAAc;;;;;CAMlB,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;AAClD,UAAO,KAAK,MAAM,QAAQ;UACpB;AACN;;;;;;;CAQJ,SAAS,sBACP,QACA,UACyB;EACzB,MAAM,OAAO,sBAAsB,OAAO,aAAa,CAAC,MAAM,UAAU,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xJH,SAAgB,WACd,cACA,aACgB;CAChB,MAAM,UAA0B,CAAC,cAAc,aAAa,CAAC;AAE7D,KAAI,YACF,SAAQ,KAAK,gBAAgB,cAAc,YAAY,CAAC;AAG1D,QAAO"}
|
|
1
|
+
{"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport type { I18nSharedConfig } from '../core/config';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function i18nDevPlugin(config: I18nDevPluginConfig): Plugin {\n let projectRoot = '';\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n projectRoot,\n config.localesDir,\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n */\n function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n // Watch locale files for changes and trigger reload\n const localesPath = path.join(projectRoot, config.localesDir);\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith('/__i18n/')) {\n return next();\n }\n\n // Named dictionary: /__i18n/{locale}/_dict/{name}.json\n const dictMatch = req.url.match(\n /^\\/__i18n\\/([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: /__i18n/{locale}/{scope}.json\n const scopeMatch = req.url.match(\n /^\\/__i18n\\/([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(rootDir, 'src', 'i18n-types.d.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\n }\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n config(config) {\n const base = config.base ?? '/';\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [i18nDevPlugin(sharedConfig)];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,cAAc,QAAqC;CACjE,IAAI,cAAc;;;;;CAMlB,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;AAClD,UAAO,KAAK,MAAM,QAAQ;UACpB;AACN;;;;;;;CAQJ,SAAS,sBACP,QACA,UACyB;EACzB,MAAM,OAAO,sBAAsB,OAAO,aAAa,CAAC,MAAM,UAAU,MAAM,SAAS,SAAS;AAChG,MAAI,CAAC,KAAM,QAAO,EAAE;EAEpB,MAAM,YAAY,KAAK,KAAK,aAAa,OAAO,YAAY,OAAO;EACnE,IAAI,QAAkB,EAAE;AACxB,MAAI;AACF,WAAQ,GAAG,YAAY,UAAU,CAAC,QAAQ,SAAS,KAAK,SAAS,QAAQ,CAAC;UACpE;AACN,UAAO,EAAE;;EAGX,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,KAAK,KA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C,QAAQ,OAAO,GAAG;AACnE,UAAO,EACL,QAAQ;IACN,iCAAiC,KAAK,UAAU,YAAY;IAC5D,oBAAoB,KAAK,UAAU,SAAS;IAC7C,EACF;;EAEH,eAAe,QAAQ;AACrB,oBAAiB;;EAEnB,cAAc;AACZ,OAAI,CAAC,eAAgB;GAErB,MAAM,SAAS,uBAAuB;IACpC,SAAS,eAAe;IACxB,YAAY,KAAK,QAAQ,eAAe,MAAM,eAAe,MAAM,OAAO;IAC1E;IACA;IACD,CAAC;AAEF,QAAK,MAAM,WAAW,OAAO,SAC3B,gBAAe,OAAO,KAAK,QAAQ;AAGrC,kBAAe,OAAO,KACpB,8BAA8B,OAAO,aAAa,2BAA2B,KAAK,SAAS,eAAe,MAAM,OAAO,aAAa,GACrI;AACD,OAAI,OAAO,eACT,gBAAe,OAAO,KACpB,0DAA0D,KAAK,SAAS,eAAe,MAAM,OAAO,eAAe,GACpH;AAEH,OAAI,OAAO,aACT,gBAAe,OAAO,KACpB,uCAAuC,KAAK,SAAS,eAAe,MAAM,OAAO,aAAa,GAC/F;;EAGN;;;;AC3LH,SAAgB,WACd,cACA,aACgB;CAChB,MAAM,UAA0B,CAAC,cAAc,aAAa,CAAC;AAE7D,KAAI,YACF,SAAQ,KAAK,gBAAgB,cAAc,YAAY,CAAC;AAG1D,QAAO"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
export interface I18nBoundaryProps {
|
|
3
|
+
/** Scope to load (e.g., 'products.index') */
|
|
4
|
+
scope: string;
|
|
5
|
+
/** Rendered while translations are loading */
|
|
6
|
+
fallback?: ReactNode;
|
|
7
|
+
/** Rendered once translations are ready */
|
|
8
|
+
children: ReactNode;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Boundary component that handles translation loading.
|
|
12
|
+
* Children only render once the scope is ready, avoiding
|
|
13
|
+
* rules-of-hooks violations from early returns in child components.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```tsx
|
|
17
|
+
* <I18nBoundary scope="products.index" fallback={<Spinner />}>
|
|
18
|
+
* <ProductsPage />
|
|
19
|
+
* </I18nBoundary>
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function I18nBoundary({ scope, fallback, children }: I18nBoundaryProps): import("react/jsx-runtime").JSX.Element;
|
package/dist/react/useI18n.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { UseI18nResult } from '../core/types';
|
|
1
|
+
import type { UseI18nResult, ValidScope } from '../core/types';
|
|
2
2
|
/**
|
|
3
3
|
* React hook for accessing translations.
|
|
4
4
|
*
|
|
@@ -30,4 +30,4 @@ import type { UseI18nResult } from '../core/types';
|
|
|
30
30
|
* t('shared.ok', 'OK'); // dictionaries still work
|
|
31
31
|
* ```
|
|
32
32
|
*/
|
|
33
|
-
export declare function useI18n(scope?:
|
|
33
|
+
export declare function useI18n(scope?: ValidScope): UseI18nResult;
|
package/dist/react.d.ts
CHANGED
|
@@ -9,3 +9,5 @@
|
|
|
9
9
|
export { I18nProvider } from './react/I18nProvider';
|
|
10
10
|
export { useI18n } from './react/useI18n';
|
|
11
11
|
export { DevToolbar } from './react/DevToolbar';
|
|
12
|
+
export { I18nBoundary } from './react/I18nBoundary';
|
|
13
|
+
export type { I18nBoundaryProps } from './react/I18nBoundary';
|