@rivinia/i18n 0.5.0 → 0.7.1

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.
@@ -22,9 +22,37 @@ const DEFAULTS = Object.freeze({
22
22
  base: 'en',
23
23
  });
24
24
 
25
+ const INIT_DEFAULTS = Object.freeze({
26
+ out: 'src/app/i18n/languages.ts',
27
+ dir: 'public/i18n',
28
+ });
29
+
25
30
  const PREFIX = '[rivinia/i18n]';
26
31
 
27
- function main(argv) {
32
+ /** Generated-file marker; its absence means a hand-written file we must not clobber. */
33
+ const INIT_BANNER =
34
+ '// Generated by `npx rivinia-i18n-keys init`. Re-run the command to regenerate.';
35
+
36
+ const LANGUAGE_ID = /^[a-z]{2,8}(-[a-z0-9]{2,8})?$/;
37
+
38
+ /** Display names and directions for the ids most projects start with. */
39
+ const KNOWN_LANGUAGES = Object.freeze({
40
+ ar: { nativeName: 'العربية', dir: 'rtl' },
41
+ en: { nativeName: 'English', dir: 'ltr' },
42
+ fr: { nativeName: 'Français', dir: 'ltr' },
43
+ de: { nativeName: 'Deutsch', dir: 'ltr' },
44
+ es: { nativeName: 'Español', dir: 'ltr' },
45
+ he: { nativeName: 'עברית', dir: 'rtl' },
46
+ fa: { nativeName: 'فارسی', dir: 'rtl' },
47
+ ur: { nativeName: 'اردو', dir: 'rtl' },
48
+ });
49
+
50
+ const RTL_IDS = new Set(['ar', 'he', 'fa', 'ur', 'ps', 'yi', 'dv', 'ku', 'sd']);
51
+
52
+ async function main(argv) {
53
+ if (argv[0] === 'init') {
54
+ return runInit(parseInitArgs(argv.slice(1)));
55
+ }
28
56
  const args = parseArgs(argv);
29
57
  if (args.error) {
30
58
  console.error(`${PREFIX} ${args.error}`);
@@ -155,6 +183,369 @@ function runParity(args) {
155
183
  return 1;
156
184
  }
157
185
 
186
+ /**
187
+ * `init` — collects the languages once and writes:
188
+ * <out> a `defineRiviniaI18n` module plus a typed `injectI18n`
189
+ * <dir>/<id>.json one empty dictionary per language (existing files kept)
190
+ *
191
+ * Ids, directions and duplicates are validated before anything is written, so a
192
+ * bad answer never leaves half a project behind.
193
+ */
194
+ async function runInit(args) {
195
+ if (args.error) {
196
+ console.error(`${PREFIX} ${args.error}`);
197
+ printInitHelp();
198
+ return 1;
199
+ }
200
+ if (args.help) {
201
+ printInitHelp();
202
+ return 0;
203
+ }
204
+
205
+ let plan;
206
+ try {
207
+ plan = args.languages
208
+ ? { entries: parseLanguageSpec(args.languages), defaultId: args.default ?? null }
209
+ : await collectLanguages();
210
+ } catch (error) {
211
+ console.error(`${PREFIX} ${error.message}`);
212
+ return 1;
213
+ }
214
+ if (plan === null) {
215
+ console.error(
216
+ `${PREFIX} No languages entered. Pass them non-interactively: ` +
217
+ '`--languages ar:العربية:rtl,en:English:ltr`.',
218
+ );
219
+ return 1;
220
+ }
221
+
222
+ const { entries } = plan;
223
+ const defaultId = plan.defaultId ?? entries[0].id;
224
+ if (!entries.some((entry) => entry.id === defaultId)) {
225
+ console.error(`${PREFIX} --default "${defaultId}" is not one of the language ids.`);
226
+ return 1;
227
+ }
228
+
229
+ const outPath = resolve(args.out ?? INIT_DEFAULTS.out);
230
+ const dirPath = resolve(args.dir ?? INIT_DEFAULTS.dir);
231
+
232
+ if (existsSync(outPath) && !readFileSync(outPath, 'utf8').startsWith(INIT_BANNER)) {
233
+ if (!args.force) {
234
+ console.error(
235
+ `${PREFIX} ${outPath} exists and was not generated by this command. ` +
236
+ 'Pass --force to overwrite it.',
237
+ );
238
+ return 1;
239
+ }
240
+ }
241
+
242
+ const dictionaryPaths = entries.map((entry) => ({
243
+ id: entry.id,
244
+ path: join(dirPath, `${entry.id}.json`),
245
+ }));
246
+
247
+ if (args.dryRun) {
248
+ console.log(`Would write ${outPath}`);
249
+ for (const dictionary of dictionaryPaths) {
250
+ console.log(`Would write ${dictionary.path}`);
251
+ }
252
+ return 0;
253
+ }
254
+
255
+ mkdirSync(dirname(outPath), { recursive: true });
256
+ writeFileSync(outPath, renderLanguagesModule(entries, defaultId), 'utf8');
257
+ console.log(`Wrote ${outPath}`);
258
+
259
+ mkdirSync(dirPath, { recursive: true });
260
+ for (const dictionary of dictionaryPaths) {
261
+ if (existsSync(dictionary.path)) {
262
+ console.log(`Kept ${dictionary.path} (already exists)`);
263
+ continue;
264
+ }
265
+ writeFileSync(dictionary.path, '{}\n', 'utf8');
266
+ console.log(`Wrote ${dictionary.path}`);
267
+ }
268
+
269
+ const appConfig = resolve('src/app/app.config.ts');
270
+ if (existsSync(appConfig) && readFileSync(appConfig, 'utf8').includes('provideRiviniaI18n(')) {
271
+ console.warn(
272
+ `${PREFIX} app.config.ts already calls provideRiviniaI18n(…) — ` +
273
+ 'remove that call and use i18n.provide() instead, or the app registers two managers.',
274
+ );
275
+ }
276
+
277
+ const relativeImport = relative(resolve('src/app'), outPath).replace(/\.ts$/, '');
278
+ const specifier = relativeImport.startsWith('.') ? relativeImport : `./${relativeImport}`;
279
+ console.log('');
280
+ console.log(
281
+ `Next: in src/app/app.config.ts add \`import { i18n } from '${specifier}';\` ` +
282
+ 'and use providers: [i18n.provide()].',
283
+ );
284
+ return 0;
285
+ }
286
+
287
+ /**
288
+ * Parses `ar:العربية:rtl,en:English:ltr`. Every part after the id is optional:
289
+ * a missing native name or direction comes from the id. `:` is the separator,
290
+ * so a native name containing a colon must be edited in the generated file.
291
+ */
292
+ function parseLanguageSpec(raw) {
293
+ const entries = [];
294
+ const seen = new Set();
295
+ for (const part of raw.split(',')) {
296
+ if (part.trim() === '') continue;
297
+ const [idPart, nativePart, dirPart] = part.split(':');
298
+ const id = idPart.trim().toLowerCase();
299
+ if (id === '') {
300
+ throw new Error('A language entry needs an id, e.g. `ar:العربية:rtl`.');
301
+ }
302
+ if (!LANGUAGE_ID.test(id)) {
303
+ throw new Error(`Invalid language id "${id}" — use ar, en, ar-EG …`);
304
+ }
305
+ if (seen.has(id)) {
306
+ throw new Error(`Duplicate language id "${id}".`);
307
+ }
308
+ seen.add(id);
309
+
310
+ const known = KNOWN_LANGUAGES[id];
311
+ const nativeName = (nativePart ?? '').trim() || known?.nativeName || id;
312
+ const dir = (
313
+ (dirPart ?? '').trim() ||
314
+ known?.dir ||
315
+ (RTL_IDS.has(id) ? 'rtl' : 'ltr')
316
+ ).toLowerCase();
317
+ if (dir !== 'ltr' && dir !== 'rtl') {
318
+ throw new Error(`Invalid direction "${dir}" for "${id}" — use ltr or rtl.`);
319
+ }
320
+ entries.push({ id, nativeName, dir });
321
+ }
322
+ if (entries.length === 0) {
323
+ throw new Error('No language ids found in --languages.');
324
+ }
325
+ return entries;
326
+ }
327
+
328
+ /**
329
+ * Asks for each language, then for the default when there is more than one.
330
+ *
331
+ * A terminal answers through `readline.question` so editing works. A pipe
332
+ * cannot: stdout is not a TTY and the lines arrive before the next question is
333
+ * asked, so answers are queued from the `line` event instead. Both adapters
334
+ * expose the same `ask` and return `null` once the input is exhausted.
335
+ */
336
+ async function collectLanguages() {
337
+ const prompter = await openPrompter();
338
+ try {
339
+ const entries = [];
340
+ const seen = new Set();
341
+ for (;;) {
342
+ let id = null;
343
+ while (id === null) {
344
+ const raw = await prompter.ask(`${PREFIX} Language id (ar, en, ar-EG …): `);
345
+ if (raw === null) return null;
346
+ const candidate = raw.toLowerCase();
347
+ if (candidate === '') {
348
+ console.error(`${PREFIX} A language needs an id.`);
349
+ } else if (!LANGUAGE_ID.test(candidate)) {
350
+ console.error(`${PREFIX} Invalid language id "${candidate}" — use ar, en, ar-EG …`);
351
+ } else if (seen.has(candidate)) {
352
+ console.error(`${PREFIX} Duplicate language id "${candidate}".`);
353
+ } else {
354
+ seen.add(candidate);
355
+ id = candidate;
356
+ }
357
+ }
358
+
359
+ const known = KNOWN_LANGUAGES[id];
360
+ const nativeDefault = known?.nativeName ?? id;
361
+ const dirDefault = known?.dir ?? (RTL_IDS.has(id) ? 'rtl' : 'ltr');
362
+
363
+ const nativeAnswer = await prompter.ask(` Native name [${nativeDefault}]: `);
364
+ if (nativeAnswer === null) return null;
365
+
366
+ let dir = '';
367
+ for (;;) {
368
+ const dirAnswer = await prompter.ask(` Direction (ltr/rtl) [${dirDefault}]: `);
369
+ if (dirAnswer === null) return null;
370
+ dir = (dirAnswer || dirDefault).toLowerCase();
371
+ if (dir === 'ltr' || dir === 'rtl') break;
372
+ console.error(`${PREFIX} Direction must be ltr or rtl.`);
373
+ }
374
+
375
+ entries.push({
376
+ id,
377
+ nativeName: nativeAnswer === '' ? nativeDefault : nativeAnswer,
378
+ dir,
379
+ });
380
+
381
+ const againDefault = entries.length === 1 ? 'y' : 'n';
382
+ const again = await prompter.ask(
383
+ ` Another language? (${againDefault === 'y' ? 'Y/n' : 'y/N'}): `,
384
+ );
385
+ if (again === null) return null;
386
+ if (!(again || againDefault).toLowerCase().startsWith('y')) break;
387
+ }
388
+
389
+ let defaultId = entries[0].id;
390
+ if (entries.length > 1) {
391
+ const choices = entries.map((entry, index) => `(${index + 1}) ${entry.id}`).join(' ');
392
+ for (;;) {
393
+ const raw = await prompter.ask(`${PREFIX} Default language — ${choices} [1]: `);
394
+ if (raw === null) return null;
395
+ if (raw === '') break;
396
+ const index = Number(raw);
397
+ if (Number.isInteger(index) && index >= 1 && index <= entries.length) {
398
+ defaultId = entries[index - 1].id;
399
+ break;
400
+ }
401
+ const byId = entries.find((entry) => entry.id === raw.toLowerCase());
402
+ if (byId) {
403
+ defaultId = byId.id;
404
+ break;
405
+ }
406
+ console.error(
407
+ `${PREFIX} Pick 1-${entries.length} or one of: ${entries.map((entry) => entry.id).join(', ')}.`,
408
+ );
409
+ }
410
+ }
411
+
412
+ return { entries, defaultId };
413
+ } finally {
414
+ prompter.close();
415
+ }
416
+ }
417
+
418
+ async function openPrompter() {
419
+ if (process.stdin.isTTY !== true) {
420
+ const { createInterface } = await import('node:readline');
421
+ const rl = createInterface({ input: process.stdin, terminal: false });
422
+ const queued = [];
423
+ const waiting = [];
424
+ let closed = false;
425
+ rl.on('line', (line) => {
426
+ const next = waiting.shift();
427
+ if (next) next(line);
428
+ else queued.push(line);
429
+ });
430
+ rl.on('close', () => {
431
+ closed = true;
432
+ for (const next of waiting.splice(0)) next(null);
433
+ });
434
+ return {
435
+ ask: async (question) => {
436
+ process.stdout.write(question);
437
+ if (queued.length > 0) return queued.shift().trim();
438
+ if (closed) return null;
439
+ const line = await new Promise((resolve) => waiting.push(resolve));
440
+ return line === null ? null : line.trim();
441
+ },
442
+ close: () => rl.close(),
443
+ };
444
+ }
445
+
446
+ const { createInterface } = await import('node:readline/promises');
447
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
448
+ let closed = false;
449
+ const onClose = new Promise((resolve) => {
450
+ rl.once('close', () => {
451
+ closed = true;
452
+ resolve(null);
453
+ });
454
+ });
455
+ return {
456
+ ask: async (question) => {
457
+ if (closed) return null;
458
+ const answer = rl.question(question);
459
+ answer.catch(() => {});
460
+ const value = await Promise.race([answer, onClose]);
461
+ return value === null ? null : value.trim();
462
+ },
463
+ close: () => rl.close(),
464
+ };
465
+ }
466
+
467
+ function renderLanguagesModule(entries, defaultId) {
468
+ const languages = entries
469
+ .map(
470
+ (entry) =>
471
+ ` { id: '${escapeTs(entry.id)}', nativeName: '${escapeTs(entry.nativeName)}', dir: '${entry.dir}' },`,
472
+ )
473
+ .join('\n');
474
+ return [
475
+ INIT_BANNER,
476
+ "import { defineRiviniaI18n } from '@rivinia/i18n';",
477
+ '',
478
+ 'export const i18n = defineRiviniaI18n({',
479
+ ` defaultLanguage: '${escapeTs(defaultId)}',`,
480
+ ' languages: [',
481
+ languages,
482
+ ' ],',
483
+ '});',
484
+ '',
485
+ '/** The typed language manager — call inside an injection context. */',
486
+ 'export const injectI18n = i18n.inject;',
487
+ '',
488
+ ].join('\n');
489
+ }
490
+
491
+ function escapeTs(value) {
492
+ return String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'");
493
+ }
494
+
495
+ function parseInitArgs(argv) {
496
+ const args = {};
497
+ for (let i = 0; i < argv.length; i++) {
498
+ const arg = argv[i];
499
+ if (arg === '--force') {
500
+ args.force = true;
501
+ } else if (arg === '--dry-run') {
502
+ args.dryRun = true;
503
+ } else if (arg === '--help' || arg === '-h') {
504
+ args.help = true;
505
+ } else if (arg === '--languages' || arg === '--default' || arg === '--out' || arg === '--dir') {
506
+ const value = argv[i + 1];
507
+ if (value === undefined || value.startsWith('--')) {
508
+ return { error: `${arg} needs a value.` };
509
+ }
510
+ args[arg.slice(2)] = value;
511
+ i++;
512
+ } else if (
513
+ arg.startsWith('--languages=') ||
514
+ arg.startsWith('--default=') ||
515
+ arg.startsWith('--out=') ||
516
+ arg.startsWith('--dir=')
517
+ ) {
518
+ const eq = arg.indexOf('=');
519
+ args[arg.slice(2, eq)] = arg.slice(eq + 1);
520
+ } else {
521
+ return { error: `Unknown option for init: ${arg}` };
522
+ }
523
+ }
524
+ return args;
525
+ }
526
+
527
+ function printInitHelp() {
528
+ console.log(
529
+ [
530
+ 'rivinia-i18n-keys init — generate the language module and empty dictionaries',
531
+ '',
532
+ 'Usage:',
533
+ ' rivinia-i18n-keys init (asks for each language)',
534
+ ' rivinia-i18n-keys init --languages <list> (non-interactive)',
535
+ '',
536
+ 'Options:',
537
+ ' --languages id[:nativeName[:dir]] pairs, comma-separated',
538
+ ' (e.g. ar:العربية:rtl,en:English:ltr; parts after the id are optional)',
539
+ ` --default Default language id (default: the first one)`,
540
+ ` --out Module to write (default: ${INIT_DEFAULTS.out})`,
541
+ ` --dir Dictionary folder (default: ${INIT_DEFAULTS.dir})`,
542
+ ' --force Overwrite <out> even when it was written by hand',
543
+ ' --dry-run Print the files without writing them',
544
+ ' --help Show this help',
545
+ ].join('\n'),
546
+ );
547
+ }
548
+
158
549
  function readDictionary(path) {
159
550
  if (!existsSync(path)) {
160
551
  console.error(`${PREFIX} Source dictionary not found: ${path}`);
@@ -384,6 +775,7 @@ function printHelp() {
384
775
  ' rivinia-i18n-keys [--source <json>] [--out <d.ts>]',
385
776
  ' rivinia-i18n-keys --check',
386
777
  ' rivinia-i18n-keys --parity [--dir <folder>] [--base <language>]',
778
+ ' rivinia-i18n-keys init [--languages <list>] [--out <ts>] [--dir <folder>]',
387
779
  '',
388
780
  'Options:',
389
781
  ` --source Dictionary to read (default: ${DEFAULTS.source})`,
@@ -397,4 +789,12 @@ function printHelp() {
397
789
  );
398
790
  }
399
791
 
400
- process.exitCode = main(process.argv.slice(2));
792
+ main(process.argv.slice(2)).then(
793
+ (code) => {
794
+ process.exitCode = code;
795
+ },
796
+ (error) => {
797
+ console.error(`${PREFIX} ${error instanceof Error ? error.message : error}`);
798
+ process.exitCode = 1;
799
+ },
800
+ );