@clarity-js/i18n 0.0.0-stage → 1.0.0

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,101 @@
1
- # Temporary Holding Version
1
+ # @clarity-js/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
+ Translations for [Clarity.js](https://clarity-js.com). Everything of the core's `@ozsarman/clarityjs/i18n`
4
+ (locale and direction as signals, lazy locales, plural objects, `Intl` formatters, RTL) from one import, and on
5
+ top of it:
6
+
7
+ - **ICU MessageFormat** in your messages: `plural` (with `=0`, `#` and `offset`), `select`, `selectordinal`,
8
+ `number`, `date` and `time`, nested, with `''` quoting;
9
+ - **onMissing** — know when a key has no translation, and choose what is shown instead;
10
+ - **`clarity-i18n check`** — the keys your code uses that a locale lacks, the keys nobody uses, the messages
11
+ whose arguments differ between locales, and the ones that are not valid ICU.
12
+
13
+ No dependencies. Plural rules, numbers and dates come from the browser's (or Node's) `Intl`.
14
+
15
+ ```sh
16
+ npm install @clarity-js/i18n
17
+ ```
18
+
19
+ ## Use
20
+
21
+ ```js
22
+ import { createI18n } from '@clarity-js/i18n'
23
+
24
+ export const i18n = createI18n({
25
+ locale: 'en',
26
+ fallbackLocale: 'en',
27
+ messages: {
28
+ en: {
29
+ inbox: '{n, plural, =0 {No mail} one {# message} other {# messages}}',
30
+ rank: 'You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}',
31
+ greeting: '{who, select, team {Hello, team} other {Hello, {name}}}',
32
+ total: 'Total: {sum, number, ::currency/EUR}',
33
+ },
34
+ tr: { inbox: '{n, plural, =0 {Posta yok} other {# ileti}}' },
35
+ },
36
+ onMissing: (key, locale) => console.warn(`no ${locale} text for ${key}`),
37
+ })
38
+
39
+ i18n.t('inbox', { n: 3 }) // '3 messages'
40
+ await i18n.setLocale('tr')
41
+ i18n.t('inbox', { n: 3 }) // '3 ileti'
42
+ i18n.t('rank', { place: 2 }) // falls back to English: 'You finished 2nd'
43
+ ```
44
+
45
+ In a component, `t` reads the locale signal, so the text changes when the locale does:
46
+
47
+ ```html
48
+ <script>
49
+ import { t } from '@clarity-js/i18n'
50
+ import { inbox } from './store.js'
51
+ </script>
52
+
53
+ <h1>{ t('inbox', { n: inbox.count.get() }) }</h1>
54
+ ```
55
+
56
+ Messages without ICU arguments (`'Hello {name}'`) and the core's plural objects
57
+ (`{ one: '{count} apple', other: '{count} apples' }`) work as before, so an app can move to ICU one message at
58
+ a time.
59
+
60
+ ### ICU, in short
61
+
62
+ | Argument | Example |
63
+ | --- | --- |
64
+ | plain | `Hello {name}` |
65
+ | plural | `{n, plural, =0 {none} one {# item} other {# items}}` |
66
+ | offset | `{g, plural, offset:1 =1 {{host} alone} other {{host} and # others}}` |
67
+ | select | `{role, select, admin {Admin} other {Member}}` |
68
+ | selectordinal | `{n, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}` |
69
+ | number | `{v, number}` `{v, number, percent}` `{v, number, integer}` `{v, number, ::currency/EUR}` `{v, number, ::compact-short}` `{v, number, ::.00}` `{v, number, ::unit/kilometer}` |
70
+ | date / time | `{d, date, long}` `{d, time, short}` (short, medium, long, full) |
71
+ | quoting | `It''s` → It's · `'{literal}'` → {literal} · inside plural `'#'` → # |
72
+
73
+ `formatMessage(message, values, locale)`, `parseMessage(message)` and `argumentsOf(message)` are exported for
74
+ use outside `t`.
75
+
76
+ ## Check your locale files
77
+
78
+ ```sh
79
+ npx clarity-i18n check --src src --locales locales
80
+ ```
81
+
82
+ ```
83
+ 42 keys used in the code · locales: en, de, tr (compared with en)
84
+
85
+ ✗ tr lacks 2: checkout.title, inbox.empty
86
+ ✗ de inbox.count: arguments {count}, en has {n}
87
+
88
+ · not used in the code (1): old.banner
89
+ ```
90
+
91
+ It reads `t('key')`, `i18n.t('key')` and `tIn('tr', 'key')` with literal keys in `.clarity`, `.js` and `.ts`
92
+ files, and the `en.json`, `tr.json`, … (or `.js` modules with a default export) in the locales folder. It
93
+ exits with 1 when a locale lacks a key the code uses, when two locales disagree about a message's arguments or
94
+ when a message is not valid ICU — put it in CI. `--write` adds the missing keys to the JSON files with the base
95
+ locale's text, ready to translate; `--json` prints the report for other tools.
96
+
97
+ The same check is a function: `import { check } from '@clarity-js/i18n/check'`.
98
+
99
+ ## License
100
+
101
+ MIT
package/check.js ADDED
@@ -0,0 +1,102 @@
1
+ // The checker behind `clarity-i18n check`: the keys the code asks for, against the keys each locale has.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { keysOf } from './index.js'
6
+ import { argumentsOf } from './icu.js'
7
+
8
+ const CODE = /\.(clarity|[cm]?[jt]sx?)$/
9
+ const SKIP = new Set(['node_modules', 'dist', 'build', '.git', '.vite', 'coverage'])
10
+ // t('key'), t("key"), i18n.t(`key`), tIn('tr', 'key') — literal keys only
11
+ const CALL2 = /(?:^|[^\w$.])(?:i18n\.)?t\(\s*(['"`])([A-Za-z0-9_.-]+)\1/g
12
+ const CALL3 = /\btIn\(\s*(['"`])[^'"`]+\1\s*,\s*(['"`])([A-Za-z0-9_.-]+)\2/g
13
+
14
+ export function usedKeys(dirs) {
15
+ const used = new Map() // key → [file:line]
16
+ const walk = (p) => {
17
+ const st = fs.statSync(p)
18
+ if (st.isDirectory()) { for (const e of fs.readdirSync(p)) if (!SKIP.has(e)) walk(path.join(p, e)); return }
19
+ if (!CODE.test(p)) return
20
+ const src = fs.readFileSync(p, 'utf8')
21
+ const lines = src.split('\n')
22
+ lines.forEach((line, n) => {
23
+ for (const re of [CALL2, CALL3]) {
24
+ re.lastIndex = 0
25
+ for (let m; (m = re.exec(line));) {
26
+ const key = re === CALL2 ? m[2] : m[3]
27
+ if (!used.has(key)) used.set(key, [])
28
+ used.get(key).push(`${p}:${n + 1}`)
29
+ }
30
+ }
31
+ })
32
+ }
33
+ for (const d of dirs) walk(d)
34
+ return used
35
+ }
36
+
37
+ export async function readLocales(dir) {
38
+ const locales = {}
39
+ for (const f of fs.readdirSync(dir).sort()) {
40
+ const m = /^([A-Za-z]{2,3}(?:[-_][A-Za-z0-9]+)*)\.(json|m?js)$/.exec(f)
41
+ if (!m) continue
42
+ const file = path.join(dir, f)
43
+ locales[m[1]] = { file, messages: m[2] === 'json' ? JSON.parse(fs.readFileSync(file, 'utf8')) : (await import(pathToFileURL(file).href)).default }
44
+ }
45
+ return locales
46
+ }
47
+
48
+ function get(messages, key) { return key.split('.').reduce((n, k) => (n && typeof n === 'object' ? n[k] : undefined), messages) }
49
+ function set(messages, key, value) {
50
+ const parts = key.split('.')
51
+ let n = messages
52
+ for (const p of parts.slice(0, -1)) { if (!n[p] || typeof n[p] !== 'object') n[p] = {}; n = n[p] }
53
+ n[parts.at(-1)] = value
54
+ }
55
+ function args(message) {
56
+ if (typeof message === 'string') { try { return argumentsOf(message) } catch { return ['<syntax error>'] } }
57
+ if (message && typeof message === 'object') return [...new Set(Object.values(message).flatMap(args))].sort()
58
+ return []
59
+ }
60
+
61
+ /**
62
+ * Compare the code with the locales. Returns { missing: {locale: [key]}, unused: [key], mismatched: [...], errors: [...] }.
63
+ */
64
+ export async function check({ src, locales: dir, base, write = false }) {
65
+ const used = usedKeys([].concat(src))
66
+ const locales = await readLocales(dir)
67
+ const names = Object.keys(locales)
68
+ if (!names.length) throw new Error(`no locale files (en.json, tr.json, …) in ${dir}`)
69
+ base ??= names.includes('en') ? 'en' : names[0]
70
+ const report = { base, locales: names, used: used.size, missing: {}, unused: [], mismatched: [], errors: [] }
71
+ const all = new Set(names.flatMap((n) => keysOf(locales[n].messages)))
72
+ for (const name of names) {
73
+ const messages = locales[name].messages
74
+ report.missing[name] = [...used.keys()].filter((k) => get(messages, k) == null).sort()
75
+ for (const k of keysOf(messages)) {
76
+ const v = get(messages, k)
77
+ if (typeof v === 'string') { try { argumentsOf(v) } catch (err) { report.errors.push({ locale: name, key: k, message: err.message }) } }
78
+ }
79
+ }
80
+ report.unused = [...all].filter((k) => !used.has(k)).sort()
81
+ const baseMessages = locales[base].messages
82
+ for (const k of keysOf(baseMessages)) {
83
+ const want = args(get(baseMessages, k)).join(',')
84
+ for (const name of names) {
85
+ if (name === base) continue
86
+ const v = get(locales[name].messages, k)
87
+ if (v == null) continue
88
+ const have = args(v).join(',')
89
+ if (have !== want) report.mismatched.push({ key: k, locale: name, expected: want, found: have })
90
+ }
91
+ }
92
+ if (write) {
93
+ for (const name of names) {
94
+ const { file, messages } = locales[name]
95
+ if (!file.endsWith('.json') || !report.missing[name].length) continue
96
+ for (const k of report.missing[name]) set(messages, k, name === base ? '' : (get(baseMessages, k) ?? ''))
97
+ fs.writeFileSync(file, JSON.stringify(messages, null, 2) + '\n')
98
+ }
99
+ }
100
+ report.ok = Object.values(report.missing).every((m) => !m.length) && !report.mismatched.length && !report.errors.length
101
+ return report
102
+ }
package/cli.js ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ // clarity-i18n check [--src src] [--locales locales] [--base en] [--write] [--json]
3
+ import { check } from './check.js'
4
+
5
+ const argv = process.argv.slice(2)
6
+ const flag = (name, otherwise) => { const i = argv.indexOf('--' + name); return i >= 0 ? argv[i + 1] : otherwise }
7
+ const has = (name) => argv.includes('--' + name)
8
+ const command = argv[0]
9
+
10
+ if (command !== 'check' || has('help')) {
11
+ console.log(`clarity-i18n check — the translation keys your code uses, against your locale files
12
+
13
+ --src <dir> where the code is (default: src); give it more than once for more folders
14
+ --locales <dir> the folder of en.json, tr.json, … (default: locales)
15
+ --base <code> the locale the others are compared with (default: en, or the first)
16
+ --write add the missing keys to the JSON files (the base locale's text, to translate)
17
+ --json print the report as JSON
18
+
19
+ It fails (exit 1) when a locale lacks a key the code uses, when two locales disagree about a message's
20
+ arguments, or when a message is not valid ICU.`)
21
+ process.exit(command === 'check' || has('help') ? 0 : 1)
22
+ }
23
+
24
+ const src = argv.flatMap((a, i) => (argv[i - 1] === '--src' ? [a] : []))
25
+ const report = await check({ src: src.length ? src : ['src'], locales: flag('locales', 'locales'), base: flag('base'), write: has('write') })
26
+ if (has('json')) { console.log(JSON.stringify(report, null, 2)); process.exit(report.ok ? 0 : 1) }
27
+
28
+ console.log(`${report.used} keys used in the code · locales: ${report.locales.join(', ')} (compared with ${report.base})`)
29
+ for (const [locale, keys] of Object.entries(report.missing)) if (keys.length) console.log(`\n✗ ${locale} lacks ${keys.length}: ${keys.join(', ')}${has('write') ? ' (added)' : ''}`)
30
+ for (const m of report.mismatched) console.log(`✗ ${m.locale} ${m.key}: arguments {${m.found}}, ${report.base} has {${m.expected}}`)
31
+ for (const e of report.errors) console.log(`✗ ${e.locale} ${e.key}: ${e.message}`)
32
+ if (report.unused.length) console.log(`\n· not used in the code (${report.unused.length}): ${report.unused.join(', ')}`)
33
+ console.log(report.ok ? '\n✓ every locale has every key the code uses' : '')
34
+ process.exit(report.ok ? 0 : 1)
package/icu.js ADDED
@@ -0,0 +1,180 @@
1
+ // ICU MessageFormat, the part apps use: arguments, number / date / time, plural (with =N and #), selectordinal
2
+ // and select, nested, and '' quoting. Parsed once per message and cached; formatted with the browser's Intl.
3
+
4
+ const cache = new Map()
5
+ const TYPES = new Set(['number', 'date', 'time', 'plural', 'selectordinal', 'select'])
6
+
7
+ export class MessageSyntaxError extends SyntaxError {
8
+ constructor(message, source, at) {
9
+ super(`${message} at ${at} in ${JSON.stringify(source)}`)
10
+ this.name = 'MessageSyntaxError'
11
+ this.offset = at
12
+ }
13
+ }
14
+
15
+ /** Parse a message into parts: strings and { arg, type, style, options }. */
16
+ export function parseMessage(source) {
17
+ if (cache.has(source)) return cache.get(source)
18
+ let i = 0
19
+ const fail = (m) => { throw new MessageSyntaxError(m, source, i) }
20
+
21
+ function text(stopAt) {
22
+ let out = ''
23
+ while (i < source.length) {
24
+ const c = source[i]
25
+ if (c === "'") {
26
+ if (source[i + 1] === "'") { out += "'"; i += 2; continue }
27
+ const next = source[i + 1]
28
+ if (next === '{' || next === '}' || (next === '#' && stopAt.has('#'))) {
29
+ const end = source.indexOf("'", i + 1)
30
+ if (end < 0) { out += source.slice(i + 1); i = source.length; break }
31
+ out += source.slice(i + 1, end).replace(/''/g, "'"); i = end + 1; continue
32
+ }
33
+ out += c; i++; continue
34
+ }
35
+ if (c === '{' || c === '}' || stopAt.has(c)) break
36
+ out += c; i++
37
+ }
38
+ return out
39
+ }
40
+ function space() { while (/\s/.test(source[i] ?? '')) i++ }
41
+ function word() { space(); const m = /^[^\s,{}]+/.exec(source.slice(i)); if (!m) fail('expected a name'); i += m[0].length; space(); return m[0] }
42
+
43
+ function parts(inPlural) {
44
+ const out = []
45
+ const stops = new Set(inPlural ? ['#'] : [])
46
+ while (i < source.length && source[i] !== '}') {
47
+ const t = text(stops)
48
+ if (t) out.push(t)
49
+ if (source[i] === '#' && inPlural) { out.push({ pound: true }); i++; continue }
50
+ if (source[i] === '{') out.push(argument(inPlural))
51
+ }
52
+ return out
53
+ }
54
+
55
+ function argument(inPlural) {
56
+ i++ // {
57
+ const arg = word()
58
+ if (source[i] === '}') { i++; return { arg } }
59
+ if (source[i] !== ',') fail('expected , or }')
60
+ i++
61
+ const type = word()
62
+ if (!TYPES.has(type)) fail(`unknown argument type "${type}" (number, date, time, plural, selectordinal, select)`)
63
+ if (source[i] === '}') { i++; return { arg, type } }
64
+ if (source[i] !== ',') fail('expected , or }')
65
+ i++
66
+ if (type === 'plural' || type === 'selectordinal' || type === 'select') {
67
+ space()
68
+ let offset = 0
69
+ const off = /^offset:\s*(\d+)/.exec(source.slice(i))
70
+ if (off) { offset = Number(off[1]); i += off[0].length }
71
+ const options = {}
72
+ for (;;) {
73
+ space()
74
+ if (source[i] === '}') { i++; break }
75
+ if (i >= source.length) fail('unclosed {')
76
+ const key = word()
77
+ if (source[i] !== '{') fail(`expected { after ${key}`)
78
+ i++
79
+ options[key] = parts(type !== 'select' || inPlural)
80
+ if (source[i] !== '}') fail('unclosed option')
81
+ i++
82
+ }
83
+ if (!('other' in options)) fail(`"${arg}" needs an "other" option`)
84
+ return { arg, type, offset, options }
85
+ }
86
+ space()
87
+ let style = ''
88
+ while (i < source.length && source[i] !== '}') style += source[i++]
89
+ if (source[i] !== '}') fail('unclosed {')
90
+ i++
91
+ return { arg, type, style: style.trim() }
92
+ }
93
+
94
+ const result = parts(false)
95
+ if (i < source.length) fail('unexpected }')
96
+ cache.set(source, result)
97
+ return result
98
+ }
99
+
100
+ const fmtCache = new Map()
101
+ function intl(Kind, locale, options) {
102
+ const key = Kind.name + locale + JSON.stringify(options)
103
+ if (!fmtCache.has(key)) fmtCache.set(key, new Kind(locale, options))
104
+ return fmtCache.get(key)
105
+ }
106
+ const DATE = { short: { dateStyle: 'short' }, medium: { dateStyle: 'medium' }, long: { dateStyle: 'long' }, full: { dateStyle: 'full' } }
107
+ const TIME = { short: { timeStyle: 'short' }, medium: { timeStyle: 'medium' }, long: { timeStyle: 'long' }, full: { timeStyle: 'full' } }
108
+ function numberOptions(style) {
109
+ if (!style) return {}
110
+ if (style === 'integer') return { maximumFractionDigits: 0 }
111
+ if (style === 'percent') return { style: 'percent' }
112
+ const cur = /^currency(?:\/(\w{3}))?$/.exec(style)
113
+ if (cur) return { style: 'currency', currency: cur[1] || 'USD' }
114
+ const skeleton = /^::\s*(.+)$/.exec(style)
115
+ if (skeleton) {
116
+ const o = {}
117
+ for (const token of skeleton[1].split(/\s+/)) {
118
+ if (token === 'percent') o.style = 'percent'
119
+ else if (token.startsWith('currency/')) { o.style = 'currency'; o.currency = token.slice(9) }
120
+ else if (/^\.0+$/.test(token)) o.minimumFractionDigits = o.maximumFractionDigits = token.length - 1
121
+ else if (/^\.0*#+$/.test(token)) { o.minimumFractionDigits = (token.match(/0/g) || []).length; o.maximumFractionDigits = token.length - 1 }
122
+ else if (token === 'compact-short') o.notation = 'compact'
123
+ else if (token === 'compact-long') { o.notation = 'compact'; o.compactDisplay = 'long' }
124
+ else if (token.startsWith('unit/')) { o.style = 'unit'; o.unit = token.slice(5) }
125
+ }
126
+ return o
127
+ }
128
+ return {}
129
+ }
130
+
131
+ function run(parts, values, locale, pound) {
132
+ let out = ''
133
+ for (const p of parts) {
134
+ if (typeof p === 'string') { out += p; continue }
135
+ if (p.pound) { out += pound === undefined ? '#' : intl(Intl.NumberFormat, locale, {}).format(pound); continue }
136
+ const v = values?.[p.arg]
137
+ switch (p.type) {
138
+ case undefined: out += v ?? `{${p.arg}}`; break
139
+ case 'number': out += intl(Intl.NumberFormat, locale, numberOptions(p.style)).format(Number(v)); break
140
+ case 'date': out += intl(Intl.DateTimeFormat, locale, DATE[p.style] ?? DATE.medium).format(new Date(v)); break
141
+ case 'time': out += intl(Intl.DateTimeFormat, locale, TIME[p.style] ?? TIME.short).format(new Date(v)); break
142
+ case 'plural':
143
+ case 'selectordinal': {
144
+ const n = Number(v) - p.offset
145
+ const exact = p.options['=' + Number(v)]
146
+ const rule = exact ? null : intl(Intl.PluralRules, locale, { type: p.type === 'plural' ? 'cardinal' : 'ordinal' }).select(n)
147
+ out += run(exact ?? p.options[rule] ?? p.options.other, values, locale, n)
148
+ break
149
+ }
150
+ case 'select': out += run(p.options[String(v)] ?? p.options.other, values, locale, pound); break
151
+ default: out += v ?? ''
152
+ }
153
+ }
154
+ return out
155
+ }
156
+
157
+ /**
158
+ * Format an ICU message:
159
+ * formatMessage('{count, plural, =0 {No items} one {# item} other {# items}}', { count: 3 }, 'en') → '3 items'
160
+ */
161
+ export function formatMessage(message, values = {}, locale = 'en') {
162
+ return run(parseMessage(String(message)), values, locale)
163
+ }
164
+
165
+ /** The argument names a message uses (for checking two locales against each other). */
166
+ export function argumentsOf(message) {
167
+ const names = new Set()
168
+ const walk = (parts) => {
169
+ for (const p of parts) {
170
+ if (typeof p === 'string' || p.pound) continue
171
+ names.add(p.arg)
172
+ if (p.options) for (const opt of Object.values(p.options)) walk(opt)
173
+ }
174
+ }
175
+ walk(parseMessage(String(message)))
176
+ return [...names].sort()
177
+ }
178
+
179
+ /** True when a string uses ICU arguments with a type (plural, select, number…) rather than plain {name}. */
180
+ export const isICU = (s) => typeof s === 'string' && /\{\s*[^\s,{}]+\s*,\s*(plural|selectordinal|select|number|date|time)\b/.test(s)
package/index.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { createI18n as coreCreateI18n } from '@ozsarman/clarityjs/i18n'
2
+
3
+ /** The core's i18n instance: locale/dir signals, t, tIn, setLocale, loadLocale, n, currency, d, relative. */
4
+ export type I18nInstance = ReturnType<typeof coreCreateI18n>
5
+
6
+ export { useI18n, t, getLocale, getIsRTL, isRTLLocale, RTL_LOCALES, applyDir, BiDiWrapper } from '@ozsarman/clarityjs/i18n'
7
+
8
+ export interface CreateI18nOptions {
9
+ locale?: string
10
+ messages?: Record<string, Record<string, unknown>>
11
+ fallbackLocale?: string
12
+ updateHtmlDir?: boolean
13
+ ssr?: boolean
14
+ /** Called when a key has no message in the locale nor the fallback. Return a string to show it instead of the key. */
15
+ onMissing?: (key: string, locale: string) => string | void
16
+ }
17
+
18
+ /** The core's createI18n, with ICU MessageFormat in messages and onMissing. */
19
+ export function createI18n(options?: CreateI18nOptions): I18nInstance
20
+
21
+ /** The keys of a nested message object, dotted. Plural-form objects ({ one, other }) count as one key. */
22
+ export function keysOf(messages: Record<string, unknown>, prefix?: string): string[]
23
+
24
+ export class MessageSyntaxError extends SyntaxError {
25
+ offset: number
26
+ }
27
+ export type MessageNode = string | { type: string; name?: string; [k: string]: unknown }
28
+ /** Parse an ICU message (cached). Throws MessageSyntaxError. */
29
+ export function parseMessage(source: string): MessageNode[]
30
+ /** Format an ICU message with values in a locale. */
31
+ export function formatMessage(message: string, values?: Record<string, unknown>, locale?: string): string
32
+ /** The argument names a message uses, sorted. */
33
+ export function argumentsOf(message: string): string[]
34
+ /** Whether a string has ICU arguments (plural, select, selectordinal, number, date, time). */
35
+ export function isICU(message: unknown): boolean
package/index.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @clarity-js/i18n — Clarity's i18n with ICU messages, a missing-key hook and a checker for translation files.
3
+ *
4
+ * Everything of `@ozsarman/clarityjs/i18n` (locale and dir as signals, plural objects, lazy locales, Intl
5
+ * formatters, RTL) from one import, and on top of it:
6
+ * - ICU MessageFormat in messages: '{count, plural, =0 {No mail} one {# message} other {# messages}}',
7
+ * select, selectordinal, number, date and time arguments;
8
+ * - onMissing(key, locale): know when a key has no translation;
9
+ * - `clarity-i18n check`: which keys the code uses that a locale lacks, which keys nobody uses, and where two
10
+ * locales disagree about a message's arguments.
11
+ *
12
+ * import { createI18n } from '@clarity-js/i18n'
13
+ * const i18n = createI18n({ locale: 'en', messages: { en: { inbox: '{n, plural, =0 {No mail} one {# message} other {# messages}}' } } })
14
+ * i18n.t('inbox', { n: 3 }) // '3 messages'
15
+ */
16
+
17
+ import * as core from '@ozsarman/clarityjs/i18n'
18
+ import { formatMessage, isICU } from './icu.js'
19
+
20
+ export { formatMessage, parseMessage, argumentsOf, isICU, MessageSyntaxError } from './icu.js'
21
+ export const { useI18n, t, getLocale, getIsRTL, isRTLLocale, RTL_LOCALES, applyDir, BiDiWrapper } = core
22
+
23
+ /**
24
+ * createI18n of the core, with ICU messages and onMissing.
25
+ * @param {object} config the core's ({ locale, messages, fallbackLocale, updateHtmlDir, ssr }) and
26
+ * onMissing?: (key, locale) => string | void — its return value, if any, is shown instead of the key
27
+ */
28
+ export function createI18n({ onMissing, ...config } = {}) {
29
+ const i18n = core.createI18n(config)
30
+ if (typeof i18n._resolve !== 'function') throw new Error('[i18n] this version of @ozsarman/clarityjs is too old (needs 1.10 or later)')
31
+ const plain = i18n._resolve.bind(i18n)
32
+ i18n._resolve = (code, key, vars = {}) => {
33
+ const raw = lookup(i18n._messages[code], key)
34
+ if (isICU(raw)) {
35
+ try { return formatMessage(raw, vars, code) } catch (err) { console.error(`[i18n] ${key} (${code}): ${err.message}`); return raw }
36
+ }
37
+ return plain(code, key, vars)
38
+ }
39
+ if (onMissing) {
40
+ const t = i18n.t, tIn = i18n.tIn
41
+ const check = (code, key, out) => (out === key && lookup(i18n._messages[code], key) == null && (!i18n._fallback || lookup(i18n._messages[i18n._fallback], key) == null) ? (onMissing(key, code) ?? key) : out)
42
+ i18n.t = (key, vars) => check(i18n.locale.get(), key, t(key, vars))
43
+ i18n.tIn = (code, key, vars) => check(code, key, tIn(code, key, vars))
44
+ }
45
+ return i18n
46
+ }
47
+
48
+ function lookup(messages, key) {
49
+ let node = messages
50
+ for (const part of String(key).split('.')) {
51
+ if (node == null || typeof node !== 'object') return undefined
52
+ node = node[part]
53
+ }
54
+ return node
55
+ }
56
+
57
+ /** The keys of a nested message object, dotted: { a: { b: 'x' } } → ['a.b']. Plural objects count as one key. */
58
+ export function keysOf(messages, prefix = '') {
59
+ const out = []
60
+ for (const [k, v] of Object.entries(messages ?? {})) {
61
+ const key = prefix ? prefix + '.' + k : k
62
+ if (v && typeof v === 'object' && !isPluralForms(v)) out.push(...keysOf(v, key))
63
+ else out.push(key)
64
+ }
65
+ return out
66
+ }
67
+ const PLURAL = new Set(['zero', 'one', 'two', 'few', 'many', 'other'])
68
+ const isPluralForms = (o) => Object.keys(o).length > 0 && Object.keys(o).every((k) => PLURAL.has(k) || /^=\d+$/.test(k))
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@clarity-js/i18n",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Translations for Clarity.js: the core's reactive locales plus ICU MessageFormat (plural, select, selectordinal, number, date), a missing-key hook, and `clarity-i18n check` for your locale files. No dependencies.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "module": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": { "types": "./index.d.ts", "import": "./index.js", "default": "./index.js" },
11
+ "./icu": { "types": "./index.d.ts", "import": "./icu.js", "default": "./icu.js" },
12
+ "./check": { "import": "./check.js", "default": "./check.js" },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "bin": { "clarity-i18n": "./cli.js" },
16
+ "files": ["index.js", "icu.js", "check.js", "cli.js", "index.d.ts", "README.md"],
17
+ "sideEffects": false,
18
+ "keywords": ["clarity", "@ozsarman/clarityjs", "i18n", "icu", "messageformat", "plural", "translation", "localization"],
19
+ "author": "Özdemir Şarman",
20
+ "license": "MIT",
21
+ "peerDependencies": { "@ozsarman/clarityjs": ">=1.10.0" },
22
+ "homepage": "https://clarity-js.com/docs/packages#i18n",
23
+ "repository": { "type": "git", "url": "git+https://gitlab.com/ozsarman/clarity.js.git", "directory": "packages/clarity-i18n" },
24
+ "engines": { "node": ">=18.0.0" }
25
+ }