@glimstone/terms 0.0.0-stage → 4.4.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.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @glimstone/terms
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
+ The words an interface uses for the same thing in every language, and a check
4
+ that holds an app's translations to them. A relay stays a relay in German and
5
+ a backup is a Sicherung there, the same in every app that takes this package.
6
+
7
+ ```sh
8
+ npm install --save-dev @glimstone/terms
9
+ ```
10
+
11
+ ## The glossary
12
+
13
+ [`terms.json`](terms.json) holds each term in all 42 languages: its singular
14
+ and plural, the gender where the language has one, the stems the check looks
15
+ for, and the variants it forbids. Each term opens with a definition.
16
+
17
+ | Term | English | German |
18
+ |---|---|---|
19
+ | `fortress` | fortress | Festung |
20
+ | `instance` | instance | Instanz |
21
+ | `member` | member | Mitglied |
22
+ | `permission` | permission | Berechtigung |
23
+ | `relay` | relay | Relay, never Relais |
24
+ | `backup` | backup | Sicherung, never Backup |
25
+ | `pairing` | pairing | Kopplung |
26
+ | `phrase` | phrase | Phrase, never Festungs-Phrase |
27
+ | `job` | job | Auftrag |
28
+
29
+ A stem is the part every inflection shares: `kopi` finds the Polish "kopia
30
+ zapasowa" and "kopii zapasowej" alike. In languages that build compounds
31
+ (German, Dutch, the Nordic languages, Finnish, Estonian) a stem counts
32
+ anywhere inside a word, so "Einstellungssicherung" carries "Sicherung". In
33
+ Japanese, Chinese, Thai and Korean it counts anywhere too. Elsewhere it has to
34
+ start a word. Case and accents do not count, since inflection moves them.
35
+
36
+ A forbidden variant matches as a whole word. A star at its end lets it run on
37
+ (`relais*`), and a star at its start lets it close a compound (`*backup*`).
38
+
39
+ ## The check
40
+
41
+ Two rules. When the English text of a key carries a term, its translation has
42
+ to carry that term's word. And no translation may use a forbidden variant.
43
+ Placeholders such as `{backup}`, paths such as `/relay/connect` and addresses
44
+ such as `wss://host` are not words and are left out. A translation that is
45
+ the English text unchanged is left to the app's own tests.
46
+
47
+ `permission` is held to its forbidden variants alone, because the English word
48
+ also names file and system permissions.
49
+
50
+ From the command line, in CI:
51
+
52
+ ```sh
53
+ npx glimstone-terms web/src/lib/i18n.ts web/src/lib/locales
54
+ ```
55
+
56
+ It reads every module, JSON and ARB file under the paths, takes the language
57
+ of each table from its constant's name (`export const de = {...}`) or from its
58
+ file name (`fr.ts`, `app_pt_BR.arb`), and prints each break with file, line,
59
+ language and key. It exits with 1 when it finds one and 2 when it cannot run,
60
+ for example without an English table.
61
+
62
+ `--terms=relay,backup` checks only those terms, so an app can take them on
63
+ one at a time. `--ignore=terms-ignore.json` names keys to leave out, as `"key"`
64
+ or `"de:key"`, where `*` stands for any run of characters:
65
+
66
+ ```json
67
+ ["de:dest.backupRepo", "pricing.membersOnly*"]
68
+ ```
69
+
70
+ From a test, such as a Vitest file beside the app's other i18n tests:
71
+
72
+ ```ts
73
+ import { checkLocales } from '@glimstone/terms';
74
+
75
+ test('the translations keep to the glossary', () => {
76
+ expect(checkLocales(['src/lib/i18n.ts', 'src/lib/locales'], { ignore })).toEqual([]);
77
+ });
78
+ ```
79
+
80
+ `glossary` hands out the terms themselves, and `checkTables`, `readLocales`
81
+ and `readLocaleText` are the steps `checkLocales` takes, for a build that
82
+ holds its texts somewhere else.
83
+
84
+ The package runs on Node 22 or later and depends on nothing.
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ // Checks an app's translations against the GlimStone glossary.
3
+ //
4
+ // Run: node check-terms.mjs [--terms=relay,backup] [--ignore=ignore.json] <file|dir>...
5
+ // Every locale source under the paths is read: a module with one object per
6
+ // language, a JSON or an ARB file. ignore.json lists keys to leave out, as
7
+ // "key" or "lang:key", where * stands for any run of characters.
8
+ // Exits 1 when a translation breaks the glossary and 2 when the run cannot start.
9
+ import { readFileSync } from 'node:fs';
10
+ import { relative } from 'node:path';
11
+ import { checkTables } from './check.mjs';
12
+ import { readLocales } from './read.mjs';
13
+
14
+ const glossary = JSON.parse(readFileSync(new URL('./terms.json', import.meta.url), 'utf8'));
15
+
16
+ function stop(message) {
17
+ console.error(message);
18
+ process.exit(2);
19
+ }
20
+
21
+ const flags = new Map();
22
+ const paths = [];
23
+ for (const arg of process.argv.slice(2)) {
24
+ const m = /^--(terms|ignore)=(.*)$/.exec(arg);
25
+ if (m) flags.set(m[1], m[2]);
26
+ else paths.push(arg);
27
+ }
28
+ if (!paths.length) stop('usage: node check-terms.mjs [--terms=ID,...] [--ignore=FILE] <file|dir>...');
29
+
30
+ const terms = flags.get('terms')?.split(',').filter(Boolean);
31
+ for (const id of terms ?? []) if (!(id in glossary.terms)) stop(`unknown term "${id}"`);
32
+ const ignore = flags.has('ignore') ? JSON.parse(readFileSync(flags.get('ignore'), 'utf8')) : [];
33
+
34
+ const tables = readLocales(paths, glossary.languages);
35
+ if (!tables.en) stop(`no English table under ${paths.join(', ')}`);
36
+
37
+ const found = checkTables(tables, { glossary, ignore, terms });
38
+ for (const v of found) {
39
+ const entry = glossary.terms[v.term][v.lang];
40
+ const message = v.kind === 'forbidden'
41
+ ? `"${v.word.replace(/^\*|\*$/g, '')}" is not used, write "${entry.singular}"`
42
+ : `the English says ${glossary.terms[v.term].en.singular}, the translation lacks "${entry.singular}"`;
43
+ console.log(`${relative(process.cwd(), v.file)}:${v.line} ${v.lang} ${v.key} ${v.term}: ${message}`);
44
+ }
45
+ const n = found.length;
46
+ console.log(n === 0 ? 'no breaks of the glossary' : `${n} break${n === 1 ? '' : 's'} of the glossary`);
47
+ process.exit(n === 0 ? 0 : 1);
package/check.mjs ADDED
@@ -0,0 +1,109 @@
1
+ // Checks translation tables against the glossary. Two rules: a translation
2
+ // whose English carries a term must carry that term's word for its language,
3
+ // and no translation may use a variant the glossary forbids.
4
+
5
+ // Accents are dropped for matching, since inflection moves them (Greek stress,
6
+ // Arabic vowel marks), but the marks of Indic and Thai vowels are letters.
7
+ const ACCENTS = /[̀-ًͯ-ٰٟ֑-ׇ]/g;
8
+ const INVISIBLE = /[­​-‍ـ]/g;
9
+ const LETTER = '[\\p{L}\\p{M}\\p{N}]';
10
+ // Run twice, so {{name}} goes along with {name}.
11
+ const PLACEHOLDER = /\{[^{}]*\}/g;
12
+
13
+ export function fold(text) {
14
+ return text
15
+ .toLowerCase()
16
+ .normalize('NFD')
17
+ .replace(ACCENTS, '')
18
+ .replace(INVISIBLE, '')
19
+ .replace(/ي/g, 'ی')
20
+ .replace(/ك/g, 'ک')
21
+ .replace(/[’ʼ]/g, "'")
22
+ .normalize('NFC');
23
+ }
24
+
25
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
+ const patterns = new Map();
27
+
28
+ // Paths and addresses such as /relay/connect or wss://host are names, not words.
29
+ const ADDRESS = /(?:[a-z][a-z0-9+.-]*:\/\/|(?<![\p{L}\p{N}])\/)\S*/giu;
30
+
31
+ function pattern(stem, startsWord, endsWord) {
32
+ const id = `${startsWord}${endsWord}\u0000${stem}`;
33
+ let re = patterns.get(id);
34
+ if (!re) {
35
+ const body = fold(stem).trim().split(/\s+/).map(escape).join('[\\s\\u00a0]+');
36
+ re = new RegExp((startsWord ? `(?<!${LETTER})` : '') + body + (endsWord ? `(?!${LETTER})` : ''), 'u');
37
+ patterns.set(id, re);
38
+ }
39
+ return re;
40
+ }
41
+
42
+ const words = (text) => fold(text.replace(PLACEHOLDER, ' ').replace(PLACEHOLDER, ' ').replace(ADDRESS, ' '));
43
+
44
+ /**
45
+ * matchesStems tells whether text holds one of the stems. A stem matches at
46
+ * the start of a word ("start"), anywhere in a word for languages that build
47
+ * compounds ("inside"), or only as a whole word ("whole").
48
+ */
49
+ export function matchesStems(text, stems, mode = 'start') {
50
+ const folded = words(text);
51
+ return stems.some((stem) => pattern(stem, mode !== 'inside', mode === 'whole').test(folded));
52
+ }
53
+
54
+ /**
55
+ * matchesForbidden tells whether text uses a forbidden word. The word is
56
+ * matched whole, a star at its end lets it run on ("relais*") and a star at
57
+ * its start lets it close a compound ("*backup*").
58
+ */
59
+ export function matchesForbidden(text, word) {
60
+ const open = word.startsWith('*');
61
+ const runs = word.endsWith('*');
62
+ return pattern(word.replace(/^\*|\*$/g, ''), !open, !runs).test(words(text));
63
+ }
64
+
65
+ function ignoreRules(ignore, languages) {
66
+ return ignore.map((rule) => {
67
+ const at = rule.indexOf(':');
68
+ const lang = at > 0 && rule.slice(0, at) in languages ? rule.slice(0, at) : null;
69
+ const key = lang ? rule.slice(at + 1) : rule;
70
+ const re = new RegExp('^' + key.split('*').map(escape).join('.*') + '$');
71
+ return (l, k) => (lang === null || lang === l) && re.test(k);
72
+ });
73
+ }
74
+
75
+ /**
76
+ * checkTables returns every place a translation breaks the glossary. tables
77
+ * maps a language code to its entries, each key to { value, file, line }, and
78
+ * must hold the English table under "en".
79
+ */
80
+ export function checkTables(tables, { glossary, ignore = [], terms } = {}) {
81
+ const english = tables.en;
82
+ if (!english) throw new Error('the English table is missing');
83
+ const { languages } = glossary;
84
+ const rules = ignoreRules(ignore, languages);
85
+ const chosen = Object.entries(glossary.terms).filter(([id]) => !terms || terms.includes(id));
86
+ const found = [];
87
+ for (const [lang, table] of Object.entries(tables)) {
88
+ if (!(lang in languages)) continue;
89
+ const mode = languages[lang].stems ?? 'start';
90
+ for (const [key, { value, file, line }] of Object.entries(table)) {
91
+ if (rules.some((skip) => skip(lang, key))) continue;
92
+ const source = english[key]?.value;
93
+ for (const [id, term] of chosen) {
94
+ const entry = term[lang];
95
+ if (!entry) continue;
96
+ const at = entry.stemsAt ?? mode;
97
+ const where = { lang, key, term: id, file, line };
98
+ const used = (entry.forbidden ?? []).filter((word) => matchesForbidden(value, word));
99
+ for (const word of used) found.push({ ...where, kind: 'forbidden', word, text: value });
100
+ if (used.length || lang === 'en' || term.enforce === false || !entry.stems) continue;
101
+ if (source === undefined || source.trim() === value.trim()) continue;
102
+ if (matchesStems(source, term.en.stems, languages.en.stems ?? 'whole') && !matchesStems(value, entry.stems, at)) {
103
+ found.push({ ...where, kind: 'missing', text: value });
104
+ }
105
+ }
106
+ }
107
+ }
108
+ return found;
109
+ }
package/index.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ export type Gender = 'm' | 'f' | 'n' | 'c';
2
+ export type StemMode = 'start' | 'inside' | 'whole';
3
+
4
+ export interface Entry {
5
+ singular: string;
6
+ plural: string;
7
+ gender?: Gender;
8
+ stems?: string[];
9
+ forbidden?: string[];
10
+ stemsAt?: StemMode;
11
+ }
12
+
13
+ export interface Language {
14
+ name: string;
15
+ stems: StemMode;
16
+ genders: Gender[];
17
+ }
18
+
19
+ export type Term = { definition: string; enforce?: false } & { [lang: string]: Entry };
20
+
21
+ export interface Glossary {
22
+ languages: Record<string, Language>;
23
+ terms: Record<string, Term>;
24
+ }
25
+
26
+ export interface Located {
27
+ value: string;
28
+ file: string;
29
+ line: number;
30
+ }
31
+
32
+ export type Tables = Record<string, Record<string, Located>>;
33
+
34
+ export interface Break {
35
+ kind: 'missing' | 'forbidden';
36
+ lang: string;
37
+ key: string;
38
+ term: string;
39
+ file: string;
40
+ line: number;
41
+ text: string;
42
+ word?: string;
43
+ }
44
+
45
+ export interface CheckOptions {
46
+ ignore?: string[];
47
+ terms?: string[];
48
+ }
49
+
50
+ export declare const glossary: Glossary;
51
+ export declare function checkLocales(paths: string[], options?: CheckOptions): Break[];
52
+ export declare function checkTables(tables: Tables, options: CheckOptions & { glossary: Glossary }): Break[];
53
+ export declare function matchesStems(text: string, stems: string[], mode?: StemMode): boolean;
54
+ export declare function matchesForbidden(text: string, word: string): boolean;
55
+ export declare function fold(text: string): string;
56
+ export declare function readLocales(paths: string[], languages: Record<string, unknown>): Tables;
57
+ export declare function languageOf(name: string | null, file: string, languages: Record<string, unknown>): string | null;
58
+ export declare function readLocaleText(text: string, options?: { json?: boolean }): { name: string | null; entries: { key: string; value: string; line: number }[] }[];
package/index.mjs ADDED
@@ -0,0 +1,16 @@
1
+ import glossary from './terms.json' with { type: 'json' };
2
+ import { checkTables } from './check.mjs';
3
+ import { readLocales } from './read.mjs';
4
+
5
+ export { glossary };
6
+ export { checkTables, fold, matchesForbidden, matchesStems } from './check.mjs';
7
+ export { languageOf, readLocales } from './read.mjs';
8
+ export { readLocaleText } from './locales.mjs';
9
+
10
+ /**
11
+ * checkLocales reads the locale sources under paths and returns every place
12
+ * they break the glossary, so a test can expect an empty list.
13
+ */
14
+ export function checkLocales(paths, { ignore = [], terms } = {}) {
15
+ return checkTables(readLocales(paths, glossary.languages), { glossary, ignore, terms });
16
+ }
package/locales.mjs ADDED
@@ -0,0 +1,204 @@
1
+ // Reads the translation tables out of a locale source without running it: a
2
+ // TypeScript or JavaScript module with one object literal per language, a JSON
3
+ // file, or a Flutter ARB file. Only keys whose value is plain text are kept,
4
+ // since a function or an interpolated template has no fixed words to check.
5
+
6
+ const PUNCT = new Set(['{', '}', '[', ']', '(', ')', ':', ',', ';', '+', '=', '.', '<', '>', '?', '!', '&', '|']);
7
+ const BEFORE_REGEX = new Set(['(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', 'return', 'typeof']);
8
+
9
+ function tokenize(text) {
10
+ const tokens = [];
11
+ let i = 0;
12
+ let line = 1;
13
+ const push = (type, value, at) => tokens.push({ type, value, line: at });
14
+ while (i < text.length) {
15
+ const c = text[i];
16
+ if (c === '\n') { line++; i++; continue; }
17
+ if (/\s/.test(c)) { i++; continue; }
18
+ if (c === '/' && text[i + 1] === '/') {
19
+ while (i < text.length && text[i] !== '\n') i++;
20
+ continue;
21
+ }
22
+ if (c === '/' && text[i + 1] === '*') {
23
+ const end = text.indexOf('*/', i + 2);
24
+ const stop = end < 0 ? text.length : end + 2;
25
+ for (; i < stop; i++) if (text[i] === '\n') line++;
26
+ continue;
27
+ }
28
+ if (c === '"' || c === "'" || c === '`') {
29
+ const at = line;
30
+ let value = '';
31
+ let plain = true;
32
+ i++;
33
+ while (i < text.length && text[i] !== c) {
34
+ const ch = text[i];
35
+ if (ch === '\n') line++;
36
+ if (ch === '\\') {
37
+ const [decoded, used] = unescape(text, i);
38
+ if (text[i + 1] === '\n') line++;
39
+ value += decoded;
40
+ i += used;
41
+ continue;
42
+ }
43
+ if (c === '`' && ch === '$' && text[i + 1] === '{') plain = false;
44
+ value += ch;
45
+ i++;
46
+ }
47
+ i++;
48
+ push(c === '`' ? 'template' : 'string', plain ? value : null, at);
49
+ continue;
50
+ }
51
+ if (c === '/') {
52
+ const prev = tokens[tokens.length - 1];
53
+ if (!prev || BEFORE_REGEX.has(prev.value)) {
54
+ i = skipRegex(text, i);
55
+ push('regex', null, line);
56
+ continue;
57
+ }
58
+ }
59
+ const word = /^[\p{L}\p{N}_$]+/u.exec(text.slice(i, i + 200));
60
+ if (word) {
61
+ push(/^\d/.test(word[0]) ? 'number' : 'ident', word[0], line);
62
+ i += word[0].length;
63
+ continue;
64
+ }
65
+ push(PUNCT.has(c) ? 'punct' : 'other', c, line);
66
+ i++;
67
+ }
68
+ return tokens;
69
+ }
70
+
71
+ function unescape(text, i) {
72
+ const n = text[i + 1];
73
+ const simple = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' };
74
+ if (n in simple) return [simple[n], 2];
75
+ if (n === 'u' && text[i + 2] === '{') {
76
+ const end = text.indexOf('}', i + 3);
77
+ return [String.fromCodePoint(parseInt(text.slice(i + 3, end), 16)), end - i + 1];
78
+ }
79
+ if (n === 'u') return [String.fromCharCode(parseInt(text.slice(i + 2, i + 6), 16)), 6];
80
+ if (n === 'x') return [String.fromCharCode(parseInt(text.slice(i + 2, i + 4), 16)), 4];
81
+ if (n === '\n') return ['', 2];
82
+ return [n, 2];
83
+ }
84
+
85
+ function skipRegex(text, i) {
86
+ let inClass = false;
87
+ for (i++; i < text.length; i++) {
88
+ const c = text[i];
89
+ if (c === '\\') { i++; continue; }
90
+ if (c === '\n') return i;
91
+ if (c === '[') inClass = true;
92
+ else if (c === ']') inClass = false;
93
+ else if (c === '/' && !inClass) break;
94
+ }
95
+ i++;
96
+ while (/[a-z]/.test(text[i] ?? '')) i++;
97
+ return i;
98
+ }
99
+
100
+ const OPEN = { '{': '}', '[': ']', '(': ')' };
101
+
102
+ class Reader {
103
+ constructor(tokens) {
104
+ this.tokens = tokens;
105
+ this.at = 0;
106
+ }
107
+ peek(ahead = 0) { return this.tokens[this.at + ahead]; }
108
+ next() { return this.tokens[this.at++]; }
109
+ is(value, ahead = 0) { return this.peek(ahead)?.value === value && this.peek(ahead).type === 'punct'; }
110
+
111
+ // Skips one expression, stopping before the comma or bracket that ends it.
112
+ skipExpression() {
113
+ const stack = [];
114
+ while (this.peek()) {
115
+ const t = this.peek();
116
+ if (t.type === 'punct') {
117
+ if (stack.length === 0 && (t.value === ',' || t.value === '}' || t.value === ']' || t.value === ')' || t.value === ';')) return;
118
+ if (OPEN[t.value]) stack.push(OPEN[t.value]);
119
+ else if (t.value === stack[stack.length - 1]) stack.pop();
120
+ }
121
+ this.next();
122
+ }
123
+ }
124
+
125
+ readObject(prefix, into) {
126
+ this.next();
127
+ while (this.peek() && !this.is('}')) {
128
+ if (this.is(',')) { this.next(); continue; }
129
+ if (this.is('.') && this.is('.', 1) && this.is('.', 2)) { this.skipExpression(); continue; }
130
+ const keyToken = this.next();
131
+ if (!['string', 'ident', 'number'].includes(keyToken.type) || keyToken.value === null || !this.is(':')) {
132
+ this.skipExpression();
133
+ continue;
134
+ }
135
+ this.next();
136
+ const key = prefix + keyToken.value;
137
+ if (this.is('{')) {
138
+ this.readObject(key + '.', into);
139
+ continue;
140
+ }
141
+ const value = this.readText();
142
+ if (value !== null && (this.is(',') || this.is('}'))) into.push({ key, value, line: keyToken.line });
143
+ else this.skipExpression();
144
+ }
145
+ this.next();
146
+ }
147
+
148
+ // Reads a string, or strings joined by +, and answers null for anything else.
149
+ readText() {
150
+ let value = '';
151
+ for (;;) {
152
+ const t = this.peek();
153
+ if (!t || (t.type !== 'string' && t.type !== 'template') || t.value === null) return null;
154
+ value += t.value;
155
+ this.next();
156
+ if (!this.is('+')) return value;
157
+ this.next();
158
+ }
159
+ }
160
+ }
161
+
162
+ /**
163
+ * readLocaleText returns the tables a locale source holds, each as its
164
+ * constant's name (null for JSON and a default export) and its entries in
165
+ * file order, with the line every key sits on.
166
+ */
167
+ export function readLocaleText(text, { json = false } = {}) {
168
+ const r = new Reader(tokenize(text));
169
+ const tables = [];
170
+ const read = (name) => {
171
+ const entries = [];
172
+ r.readObject('', entries);
173
+ tables.push({ name, entries: json ? entries.filter((e) => !e.key.startsWith('@')) : entries });
174
+ };
175
+ if (json) {
176
+ while (r.peek() && !r.is('{')) r.next();
177
+ if (r.peek()) read(null);
178
+ return tables;
179
+ }
180
+ let depth = 0;
181
+ while (r.peek()) {
182
+ const t = r.next();
183
+ if (t.type === 'punct') {
184
+ if (OPEN[t.value]) depth++;
185
+ else if (t.value === '}' || t.value === ']' || t.value === ')') depth--;
186
+ continue;
187
+ }
188
+ if (depth !== 0 || t.type !== 'ident') continue;
189
+ if (t.value === 'default' && r.is('{')) { read(null); continue; }
190
+ if (!['const', 'let', 'var'].includes(t.value) || r.peek()?.type !== 'ident') continue;
191
+ const name = r.next().value;
192
+ let angle = 0;
193
+ while (r.peek() && !(angle === 0 && (r.is('=') || r.is(';')))) {
194
+ if (r.is('<')) angle++;
195
+ else if (r.is('>')) angle--;
196
+ r.next();
197
+ }
198
+ if (r.is('=') && r.is('{', 1)) {
199
+ r.next();
200
+ read(name);
201
+ }
202
+ }
203
+ return tables;
204
+ }
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "@glimstone/terms",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.4.1",
4
+ "description": "The shared words of an interface in 42 languages, and a check that holds translations to them",
5
+ "license": "AGPL-3.0-only",
6
+ "repository": { "type": "git", "url": "git+https://github.com/junkerderprovinz/glimstone.git", "directory": "packages/terms" },
7
+ "homepage": "https://junkerderprovinz.github.io/glimstone/",
8
+ "type": "module",
9
+ "sideEffects": false,
10
+ "engines": { "node": ">=22" },
11
+ "bin": { "glimstone-terms": "./check-terms.mjs" },
12
+ "exports": {
13
+ ".": { "types": "./index.d.ts", "default": "./index.mjs" },
14
+ "./terms.json": "./terms.json"
15
+ },
16
+ "files": ["index.mjs", "index.d.ts", "check.mjs", "read.mjs", "locales.mjs", "check-terms.mjs", "terms.json"]
17
+ }
package/read.mjs ADDED
@@ -0,0 +1,53 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { basename, extname, join } from 'node:path';
3
+ import { readLocaleText } from './locales.mjs';
4
+
5
+ const SOURCES = new Set(['.ts', '.tsx', '.js', '.mjs', '.json', '.arb']);
6
+ const SKIPPED = /\.(test|spec)\.|\.d\.ts$/;
7
+
8
+ /**
9
+ * languageOf names the language of a table: its constant's name when that is
10
+ * a language code, or else the code that ends its file name (fr.ts,
11
+ * app_pt_BR.arb, de-AT.json), passing over a region in capitals. It answers
12
+ * null for anything else.
13
+ */
14
+ export function languageOf(name, file, languages) {
15
+ if (name && name in languages) return name;
16
+ const parts = basename(file, extname(file)).split(/[_.-]/);
17
+ if (parts.length > 1 && /^[A-Z]{2}$/.test(parts[parts.length - 1])) parts.pop();
18
+ const code = parts[parts.length - 1].toLowerCase();
19
+ return code in languages ? code : null;
20
+ }
21
+
22
+ function* files(path) {
23
+ if (!statSync(path).isDirectory()) {
24
+ yield path;
25
+ return;
26
+ }
27
+ for (const name of readdirSync(path).sort()) {
28
+ if (name === 'node_modules' || name.startsWith('.')) continue;
29
+ const child = join(path, name);
30
+ if (statSync(child).isDirectory()) yield* files(child);
31
+ else if (SOURCES.has(extname(name)) && !SKIPPED.test(name)) yield child;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * readLocales reads every locale source under the given files and
37
+ * directories into one table per language: key to { value, file, line }.
38
+ */
39
+ export function readLocales(paths, languages) {
40
+ const tables = {};
41
+ for (const path of paths) {
42
+ for (const file of files(path)) {
43
+ const json = ['.json', '.arb'].includes(extname(file));
44
+ for (const table of readLocaleText(readFileSync(file, 'utf8'), { json })) {
45
+ const lang = languageOf(table.name, file, languages);
46
+ if (!lang) continue;
47
+ tables[lang] ??= {};
48
+ for (const { key, value, line } of table.entries) tables[lang][key] = { value, file, line };
49
+ }
50
+ }
51
+ }
52
+ return tables;
53
+ }