@pie-qti/i18n 0.1.0 → 0.1.5

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 (63) hide show
  1. package/dist/core/I18n.d.ts +3 -2
  2. package/dist/core/I18n.d.ts.map +1 -1
  3. package/dist/core/I18n.js +11 -6
  4. package/dist/core/I18n.js.map +1 -1
  5. package/dist/locales/ar-SA.d.ts +43 -0
  6. package/dist/locales/ar-SA.d.ts.map +1 -1
  7. package/dist/locales/ar-SA.js +44 -0
  8. package/dist/locales/ar-SA.js.map +1 -1
  9. package/dist/locales/en-US.d.ts +43 -0
  10. package/dist/locales/en-US.d.ts.map +1 -1
  11. package/dist/locales/en-US.js +44 -0
  12. package/dist/locales/en-US.js.map +1 -1
  13. package/dist/locales/es-ES.d.ts +43 -0
  14. package/dist/locales/es-ES.d.ts.map +1 -1
  15. package/dist/locales/es-ES.js +44 -0
  16. package/dist/locales/es-ES.js.map +1 -1
  17. package/dist/locales/fr-FR.d.ts +43 -0
  18. package/dist/locales/fr-FR.d.ts.map +1 -1
  19. package/dist/locales/fr-FR.js +44 -0
  20. package/dist/locales/fr-FR.js.map +1 -1
  21. package/dist/locales/nl-NL.d.ts +43 -0
  22. package/dist/locales/nl-NL.d.ts.map +1 -1
  23. package/dist/locales/nl-NL.js +44 -0
  24. package/dist/locales/nl-NL.js.map +1 -1
  25. package/dist/locales/ro-RO.d.ts +43 -0
  26. package/dist/locales/ro-RO.d.ts.map +1 -1
  27. package/dist/locales/ro-RO.js +44 -0
  28. package/dist/locales/ro-RO.js.map +1 -1
  29. package/dist/locales/th-TH.d.ts +43 -0
  30. package/dist/locales/th-TH.d.ts.map +1 -1
  31. package/dist/locales/th-TH.js +44 -0
  32. package/dist/locales/th-TH.js.map +1 -1
  33. package/dist/locales/zh-CN.d.ts +43 -0
  34. package/dist/locales/zh-CN.d.ts.map +1 -1
  35. package/dist/locales/zh-CN.js +44 -0
  36. package/dist/locales/zh-CN.js.map +1 -1
  37. package/dist/providers/SvelteI18nProvider.d.ts +5 -14
  38. package/dist/providers/SvelteI18nProvider.d.ts.map +1 -1
  39. package/dist/providers/SvelteI18nProvider.js +7 -47
  40. package/dist/providers/SvelteI18nProvider.js.map +1 -1
  41. package/package.json +29 -7
  42. package/.turbo/turbo-build.log +0 -264
  43. package/docs/ADVANCED_FEATURES.md +0 -556
  44. package/docs/COMPONENT_PATTERNS.md +0 -896
  45. package/docs/INTEGRATION_GUIDE.md +0 -695
  46. package/scripts/check-translations.ts +0 -289
  47. package/scripts/scan-hardcoded-strings.ts +0 -266
  48. package/src/core/I18n.ts +0 -235
  49. package/src/core/I18nProvider.ts +0 -68
  50. package/src/core/types.ts +0 -45
  51. package/src/index.ts +0 -22
  52. package/src/locales/ar-SA.ts +0 -860
  53. package/src/locales/en-US.ts +0 -828
  54. package/src/locales/es-ES.ts +0 -816
  55. package/src/locales/fr-FR.ts +0 -815
  56. package/src/locales/nl-NL.ts +0 -815
  57. package/src/locales/ro-RO.ts +0 -815
  58. package/src/locales/th-TH.ts +0 -816
  59. package/src/locales/zh-CN.ts +0 -828
  60. package/src/providers/SvelteI18nProvider.ts +0 -170
  61. package/tests/i18n.test.ts +0 -146
  62. package/tsconfig.json +0 -10
  63. package/tsconfig.tsbuildinfo +0 -1
