i18n-json-react 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +401 -2
- package/bundlers/shared.cjs +92 -0
- package/dist/cjs/api-types.d.ts +17 -0
- package/dist/cjs/api-types.d.ts.map +1 -0
- package/dist/cjs/api-types.js +3 -0
- package/dist/cjs/api-types.js.map +1 -0
- package/dist/cjs/core.d.ts +10 -0
- package/dist/cjs/core.d.ts.map +1 -0
- package/dist/cjs/core.js +31 -0
- package/dist/cjs/core.js.map +1 -0
- package/dist/cjs/default-store.d.ts +7 -0
- package/dist/cjs/default-store.d.ts.map +1 -0
- package/dist/cjs/default-store.js +96 -0
- package/dist/cjs/default-store.js.map +1 -0
- package/dist/cjs/dictionaries.d.ts +7 -0
- package/dist/cjs/dictionaries.d.ts.map +1 -0
- package/dist/cjs/dictionaries.js +31 -0
- package/dist/cjs/dictionaries.js.map +1 -0
- package/dist/cjs/index.d.ts +24 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +38 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/interpolation.d.ts +6 -0
- package/dist/cjs/interpolation.d.ts.map +1 -0
- package/dist/cjs/interpolation.js +26 -0
- package/dist/cjs/interpolation.js.map +1 -0
- package/dist/cjs/languages.d.ts +4 -0
- package/dist/cjs/languages.d.ts.map +1 -0
- package/dist/cjs/languages.js +61 -0
- package/dist/cjs/languages.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/react.d.ts +15 -0
- package/dist/cjs/react.d.ts.map +1 -0
- package/dist/cjs/react.js +54 -0
- package/dist/cjs/react.js.map +1 -0
- package/dist/cjs/resource.d.ts +8 -0
- package/dist/cjs/resource.d.ts.map +1 -0
- package/dist/cjs/resource.js +34 -0
- package/dist/cjs/resource.js.map +1 -0
- package/dist/cjs/store-types.d.ts +10 -0
- package/dist/cjs/store-types.d.ts.map +1 -0
- package/dist/cjs/store-types.js +17 -0
- package/dist/cjs/store-types.js.map +1 -0
- package/dist/cjs/store.d.ts +24 -0
- package/dist/cjs/store.d.ts.map +1 -0
- package/dist/cjs/store.js +139 -0
- package/dist/cjs/store.js.map +1 -0
- package/dist/cjs/typed-react.d.ts +5 -0
- package/dist/cjs/typed-react.d.ts.map +1 -0
- package/dist/cjs/typed-react.js +23 -0
- package/dist/cjs/typed-react.js.map +1 -0
- package/dist/cjs/types.d.ts +91 -0
- package/dist/cjs/types.d.ts.map +1 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/esm/api-types.d.ts +17 -0
- package/dist/esm/api-types.d.ts.map +1 -0
- package/dist/esm/api-types.js +2 -0
- package/dist/esm/api-types.js.map +1 -0
- package/dist/esm/core.d.ts +10 -0
- package/dist/esm/core.d.ts.map +1 -0
- package/dist/esm/core.js +25 -0
- package/dist/esm/core.js.map +1 -0
- package/dist/esm/default-store.d.ts +7 -0
- package/dist/esm/default-store.d.ts.map +1 -0
- package/dist/esm/default-store.js +93 -0
- package/dist/esm/default-store.js.map +1 -0
- package/dist/esm/dictionaries.d.ts +7 -0
- package/dist/esm/dictionaries.d.ts.map +1 -0
- package/dist/esm/dictionaries.js +26 -0
- package/dist/esm/dictionaries.js.map +1 -0
- package/dist/esm/index.d.ts +24 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +31 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/interpolation.d.ts +6 -0
- package/dist/esm/interpolation.d.ts.map +1 -0
- package/dist/esm/interpolation.js +22 -0
- package/dist/esm/interpolation.js.map +1 -0
- package/dist/esm/languages.d.ts +4 -0
- package/dist/esm/languages.d.ts.map +1 -0
- package/dist/esm/languages.js +57 -0
- package/dist/esm/languages.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/react.d.ts +15 -0
- package/dist/esm/react.d.ts.map +1 -0
- package/dist/esm/react.js +51 -0
- package/dist/esm/react.js.map +1 -0
- package/dist/esm/resource.d.ts +8 -0
- package/dist/esm/resource.d.ts.map +1 -0
- package/dist/esm/resource.js +31 -0
- package/dist/esm/resource.js.map +1 -0
- package/dist/esm/store-types.d.ts +10 -0
- package/dist/esm/store-types.d.ts.map +1 -0
- package/dist/esm/store-types.js +14 -0
- package/dist/esm/store-types.js.map +1 -0
- package/dist/esm/store.d.ts +24 -0
- package/dist/esm/store.d.ts.map +1 -0
- package/dist/esm/store.js +136 -0
- package/dist/esm/store.js.map +1 -0
- package/dist/esm/typed-react.d.ts +5 -0
- package/dist/esm/typed-react.d.ts.map +1 -0
- package/dist/esm/typed-react.js +20 -0
- package/dist/esm/typed-react.js.map +1 -0
- package/dist/esm/types.d.ts +91 -0
- package/dist/esm/types.d.ts.map +1 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/types/registry.d.cts +10 -0
- package/native/README.md +179 -0
- package/native/android/README.md +14 -0
- package/native/android/cli.cjs +2 -0
- package/native/android/expo.cjs +1 -0
- package/native/android/expo.d.cts +1 -0
- package/native/android/index.cjs +3 -0
- package/native/android/index.d.cts +5 -0
- package/native/android/metro.cjs +3 -0
- package/native/android/metro.d.cts +7 -0
- package/native/android/prepare.cjs +3 -0
- package/native/cli.cjs +43 -0
- package/native/expo.cjs +17 -0
- package/native/expo.d.cts +7 -0
- package/native/index.cjs +18 -0
- package/native/index.d.cts +14 -0
- package/native/ios/README.md +58 -0
- package/native/ios/cli.cjs +2 -0
- package/native/ios/expo.cjs +1 -0
- package/native/ios/expo.d.cts +1 -0
- package/native/ios/index.cjs +3 -0
- package/native/ios/index.d.cts +5 -0
- package/native/ios/metro.cjs +3 -0
- package/native/ios/metro.d.cts +7 -0
- package/native/ios/prepare.cjs +3 -0
- package/native/metro.cjs +45 -0
- package/native/metro.d.cts +34 -0
- package/native/prepare.cjs +120 -0
- package/package.json +165 -4
- package/src/api-types.ts +42 -0
- package/src/core.ts +29 -0
- package/src/default-store.ts +106 -0
- package/src/dictionaries.ts +31 -0
- package/src/index.ts +46 -0
- package/src/interpolation.ts +31 -0
- package/src/languages.ts +62 -0
- package/src/react.ts +83 -0
- package/src/resource.ts +40 -0
- package/src/store-types.ts +36 -0
- package/src/store.ts +150 -0
- package/src/typed-react.ts +33 -0
- package/src/types.ts +113 -0
- package/types/registry.d.cts +10 -0
- package/vite/index.cjs +145 -0
- package/vite/index.d.cts +15 -0
- package/webpack/index.cjs +46 -0
- package/webpack/index.d.cts +22 -0
- package/webpack/loader.cjs +21 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { I18nStore as Store } from './store.js';
|
|
2
|
+
import type {
|
|
3
|
+
CheckedDictionary,
|
|
4
|
+
DictionaryInput,
|
|
5
|
+
DictionaryKeys,
|
|
6
|
+
GetterOptions,
|
|
7
|
+
InterpolationValues,
|
|
8
|
+
} from './types.js';
|
|
9
|
+
|
|
10
|
+
export interface DictionaryGetters<L extends string, F extends string = never> {
|
|
11
|
+
createTypoGetter<const D extends DictionaryInput>(
|
|
12
|
+
info: CheckedDictionary<D, L, F>,
|
|
13
|
+
options?: GetterOptions<L>,
|
|
14
|
+
): (key: DictionaryKeys<D>, values?: InterpolationValues) => string;
|
|
15
|
+
getTypoAsObject<const D extends DictionaryInput>(
|
|
16
|
+
info: CheckedDictionary<D, L, F>,
|
|
17
|
+
language?: L,
|
|
18
|
+
): Record<DictionaryKeys<D>, string | undefined>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type I18nStore<L extends string, F extends string = never> = Omit<Store<L>, keyof DictionaryGetters<L, F>> &
|
|
22
|
+
DictionaryGetters<L, F>;
|
|
23
|
+
|
|
24
|
+
/** Keep the original inferred dictionary when forwarding a checked argument to the store. */
|
|
25
|
+
export function withDictionaryTypes<L extends string, F extends string = never>(store: Store<L>): I18nStore<L, F> {
|
|
26
|
+
const { createTypoGetter, getTypoAsObject } = store;
|
|
27
|
+
const methods: DictionaryGetters<L, F> = {
|
|
28
|
+
createTypoGetter<const D extends DictionaryInput>(info: CheckedDictionary<D, L, F>, options?: GetterOptions<L>) {
|
|
29
|
+
return createTypoGetter<D>(info, options);
|
|
30
|
+
},
|
|
31
|
+
getTypoAsObject<const D extends DictionaryInput>(info: CheckedDictionary<D, L, F>, language?: L) {
|
|
32
|
+
return getTypoAsObject<D>(info, language);
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
return Object.assign(store, methods);
|
|
36
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { getMessages, validateLanguageDictionary } from './dictionaries.js';
|
|
2
|
+
import { createInterpolator } from './interpolation.js';
|
|
3
|
+
import { createLanguageResolver, detectLanguage } from './languages.js';
|
|
4
|
+
import { createAsyncResource } from './resource.js';
|
|
5
|
+
import type { AsyncResource } from './resource.js';
|
|
6
|
+
import type {
|
|
7
|
+
DictionaryInput,
|
|
8
|
+
DictionaryKeys,
|
|
9
|
+
GetterOptions,
|
|
10
|
+
I18nOptions,
|
|
11
|
+
InterpolationValues,
|
|
12
|
+
LanguageDictionary,
|
|
13
|
+
LoadOptions,
|
|
14
|
+
Messages,
|
|
15
|
+
} from './types.js';
|
|
16
|
+
|
|
17
|
+
/** A React-independent store. Share one instance between roots, or create one per SSR request. */
|
|
18
|
+
export function createI18nStore<const L extends string>(options: I18nOptions<L>) {
|
|
19
|
+
const interpolate = createInterpolator(options.interpolation);
|
|
20
|
+
const languages = Object.freeze([...options.supportedLanguages]);
|
|
21
|
+
const supported = new Set(languages);
|
|
22
|
+
if (!supported.has(options.fallbackLanguage)) throw new Error('fallbackLanguage must be supported');
|
|
23
|
+
if (options.initialLanguage !== undefined && !supported.has(options.initialLanguage)) {
|
|
24
|
+
throw new Error('initialLanguage must be supported');
|
|
25
|
+
}
|
|
26
|
+
const resolveLanguage = createLanguageResolver(languages);
|
|
27
|
+
const listeners = new Set<() => void>();
|
|
28
|
+
const dictionaries = new Map<L, LanguageDictionary>();
|
|
29
|
+
const resources = new Map<L, AsyncResource<void>>();
|
|
30
|
+
const onError = options.onError ?? console.error;
|
|
31
|
+
let currentLanguage: L | undefined;
|
|
32
|
+
let revision = 0;
|
|
33
|
+
|
|
34
|
+
for (const language of languages) {
|
|
35
|
+
const dictionary = options.dictionaries?.[language];
|
|
36
|
+
if (dictionary !== undefined) {
|
|
37
|
+
validateLanguageDictionary(dictionary);
|
|
38
|
+
dictionaries.set(language, dictionary);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const getStorage = () =>
|
|
43
|
+
options.storage === false
|
|
44
|
+
? undefined
|
|
45
|
+
: (options.storage ?? (typeof window === 'undefined' ? undefined : window.localStorage));
|
|
46
|
+
const emit = () => {
|
|
47
|
+
revision += 1;
|
|
48
|
+
for (const listener of listeners) listener();
|
|
49
|
+
};
|
|
50
|
+
const getCurrentLang = (): L => {
|
|
51
|
+
currentLanguage ??= detectLanguage(options, resolveLanguage, getStorage, onError);
|
|
52
|
+
return currentLanguage;
|
|
53
|
+
};
|
|
54
|
+
const assertSupported = (language: L) => {
|
|
55
|
+
if (!supported.has(language)) throw new Error(`Unsupported language: ${language}`);
|
|
56
|
+
};
|
|
57
|
+
const getResource = (language: L, retry = false) => {
|
|
58
|
+
assertSupported(language);
|
|
59
|
+
if (dictionaries.has(language)) return undefined;
|
|
60
|
+
const cached = resources.get(language);
|
|
61
|
+
if (cached && !(retry && cached.isRejected())) return cached;
|
|
62
|
+
const resource = createAsyncResource(async () => {
|
|
63
|
+
if (!options.loadDictionary) {
|
|
64
|
+
throw new Error('Configure loadDictionary or provide preloaded dictionaries for extracted JSON');
|
|
65
|
+
}
|
|
66
|
+
const dictionary = await options.loadDictionary(language);
|
|
67
|
+
validateLanguageDictionary(dictionary);
|
|
68
|
+
dictionaries.set(language, dictionary);
|
|
69
|
+
emit();
|
|
70
|
+
});
|
|
71
|
+
resources.set(language, resource);
|
|
72
|
+
return resource;
|
|
73
|
+
};
|
|
74
|
+
const requiredResources = (language: L, retry = false) => {
|
|
75
|
+
assertSupported(language);
|
|
76
|
+
return [...new Set([options.fallbackLanguage, language])].map(lang => getResource(lang, retry));
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
function getTypoAsObject<const D extends DictionaryInput>(
|
|
80
|
+
info: D,
|
|
81
|
+
language?: L,
|
|
82
|
+
): Record<DictionaryKeys<D>, string | undefined>;
|
|
83
|
+
function getTypoAsObject(info: DictionaryInput, language: L = getCurrentLang()) {
|
|
84
|
+
assertSupported(language);
|
|
85
|
+
const merged = new Map(Object.entries(getMessages(info, options.fallbackLanguage, dictionaries) ?? {}));
|
|
86
|
+
for (const [key, value] of Object.entries(getMessages(info, language, dictionaries) ?? {})) {
|
|
87
|
+
if (value !== undefined) merged.set(key, value);
|
|
88
|
+
}
|
|
89
|
+
return Object.fromEntries(merged);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
supportedLanguages: languages,
|
|
94
|
+
fallbackLanguage: options.fallbackLanguage,
|
|
95
|
+
/** Interpolates with this instance's configured delimiters. */
|
|
96
|
+
interpolateTypo: interpolate,
|
|
97
|
+
resolveLanguage,
|
|
98
|
+
getCurrentLang,
|
|
99
|
+
/** A stable SSR snapshot; match initialLanguage between server and client for hydration. */
|
|
100
|
+
getServerLanguage: () => options.initialLanguage ?? options.fallbackLanguage,
|
|
101
|
+
setCurrentLang(language: L) {
|
|
102
|
+
assertSupported(language);
|
|
103
|
+
const previous = getCurrentLang();
|
|
104
|
+
try {
|
|
105
|
+
getStorage()?.setItem(options.storageKey ?? 'i18n-language', language);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
onError(error);
|
|
108
|
+
}
|
|
109
|
+
if (previous === language) return;
|
|
110
|
+
currentLanguage = language;
|
|
111
|
+
emit();
|
|
112
|
+
},
|
|
113
|
+
subscribe(listener: () => void) {
|
|
114
|
+
listeners.add(listener);
|
|
115
|
+
return () => {
|
|
116
|
+
listeners.delete(listener);
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
getSnapshot: () => revision,
|
|
120
|
+
getServerSnapshot: () => 0,
|
|
121
|
+
/** Loads the selected language and fallback concurrently, deduplicating each request. */
|
|
122
|
+
async loadLanguage(language: L = getCurrentLang(), loadOptions: LoadOptions = {}) {
|
|
123
|
+
await Promise.all(requiredResources(language, loadOptions.retry).map(resource => resource?.promise));
|
|
124
|
+
},
|
|
125
|
+
/** Throws a cached promise/error for React Suspense and error boundaries. */
|
|
126
|
+
readLanguage(language: L = getCurrentLang()) {
|
|
127
|
+
for (const resource of requiredResources(language)) resource?.read();
|
|
128
|
+
},
|
|
129
|
+
createTypoGetter<const D extends DictionaryInput>(info: D, getterOptions: GetterOptions<L> = {}) {
|
|
130
|
+
if (getterOptions.language !== undefined) assertSupported(getterOptions.language);
|
|
131
|
+
return (key: DictionaryKeys<D>, values?: InterpolationValues): string => {
|
|
132
|
+
const language = getterOptions.language ?? getCurrentLang();
|
|
133
|
+
const selected = getMessages(info, language, dictionaries);
|
|
134
|
+
const fallback = getMessages(info, options.fallbackLanguage, dictionaries);
|
|
135
|
+
const template =
|
|
136
|
+
ownMessage(selected, key) ??
|
|
137
|
+
ownMessage(fallback, key) ??
|
|
138
|
+
(getterOptions.placehold === false ? '' : `i18n(${key})`);
|
|
139
|
+
return values ? interpolate(template, values) : template;
|
|
140
|
+
};
|
|
141
|
+
},
|
|
142
|
+
getTypoAsObject,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export type I18nStore<L extends string> = ReturnType<typeof createI18nStore<L>>;
|
|
147
|
+
|
|
148
|
+
function ownMessage(messages: Messages | undefined, key: string) {
|
|
149
|
+
return messages && Object.hasOwn(messages, key) ? messages[key] : undefined;
|
|
150
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createReactBindings } from './react.js';
|
|
2
|
+
import type { NamedExoticComponent } from 'react';
|
|
3
|
+
import type { DictionaryReactBindings, ReactBindings } from './api-types.js';
|
|
4
|
+
import type { I18nStore } from './store.js';
|
|
5
|
+
import type { CheckedDictionary, DictionaryInput, DictionaryKeys, RemovePrefix, TypoProps } from './types.js';
|
|
6
|
+
|
|
7
|
+
/** Validates locale keys at the public boundary while keeping the existing React implementation. */
|
|
8
|
+
export function bindReact<L extends string, F extends string = never>(store: I18nStore<L>): ReactBindings<L, F> {
|
|
9
|
+
const bindings = createReactBindings(store);
|
|
10
|
+
const { createTypo: createRawTypo, createUseTypo: createRawUseTypo, useTypoAsObject: useRawTypoAsObject } = bindings;
|
|
11
|
+
|
|
12
|
+
function createTypo<const D extends DictionaryInput>(
|
|
13
|
+
info: CheckedDictionary<D, L, F>,
|
|
14
|
+
): NamedExoticComponent<TypoProps<DictionaryKeys<D>>>;
|
|
15
|
+
function createTypo<const D extends DictionaryInput, P extends string>(
|
|
16
|
+
info: CheckedDictionary<D, L, F>,
|
|
17
|
+
prefix: P,
|
|
18
|
+
): NamedExoticComponent<TypoProps<RemovePrefix<DictionaryKeys<D>, P>>>;
|
|
19
|
+
function createTypo<const D extends DictionaryInput, P extends string>(info: D, prefix?: P) {
|
|
20
|
+
return prefix === undefined ? createRawTypo<D>(info) : createRawTypo<D, P>(info, prefix);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const methods: DictionaryReactBindings<L, F> = {
|
|
24
|
+
createTypo,
|
|
25
|
+
createUseTypo<const D extends DictionaryInput>(info: CheckedDictionary<D, L, F>) {
|
|
26
|
+
return createRawUseTypo<D>(info);
|
|
27
|
+
},
|
|
28
|
+
useTypoAsObject<const D extends DictionaryInput>(info: CheckedDictionary<D, L, F>) {
|
|
29
|
+
return useRawTypoAsObject<D>(info);
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
return Object.assign(bindings, methods);
|
|
33
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { RegisteredFallbackLanguage, SupportedLanguage } from '../types/registry.cjs';
|
|
2
|
+
|
|
3
|
+
export type { CustomTypeOptions, RegisteredFallbackLanguage, SupportedLanguage } from '../types/registry.cjs';
|
|
4
|
+
|
|
5
|
+
export type Messages = Readonly<Record<string, string | undefined>>;
|
|
6
|
+
|
|
7
|
+
/** A feature's original JSON: language -> flat translation keys. */
|
|
8
|
+
export type FeatureDictionary<L extends string = string> = Readonly<Partial<Record<L, Messages>>>;
|
|
9
|
+
|
|
10
|
+
/** Emitted by the Webpack loader. The optional phantom field preserves keys for custom loaders. */
|
|
11
|
+
export interface DictionaryReference<K extends string = string> {
|
|
12
|
+
readonly __id: string;
|
|
13
|
+
readonly __keys?: K;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type DictionaryInput = FeatureDictionary | DictionaryReference;
|
|
17
|
+
|
|
18
|
+
/** Imported variables need an exact key check: structural object typing alone permits extra locales. */
|
|
19
|
+
export type CheckedDictionary<D extends DictionaryInput, L extends string, F extends string = never> = D &
|
|
20
|
+
(NoInfer<D> extends DictionaryReference
|
|
21
|
+
? unknown
|
|
22
|
+
: Record<Exclude<keyof NoInfer<D>, L>, never> & Record<F, Messages>);
|
|
23
|
+
|
|
24
|
+
export type DictionaryKeys<D extends DictionaryInput> =
|
|
25
|
+
D extends DictionaryReference<infer K> ? K : { [L in keyof D]: keyof NonNullable<D[L]> }[keyof D] & string;
|
|
26
|
+
|
|
27
|
+
/** Contents of one emitted language file: feature ID -> translations. */
|
|
28
|
+
export type LanguageDictionary = Readonly<Record<string, Messages | undefined>>;
|
|
29
|
+
|
|
30
|
+
export type InterpolationValues = Readonly<Record<string, string | number | null | undefined>>;
|
|
31
|
+
|
|
32
|
+
export interface InterpolationDelimiters {
|
|
33
|
+
/** Literal opening delimiter, e.g. '{', '{{', '${', or a quote. Must not be empty. */
|
|
34
|
+
readonly prefix: string;
|
|
35
|
+
/** Literal closing delimiter, e.g. '}', '}}', or the same quote. Must not be empty. */
|
|
36
|
+
readonly suffix: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type RemovePrefix<K extends string, P extends string> = K extends `${P}${infer Suffix}` ? Suffix : never;
|
|
40
|
+
|
|
41
|
+
export interface Typo<K extends string> {
|
|
42
|
+
(key: K, values?: InterpolationValues): string;
|
|
43
|
+
/** Allows `const { t } = useFeatureTypo()`. */
|
|
44
|
+
readonly t: (key: K, values?: InterpolationValues) => string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface TypoOptions<P extends string = string> {
|
|
48
|
+
keyPrefix?: P;
|
|
49
|
+
/** Show `i18n(key)` for a missing message. Defaults to true; false returns an empty string. */
|
|
50
|
+
placehold?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface TypoHook<K extends string> {
|
|
54
|
+
<P extends string>(options: TypoOptions<P> & { keyPrefix: P }): Typo<RemovePrefix<K, P>>;
|
|
55
|
+
(options?: TypoOptions<never>): Typo<K>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface TypoProps<K extends string> {
|
|
59
|
+
id: K;
|
|
60
|
+
values?: InterpolationValues;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface StorageAdapter {
|
|
64
|
+
getItem(key: string): string | null;
|
|
65
|
+
setItem(key: string, value: string): void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface I18nOptions<L extends string> {
|
|
69
|
+
supportedLanguages: readonly L[];
|
|
70
|
+
fallbackLanguage: NoInfer<L>;
|
|
71
|
+
/** Overrides storage/browser detection. Use the same value on the server and during hydration. */
|
|
72
|
+
initialLanguage?: NoInfer<L>;
|
|
73
|
+
/** Defaults to browser localStorage. false disables persistence. Values are plain language strings. */
|
|
74
|
+
storage?: StorageAdapter | false;
|
|
75
|
+
storageKey?: string;
|
|
76
|
+
/** Interpolation placeholder delimiters. Defaults to { prefix: '{', suffix: '}' }. */
|
|
77
|
+
interpolation?: InterpolationDelimiters;
|
|
78
|
+
/** Defaults to navigator.languages, with navigator.language as a fallback. */
|
|
79
|
+
getBrowserLanguages?: () => readonly string[];
|
|
80
|
+
/** Optional preloaded emitted dictionaries, useful for SSR. */
|
|
81
|
+
dictionaries?: Readonly<Partial<Record<L, LanguageDictionary>>>;
|
|
82
|
+
/** Without a loader only inline JSON dictionaries can be used. */
|
|
83
|
+
loadDictionary?: (language: L) => Promise<LanguageDictionary>;
|
|
84
|
+
/** Receives storage errors. Defaults to console.error. Loading errors reject/throw instead. */
|
|
85
|
+
onError?: (error: unknown) => void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface GetterOptions<L extends string> {
|
|
89
|
+
/** Omit to follow the instance's current language on every call. */
|
|
90
|
+
language?: L;
|
|
91
|
+
placehold?: boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Runtime configuration must agree with any application-wide language/fallback declaration. */
|
|
95
|
+
export type DefaultI18nOptions<L extends SupportedLanguage = SupportedLanguage> = I18nOptions<L> &
|
|
96
|
+
([RegisteredFallbackLanguage] extends [never] ? unknown : { fallbackLanguage: RegisteredFallbackLanguage }) &
|
|
97
|
+
(string extends SupportedLanguage
|
|
98
|
+
? unknown
|
|
99
|
+
: [SupportedLanguage] extends [NoInfer<L>]
|
|
100
|
+
? unknown
|
|
101
|
+
: { supportedLanguages: never });
|
|
102
|
+
|
|
103
|
+
export interface LoadOptions {
|
|
104
|
+
/** Retry a failed language request. Successful requests stay cached. */
|
|
105
|
+
retry?: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface FetchDictionaryOptions {
|
|
109
|
+
/** Defaults to "i18n". Include any bundler public path, e.g. "/app/assets/i18n". */
|
|
110
|
+
baseUrl?: string;
|
|
111
|
+
fetch?: typeof globalThis.fetch;
|
|
112
|
+
requestInit?: RequestInit;
|
|
113
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Augment this interface through 'i18n-json-react' to type the application's shared instance. */
|
|
2
|
+
export interface CustomTypeOptions {}
|
|
3
|
+
|
|
4
|
+
/** Registered language identifiers, or string when no application registration is supplied. */
|
|
5
|
+
export type SupportedLanguage = CustomTypeOptions extends { supportedLanguages: infer L extends string } ? L : string;
|
|
6
|
+
|
|
7
|
+
/** Registering a fallback also requires that locale's entry in feature dictionaries. */
|
|
8
|
+
export type RegisteredFallbackLanguage = CustomTypeOptions extends { fallbackLanguage: infer F extends string }
|
|
9
|
+
? F
|
|
10
|
+
: never;
|
package/vite/index.cjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
const { readFile, realpath } = require('node:fs/promises');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const {
|
|
4
|
+
resolveRoot,
|
|
5
|
+
computeId,
|
|
6
|
+
parseFeature,
|
|
7
|
+
resolveOutputDir,
|
|
8
|
+
collectDictionaries,
|
|
9
|
+
} = require('../bundlers/shared.cjs');
|
|
10
|
+
|
|
11
|
+
const VIRTUAL_PREFIX = '\0i18n-json-react:';
|
|
12
|
+
const FEATURE_FILE = /(?:^|[/\\])(?:i18n|[^/\\]+\.i18n)\.json$/;
|
|
13
|
+
|
|
14
|
+
/** Extracts feature JSON for Vite builds and serves language dictionaries during development. */
|
|
15
|
+
function i18nJsonPlugin(options = {}) {
|
|
16
|
+
const outputDir = resolveOutputDir(options.outputDir);
|
|
17
|
+
let config;
|
|
18
|
+
let root;
|
|
19
|
+
let collected;
|
|
20
|
+
let collection;
|
|
21
|
+
let server;
|
|
22
|
+
const virtualFiles = new Map();
|
|
23
|
+
|
|
24
|
+
async function collect() {
|
|
25
|
+
const directories = new Set();
|
|
26
|
+
const outDir = path.relative(root, path.resolve(config.root, config.build.outDir)).split(path.sep).join('/');
|
|
27
|
+
const result = await collectDictionaries(
|
|
28
|
+
root,
|
|
29
|
+
{
|
|
30
|
+
...options,
|
|
31
|
+
exclude: [...(options.exclude ?? []), ...(outDir && !outDir.startsWith('..') ? [`${outDir}/**`] : [])],
|
|
32
|
+
},
|
|
33
|
+
directory => directories.add(directory),
|
|
34
|
+
);
|
|
35
|
+
collected = { ...result, files: new Set(result.files), directories };
|
|
36
|
+
server?.watcher.add([...directories, ...result.files]);
|
|
37
|
+
return collected;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function refresh() {
|
|
41
|
+
// Serialize scans so requests cannot observe an older scan finishing after a newer edit.
|
|
42
|
+
collection = (collection ?? Promise.resolve()).then(collect, collect);
|
|
43
|
+
return collection;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
name: 'vite-plugin-i18n-json-react',
|
|
48
|
+
enforce: 'pre',
|
|
49
|
+
configResolved(resolved) {
|
|
50
|
+
config = resolved;
|
|
51
|
+
root = resolveRoot(config.root, options.root);
|
|
52
|
+
},
|
|
53
|
+
async buildStart() {
|
|
54
|
+
const current = await refresh();
|
|
55
|
+
for (const file of [...current.directories, ...current.files]) this.addWatchFile(file);
|
|
56
|
+
},
|
|
57
|
+
async resolveId(source, importer) {
|
|
58
|
+
const [file, query = ''] = source.split('?', 2);
|
|
59
|
+
if (!FEATURE_FILE.test(file) || source.startsWith(VIRTUAL_PREFIX)) return null;
|
|
60
|
+
// Explicit asset/raw imports retain Vite's usual semantics.
|
|
61
|
+
if ([...new URLSearchParams(query).keys()].some(key => !['import', 't', 'v'].includes(key))) return null;
|
|
62
|
+
const resolved = await this.resolve(source, importer, { skipSelf: true });
|
|
63
|
+
if (!resolved || resolved.external) return null;
|
|
64
|
+
const absolute = await realpath(resolved.id.split('?', 1)[0]);
|
|
65
|
+
const current = await (collection ?? refresh());
|
|
66
|
+
if (!current.files.has(absolute)) return null;
|
|
67
|
+
// A virtual ID avoids Vite's built-in JSON transform parsing the generated JavaScript.
|
|
68
|
+
const id = `${VIRTUAL_PREFIX}${Buffer.from(absolute).toString('base64url')}`;
|
|
69
|
+
virtualFiles.set(id, absolute);
|
|
70
|
+
return { id, moduleSideEffects: false };
|
|
71
|
+
},
|
|
72
|
+
async load(id) {
|
|
73
|
+
const file = virtualFiles.get(id);
|
|
74
|
+
if (!file) return null;
|
|
75
|
+
const content = await readFile(file, 'utf8');
|
|
76
|
+
parseFeature(content, file);
|
|
77
|
+
this.addWatchFile(file);
|
|
78
|
+
return {
|
|
79
|
+
code: `export default ${JSON.stringify({ __id: computeId(file, root) })};`,
|
|
80
|
+
map: { version: 3, names: [], sources: [file], sourcesContent: [content], mappings: 'AAAA' },
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
async generateBundle() {
|
|
84
|
+
const current = await collection;
|
|
85
|
+
for (const [language, dictionary] of current.perLanguage) {
|
|
86
|
+
this.emitFile({
|
|
87
|
+
type: 'asset',
|
|
88
|
+
fileName: path.posix.join(outputDir, `${language}.json`),
|
|
89
|
+
source: JSON.stringify(dictionary, null, config.isProduction ? 0 : 2),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
async configureServer(devServer) {
|
|
94
|
+
server = devServer;
|
|
95
|
+
await refresh();
|
|
96
|
+
const base = new URL(config.base, 'http://vite.local/').pathname.replace(/\/?$/, '/');
|
|
97
|
+
const prefix = `${base}${outputDir ? `${outputDir}/` : ''}`;
|
|
98
|
+
server.middlewares.use((request, response, next) => {
|
|
99
|
+
const url = new URL(request.url, 'http://vite.local/');
|
|
100
|
+
const pathname = url.pathname;
|
|
101
|
+
if (['raw', 'url', 'import'].some(key => url.searchParams.has(key))) return next();
|
|
102
|
+
if (!pathname.startsWith(prefix) || !pathname.endsWith('.json')) return next();
|
|
103
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return next();
|
|
104
|
+
void (async () => {
|
|
105
|
+
const language = decodeURIComponent(pathname.slice(prefix.length, -5));
|
|
106
|
+
const current = await collection;
|
|
107
|
+
const dictionary = current.perLanguage.get(language);
|
|
108
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
109
|
+
response.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
110
|
+
response.statusCode = dictionary ? 200 : 404;
|
|
111
|
+
response.end(
|
|
112
|
+
request.method === 'HEAD' ? undefined : JSON.stringify(dictionary ?? { error: 'Unknown language' }),
|
|
113
|
+
);
|
|
114
|
+
})().catch(next);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const onChange = (event, file) => {
|
|
118
|
+
if (!['add', 'change', 'unlink'].includes(event) || !FEATURE_FILE.test(file)) return;
|
|
119
|
+
file = path.resolve(file);
|
|
120
|
+
const wasIncluded = collected.files.has(file);
|
|
121
|
+
void refresh()
|
|
122
|
+
.then(current => {
|
|
123
|
+
if (!wasIncluded && !current.files.has(file)) return;
|
|
124
|
+
for (const id of virtualFiles.keys()) {
|
|
125
|
+
const module = server.moduleGraph.getModuleById(id);
|
|
126
|
+
if (module) server.moduleGraph.invalidateModule(module);
|
|
127
|
+
}
|
|
128
|
+
// The runtime intentionally caches loaded languages. A reload creates fresh resources.
|
|
129
|
+
server.ws.send({ type: 'full-reload', path: '*' });
|
|
130
|
+
})
|
|
131
|
+
.catch(error => {
|
|
132
|
+
server.config.logger.error(error.stack ?? String(error));
|
|
133
|
+
server.ws.send({
|
|
134
|
+
type: 'error',
|
|
135
|
+
err: { message: error.message ?? String(error), stack: error.stack ?? '' },
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
server.watcher.on('all', onChange);
|
|
140
|
+
server.watcher.once('close', () => server.watcher.off('all', onChange));
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
module.exports = { i18nJsonPlugin };
|
package/vite/index.d.cts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
|
|
3
|
+
export interface I18nViteOptions {
|
|
4
|
+
/** Absolute or relative to Vite root. IDs and directory patterns use this root. */
|
|
5
|
+
root?: string;
|
|
6
|
+
/** Directory globs relative to root. Defaults to ['.']; list dependency packages explicitly. */
|
|
7
|
+
dirs?: string[];
|
|
8
|
+
/** File/directory globs relative to root, e.g. ['scripts/**']. Vite's outDir is excluded automatically. */
|
|
9
|
+
exclude?: string[];
|
|
10
|
+
/** Relative asset path, used for build output and dev requests. Defaults to 'i18n'. */
|
|
11
|
+
outputDir?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Extracts JSON imports and emits/serves per-language dictionaries; edits trigger a full dev reload. */
|
|
15
|
+
export declare function i18nJsonPlugin(options?: I18nViteOptions): Plugin;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const path = require('node:path');
|
|
2
|
+
const { resolveRoot, resolveOutputDir, collectDictionaries } = require('../bundlers/shared.cjs');
|
|
3
|
+
|
|
4
|
+
const PLUGIN_NAME = 'I18nCollectPlugin';
|
|
5
|
+
|
|
6
|
+
/** Rule that substitutes imported i18n.json and *.i18n.json files with { __id }. */
|
|
7
|
+
function i18nLoaderRule(options = {}) {
|
|
8
|
+
return {
|
|
9
|
+
test: [/\.i18n\.json$/, /[\\/]i18n\.json$/],
|
|
10
|
+
type: 'javascript/auto',
|
|
11
|
+
loader: require.resolve('./loader.cjs'),
|
|
12
|
+
options,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Collects feature-local dictionaries into one JSON asset per language. */
|
|
17
|
+
class I18nCollectPlugin {
|
|
18
|
+
constructor(options = {}) {
|
|
19
|
+
this.options = options;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
apply(compiler) {
|
|
23
|
+
const { Compilation, sources } = compiler.webpack;
|
|
24
|
+
const outputDir = resolveOutputDir(this.options.outputDir);
|
|
25
|
+
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
|
|
26
|
+
compilation.hooks.processAssets.tapPromise(
|
|
27
|
+
{ name: PLUGIN_NAME, stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS },
|
|
28
|
+
async () => {
|
|
29
|
+
const root = resolveRoot(compiler.context, this.options.root);
|
|
30
|
+
const { files, perLanguage } = await collectDictionaries(root, this.options, dir => {
|
|
31
|
+
compilation.contextDependencies.add(dir);
|
|
32
|
+
});
|
|
33
|
+
for (const file of files) compilation.fileDependencies.add(file);
|
|
34
|
+
for (const [language, dictionary] of perLanguage) {
|
|
35
|
+
compilation.emitAsset(
|
|
36
|
+
path.posix.join(outputDir, `${language}.json`),
|
|
37
|
+
new sources.RawSource(JSON.stringify(dictionary, null, compiler.options.mode === 'production' ? 0 : 2)),
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = { i18nLoaderRule, I18nCollectPlugin };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Compiler, RuleSetRule, WebpackPluginInstance } from 'webpack';
|
|
2
|
+
|
|
3
|
+
export interface I18nLoaderOptions {
|
|
4
|
+
/** Absolute or relative to Webpack context. Must match the collector's root. */
|
|
5
|
+
root?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface I18nCollectPluginOptions extends I18nLoaderOptions {
|
|
9
|
+
/** Directories/globs relative to root. Defaults to ['.']; list dependency packages explicitly. */
|
|
10
|
+
dirs?: string[];
|
|
11
|
+
/** File/directory globs relative to root, e.g. ['scripts/**', 'dist/**']. */
|
|
12
|
+
exclude?: string[];
|
|
13
|
+
/** Relative emitted asset directory. Defaults to 'i18n'. Match the runtime loader's baseUrl. */
|
|
14
|
+
outputDir?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export declare function i18nLoaderRule(options?: I18nLoaderOptions): RuleSetRule;
|
|
18
|
+
|
|
19
|
+
export declare class I18nCollectPlugin implements WebpackPluginInstance {
|
|
20
|
+
constructor(options?: I18nCollectPluginOptions);
|
|
21
|
+
apply(compiler: Compiler): void;
|
|
22
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const path = require('node:path');
|
|
2
|
+
const { resolveRoot, computeId, parseFeature } = require('../bundlers/shared.cjs');
|
|
3
|
+
|
|
4
|
+
/** Replaces a feature dictionary with an opaque ID while TypeScript still sees the original JSON. */
|
|
5
|
+
module.exports = function i18nJsonLoader(content) {
|
|
6
|
+
this.cacheable();
|
|
7
|
+
parseFeature(content, this.resourcePath);
|
|
8
|
+
const root = resolveRoot(this.rootContext, this.getOptions().root);
|
|
9
|
+
const code = `export default ${JSON.stringify({ __id: computeId(this.resourcePath, root) })};`;
|
|
10
|
+
const map = this.sourceMap
|
|
11
|
+
? {
|
|
12
|
+
version: 3,
|
|
13
|
+
file: path.basename(this.resourcePath),
|
|
14
|
+
sources: [this.resourcePath],
|
|
15
|
+
sourcesContent: [content],
|
|
16
|
+
names: [],
|
|
17
|
+
mappings: 'AAAA',
|
|
18
|
+
}
|
|
19
|
+
: undefined;
|
|
20
|
+
this.callback(null, code, map);
|
|
21
|
+
};
|