-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathextract.ts
More file actions
253 lines (231 loc) · 9.51 KB
/
Copy pathextract.ts
File metadata and controls
253 lines (231 loc) · 9.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import fs from 'fs';
import path from 'path';
import { Args, Command, Flags } from '@oclif/core';
import chalk from 'chalk';
import { normalizeStackInput } from '@objectstack/spec';
import { loadConfig } from '../../utils/config.js';
import {
printHeader,
printSuccess,
printError,
printInfo,
printStep,
createTimer,
} from '../../utils/format.js';
import { extractTranslations, renderTranslationModule, type FillStrategy } from '../../utils/i18n-extract.js';
const FILL_STRATEGIES: FillStrategy[] = ['empty', 'default', 'todo'];
/** Count string-leaf entries under a nested object — used for reporting. */
function countLeaves(obj: unknown): number {
if (!obj || typeof obj !== 'object') return 0;
let n = 0;
for (const v of Object.values(obj as Record<string, unknown>)) {
if (typeof v === 'string') n += 1;
else if (v && typeof v === 'object') n += countLeaves(v);
}
return n;
}
/**
* `os i18n extract` — scaffold translation skeletons.
*
* Walks the normalized stack config and emits ready-to-edit `TranslationData`
* fragments for every requested locale. Designed as the companion to
* `os i18n check`: extract bootstraps the bundle, check validates it.
*/
export default class I18nExtract extends Command {
static override description =
'Scaffold per-locale translation skeletons from a stack config. Default locale is filled from schema labels; other locales follow --fill.';
static override examples = [
'$ os i18n extract',
'$ os i18n extract --locales=zh-CN,ja-JP,es-ES',
'$ os i18n extract --filter="^sys_" --out=./src/translations',
'$ os i18n extract --fill=default --out=./src/translations',
'$ os i18n extract --json',
];
static override args = {
config: Args.string({ description: 'Configuration file path', required: false }),
};
static override flags = {
json: Flags.boolean({ description: 'Output JSON instead of writing files' }),
'default-locale': Flags.string({
description: 'Locale filled from schema labels',
default: 'en',
}),
locales: Flags.string({
description: 'Comma-separated list of locales to emit (always includes default-locale)',
}),
fill: Flags.string({
description: 'How non-default locales are filled: empty | default | todo',
default: 'empty',
options: FILL_STRATEGIES as unknown as string[],
}),
filter: Flags.string({
description: 'Regex; only entries matching objectName, appName or path are emitted',
}),
out: Flags.string({
description: 'Directory to write <locale>.objects.generated.ts files into',
}),
'no-merge': Flags.boolean({
description: 'Do not merge against existing translations — emit every expected key',
default: false,
}),
'objects-only': Flags.boolean({
description: 'Emit only the objects/globalActions subtree (default). Disable to include apps/dashboards.',
default: true,
allowNo: true,
}),
'dry-run': Flags.boolean({
description: 'Print to stdout instead of writing to --out',
default: false,
}),
check: Flags.boolean({
description: 'Write nothing; fail if the committed bundles in --out differ from a fresh extract',
default: false,
}),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(I18nExtract);
const timer = createTimer();
if (!flags.json) {
printHeader('I18n Extract');
printStep('Loading configuration...');
}
try {
const { config, absolutePath } = await loadConfig(args.config);
if (!flags.json) printInfo(`Config: ${chalk.white(absolutePath)}`);
const normalized = normalizeStackInput(config as Record<string, unknown>);
const filter = flags.filter ? new RegExp(flags.filter) : undefined;
const locales = flags.locales
? flags.locales.split(',').map((s) => s.trim()).filter(Boolean)
: undefined;
const result = extractTranslations(normalized, {
defaultLocale: flags['default-locale'],
locales,
fill: flags.fill as FillStrategy,
filter,
mergeExisting: !flags['no-merge'],
});
const localesEmitted = Object.keys(result.bundles);
const objectsOnly = flags['objects-only'];
// Count metadataForms keys per locale (computed separately so we
// can show users an honest summary even when --objects-only).
const metadataFormsCounts: Record<string, number> = {};
for (const locale of localesEmitted) {
metadataFormsCounts[locale] = countLeaves(result.bundles[locale]?.metadataForms);
}
const anyMetadataForms = Object.values(metadataFormsCounts).some((n) => n > 0);
if (flags.json) {
console.log(JSON.stringify({
totalExpected: result.totalExpected,
counts: result.counts,
metadataFormsCounts,
bundles: objectsOnly
? Object.fromEntries(localesEmitted.map((l) => [l, result.bundles[l].objects ?? {}]))
: result.bundles,
duration: timer.elapsed(),
}, null, 2));
return;
}
console.log('');
console.log(chalk.bold(' Skeleton summary'));
const nameWidth = Math.max(8, ...localesEmitted.map((l) => l.length));
for (const locale of localesEmitted) {
const n = result.counts[locale];
const tone = n === 0 ? chalk.green : chalk.yellow;
const mfN = metadataFormsCounts[locale] ?? 0;
const mfTail = mfN > 0 ? chalk.dim(` + ${mfN} metadataForms key(s)`) : '';
console.log(
` ${locale.padEnd(nameWidth)} ${tone(String(n).padStart(5))} key(s)` +
chalk.dim(` (of ${result.totalExpected} expected)`) + mfTail,
);
}
console.log('');
if (flags.check && !flags.out) {
throw new Error('--check needs --out=<dir> — it compares a fresh extract against the bundles committed there.');
}
if (flags['dry-run'] || !flags.out) {
for (const locale of localesEmitted) {
if (result.counts[locale] === 0 && metadataFormsCounts[locale] === 0) continue;
console.log(chalk.dim(`── ${locale} (objects) ──`));
console.log(renderTranslationModule(result.bundles[locale], {
locale,
objectsOnly,
}));
if (metadataFormsCounts[locale] > 0) {
console.log(chalk.dim(`── ${locale} (metadataForms) ──`));
console.log(renderTranslationModule(result.bundles[locale], {
locale,
kind: 'metadataForms',
}));
}
}
printInfo('Dry run — no files written (pass --out=<dir> to write).');
return;
}
const outDir = path.resolve(process.cwd(), flags.out);
// Every file a normal run would emit, paired with its rendered content.
// Both branches below iterate this, so `--check` can never diverge from
// what a real extract writes.
const emitted: Array<{ file: string; content: string; keys: number }> = [];
for (const locale of localesEmitted) {
if (result.counts[locale] > 0) {
emitted.push({
file: path.join(outDir, `${locale}.objects.generated.ts`),
content: renderTranslationModule(result.bundles[locale], { locale, objectsOnly }),
keys: result.counts[locale],
});
}
if (metadataFormsCounts[locale] > 0) {
emitted.push({
file: path.join(outDir, `${locale}.metadata-forms.generated.ts`),
content: renderTranslationModule(result.bundles[locale], { locale, kind: 'metadataForms' }),
keys: metadataFormsCounts[locale],
});
}
}
if (flags.check) {
const stale: string[] = [];
const missing: string[] = [];
for (const { file, content } of emitted) {
const rel = path.relative(process.cwd(), file);
if (!fs.existsSync(file)) missing.push(rel);
else if (fs.readFileSync(file, 'utf8') !== content) stale.push(rel);
}
if (missing.length === 0 && stale.length === 0) {
console.log('');
printSuccess(`${emitted.length} bundle(s) are in sync with the schema ${chalk.dim(`(${timer.display()})`)}`);
return;
}
for (const rel of missing) printError(`missing: ${rel}`);
for (const rel of stale) printError(`out of date: ${rel}`);
console.log('');
printError(
'Translation bundles have drifted from the schema. Regenerate and commit:\n' +
` os i18n extract ${args.config ?? ''} --locales=${localesEmitted.filter((l) => l !== flags['default-locale']).join(',')} ` +
`--fill=${flags.fill} --out=${flags.out}`.replace(/\s+/g, ' '),
);
process.exit(1);
}
fs.mkdirSync(outDir, { recursive: true });
let written = 0;
for (const { file, content, keys } of emitted) {
fs.writeFileSync(file, content, 'utf8');
written += 1;
printInfo(`Wrote ${chalk.white(path.relative(process.cwd(), file))} (${keys} keys)`);
}
if (!anyMetadataForms) {
printInfo('(no metadataForms keys discovered for these locales)');
}
console.log('');
printSuccess(`Generated ${written} file(s) ${chalk.dim(`(${timer.display()})`)}`);
} catch (error: any) {
if (flags.json) {
console.log(JSON.stringify({ error: error.message }));
process.exit(1);
}
console.log('');
printError(error.message || String(error));
process.exit(1);
}
}
}