@@ -1,289 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Translation Coverage Checker
4
- *
5
- * This script compares all locale files against the en-US reference to detect:
6
- * 1. Missing keys in other locales
7
- * 2. Extra keys that don't exist in en-US (likely obsolete)
8
- * 3. Keys with identical values to en-US (likely untranslated)
9
- *
10
- * Usage:
11
- * bun run scripts/check-translations.ts
12
- * bun run scripts/check-translations.ts --locale nl-NL # Check specific locale
13
- * bun run scripts/check-translations.ts --fix # Auto-add missing keys with TODO markers
14
- */
15
-
16
- import { readdir, readFile, writeFile } from 'fs/promises';
17
- import { join, dirname } from 'path';
18
- import { fileURLToPath } from 'url';
19
-
20
- const __dirname = dirname(fileURLToPath(import.meta.url));
21
- const LOCALES_DIR = join(__dirname, '../src/locales');
22
- const REFERENCE_LOCALE = 'en-US';
23
-
24
- interface TranslationObject {
25
- [key: string]: string | TranslationObject;
26
- }
27
-
28
- interface LocaleData {
29
- locale: string;
30
- data: TranslationObject;
31
- filePath: string;
32
- }
33
-
34
- /**
35
- * Flatten nested object into dot-notation keys
36
- * Example: { common: { submit: 'Submit' } } => { 'common.submit': 'Submit' }
37
- */
38
- function flattenObject(obj: TranslationObject, prefix = ''): Record<string, string> {
39
- const result: Record<string, string> = {};
40
-
41
- for (const [key, value] of Object.entries(obj)) {
42
- const fullKey = prefix ? `${prefix}.${key}` : key;
43
-
44
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
45
- // Handle nested objects (but not arrays like plural forms)
46
- Object.assign(result, flattenObject(value, fullKey));
47
- } else {
48
- // Leaf node - store the value as string
49
- result[fullKey] = typeof value === 'string' ? value : JSON.stringify(value);
50
- }
51
- }
52
-
53
- return result;
54
- }
55
-
56
- /**
57
- * Load and parse a locale file
58
- */
59
- async function loadLocale(localeName: string): Promise<LocaleData> {
60
- const filePath = join(LOCALES_DIR, `${localeName}.ts`);
61
- const content = await readFile(filePath, 'utf-8');
62
-
63
- // Extract the default export object
64
- // This is a simple approach - assumes the file exports a single object
65
- const match = content.match(/export default\s+({[\s\S]*})\s+as const;?/);
66
- if (!match) {
67
- throw new Error(`Could not parse locale file: ${localeName}`);
68
- }
69
-
70
- // Use eval to parse the object (safe since we control the source)
71
- // In production, you might want to use a proper TypeScript parser
72
- const objectString = match[1];
73
- const data = eval(`(${objectString})`);
74
-
75
- return {
76
- locale: localeName,
77
- data,
78
- filePath,
79
- };
80
- }
81
-
82
- /**
83
- * Get all locale files except the reference
84
- */
85
- async function getLocaleFiles(): Promise<string[]> {
86
- const files = await readdir(LOCALES_DIR);
87
- return files
88
- .filter((f) => f.endsWith('.ts') && f !== `${REFERENCE_LOCALE}.ts`)
89
- .map((f) => f.replace('.ts', ''));
90
- }
91
-
92
- /**
93
- * Compare two flattened locale objects and find differences
94
- */
95
- /**
96
- * Check if a key is a valid plural form extension
97
- * Languages like Arabic have more plural forms than English (zero, one, two, few, many, other)
98
- */
99
- function isValidPluralExtension(key: string): boolean {
100
- // Arabic and other languages with extended plural forms
101
- const pluralForms = ['.zero', '.one', '.two', '.few', '.many', '.other'];
102
- return pluralForms.some(form => key.endsWith(form)) && key.startsWith('plurals.');
103
- }
104
-
105
- function compareLocales(reference: Record<string, string>, target: Record<string, string>) {
106
- const missing: string[] = [];
107
- const extra: string[] = [];
108
- const untranslated: string[] = [];
109
-
110
- // Find missing keys
111
- for (const key of Object.keys(reference)) {
112
- if (!(key in target)) {
113
- missing.push(key);
114
- } else if (reference[key] === target[key] && reference[key].length > 0) {
115
- // Key exists but value is identical to reference (likely untranslated)
116
- untranslated.push(key);
117
- }
118
- }
119
-
120
- // Find extra keys (exist in target but not in reference)
121
- for (const key of Object.keys(target)) {
122
- if (!(key in reference)) {
123
- // Don't flag valid plural form extensions as "extra"
124
- if (!isValidPluralExtension(key)) {
125
- extra.push(key);
126
- }
127
- }
128
- }
129
-
130
- return { missing, extra, untranslated };
131
- }
132
-
133
- /**
134
- * Format the report for a single locale
135
- */
136
- function formatLocaleReport(
137
- localeName: string,
138
- missing: string[],
139
- extra: string[],
140
- untranslated: string[],
141
- totalKeys: number
142
- ): string {
143
- const coveragePercent = ((totalKeys - missing.length) / totalKeys * 100).toFixed(1);
144
-
145
- let report = `\n${'='.repeat(80)}\n`;
146
- report += `šŸ“‹ Locale: ${localeName}\n`;
147
- report += `${'='.repeat(80)}\n`;
148
- report += `Coverage: ${coveragePercent}% (${totalKeys - missing.length}/${totalKeys} keys)\n`;
149
-
150
- if (missing.length === 0 && extra.length === 0 && untranslated.length === 0) {
151
- report += `āœ… Perfect! All keys are present and translated.\n`;
152
- return report;
153
- }
154
-
155
- if (missing.length > 0) {
156
- report += `\nāŒ Missing Keys (${missing.length}):\n`;
157
- report += `${'─'.repeat(80)}\n`;
158
- missing.sort().forEach((key) => {
159
- report += ` • ${key}\n`;
160
- });
161
- }
162
-
163
- if (extra.length > 0) {
164
- report += `\nāš ļø Extra Keys (${extra.length}) - Not in reference, possibly obsolete:\n`;
165
- report += `${'─'.repeat(80)}\n`;
166
- extra.sort().forEach((key) => {
167
- report += ` • ${key}\n`;
168
- });
169
- }
170
-
171
- if (untranslated.length > 0) {
172
- report += `\nāš ļø Potentially Untranslated (${untranslated.length}) - Same value as en-US:\n`;
173
- report += `${'─'.repeat(80)}\n`;
174
- untranslated.sort().forEach((key) => {
175
- report += ` • ${key}\n`;
176
- });
177
- }
178
-
179
- return report;
180
- }
181
-
182
- /**
183
- * Main function
184
- */
185
- async function main() {
186
- const args = process.argv.slice(2);
187
- const specificLocale = args.find((arg) => arg.startsWith('--locale='))?.split('=')[1];
188
- const fixMode = args.includes('--fix');
189
-
190
- console.log('šŸ” Translation Coverage Checker\n');
191
- console.log(`šŸ“ Locales directory: ${LOCALES_DIR}`);
192
- console.log(`šŸ“– Reference locale: ${REFERENCE_LOCALE}\n`);
193
-
194
- // Load reference locale
195
- const reference = await loadLocale(REFERENCE_LOCALE);
196
- const referenceFlat = flattenObject(reference.data);
197
- const totalKeys = Object.keys(referenceFlat).length;
198
-
199
- console.log(`āœ“ Loaded reference: ${REFERENCE_LOCALE} (${totalKeys} keys)\n`);
200
-
201
- // Get all locales to check
202
- const allLocales = await getLocaleFiles();
203
- const localesToCheck = specificLocale
204
- ? allLocales.filter((l) => l === specificLocale)
205
- : allLocales;
206
-
207
- if (localesToCheck.length === 0) {
208
- console.error(`āŒ Locale not found: ${specificLocale}`);
209
- process.exit(1);
210
- }
211
-
212
- let hasIssues = false;
213
- const summaryData: Array<{
214
- locale: string;
215
- coverage: number;
216
- missing: number;
217
- extra: number;
218
- untranslated: number;
219
- }> = [];
220
-
221
- // Check each locale
222
- for (const localeName of localesToCheck) {
223
- const target = await loadLocale(localeName);
224
- const targetFlat = flattenObject(target.data);
225
-
226
- const { missing, extra, untranslated } = compareLocales(referenceFlat, targetFlat);
227
-
228
- const coverage = ((totalKeys - missing.length) / totalKeys * 100);
229
- summaryData.push({
230
- locale: localeName,
231
- coverage,
232
- missing: missing.length,
233
- extra: extra.length,
234
- untranslated: untranslated.length,
235
- });
236
-
237
- const report = formatLocaleReport(localeName, missing, extra, untranslated, totalKeys);
238
- console.log(report);
239
-
240
- if (missing.length > 0 || extra.length > 0) {
241
- hasIssues = true;
242
- }
243
-
244
- if (fixMode && missing.length > 0) {
245
- console.log(`\nšŸ”§ Fix mode enabled - adding missing keys to ${localeName}...\n`);
246
- // Note: Actual fix implementation would go here
247
- // This requires reconstructing the nested object structure and updating the file
248
- console.log(` (Fix mode not yet implemented - would add ${missing.length} keys)\n`);
249
- }
250
- }
251
-
252
- // Print summary table
253
- if (localesToCheck.length > 1) {
254
- console.log(`\n${'='.repeat(80)}`);
255
- console.log(`šŸ“Š SUMMARY TABLE`);
256
- console.log(`${'='.repeat(80)}\n`);
257
- console.log(`Locale Coverage Missing Extra Untranslated`);
258
- console.log(`${'─'.repeat(80)}`);
259
-
260
- summaryData
261
- .sort((a, b) => b.coverage - a.coverage)
262
- .forEach((item) => {
263
- const status = item.coverage === 100 && item.extra === 0 ? 'āœ…' : 'āš ļø ';
264
- const coverageStr = `${item.coverage.toFixed(1)}%`.padEnd(10);
265
- const localeStr = item.locale.padEnd(10);
266
- const missingStr = item.missing.toString().padEnd(9);
267
- const extraStr = item.extra.toString().padEnd(8);
268
- const untransStr = item.untranslated.toString().padEnd(8);
269
-
270
- console.log(`${status} ${localeStr} ${coverageStr} ${missingStr} ${extraStr} ${untransStr}`);
271
- });
272
-
273
- console.log(`${'─'.repeat(80)}\n`);
274
- }
275
-
276
- // Exit with error code if issues found
277
- if (hasIssues) {
278
- console.log('āŒ Translation coverage issues detected.\n');
279
- process.exit(1);
280
- } else {
281
- console.log('āœ… All locales have complete translation coverage!\n');
282
- process.exit(0);
283
- }
284
- }
285
-
286
- main().catch((error) => {
287
- console.error('āŒ Error:', error.message);
288
- process.exit(1);
289
- });
@@ -1,266 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Hardcoded String Scanner
4
- *
5
- * Scans component files (.svelte, .ts) for potential hardcoded English strings
6
- * that should use i18n translations instead.
7
- *
8
- * Usage:
9
- * bun run scripts/scan-hardcoded-strings.ts
10
- * bun run scripts/scan-hardcoded-strings.ts --path=../default-components
11
- */
12
-
13
- import { readdir, readFile } from 'fs/promises';
14
- import { join, dirname, relative } from 'path';
15
- import { fileURLToPath } from 'url';
16
-
17
- const __dirname = dirname(fileURLToPath(import.meta.url));
18
- const LOCALES_DIR = join(__dirname, '../src/locales');
19
-
20
- interface HardcodedMatch {
21
- file: string;
22
- line: number;
23
- content: string;
24
- potentialKey?: string;
25
- }
26
-
27
- /**
28
- * Flatten nested object into key-value pairs
29
- */
30
- function flattenObject(obj: any, prefix = ''): Record<string, string> {
31
- const result: Record<string, string> = {};
32
-
33
- for (const [key, value] of Object.entries(obj)) {
34
- const fullKey = prefix ? `${prefix}.${key}` : key;
35
-
36
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
37
- Object.assign(result, flattenObject(value, fullKey));
38
- } else if (typeof value === 'string') {
39
- result[fullKey] = value;
40
- }
41
- }
42
-
43
- return result;
44
- }
45
-
46
- /**
47
- * Load all English translation values to compare against
48
- */
49
- async function loadEnglishTranslations(): Promise<Map<string, { key: string; value: string }>> {
50
- const enUSPath = join(LOCALES_DIR, 'en-US.ts');
51
-
52
- // Dynamically import the locale file
53
- const localeModule = await import(enUSPath);
54
- const localeData = localeModule.default;
55
-
56
- // Flatten the translations
57
- const flattened = flattenObject(localeData);
58
- const translations = new Map<string, { key: string; value: string }>();
59
-
60
- for (const [key, value] of Object.entries(flattened)) {
61
- // Normalize: lowercase, trim, collapse whitespace
62
- const normalized = value.toLowerCase().replace(/\s+/g, ' ').trim();
63
-
64
- // Skip very short strings, technical terms, and interpolations
65
- if (normalized.length >= 8 &&
66
- !normalized.includes('{') &&
67
- !normalized.includes('http') &&
68
- !key.includes('demo.')) {
69
- translations.set(normalized, { key, value });
70
- }
71
- }
72
-
73
- return translations;
74
- }
75
-
76
- /**
77
- * Scan a file for potential hardcoded strings
78
- */
79
- async function scanFile(
80
- filePath: string,
81
- knownTranslations: Map<string, { key: string; value: string }>
82
- ): Promise<HardcodedMatch[]> {
83
- const content = await readFile(filePath, 'utf-8');
84
- const lines = content.split('\n');
85
- const matches: HardcodedMatch[] = [];
86
-
87
- // Patterns to detect hardcoded strings
88
- const patterns = [
89
- // HTML text content between tags (but not attributes)
90
- />([A-Z][a-zA-Z\s\(\)]{7,})</g,
91
- // String literals in quotes (but not in i18n calls or imports)
92
- /(?<!i18n\?\.t\(|i18n\.t\(|import |from )['"]([A-Z][a-zA-Z\s\(\)]{8,})['"]/g,
93
- ];
94
-
95
- lines.forEach((line, index) => {
96
- // Skip comments
97
- if (line.trim().startsWith('//') || line.trim().startsWith('*') || line.trim().startsWith('<!--')) {
98
- return;
99
- }
100
-
101
- // Skip lines that already use i18n
102
- if (line.includes('i18n?.t(') || line.includes('i18n.t(')) {
103
- return;
104
- }
105
-
106
- // Skip imports, type definitions, and console logs
107
- if (line.includes('import') || line.includes('interface') || line.includes('type ') || line.includes('console.')) {
108
- return;
109
- }
110
-
111
- for (const pattern of patterns) {
112
- pattern.lastIndex = 0; // Reset regex
113
- let match: RegExpExecArray | null;
114
-
115
- while ((match = pattern.exec(line)) !== null) {
116
- const text = match[1].trim();
117
-
118
- // Skip if too short or looks like code
119
- if (text.length < 8 || text.includes('{}') || text.includes('[]')) {
120
- continue;
121
- }
122
-
123
- // Check if this text exists in translations
124
- const normalized = text.toLowerCase().replace(/\s+/g, ' ').trim();
125
- if (knownTranslations.has(normalized)) {
126
- const translation = knownTranslations.get(normalized)!;
127
- matches.push({
128
- file: filePath,
129
- line: index + 1,
130
- content: line.trim(),
131
- potentialKey: `Use: i18n?.t('${translation.key}') ?? '${translation.value}'`,
132
- });
133
- }
134
- }
135
- }
136
- });
137
-
138
- return matches;
139
- }
140
-
141
- /**
142
- * Recursively scan directory for component files
143
- */
144
- async function scanDirectory(
145
- dirPath: string,
146
- knownTranslations: Map<string, { key: string; value: string }>
147
- ): Promise<HardcodedMatch[]> {
148
- const allMatches: HardcodedMatch[] = [];
149
-
150
- async function scan(currentPath: string) {
151
- const entries = await readdir(currentPath, { withFileTypes: true });
152
-
153
- for (const entry of entries) {
154
- const fullPath = join(currentPath, entry.name);
155
-
156
- if (entry.isDirectory()) {
157
- // Skip node_modules, dist, .git
158
- if (!['node_modules', 'dist', '.git', 'build'].includes(entry.name)) {
159
- await scan(fullPath);
160
- }
161
- } else if (entry.isFile()) {
162
- // Only scan component files
163
- if (entry.name.endsWith('.svelte') || entry.name.endsWith('.ts')) {
164
- // Skip test files and type definition files
165
- if (!entry.name.includes('.test.') && !entry.name.endsWith('.d.ts')) {
166
- const matches = await scanFile(fullPath, knownTranslations);
167
- allMatches.push(...matches);
168
- }
169
- }
170
- }
171
- }
172
- }
173
-
174
- await scan(dirPath);
175
- return allMatches;
176
- }
177
-
178
- /**
179
- * Main function
180
- */
181
- async function main() {
182
- const args = process.argv.slice(2);
183
- let scanPaths: string[] = [];
184
-
185
- // Parse command line arguments
186
- let customPath = false;
187
- for (const arg of args) {
188
- if (arg.startsWith('--path=')) {
189
- const path = arg.substring('--path='.length);
190
- scanPaths = [join(__dirname, path)];
191
- customPath = true;
192
- }
193
- }
194
-
195
- // Default: scan all player packages
196
- if (!customPath) {
197
- scanPaths = [
198
- join(__dirname, '../../item-player/src'),
199
- join(__dirname, '../../assessment-player/src'),
200
- join(__dirname, '../../default-components/src'),
201
- ];
202
- }
203
-
204
- console.log('šŸ” Hardcoded String Scanner\n');
205
- console.log(`šŸ“ Scanning directories:`);
206
- for (const path of scanPaths) {
207
- console.log(` - ${path}`);
208
- }
209
- console.log(`\nšŸ“– Loading English translations...\n`);
210
-
211
- const knownTranslations = await loadEnglishTranslations();
212
- console.log(`āœ“ Loaded ${knownTranslations.size} translation values\n`);
213
-
214
- console.log('šŸ”Ž Scanning for hardcoded strings...\n');
215
-
216
- // Scan all directories and collect matches
217
- const allMatches: HardcodedMatch[] = [];
218
- for (const scanPath of scanPaths) {
219
- const matches = await scanDirectory(scanPath, knownTranslations);
220
- allMatches.push(...matches);
221
- }
222
-
223
- const matches = allMatches;
224
-
225
- if (matches.length === 0) {
226
- console.log('āœ… No hardcoded strings detected that match known translations!\n');
227
- process.exit(0);
228
- }
229
-
230
- // Group by file
231
- const byFile = new Map<string, HardcodedMatch[]>();
232
- for (const match of matches) {
233
- if (!byFile.has(match.file)) {
234
- byFile.set(match.file, []);
235
- }
236
- byFile.get(match.file)!.push(match);
237
- }
238
-
239
- console.log(`āš ļø Found ${matches.length} potential hardcoded strings in ${byFile.size} files:\n`);
240
- console.log('═'.repeat(80));
241
-
242
- const rootPath = join(__dirname, '../..');
243
- for (const [file, fileMatches] of byFile.entries()) {
244
- const relPath = relative(rootPath, file);
245
- console.log(`\nšŸ“„ ${relPath} (${fileMatches.length} matches)`);
246
- console.log('─'.repeat(80));
247
-
248
- for (const match of fileMatches) {
249
- console.log(` Line ${match.line}: ${match.content}`);
250
- if (match.potentialKey) {
251
- console.log(` ${match.potentialKey}`);
252
- }
253
- }
254
- }
255
-
256
- console.log('\n' + '═'.repeat(80));
257
- console.log(`\nšŸ’” Tip: These strings should use i18n?.t('key') ?? 'fallback' pattern\n`);
258
-
259
- // Don't exit with error - this is informational
260
- process.exit(0);
261
- }
262
-
263
- main().catch((error) => {
264
- console.error('āŒ Error:', error.message);
265
- process.exit(1);
266
- });