vite-bundled-i18n 0.1.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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +322 -0
  3. package/dist/cli/commands.d.ts +46 -0
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +231 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/core/args.d.ts +15 -0
  8. package/dist/core/compiled-runtime.d.ts +75 -0
  9. package/dist/core/config.d.ts +65 -0
  10. package/dist/core/createI18n.d.ts +40 -0
  11. package/dist/core/data.d.ts +10 -0
  12. package/dist/core/fetcher.d.ts +5 -0
  13. package/dist/core/getTranslations.d.ts +20 -0
  14. package/dist/core/interpolator.d.ts +27 -0
  15. package/dist/core/resolver.d.ts +51 -0
  16. package/dist/core/store.d.ts +61 -0
  17. package/dist/core/t.d.ts +53 -0
  18. package/dist/core/types.d.ts +396 -0
  19. package/dist/data-Trz4mxne.js +894 -0
  20. package/dist/data-Trz4mxne.js.map +1 -0
  21. package/dist/extractor/ast-utils.d.ts +19 -0
  22. package/dist/extractor/bundle-generator.d.ts +46 -0
  23. package/dist/extractor/compiler.d.ts +47 -0
  24. package/dist/extractor/dictionary-ownership.d.ts +18 -0
  25. package/dist/extractor/extract.d.ts +12 -0
  26. package/dist/extractor/patterns.d.ts +10 -0
  27. package/dist/extractor/reports.d.ts +109 -0
  28. package/dist/extractor/scope-bundles.d.ts +9 -0
  29. package/dist/extractor/type-generator.d.ts +34 -0
  30. package/dist/extractor/types.d.ts +45 -0
  31. package/dist/extractor/walker-types.d.ts +44 -0
  32. package/dist/extractor/walker.d.ts +38 -0
  33. package/dist/getTranslations-D3q3OBTn.js +120 -0
  34. package/dist/getTranslations-D3q3OBTn.js.map +1 -0
  35. package/dist/index.d.ts +20 -0
  36. package/dist/index.js +5 -0
  37. package/dist/plugin/buildPlugin.d.ts +39 -0
  38. package/dist/plugin/devPlugin.d.ts +51 -0
  39. package/dist/plugin.d.ts +16 -0
  40. package/dist/plugin.js +226 -0
  41. package/dist/plugin.js.map +1 -0
  42. package/dist/react/DevToolbar.d.ts +22 -0
  43. package/dist/react/I18nProvider.d.ts +20 -0
  44. package/dist/react/context.d.ts +19 -0
  45. package/dist/react/useI18n.d.ts +33 -0
  46. package/dist/react.d.ts +11 -0
  47. package/dist/react.js +626 -0
  48. package/dist/react.js.map +1 -0
  49. package/dist/server-BpEocC73.js +58 -0
  50. package/dist/server-BpEocC73.js.map +1 -0
  51. package/dist/server-entry.d.ts +7 -0
  52. package/dist/server.d.ts +22 -0
  53. package/dist/server.js +4 -0
  54. package/dist/t-Bfb3ut7N.js +75 -0
  55. package/dist/t-Bfb3ut7N.js.map +1 -0
  56. package/dist/vanilla.d.ts +43 -0
  57. package/dist/vanilla.js +39 -0
  58. package/dist/vanilla.js.map +1 -0
  59. package/dist/vue.d.ts +31 -0
  60. package/dist/vue.js +87 -0
  61. package/dist/vue.js.map +1 -0
  62. package/dist/walker-DqlV3VrX.js +1307 -0
  63. package/dist/walker-DqlV3VrX.js.map +1 -0
  64. package/package.json +121 -0
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Compiled runtime for i18n production mode.
3
+ *
4
+ * Replaces the full store + resolver + fetcher stack with a single flat
5
+ * `Map<string, string>` that is populated at build time. Lookups are O(1)
6
+ * — no namespace inference, no dot-path traversal, no fallback chain.
7
+ */
8
+ export type CompiledTranslationMap = Map<string, string>;
9
+ export type CompiledModuleLoader = () => Promise<{
10
+ default: CompiledTranslationMap;
11
+ }>;
12
+ export interface CompiledManifestModule {
13
+ scopes: Record<string, Record<string, CompiledModuleLoader>>;
14
+ dictionaries?: Record<string, Record<string, CompiledModuleLoader>>;
15
+ }
16
+ /**
17
+ * Replaces the active translation map entirely.
18
+ *
19
+ * Intended to be called once per locale load (e.g. on app boot or locale
20
+ * switch). The map is copied so that mutations to the original do not
21
+ * affect the runtime state.
22
+ *
23
+ * @param map - A flat `Map` of dot-path translation keys to their string values.
24
+ */
25
+ export declare function setTranslations(map: Map<string, string>): void;
26
+ /**
27
+ * Merges additional translations into the current map.
28
+ *
29
+ * Existing keys are overwritten if they appear in the incoming map. This
30
+ * is used when loading scope bundles (e.g. lazy-loaded route namespaces)
31
+ * on top of a base dictionary that was set via {@link setTranslations}.
32
+ *
33
+ * @param map - A flat `Map` of dot-path translation keys to merge in.
34
+ */
35
+ export declare function mergeTranslations(map: Map<string, string>): void;
36
+ /**
37
+ * Clears all translations from the runtime map.
38
+ *
39
+ * Resets state to an empty map. Primarily intended for use in tests via
40
+ * `beforeEach` to ensure isolation between test cases.
41
+ */
42
+ export declare function clearTranslations(): void;
43
+ /**
44
+ * Returns `true` if the given key exists in the compiled translation map.
45
+ *
46
+ * Useful for conditional rendering or feature detection without triggering
47
+ * a full translation lookup.
48
+ *
49
+ * @param key - The dot-path translation key to check.
50
+ */
51
+ export declare function compiledHasKey(key: string): boolean;
52
+ export declare function compiledTryTranslate(key: string, params?: Record<string, unknown>): string | undefined;
53
+ export declare function compiledHasKeyInMap(map: CompiledTranslationMap, key: string): boolean;
54
+ export declare function compiledTryTranslateFromMap(map: CompiledTranslationMap, key: string, params?: Record<string, unknown>): string | undefined;
55
+ /**
56
+ * Resolves a translation key from the compiled flat map.
57
+ *
58
+ * Lookup is O(1) — no namespace inference, no dot-path traversal, no
59
+ * fallback chain. If the key is found, its value is returned (with
60
+ * optional `{{param}}` interpolation). If not found, `fallback` is used
61
+ * (also interpolated if provided). If neither is available, the raw `key`
62
+ * string is returned so the UI degrades gracefully.
63
+ *
64
+ * @param key - The dot-path translation key to look up.
65
+ * @param params - Optional map of placeholder names to replacement values.
66
+ * Placeholders are written as `{{name}}` or `{{ name }}`.
67
+ * Placeholders whose name is absent from `params` are left
68
+ * untouched in the output.
69
+ * @param fallback - Optional string to use when `key` is not in the map.
70
+ * Subject to the same `params` interpolation as a found value.
71
+ * @returns The resolved (and optionally interpolated) string.
72
+ */
73
+ export declare function compiledTranslate(key: string, params?: Record<string, unknown>, fallback?: string): string;
74
+ export declare function compiledTranslateFromMap(map: CompiledTranslationMap, key: string, params?: Record<string, unknown>, fallback?: string): string;
75
+ export declare function loadCompiledManifest(url: string): Promise<CompiledManifestModule>;
@@ -0,0 +1,65 @@
1
+ import type { DictionaryConfig } from './types';
2
+ /**
3
+ * Shared i18n configuration used by both the runtime (`createI18n`) and
4
+ * the Vite dev plugin (`i18nDevPlugin`). Define this once in a shared
5
+ * file and import it in both places to prevent config drift.
6
+ *
7
+ * This is the subset of config that must be identical between the
8
+ * runtime and the plugin. Runtime-only fields (like `locale`) are
9
+ * not included here.
10
+ */
11
+ export interface I18nSharedConfig {
12
+ /** Path to the locales directory. Relative to project root for the plugin, URL path for the runtime. */
13
+ localesDir: string;
14
+ /** Named groups of namespaces. Must be identical between runtime and plugin. */
15
+ dictionaries?: Record<string, DictionaryConfig>;
16
+ /** Extraction configuration shared between the plugin and CLI. */
17
+ extraction?: {
18
+ /** Additional property names to scan as translation key fields. */
19
+ keyFields?: string[];
20
+ };
21
+ }
22
+ /**
23
+ * Defines the shared i18n configuration.
24
+ *
25
+ * Use this to create a config object that is imported by both `createI18n()`
26
+ * and `i18nDevPlugin()`, ensuring they stay in sync.
27
+ *
28
+ * @param config - The shared configuration
29
+ * @returns The same config object (identity function for type safety and readability)
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * // src/i18n.config.ts
34
+ * import { defineI18nConfig } from 'vite-bundled-i18n';
35
+ *
36
+ * export const i18nConfig = defineI18nConfig({
37
+ * localesDir: 'locales',
38
+ * dictionaries: {
39
+ * global: { keys: ['shared', 'global', 'actions'] },
40
+ * },
41
+ * });
42
+ * ```
43
+ *
44
+ * ```ts
45
+ * // src/i18n.ts — runtime
46
+ * import { createI18n } from 'vite-bundled-i18n';
47
+ * import { i18nConfig } from './i18n.config';
48
+ *
49
+ * export const i18n = createI18n({
50
+ * ...i18nConfig,
51
+ * localesDir: '/' + i18nConfig.localesDir, // URL path for browser
52
+ * locale: 'en',
53
+ * defaultLocale: 'en',
54
+ * supportedLocales: ['en', 'bg'],
55
+ * });
56
+ * ```
57
+ *
58
+ * ```ts
59
+ * // vite.config.ts — plugin
60
+ * import { i18nConfig } from './src/i18n.config';
61
+ *
62
+ * i18nDevPlugin(i18nConfig)
63
+ * ```
64
+ */
65
+ export declare function defineI18nConfig(config: I18nSharedConfig): I18nSharedConfig;
@@ -0,0 +1,40 @@
1
+ import type { I18nConfig, I18nInstance } from './types';
2
+ /**
3
+ * Resolves the requestInit config value to a concrete RequestInit object.
4
+ * Handles static objects, sync functions, and async functions.
5
+ */
6
+ export declare function resolveRequestInit(requestInit: RequestInit | (() => RequestInit | Promise<RequestInit>) | undefined): Promise<RequestInit | undefined>;
7
+ /**
8
+ * Creates and configures an i18n instance.
9
+ *
10
+ * This is the main entry point for setting up translations. It assembles
11
+ * the resource store, key resolver, interpolator, and fetcher into a
12
+ * single {@link I18nInstance} with a unified API.
13
+ *
14
+ * Translation loading uses bundles:
15
+ * - **Named dictionaries** — one HTTP request per dictionary name
16
+ * (`/__i18n/{locale}/_dict/{name}.json`), loaded in declaration order.
17
+ * - **Scope bundles** — one HTTP request per page scope
18
+ * (`/__i18n/{locale}/{scope}.json`).
19
+ *
20
+ * The dev plugin (`i18nDevPlugin`) serves these by combining individual
21
+ * namespace JSON files on the fly.
22
+ *
23
+ * @param config - The i18n configuration
24
+ * @returns A configured {@link I18nInstance}
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const i18n = createI18n({
29
+ * locale: 'en',
30
+ * defaultLocale: 'en',
31
+ * supportedLocales: ['en', 'bg'],
32
+ * localesDir: '/locales',
33
+ * dictionaries: {
34
+ * global: { keys: ['shared', 'global', 'actions'] },
35
+ * admin: { keys: ['admin'] },
36
+ * },
37
+ * });
38
+ * ```
39
+ */
40
+ export declare function createI18n(config: I18nConfig): I18nInstance;
@@ -0,0 +1,10 @@
1
+ import type { TranslationKey } from './types';
2
+ /**
3
+ * Marks a serializable data structure as i18n-owned without changing it.
4
+ * Useful for navigation configs, tables, and other shared data files.
5
+ */
6
+ export declare function defineI18nData<const T>(data: T): T;
7
+ /**
8
+ * Typed identity helper for translation keys in arbitrary field names.
9
+ */
10
+ export declare function i18nKey<K extends TranslationKey>(key: K): K;
@@ -0,0 +1,5 @@
1
+ import type { NestedTranslations } from './types';
2
+ export declare function buildLoadPath(localesDir: string, locale: string, namespace: string): string;
3
+ export declare function buildBundlePath(locale: string, bundleName: string): string;
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>>;
@@ -0,0 +1,20 @@
1
+ import type { I18nInstance, Translations } from './types';
2
+ interface GetTranslationsOptions {
3
+ /** Override the locale. Defaults to the instance's current locale. */
4
+ locale?: string;
5
+ }
6
+ export declare function createTranslations(instance: I18nInstance, locale: string): Translations;
7
+ /**
8
+ * Loads translations and returns a translation function — no React context needed.
9
+ *
10
+ * Works in server components, API routes, scripts, SSR, or any context
11
+ * where React hooks aren't available. Ensures dictionaries (and optionally
12
+ * a scope bundle) are loaded before returning.
13
+ *
14
+ * @param instance - The i18n instance from createI18n()
15
+ * @param scope - Optional scope to load (e.g., 'products.show')
16
+ * @param options - Optional settings (locale override)
17
+ * @returns Object with t function, locale, and hasKey
18
+ */
19
+ export declare function getTranslations(instance: I18nInstance, scope?: string, options?: GetTranslationsOptions): Promise<Translations>;
20
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Replaces `{{paramName}}` placeholders in a translation string with
3
+ * values from the provided params object.
4
+ *
5
+ * Rules:
6
+ * - `{{param}}` and `{{ param }}` both resolve to the `param` key
7
+ * - Missing params leave the placeholder as-is (aids debugging)
8
+ * - Values are converted to strings via `String(value)`
9
+ * - If no params are provided, the string is returned unchanged
10
+ *
11
+ * @param text - The translation string containing `{{placeholders}}`
12
+ * @param params - Optional object mapping parameter names to values
13
+ * @returns The interpolated string
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * interpolate('Hello {{name}}', { name: 'Alice' });
18
+ * // 'Hello Alice'
19
+ *
20
+ * interpolate('Price: {{amount}}', { amount: 29.99 });
21
+ * // 'Price: 29.99'
22
+ *
23
+ * interpolate('Hello {{name}}', {});
24
+ * // 'Hello {{name}}' — missing param left as-is
25
+ * ```
26
+ */
27
+ export declare function interpolate(text: string, params?: Record<string, unknown>): string;
@@ -0,0 +1,51 @@
1
+ import type { NestedTranslations } from './types';
2
+ /**
3
+ * Extracts the namespace from a fully qualified key.
4
+ *
5
+ * The namespace is the first dot-separated segment. This determines
6
+ * which JSON file to load (e.g., `'products'` loads `products.json`).
7
+ *
8
+ * @param key - Fully qualified key (e.g., `'products.show.title'`)
9
+ * @returns The namespace name (e.g., `'products'`)
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * inferNamespace('products.show.title'); // 'products'
14
+ * inferNamespace('shared.ok'); // 'shared'
15
+ * inferNamespace('checkout'); // 'checkout'
16
+ * ```
17
+ */
18
+ export declare function inferNamespace(key: string): string;
19
+ /**
20
+ * Extracts the subkey path from a fully qualified key (everything after the namespace).
21
+ *
22
+ * @param key - Fully qualified key (e.g., `'products.show.title'`)
23
+ * @returns The subkey path (e.g., `'show.title'`), or empty string if no subkey
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * extractSubkey('products.show.title'); // 'show.title'
28
+ * extractSubkey('shared.ok'); // 'ok'
29
+ * extractSubkey('checkout'); // ''
30
+ * ```
31
+ */
32
+ export declare function extractSubkey(key: string): string;
33
+ /**
34
+ * Resolves a dot-separated key path against a nested translations object.
35
+ *
36
+ * Traverses the object tree following each segment of the key path.
37
+ * Returns the string value at the leaf, or `undefined` if the path
38
+ * doesn't exist or resolves to a non-string (branch node).
39
+ *
40
+ * @param data - The nested translations object to search
41
+ * @param keyPath - Dot-separated path (e.g., `'show.title'`)
42
+ * @returns The translated string, or `undefined` if not found
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const data = { show: { title: 'Product Details' } };
47
+ * resolveKey(data, 'show.title'); // 'Product Details'
48
+ * resolveKey(data, 'show.missing'); // undefined
49
+ * ```
50
+ */
51
+ export declare function resolveKey(data: NestedTranslations, keyPath: string): string | undefined;
@@ -0,0 +1,61 @@
1
+ import type { NestedTranslations } from './types';
2
+ type StoreSource = 'dictionary' | 'scope' | 'manual';
3
+ interface StoreEntry {
4
+ locale: string;
5
+ namespace: string;
6
+ data: NestedTranslations;
7
+ source: StoreSource;
8
+ pinned: boolean;
9
+ lastAccessedAt: number;
10
+ approxSize: number;
11
+ }
12
+ interface StoreStats {
13
+ totalLocales: number;
14
+ totalNamespaces: number;
15
+ approxTotalBytes: number;
16
+ pinnedNamespaces: number;
17
+ }
18
+ /**
19
+ * The resource store's public interface.
20
+ * Manages an in-memory map of `locale → namespace → translations`.
21
+ */
22
+ export interface ResourceStore {
23
+ /** Stores translation data for a locale and namespace. Overwrites if already present. */
24
+ addResources: (locale: string, namespace: string, data: NestedTranslations, options?: {
25
+ source?: StoreSource;
26
+ pinned?: boolean;
27
+ }) => void;
28
+ /** Retrieves translation data for a locale and namespace. Returns undefined if not loaded. */
29
+ getResource: (locale: string, namespace: string) => NestedTranslations | undefined;
30
+ /** Checks whether a namespace has been loaded for a locale. */
31
+ hasNamespace: (locale: string, namespace: string) => boolean;
32
+ /** Removes a namespace from a locale. */
33
+ removeNamespace: (locale: string, namespace: string) => void;
34
+ /** Removes an entire locale from the store. */
35
+ removeLocale: (locale: string) => void;
36
+ /** Returns cache metadata for all entries. */
37
+ getEntries: () => StoreEntry[];
38
+ /** Returns store-level stats. */
39
+ getStats: () => StoreStats;
40
+ /** Removes all stored translation data. */
41
+ clear: () => void;
42
+ }
43
+ /**
44
+ * Creates a new in-memory resource store.
45
+ *
46
+ * The store holds loaded translation data in a two-level map:
47
+ * `locale → namespace → NestedTranslations`. It provides no fetching logic —
48
+ * data is added externally via `addResources` after being loaded by the fetcher.
49
+ *
50
+ * @returns A {@link ResourceStore} instance
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * const store = createStore();
55
+ * store.addResources('en', 'shared', { ok: 'OK', cancel: 'Cancel' });
56
+ * store.getResource('en', 'shared'); // { ok: 'OK', cancel: 'Cancel' }
57
+ * store.hasNamespace('en', 'shared'); // true
58
+ * ```
59
+ */
60
+ export declare function createStore(): ResourceStore;
61
+ export {};
@@ -0,0 +1,53 @@
1
+ import type { I18nInstance, TFunction, ScopedTFunction, Translations } from './types';
2
+ export { resolveArgs } from './args';
3
+ /**
4
+ * Registers the global i18n instance used by the module-level `t()`, `hasKey()`,
5
+ * and `scopedT()` functions.
6
+ *
7
+ * Called automatically by `I18nProvider` on mount. You only need to call this
8
+ * directly if using the global functions outside of React.
9
+ *
10
+ * @param instance - The instance returned by `createI18n()`
11
+ */
12
+ export declare function setGlobalInstance(instance: I18nInstance): void;
13
+ export declare function getGlobalTranslations(): Translations;
14
+ /**
15
+ * Global translation function.
16
+ *
17
+ * Translates a fully qualified key using the global i18n instance.
18
+ * Supports two calling conventions:
19
+ * - `t(key, fallback?)` — when no interpolation is needed
20
+ * - `t(key, params, fallback?)` — when interpolation parameters are needed
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * t('shared.ok', 'OK');
25
+ * t('products.show.price', { amount: 29.99 }, 'Price: {{amount}}');
26
+ * ```
27
+ */
28
+ export declare const t: TFunction;
29
+ /**
30
+ * Checks whether a translation key exists in the currently loaded translations
31
+ * for the active locale.
32
+ *
33
+ * @param key - Fully qualified key path (e.g., `'products.show.title'`)
34
+ * @returns `true` if the key exists, `false` otherwise
35
+ */
36
+ export declare function hasKey(key: string): boolean;
37
+ /**
38
+ * Creates a translation function fixed to a specific language and namespace.
39
+ *
40
+ * Useful for SSR, emails, or other contexts outside the React tree.
41
+ *
42
+ * @param language - Locale code (e.g., `'bg'`)
43
+ * @param namespace - Namespace to bind to (e.g., `'products'`)
44
+ * @param keyPrefix - Optional key prefix to prepend
45
+ * @returns A `TFunction` bound to the specified language and namespace
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const tBulgarian = scopedT('bg', 'products', 'show');
50
+ * tBulgarian('title'); // resolves 'products.show.title' in Bulgarian
51
+ * ```
52
+ */
53
+ export declare function scopedT(language: string, namespace: string, keyPrefix?: string): ScopedTFunction;