xertica-ui 2.5.2 → 2.5.3

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.
@@ -1,359 +1,359 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // bin/language-config.ts
3
- //
4
- // CLI-side helpers for managing the set of languages a scaffolded project
5
- // supports. This is the single source of truth for:
6
- // - The `init` prompt (which languages does the user want?)
7
- // - The `update languages` command (add/remove later)
8
- // - The generated App.tsx (`availableLanguages` prop on XerticaProvider)
9
- // - Which locale JSON files get copied/removed in the consumer project
10
- //
11
- // The selection is persisted in `src/locales/.languages.json` in the consumer
12
- // project so the CLI can re-read it on `update` without prompting again.
13
- // ─────────────────────────────────────────────────────────────────────────────
14
-
15
- import fs from 'fs-extra';
16
- import path from 'path';
17
-
18
- /** A language definition known to the CLI / shipped with the library. */
19
- export interface CliLanguageDefinition {
20
- code: string;
21
- label: string;
22
- shortLabel: string;
23
- /** Filename inside templates/src/locales/ (without extension) */
24
- jsonFile: string;
25
- }
26
-
27
- /**
28
- * The built-in languages the library ships with. Adding a new language here
29
- * (and a matching JSON file in templates/src/locales/) is all that's needed
30
- * to expose it via the CLI prompts.
31
- */
32
- export const SUPPORTED_LANGUAGES: CliLanguageDefinition[] = [
33
- { code: 'pt-BR', label: 'Português (BR)', shortLabel: 'PT', jsonFile: 'pt-BR' },
34
- { code: 'en', label: 'English', shortLabel: 'EN', jsonFile: 'en' },
35
- { code: 'es', label: 'Español', shortLabel: 'ES', jsonFile: 'es' },
36
- ];
37
-
38
- /** Default selection when the user accepts everything. */
39
- export const DEFAULT_SELECTION = SUPPORTED_LANGUAGES.map(l => l.code);
40
-
41
- /** File written to `src/locales/.languages.json` to persist the selection. */
42
- export const LANGUAGES_CONFIG_FILENAME = '.languages.json';
43
-
44
- interface LanguagesConfigFile {
45
- /** Schema version — bump if the file format changes. */
46
- version: 1;
47
- /** Codes of the languages the project currently supports. */
48
- codes: string[];
49
- }
50
-
51
- // ── Persistence helpers ──────────────────────────────────────────────────────
52
-
53
- /**
54
- * Read the persisted language selection from a project. Returns `null` if the
55
- * file does not exist (legacy projects scaffolded before this feature shipped).
56
- */
57
- export async function readLanguagesConfig(targetDir: string): Promise<string[] | null> {
58
- const configPath = path.join(targetDir, 'src', 'locales', LANGUAGES_CONFIG_FILENAME);
59
- if (!(await fs.pathExists(configPath))) {
60
- return null;
61
- }
62
- try {
63
- const content = (await fs.readJson(configPath)) as LanguagesConfigFile;
64
- if (Array.isArray(content?.codes) && content.codes.length > 0) {
65
- return content.codes;
66
- }
67
- } catch {
68
- // Corrupt file — treat as missing
69
- }
70
- return null;
71
- }
72
-
73
- /** Write the language selection to `src/locales/.languages.json`. */
74
- export async function writeLanguagesConfig(targetDir: string, codes: string[]): Promise<void> {
75
- const configPath = path.join(targetDir, 'src', 'locales', LANGUAGES_CONFIG_FILENAME);
76
- await fs.ensureDir(path.dirname(configPath));
77
- const payload: LanguagesConfigFile = { version: 1, codes };
78
- await fs.writeJson(configPath, payload, { spaces: 2 });
79
- }
80
-
81
- // ── File-system helpers ──────────────────────────────────────────────────────
82
-
83
- /**
84
- * Copy only the locale folders matching the selected codes into the project,
85
- * leaving previously-copied locales for unselected languages in place ONLY if
86
- * `pruneOthers` is false. When `true` (typical for re-selection on update),
87
- * the unselected language folders are deleted from the project.
88
- *
89
- * Each language is shipped as a folder of split JSON files:
90
- *
91
- * templates/src/locales/<lang>/{common,nav,errors,languageSelector,themeToggle}.json
92
- * templates/src/locales/<lang>/pages/<page>.json
93
- * templates/src/locales/<lang>/components/<component>.json
94
- *
95
- * Also migrates legacy projects that still have flat `<lang>.json` files
96
- * (deletes them so they don't shadow the new folder).
97
- */
98
- export async function syncLocaleFiles(
99
- templatesDir: string,
100
- targetDir: string,
101
- selectedCodes: string[],
102
- options: { pruneOthers: boolean }
103
- ): Promise<{ copied: string[]; removed: string[] }> {
104
- const targetLocalesDir = path.join(targetDir, 'src', 'locales');
105
- await fs.ensureDir(targetLocalesDir);
106
-
107
- const selectedLangs = SUPPORTED_LANGUAGES.filter(l => selectedCodes.includes(l.code));
108
- const unselectedLangs = SUPPORTED_LANGUAGES.filter(l => !selectedCodes.includes(l.code));
109
-
110
- const copied: string[] = [];
111
- const removed: string[] = [];
112
-
113
- // Copy selected language folders from the library templates
114
- for (const lang of selectedLangs) {
115
- const src = path.join(templatesDir, 'src', 'locales', lang.jsonFile);
116
- const dest = path.join(targetLocalesDir, lang.jsonFile);
117
- if (await fs.pathExists(src)) {
118
- // Clear the target folder first so removed keys don't linger
119
- await fs.remove(dest);
120
- await fs.copy(src, dest, { overwrite: true });
121
- copied.push(`${lang.jsonFile}/`);
122
- }
123
-
124
- // Migrate legacy flat file if it exists alongside the new folder
125
- const legacyFlat = path.join(targetLocalesDir, `${lang.jsonFile}.json`);
126
- if (await fs.pathExists(legacyFlat)) {
127
- await fs.remove(legacyFlat);
128
- }
129
- }
130
-
131
- // Remove unselected language folders from the project (when pruning)
132
- if (options.pruneOthers) {
133
- for (const lang of unselectedLangs) {
134
- const dest = path.join(targetLocalesDir, lang.jsonFile);
135
- if (await fs.pathExists(dest)) {
136
- await fs.remove(dest);
137
- removed.push(`${lang.jsonFile}/`);
138
- }
139
- // Also prune any legacy flat file
140
- const legacyFlat = path.join(targetLocalesDir, `${lang.jsonFile}.json`);
141
- if (await fs.pathExists(legacyFlat)) {
142
- await fs.remove(legacyFlat);
143
- removed.push(`${lang.jsonFile}.json`);
144
- }
145
- }
146
- }
147
-
148
- return { copied, removed };
149
- }
150
-
151
- // ── Code generators ──────────────────────────────────────────────────────────
152
-
153
- /**
154
- * Generate the contents of `src/i18n.ts` for a freshly-scaffolded project.
155
- *
156
- * Each selected language is pulled via Vite's `import.meta.glob` (one glob per
157
- * language) — resolved statically at build time so JSON gets inlined and
158
- * tree-shaken. No per-chunk imports to maintain; adding a new
159
- * `locales/<lang>/pages/foo.json` is picked up automatically on the next
160
- * Vite build.
161
- */
162
- export function generateI18nFile(selectedCodes: string[]): string {
163
- const selectedLangs = SUPPORTED_LANGUAGES.filter(l => selectedCodes.includes(l.code));
164
- if (selectedLangs.length === 0) {
165
- throw new Error('generateI18nFile: must include at least one language');
166
- }
167
-
168
- const fallback = selectedLangs[0].code;
169
-
170
- const bundleLines = selectedLangs
171
- .map(
172
- lang =>
173
- `const ${toJsIdent(lang.code)} = bundleLang(\n` +
174
- ` import.meta.glob('./locales/${lang.jsonFile}/**/*.json', { eager: true, import: 'default' })\n` +
175
- `);`
176
- )
177
- .join('\n');
178
-
179
- const resourceEntries = selectedLangs
180
- .map(l => ` '${l.code}': { translation: ${toJsIdent(l.code)} },`)
181
- .join('\n');
182
-
183
- return `// ─────────────────────────────────────────────────────────────────────────────
184
- // i18n.ts — i18next configuration (generated by xertica-ui CLI)
185
- //
186
- // Import this file once at the application entry point (main.tsx) BEFORE any
187
- // component is rendered. The side-effect initializes i18next synchronously so
188
- // that \`useTranslation()\` is ready on first render.
189
- //
190
- // Locale layout (split for maintainability — merged at boot into a single
191
- // \`translation\` namespace so all existing \`t('home.welcome')\`-style calls
192
- // keep working without changes):
193
- //
194
- // locales/<lang>/{common,nav,errors,languageSelector,themeToggle}.json
195
- // locales/<lang>/pages/{home,templates,login,resetPassword,verifyEmail}.json
196
- // locales/<lang>/components/{assistant,sidebar,media,projectCard,
197
- // profileCard,notificationCard,activityCard,
198
- // stats,team}.json
199
- //
200
- // To add or remove a language, run: npx xertica-ui update → Languages
201
- // The CLI will regenerate this file and copy/remove locale folders accordingly.
202
- // ─────────────────────────────────────────────────────────────────────────────
203
-
204
- import i18n from 'i18next';
205
- import { initReactI18next } from 'react-i18next';
206
-
207
- /**
208
- * Merge a Vite glob result into a single { key: contents } bundle. The key is
209
- * derived from the file basename — folders (pages/components) are discarded
210
- * because the legacy flat JSON layout used a single namespace.
211
- */
212
- function bundleLang(chunks: Record<string, unknown>): Record<string, unknown> {
213
- const out: Record<string, unknown> = {};
214
- for (const [filePath, value] of Object.entries(chunks)) {
215
- const base = filePath.split('/').pop();
216
- if (!base) continue;
217
- const key = base.replace(/\\.json$/, '');
218
- out[key] = value;
219
- }
220
- return out;
221
- }
222
-
223
- // One \`import.meta.glob\` call per language — Vite requires literal patterns,
224
- // so we can't loop. \`eager: true\` inlines the JSON; \`import: 'default'\`
225
- // returns the JSON value directly instead of \`{ default: ... }\`.
226
- ${bundleLines}
227
-
228
- const STORAGE_KEY = 'xertica_language';
229
- const DEFAULT_FALLBACK = '${fallback}';
230
-
231
- const savedLanguage =
232
- typeof window !== 'undefined'
233
- ? (localStorage.getItem(STORAGE_KEY) ?? DEFAULT_FALLBACK)
234
- : DEFAULT_FALLBACK;
235
-
236
- i18n.use(initReactI18next).init({
237
- resources: {
238
- ${resourceEntries}
239
- },
240
- lng: savedLanguage,
241
- fallbackLng: DEFAULT_FALLBACK,
242
- interpolation: {
243
- // React already escapes values — no need for i18next to double-escape
244
- escapeValue: false,
245
- },
246
- });
247
-
248
- /**
249
- * Register an additional locale at runtime (e.g. for late-loaded plugins).
250
- * Safe to call multiple times — a bundle is only added the first time it
251
- * appears for a given \`(code, namespace)\` pair.
252
- */
253
- export function registerLanguageResource(
254
- code: string,
255
- json: Record<string, unknown>,
256
- ns: string = 'translation'
257
- ): void {
258
- if (!i18n.hasResourceBundle(code, ns)) {
259
- i18n.addResourceBundle(code, ns, json, true, true);
260
- }
261
- }
262
-
263
- export default i18n;
264
- `;
265
- }
266
-
267
- /**
268
- * Generate the App.tsx source with the appropriate `availableLanguages` prop
269
- * on `<XerticaProvider>`. When the project ships with the default 3 languages,
270
- * we omit the prop entirely (the library default already matches). Otherwise
271
- * we emit an explicit array.
272
- */
273
- export function generateAppTsx(selectedCodes: string[], disableDarkMode: boolean = false): string {
274
- const selectedLangs = SUPPORTED_LANGUAGES.filter(l => selectedCodes.includes(l.code));
275
- const isMonolingual = selectedLangs.length === 1;
276
- const disableDarkModeProp = disableDarkMode ? `\n disableDarkMode={true}` : '';
277
- const isAllDefaults =
278
- selectedLangs.length === SUPPORTED_LANGUAGES.length &&
279
- selectedLangs.every(l => DEFAULT_SELECTION.includes(l.code));
280
-
281
- // Decide whether and how to render the `availableLanguages` prop on
282
- // XerticaProvider. When the user selected all 3 defaults, we can omit the
283
- // prop (the library default matches). Otherwise we emit the explicit set.
284
- const languagesArrayLiteral = selectedLangs
285
- .map(
286
- l => ` { code: '${l.code}', label: '${l.label}', shortLabel: '${l.shortLabel}' },`
287
- )
288
- .join('\n');
289
-
290
- const availableLanguagesProp = isAllDefaults
291
- ? ''
292
- : `\n availableLanguages={[
293
- ${languagesArrayLiteral}
294
- ]}`;
295
-
296
- const monolingualBanner = isMonolingual
297
- ? `\n// This project is configured for a single language — the LanguageSelector
298
- // auto-hides because there is nothing to switch to.`
299
- : '';
300
-
301
- return `import React, { Suspense } from 'react';
302
- import { BrowserRouter as Router } from 'react-router-dom';
303
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
304
- import { XerticaProvider } from 'xertica-ui/brand';
305
- import { AuthProvider } from './context/AuthContext';
306
- import { AuthGuard } from './components/AuthGuard';
307
- import { AppErrorBoundary, PageErrorBoundary } from '../shared/error-boundary';
308
-
309
- // ─── Query client ─────────────────────────────────────────────────────────────
310
- // Shared instance — configure defaults here.
311
- // To add React Query Devtools: npm i @tanstack/react-query-devtools and wrap below.
312
-
313
- const queryClient = new QueryClient({
314
- defaultOptions: {
315
- queries: {
316
- retry: 1,
317
- refetchOnWindowFocus: false,
318
- },
319
- },
320
- });
321
-
322
- // ─── App ─────────────────────────────────────────────────────────────────────${monolingualBanner}
323
-
324
- export default function App() {
325
- const geminiApiKey = import.meta.env.VITE_GEMINI_API_KEY;
326
- const googleMapsApiKey = import.meta.env.VITE_GOOGLE_MAPS_API_KEY;
327
-
328
- return (
329
- <AppErrorBoundary>
330
- <QueryClientProvider client={queryClient}>
331
- <XerticaProvider
332
- apiKey={geminiApiKey}
333
- googleMapsApiKey={googleMapsApiKey}
334
- useCustomTokens={true}${availableLanguagesProp}${disableDarkModeProp}
335
- >
336
- <Router>
337
- {/* AuthProvider must be inside Router (needs useNavigate) */}
338
- <AuthProvider>
339
- <PageErrorBoundary>
340
- <Suspense fallback={null}>
341
- <AuthGuard />
342
- </Suspense>
343
- </PageErrorBoundary>
344
- </AuthProvider>
345
- </Router>
346
- </XerticaProvider>
347
- </QueryClientProvider>
348
- </AppErrorBoundary>
349
- );
350
- }
351
- `;
352
- }
353
-
354
- // ── Internal ─────────────────────────────────────────────────────────────────
355
-
356
- /** Convert a BCP-47 code to a safe JS identifier (e.g. 'pt-BR' → 'ptBR'). */
357
- function toJsIdent(code: string): string {
358
- return code.replace(/[^a-zA-Z0-9]/g, '');
359
- }
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // bin/language-config.ts
3
+ //
4
+ // CLI-side helpers for managing the set of languages a scaffolded project
5
+ // supports. This is the single source of truth for:
6
+ // - The `init` prompt (which languages does the user want?)
7
+ // - The `update languages` command (add/remove later)
8
+ // - The generated App.tsx (`availableLanguages` prop on XerticaProvider)
9
+ // - Which locale JSON files get copied/removed in the consumer project
10
+ //
11
+ // The selection is persisted in `src/locales/.languages.json` in the consumer
12
+ // project so the CLI can re-read it on `update` without prompting again.
13
+ // ─────────────────────────────────────────────────────────────────────────────
14
+
15
+ import fs from 'fs-extra';
16
+ import path from 'path';
17
+
18
+ /** A language definition known to the CLI / shipped with the library. */
19
+ export interface CliLanguageDefinition {
20
+ code: string;
21
+ label: string;
22
+ shortLabel: string;
23
+ /** Filename inside templates/src/locales/ (without extension) */
24
+ jsonFile: string;
25
+ }
26
+
27
+ /**
28
+ * The built-in languages the library ships with. Adding a new language here
29
+ * (and a matching JSON file in templates/src/locales/) is all that's needed
30
+ * to expose it via the CLI prompts.
31
+ */
32
+ export const SUPPORTED_LANGUAGES: CliLanguageDefinition[] = [
33
+ { code: 'pt-BR', label: 'Português (BR)', shortLabel: 'PT', jsonFile: 'pt-BR' },
34
+ { code: 'en', label: 'English', shortLabel: 'EN', jsonFile: 'en' },
35
+ { code: 'es', label: 'Español', shortLabel: 'ES', jsonFile: 'es' },
36
+ ];
37
+
38
+ /** Default selection when the user accepts everything. */
39
+ export const DEFAULT_SELECTION = SUPPORTED_LANGUAGES.map(l => l.code);
40
+
41
+ /** File written to `src/locales/.languages.json` to persist the selection. */
42
+ export const LANGUAGES_CONFIG_FILENAME = '.languages.json';
43
+
44
+ interface LanguagesConfigFile {
45
+ /** Schema version — bump if the file format changes. */
46
+ version: 1;
47
+ /** Codes of the languages the project currently supports. */
48
+ codes: string[];
49
+ }
50
+
51
+ // ── Persistence helpers ──────────────────────────────────────────────────────
52
+
53
+ /**
54
+ * Read the persisted language selection from a project. Returns `null` if the
55
+ * file does not exist (legacy projects scaffolded before this feature shipped).
56
+ */
57
+ export async function readLanguagesConfig(targetDir: string): Promise<string[] | null> {
58
+ const configPath = path.join(targetDir, 'src', 'locales', LANGUAGES_CONFIG_FILENAME);
59
+ if (!(await fs.pathExists(configPath))) {
60
+ return null;
61
+ }
62
+ try {
63
+ const content = (await fs.readJson(configPath)) as LanguagesConfigFile;
64
+ if (Array.isArray(content?.codes) && content.codes.length > 0) {
65
+ return content.codes;
66
+ }
67
+ } catch {
68
+ // Corrupt file — treat as missing
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** Write the language selection to `src/locales/.languages.json`. */
74
+ export async function writeLanguagesConfig(targetDir: string, codes: string[]): Promise<void> {
75
+ const configPath = path.join(targetDir, 'src', 'locales', LANGUAGES_CONFIG_FILENAME);
76
+ await fs.ensureDir(path.dirname(configPath));
77
+ const payload: LanguagesConfigFile = { version: 1, codes };
78
+ await fs.writeJson(configPath, payload, { spaces: 2 });
79
+ }
80
+
81
+ // ── File-system helpers ──────────────────────────────────────────────────────
82
+
83
+ /**
84
+ * Copy only the locale folders matching the selected codes into the project,
85
+ * leaving previously-copied locales for unselected languages in place ONLY if
86
+ * `pruneOthers` is false. When `true` (typical for re-selection on update),
87
+ * the unselected language folders are deleted from the project.
88
+ *
89
+ * Each language is shipped as a folder of split JSON files:
90
+ *
91
+ * templates/src/locales/<lang>/{common,nav,errors,languageSelector,themeToggle}.json
92
+ * templates/src/locales/<lang>/pages/<page>.json
93
+ * templates/src/locales/<lang>/components/<component>.json
94
+ *
95
+ * Also migrates legacy projects that still have flat `<lang>.json` files
96
+ * (deletes them so they don't shadow the new folder).
97
+ */
98
+ export async function syncLocaleFiles(
99
+ templatesDir: string,
100
+ targetDir: string,
101
+ selectedCodes: string[],
102
+ options: { pruneOthers: boolean }
103
+ ): Promise<{ copied: string[]; removed: string[] }> {
104
+ const targetLocalesDir = path.join(targetDir, 'src', 'locales');
105
+ await fs.ensureDir(targetLocalesDir);
106
+
107
+ const selectedLangs = SUPPORTED_LANGUAGES.filter(l => selectedCodes.includes(l.code));
108
+ const unselectedLangs = SUPPORTED_LANGUAGES.filter(l => !selectedCodes.includes(l.code));
109
+
110
+ const copied: string[] = [];
111
+ const removed: string[] = [];
112
+
113
+ // Copy selected language folders from the library templates
114
+ for (const lang of selectedLangs) {
115
+ const src = path.join(templatesDir, 'src', 'locales', lang.jsonFile);
116
+ const dest = path.join(targetLocalesDir, lang.jsonFile);
117
+ if (await fs.pathExists(src)) {
118
+ // Clear the target folder first so removed keys don't linger
119
+ await fs.remove(dest);
120
+ await fs.copy(src, dest, { overwrite: true });
121
+ copied.push(`${lang.jsonFile}/`);
122
+ }
123
+
124
+ // Migrate legacy flat file if it exists alongside the new folder
125
+ const legacyFlat = path.join(targetLocalesDir, `${lang.jsonFile}.json`);
126
+ if (await fs.pathExists(legacyFlat)) {
127
+ await fs.remove(legacyFlat);
128
+ }
129
+ }
130
+
131
+ // Remove unselected language folders from the project (when pruning)
132
+ if (options.pruneOthers) {
133
+ for (const lang of unselectedLangs) {
134
+ const dest = path.join(targetLocalesDir, lang.jsonFile);
135
+ if (await fs.pathExists(dest)) {
136
+ await fs.remove(dest);
137
+ removed.push(`${lang.jsonFile}/`);
138
+ }
139
+ // Also prune any legacy flat file
140
+ const legacyFlat = path.join(targetLocalesDir, `${lang.jsonFile}.json`);
141
+ if (await fs.pathExists(legacyFlat)) {
142
+ await fs.remove(legacyFlat);
143
+ removed.push(`${lang.jsonFile}.json`);
144
+ }
145
+ }
146
+ }
147
+
148
+ return { copied, removed };
149
+ }
150
+
151
+ // ── Code generators ──────────────────────────────────────────────────────────
152
+
153
+ /**
154
+ * Generate the contents of `src/i18n.ts` for a freshly-scaffolded project.
155
+ *
156
+ * Each selected language is pulled via Vite's `import.meta.glob` (one glob per
157
+ * language) — resolved statically at build time so JSON gets inlined and
158
+ * tree-shaken. No per-chunk imports to maintain; adding a new
159
+ * `locales/<lang>/pages/foo.json` is picked up automatically on the next
160
+ * Vite build.
161
+ */
162
+ export function generateI18nFile(selectedCodes: string[]): string {
163
+ const selectedLangs = SUPPORTED_LANGUAGES.filter(l => selectedCodes.includes(l.code));
164
+ if (selectedLangs.length === 0) {
165
+ throw new Error('generateI18nFile: must include at least one language');
166
+ }
167
+
168
+ const fallback = selectedLangs[0].code;
169
+
170
+ const bundleLines = selectedLangs
171
+ .map(
172
+ lang =>
173
+ `const ${toJsIdent(lang.code)} = bundleLang(\n` +
174
+ ` import.meta.glob('./locales/${lang.jsonFile}/**/*.json', { eager: true, import: 'default' })\n` +
175
+ `);`
176
+ )
177
+ .join('\n');
178
+
179
+ const resourceEntries = selectedLangs
180
+ .map(l => ` '${l.code}': { translation: ${toJsIdent(l.code)} },`)
181
+ .join('\n');
182
+
183
+ return `// ─────────────────────────────────────────────────────────────────────────────
184
+ // i18n.ts — i18next configuration (generated by xertica-ui CLI)
185
+ //
186
+ // Import this file once at the application entry point (main.tsx) BEFORE any
187
+ // component is rendered. The side-effect initializes i18next synchronously so
188
+ // that \`useTranslation()\` is ready on first render.
189
+ //
190
+ // Locale layout (split for maintainability — merged at boot into a single
191
+ // \`translation\` namespace so all existing \`t('home.welcome')\`-style calls
192
+ // keep working without changes):
193
+ //
194
+ // locales/<lang>/{common,nav,errors,languageSelector,themeToggle}.json
195
+ // locales/<lang>/pages/{home,templates,login,resetPassword,verifyEmail}.json
196
+ // locales/<lang>/components/{assistant,sidebar,media,projectCard,
197
+ // profileCard,notificationCard,activityCard,
198
+ // stats,team}.json
199
+ //
200
+ // To add or remove a language, run: npx xertica-ui update → Languages
201
+ // The CLI will regenerate this file and copy/remove locale folders accordingly.
202
+ // ─────────────────────────────────────────────────────────────────────────────
203
+
204
+ import i18n from 'i18next';
205
+ import { initReactI18next } from 'react-i18next';
206
+
207
+ /**
208
+ * Merge a Vite glob result into a single { key: contents } bundle. The key is
209
+ * derived from the file basename — folders (pages/components) are discarded
210
+ * because the legacy flat JSON layout used a single namespace.
211
+ */
212
+ function bundleLang(chunks: Record<string, unknown>): Record<string, unknown> {
213
+ const out: Record<string, unknown> = {};
214
+ for (const [filePath, value] of Object.entries(chunks)) {
215
+ const base = filePath.split('/').pop();
216
+ if (!base) continue;
217
+ const key = base.replace(/\\.json$/, '');
218
+ out[key] = value;
219
+ }
220
+ return out;
221
+ }
222
+
223
+ // One \`import.meta.glob\` call per language — Vite requires literal patterns,
224
+ // so we can't loop. \`eager: true\` inlines the JSON; \`import: 'default'\`
225
+ // returns the JSON value directly instead of \`{ default: ... }\`.
226
+ ${bundleLines}
227
+
228
+ const STORAGE_KEY = 'xertica_language';
229
+ const DEFAULT_FALLBACK = '${fallback}';
230
+
231
+ const savedLanguage =
232
+ typeof window !== 'undefined'
233
+ ? (localStorage.getItem(STORAGE_KEY) ?? DEFAULT_FALLBACK)
234
+ : DEFAULT_FALLBACK;
235
+
236
+ i18n.use(initReactI18next).init({
237
+ resources: {
238
+ ${resourceEntries}
239
+ },
240
+ lng: savedLanguage,
241
+ fallbackLng: DEFAULT_FALLBACK,
242
+ interpolation: {
243
+ // React already escapes values — no need for i18next to double-escape
244
+ escapeValue: false,
245
+ },
246
+ });
247
+
248
+ /**
249
+ * Register an additional locale at runtime (e.g. for late-loaded plugins).
250
+ * Safe to call multiple times — a bundle is only added the first time it
251
+ * appears for a given \`(code, namespace)\` pair.
252
+ */
253
+ export function registerLanguageResource(
254
+ code: string,
255
+ json: Record<string, unknown>,
256
+ ns: string = 'translation'
257
+ ): void {
258
+ if (!i18n.hasResourceBundle(code, ns)) {
259
+ i18n.addResourceBundle(code, ns, json, true, true);
260
+ }
261
+ }
262
+
263
+ export default i18n;
264
+ `;
265
+ }
266
+
267
+ /**
268
+ * Generate the App.tsx source with the appropriate `availableLanguages` prop
269
+ * on `<XerticaProvider>`. When the project ships with the default 3 languages,
270
+ * we omit the prop entirely (the library default already matches). Otherwise
271
+ * we emit an explicit array.
272
+ */
273
+ export function generateAppTsx(selectedCodes: string[], disableDarkMode: boolean = false): string {
274
+ const selectedLangs = SUPPORTED_LANGUAGES.filter(l => selectedCodes.includes(l.code));
275
+ const isMonolingual = selectedLangs.length === 1;
276
+ const disableDarkModeProp = disableDarkMode ? `\n disableDarkMode={true}` : '';
277
+ const isAllDefaults =
278
+ selectedLangs.length === SUPPORTED_LANGUAGES.length &&
279
+ selectedLangs.every(l => DEFAULT_SELECTION.includes(l.code));
280
+
281
+ // Decide whether and how to render the `availableLanguages` prop on
282
+ // XerticaProvider. When the user selected all 3 defaults, we can omit the
283
+ // prop (the library default matches). Otherwise we emit the explicit set.
284
+ const languagesArrayLiteral = selectedLangs
285
+ .map(
286
+ l => ` { code: '${l.code}', label: '${l.label}', shortLabel: '${l.shortLabel}' },`
287
+ )
288
+ .join('\n');
289
+
290
+ const availableLanguagesProp = isAllDefaults
291
+ ? ''
292
+ : `\n availableLanguages={[
293
+ ${languagesArrayLiteral}
294
+ ]}`;
295
+
296
+ const monolingualBanner = isMonolingual
297
+ ? `\n// This project is configured for a single language — the LanguageSelector
298
+ // auto-hides because there is nothing to switch to.`
299
+ : '';
300
+
301
+ return `import React, { Suspense } from 'react';
302
+ import { BrowserRouter as Router } from 'react-router-dom';
303
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
304
+ import { XerticaProvider } from 'xertica-ui/brand';
305
+ import { AuthProvider } from './context/AuthContext';
306
+ import { AuthGuard } from './components/AuthGuard';
307
+ import { AppErrorBoundary, PageErrorBoundary } from '../shared/error-boundary';
308
+
309
+ // ─── Query client ─────────────────────────────────────────────────────────────
310
+ // Shared instance — configure defaults here.
311
+ // To add React Query Devtools: npm i @tanstack/react-query-devtools and wrap below.
312
+
313
+ const queryClient = new QueryClient({
314
+ defaultOptions: {
315
+ queries: {
316
+ retry: 1,
317
+ refetchOnWindowFocus: false,
318
+ },
319
+ },
320
+ });
321
+
322
+ // ─── App ─────────────────────────────────────────────────────────────────────${monolingualBanner}
323
+
324
+ export default function App() {
325
+ const geminiApiKey = import.meta.env.VITE_GEMINI_API_KEY;
326
+ const googleMapsApiKey = import.meta.env.VITE_GOOGLE_MAPS_API_KEY;
327
+
328
+ return (
329
+ <AppErrorBoundary>
330
+ <QueryClientProvider client={queryClient}>
331
+ <XerticaProvider
332
+ apiKey={geminiApiKey}
333
+ googleMapsApiKey={googleMapsApiKey}
334
+ useCustomTokens={true}${availableLanguagesProp}${disableDarkModeProp}
335
+ >
336
+ <Router>
337
+ {/* AuthProvider must be inside Router (needs useNavigate) */}
338
+ <AuthProvider>
339
+ <PageErrorBoundary>
340
+ <Suspense fallback={null}>
341
+ <AuthGuard />
342
+ </Suspense>
343
+ </PageErrorBoundary>
344
+ </AuthProvider>
345
+ </Router>
346
+ </XerticaProvider>
347
+ </QueryClientProvider>
348
+ </AppErrorBoundary>
349
+ );
350
+ }
351
+ `;
352
+ }
353
+
354
+ // ── Internal ─────────────────────────────────────────────────────────────────
355
+
356
+ /** Convert a BCP-47 code to a safe JS identifier (e.g. 'pt-BR' → 'ptBR'). */
357
+ function toJsIdent(code: string): string {
358
+ return code.replace(/[^a-zA-Z0-9]/g, '');
359
+ }