@kivacore/i18n 0.0.0-stage → 0.2.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/README.md CHANGED
@@ -1,3 +1,392 @@
1
- # Temporary Holding Version
1
+ # @kivacore/i18n
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Internationalization provider for Docyrus apps. Provides `DocyrusI18nProvider` + `t()` function with API-based and static translation support, cookie-based locale persistence, and `{{variable}}` interpolation.
4
+
5
+ Supports **React**, **React Native**, **Vue**, and **SSR** (Next.js Server Components) via separate entrypoints.
6
+
7
+ ## Features
8
+
9
+ - **Translation Provider**: Wrap your app with `DocyrusI18nProvider` and use `t()` anywhere
10
+ - **API + Static Merge**: Fetch translations from API (`GET /v1/tenant/translations`) and/or provide static JSON
11
+ - **Cookie-based Locale**: Persists locale in a cookie (`docyrus-locale`), survives page reloads
12
+ - **Locale Switching**: `setLocale('en')` writes cookie + refetches translations automatically
13
+ - **Interpolation**: Supports `{{name}}`, `{name}`, and `{0}` placeholder formats
14
+ - **SSR + CSR**: `'use client'` directive for Next.js; static translations available immediately (no loading flash)
15
+ - **Auth Integration**: Accepts `RestApiClient` from `@kivacore/api-client` (auto Authorization header)
16
+ - **Translate Values**: `tv('translate.Active')` for API response values with "translate." prefix
17
+ - **React Hooks**: `useDocyrusI18n()` (full context) and `useTranslation()` (lightweight)
18
+ - **React Native**: `useI18n()` with graceful fallback (works without provider), `DocyI18nProvider` with MMKV/AsyncStorage support
19
+ - **Vue Composables**: `useDocyrusI18n()` and `useTranslation()` for Vue 3
20
+ - **Framework-Agnostic Core**: `I18nManager` class for custom integrations
21
+ - **Pluggable Storage**: `CookieStorageAdapter` (web), `MemoryStorageAdapter` (SSR/testing), custom adapters (MMKV, AsyncStorage)
22
+ - **TypeScript**: Full type definitions included
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ npm install @kivacore/i18n @kivacore/api-client
28
+ ```
29
+
30
+ ```bash
31
+ pnpm add @kivacore/i18n @kivacore/api-client
32
+ ```
33
+
34
+ ### Peer Dependencies
35
+
36
+ - `@kivacore/api-client` >= 0.0.9 (optional — needed for API-based translations)
37
+ - `react` >= 19.2.0 (optional — required for React/Next.js/React Native entrypoints)
38
+ - `vue` >= 3.5.0 (optional — required for Vue entrypoint)
39
+
40
+ ## Entrypoints
41
+
42
+ | Import Path | Description | Framework |
43
+ |-------------|-------------|-----------|
44
+ | `@kivacore/i18n` | React provider, hooks | React, Next.js |
45
+ | `@kivacore/i18n/rn` | React Native provider, hooks (graceful fallback) | React Native (Expo) |
46
+ | `@kivacore/i18n/vue` | Vue provider, composables | Vue 3 |
47
+ | `@kivacore/i18n/core` | Pure TypeScript core (no framework dependency) | Any |
48
+
49
+ ## Quick Start (React)
50
+
51
+ ```tsx
52
+ import { DocyrusI18nProvider, useTranslation, useDocyrusI18n } from '@kivacore/i18n';
53
+ import { useDocyrusClient } from '@kivacore/signin';
54
+
55
+ function App() {
56
+ const client = useDocyrusClient();
57
+
58
+ return (
59
+ <DocyrusI18nProvider
60
+ client={client}
61
+ staticTranslations={{ 'common.loading': 'Yükleniyor...' }}
62
+ >
63
+ <Dashboard />
64
+ </DocyrusI18nProvider>
65
+ );
66
+ }
67
+
68
+ function Dashboard() {
69
+ const { t, isLoading } = useTranslation();
70
+
71
+ if (isLoading) return <div>{t('common.loading')}</div>;
72
+
73
+ return <h1>{t('dashboard.title')}</h1>;
74
+ }
75
+ ```
76
+
77
+ ## Quick Start (Next.js SSR)
78
+
79
+ ```tsx
80
+ // app/layout.tsx (Server Component)
81
+ import { I18nClientProvider } from './i18n-client-provider';
82
+
83
+ async function getTranslations() {
84
+ const res = await fetch(`${API_URL}/v1/tenant/translations`, {
85
+ headers: { Authorization: `Bearer ${serverToken}` }
86
+ });
87
+ return res.json();
88
+ }
89
+
90
+ export default async function Layout({ children }: { children: React.ReactNode }) {
91
+ const { data: translations } = await getTranslations();
92
+
93
+ return (
94
+ <html>
95
+ <body>
96
+ <I18nClientProvider staticTranslations={translations}>
97
+ {children}
98
+ </I18nClientProvider>
99
+ </body>
100
+ </html>
101
+ );
102
+ }
103
+ ```
104
+
105
+ ```tsx
106
+ // components/i18n-client-provider.tsx (Client Component)
107
+ 'use client';
108
+
109
+ import { DocyrusI18nProvider, type TranslationDictionary } from '@kivacore/i18n';
110
+ import { useDocyrusClient } from '@kivacore/signin';
111
+
112
+ export function I18nClientProvider({
113
+ children,
114
+ staticTranslations
115
+ }: {
116
+ children: React.ReactNode;
117
+ staticTranslations: TranslationDictionary;
118
+ }) {
119
+ const client = useDocyrusClient();
120
+
121
+ return (
122
+ <DocyrusI18nProvider
123
+ client={client}
124
+ staticTranslations={staticTranslations}
125
+ >
126
+ {children}
127
+ </DocyrusI18nProvider>
128
+ );
129
+ }
130
+ ```
131
+
132
+ ## Quick Start (Vue)
133
+
134
+ ```vue
135
+ <!-- App.vue -->
136
+ <script setup lang="ts">
137
+ import { RouterView } from 'vue-router';
138
+ import { DocyrusI18nProvider } from '@kivacore/i18n/vue';
139
+ import { useDocyrusClient } from '@kivacore/signin/vue';
140
+
141
+ const client = useDocyrusClient();
142
+ </script>
143
+
144
+ <template>
145
+ <DocyrusI18nProvider :client="client">
146
+ <RouterView />
147
+ </DocyrusI18nProvider>
148
+ </template>
149
+ ```
150
+
151
+ ```vue
152
+ <!-- Dashboard.vue -->
153
+ <script setup lang="ts">
154
+ import { useDocyrusI18n } from '@kivacore/i18n/vue';
155
+
156
+ const { t, locale, setLocale, isLoading } = useDocyrusI18n();
157
+ </script>
158
+
159
+ <template>
160
+ <div v-if="isLoading">Loading...</div>
161
+ <div v-else>
162
+ <h1>{{ t('dashboard.title') }}</h1>
163
+ <select :value="locale" @change="setLocale(($event.target as HTMLSelectElement).value)">
164
+ <option value="tr">Turkce</option>
165
+ <option value="en">English</option>
166
+ </select>
167
+ </div>
168
+ </template>
169
+ ```
170
+
171
+ ## Quick Start (React Native)
172
+
173
+ ```tsx
174
+ import { DocyI18nProvider, useI18n, type SupportedLanguage } from '@kivacore/i18n/rn';
175
+
176
+ // Storage is optional — use any getString/setString compatible adapter:
177
+ // MMKV, AsyncStorage, expo-sqlite, or no storage at all (session-only)
178
+ import { MMKV } from 'react-native-mmkv';
179
+
180
+ const mmkv = new MMKV();
181
+ const storage = {
182
+ getString: (key: string) => mmkv.getString(key),
183
+ setString: (key: string, value: string) => mmkv.set(key, value)
184
+ };
185
+
186
+ // translations.json — nested format
187
+ const translations = {
188
+ en: { common: { save: 'Save', cancel: 'Cancel' } },
189
+ tr: { common: { save: 'Kaydet', cancel: 'İptal' } }
190
+ };
191
+
192
+ function App() {
193
+ return (
194
+ <DocyI18nProvider
195
+ defaultTranslations={translations}
196
+ defaultLanguage="tr"
197
+ storage={storage}
198
+ >
199
+ <Dashboard />
200
+ </DocyI18nProvider>
201
+ );
202
+ }
203
+
204
+ function Dashboard() {
205
+ const { t, tv, lang, setLanguage } = useI18n();
206
+
207
+ return (
208
+ <View>
209
+ <Text>{t('common.save', 'Save')}</Text>
210
+ <Text>{tv('translate.Active')}</Text>
211
+ <Button onPress={() => setLanguage('en')} title="English" />
212
+ </View>
213
+ );
214
+ }
215
+ ```
216
+
217
+ **Key differences from React/Web entrypoint:**
218
+ - `useI18n()` works **without** a provider (graceful fallback — returns key or fallback string)
219
+ - `DocyI18nProvider` accepts nested translations (`{ en: { common: { save: "Save" } } }`)
220
+ - `t('key', 'Fallback')` — second argument is a fallback string (not params)
221
+ - `lang` / `setLanguage` aliases for `locale` / `setLocale`
222
+ - Storage uses `getString/setString` pattern — compatible with **MMKV**, **AsyncStorage**, **expo-sqlite**, or any custom adapter
223
+ - `storage` prop is **optional** — if not provided, language preference won't persist across sessions
224
+
225
+ ## Configuration
226
+
227
+ | Prop | Type | Default | Description |
228
+ |------|------|---------|-------------|
229
+ | `client` | `RestApiClient \| null` | `null` | Pre-configured API client with auth tokens |
230
+ | `getAccessToken` | `() => Promise<string \| null>` | `undefined` | Alternative auth callback (for SSR or custom setups) |
231
+ | `apiUrl` | `string` | `undefined` | API base URL (required with `getAccessToken`) |
232
+ | `translationsEndpoint` | `string` | `'v1/tenant/translations'` | API endpoint path |
233
+ | `staticTranslations` | `Record<string, string>` | `{}` | Pre-loaded translations (available immediately) |
234
+ | `cookieKey` | `string` | `'docyrus-locale'` | Cookie name for locale persistence |
235
+ | `mergeStrategy` | `'api-first' \| 'static-first'` | `'api-first'` | How to merge static and API translations |
236
+ | `fallback` | `'key' \| 'empty' \| (key) => string` | `'key'` | What to return when a key is not found |
237
+ | `disableApiFetch` | `boolean` | `false` | Skip API fetch entirely (use only static translations) |
238
+ | `userLanguageEndpoint` | `string \| false` | `'v1/users/me'` | PATCH endpoint to persist user language. Set `false` to disable |
239
+
240
+ ## Hooks / Composables
241
+
242
+ ### useDocyrusI18n() (React / Vue)
243
+
244
+ Full i18n context. Available in React (`@kivacore/i18n`) and Vue (`@kivacore/i18n/vue`). Throws if no provider.
245
+
246
+ ```tsx
247
+ const {
248
+ t, // (key, fallbackOrParams?) => string
249
+ tv, // (value) => string — translate "translate.Active" values
250
+ locale, // current locale string | null
251
+ setLocale, // (locale: string) => void — writes cookie + refetches
252
+ status, // 'loading' | 'ready' | 'error'
253
+ isLoading, // boolean
254
+ translations, // Record<string, string>
255
+ error, // Error | null
256
+ refetch // () => Promise<void>
257
+ } = useDocyrusI18n();
258
+ ```
259
+
260
+ ### useI18n() (React Native)
261
+
262
+ Full i18n context with graceful fallback. Works **with or without** provider. Use in shared library components.
263
+
264
+ ```tsx
265
+ import { useI18n } from '@kivacore/i18n/rn';
266
+
267
+ const {
268
+ t, // (key, fallbackOrParams?) => string
269
+ tv, // (value) => string
270
+ lang, // SupportedLanguage ('en' | 'tr')
271
+ locale, // alias for lang
272
+ setLanguage, // (lang: string) => void
273
+ setLocale, // alias for setLanguage
274
+ isLoading, // boolean
275
+ error, // Error | null
276
+ refetch, // () => Promise<void>
277
+ reloadTranslations // () => Promise<void>
278
+ } = useI18n();
279
+ ```
280
+
281
+ ### useTranslation()
282
+
283
+ Lightweight hook for components that only need `t()`:
284
+
285
+ ```tsx
286
+ const { t, tv, isLoading } = useTranslation();
287
+ ```
288
+
289
+ ## Merge Strategy
290
+
291
+ - **`'api-first'`** (default): `{ ...static, ...api }` — API translations override static. Use this when static translations are fallbacks.
292
+ - **`'static-first'`**: `{ ...api, ...static }` — Static translations override API. Use this for hardcoded overrides.
293
+
294
+ Static translations are available immediately on mount (no loading flash). API translations are fetched asynchronously and merged in.
295
+
296
+ ## Locale Management
297
+
298
+ ### Web (React / Vue)
299
+ 1. On mount: read locale from storage (cookie by default). If not set, locale is `null`.
300
+ 2. `setLocale('en')`: write to storage + `PATCH users/me { language }` + refetch translations.
301
+ 3. SSR: cookie can be read server-side via Next.js `cookies()` API.
302
+
303
+ ### React Native
304
+ 1. On mount: read from MMKV/AsyncStorage via `storage.getString(storageKey)`.
305
+ 2. `userLanguage` prop syncs with user profile language (e.g., "tr_TR" → "tr").
306
+ 3. `setLanguage('en')`: write to storage + call `onLanguageChange` callback.
307
+ 4. Remote translations fetched via `fetchRemote` prop.
308
+
309
+ ## Translation Function
310
+
311
+ The `t()` function accepts two call signatures:
312
+
313
+ ```tsx
314
+ // Basic lookup (returns key if not found)
315
+ t('common.save') // "Kaydet" or "common.save"
316
+
317
+ // With fallback string (returns fallback if key not found)
318
+ t('common.save', 'Save') // "Kaydet" or "Save"
319
+
320
+ // With interpolation params
321
+ t('greeting', { name: 'Ali' }) // "Merhaba, {{name}}!" → "Merhaba, Ali!"
322
+ ```
323
+
324
+ ### Interpolation
325
+
326
+ Three placeholder formats are supported:
327
+
328
+ ```tsx
329
+ // Double-brace (static translations convention)
330
+ t('greeting', { name: 'Ali' }) // "Merhaba, {{name}}!" → "Merhaba, Ali!"
331
+
332
+ // Single-brace named (API convention)
333
+ t('ai.chat', { name: 'Docyrus' }) // "Talk to {name} AI" → "Talk to Docyrus AI"
334
+
335
+ // Single-brace positional (API convention)
336
+ t('add.new', { '0': 'User' }) // "Add New {0}" → "Add New User"
337
+ ```
338
+
339
+ ### Translate Values (tv)
340
+
341
+ For API responses containing translatable values:
342
+
343
+ ```tsx
344
+ tv('translate.Active') // → t('common.Active') → "Aktif"
345
+ tv('Regular text') // → "Regular text" (unchanged)
346
+ ```
347
+
348
+ ## API Response Format
349
+
350
+ The API endpoint (`GET /v1/tenant/translations`) must return:
351
+
352
+ ```json
353
+ {
354
+ "success": true,
355
+ "data": {
356
+ "Show Expand Detail Button": "Detayı Genişlet Butonunu Göster",
357
+ "Add New {0}": "Yeni {0} Ekle",
358
+ "Talk to {name} AI": "{name} AI ile Konuş"
359
+ }
360
+ }
361
+ ```
362
+
363
+ Translation keys are flat strings (not dot-notation). Values may contain `{0}` or `{name}` placeholders.
364
+
365
+ ## Core (Framework-Agnostic)
366
+
367
+ ```tsx
368
+ import { I18nManager, interpolate, CookieStorageAdapter, MemoryStorageAdapter } from '@kivacore/i18n/core';
369
+
370
+ const manager = new I18nManager({
371
+ staticTranslations: { 'hello': 'Merhaba, {{name}}!' }
372
+ });
373
+
374
+ manager.subscribe((state) => console.log(state.status, state.translations));
375
+ await manager.initialize();
376
+
377
+ console.log(manager.t('hello', { name: 'Ali' })); // "Merhaba, Ali!"
378
+ ```
379
+
380
+ ## Development
381
+
382
+ ```bash
383
+ pnpm install
384
+ pnpm dev # Watch mode
385
+ pnpm build # Build ESM + dts
386
+ pnpm lint # ESLint
387
+ pnpm typecheck # ESLint + tsc --noEmit
388
+ ```
389
+
390
+ ## License
391
+
392
+ MIT
@@ -0,0 +1,27 @@
1
+ export { C as CookieStorageAdapter, I as I18nManager, a as I18nStateListener, M as MemoryStorageAdapter, g as getLocale, i as interpolate, s as setLocale, t as translateValue } from './locale-storage-DfFDJf0I.js';
2
+ import { T as TranslationDictionary } from './types-Bj3Uk0wv.js';
3
+ export { a as DocyrusI18nConfig, D as DocyrusI18nContextValue, F as FallbackStrategy, I as I18nStatus, b as I18nStorageAdapter, c as TranslationsResponse } from './types-Bj3Uk0wv.js';
4
+ import '@kivacore/api-client';
5
+
6
+ interface FetchTranslationsSSROptions {
7
+ /** Access token for API authentication. */
8
+ token: string;
9
+ /** API base URL. Required. */
10
+ apiUrl: string;
11
+ /** API endpoint path for translations. Default: 'v1/tenant/translations' */
12
+ translationsEndpoint?: string;
13
+ /** Next.js revalidate interval in seconds. Default: 300 */
14
+ revalidate?: number;
15
+ }
16
+ /**
17
+ * Fetch translations on the server (SSR / RSC).
18
+ *
19
+ * Designed for Next.js Server Components where React hooks are unavailable.
20
+ * Returns a TranslationDictionary to pass as `staticTranslations` to the provider.
21
+ *
22
+ * Returns `undefined` on failure — the provider will fall back to API fetch on client.
23
+ */
24
+ declare function fetchTranslationsSSR(options: FetchTranslationsSSROptions): Promise<TranslationDictionary | undefined>;
25
+
26
+ export { TranslationDictionary, fetchTranslationsSSR };
27
+ export type { FetchTranslationsSSROptions };