@kizunajs/i18n 0.0.0-stage → 0.1.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/LICENSE.MD +9 -0
- package/README.md +233 -2
- package/dist/bin.cjs +174 -0
- package/dist/bin.d.cts +1 -0
- package/dist/bin.d.mts +1 -0
- package/dist/bin.mjs +175 -0
- package/dist/generate.cjs +393 -0
- package/dist/generate.d.cts +262 -0
- package/dist/generate.d.mts +262 -0
- package/dist/generate.mjs +385 -0
- package/dist/index.cjs +72 -0
- package/dist/index.d.cts +150 -0
- package/dist/index.d.mts +150 -0
- package/dist/index.mjs +71 -0
- package/dist/load-CE9FYddD.mjs +255 -0
- package/dist/load-dVzjsBK6.cjs +290 -0
- package/dist/source-BrYHodVt.mjs +11 -0
- package/dist/source-CAF21cuM.d.cts +35 -0
- package/dist/source-CDwD6Wcn.cjs +22 -0
- package/dist/source-DJMnQ2hS.d.mts +35 -0
- package/package.json +84 -3
package/LICENSE.MD
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sondre Ørland
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,234 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Kizuna i18n
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
Write your translations in TypeScript. Get typed text in your app, and a build that fails when a language is missing or a text won't fit.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Broken translations don't compile**: forget Norwegian, or write `{fornavn}` where English has `{firstName}`, and `tsc` names the language that's wrong
|
|
10
|
+
- **Text that fits**: `.maxLength(16)` on a button label, and a German text that's too long fails the build
|
|
11
|
+
- **Docs on hover**: every message shows its text, what it's for and its limit in your editor
|
|
12
|
+
- **Nothing to install**: the generated file has no imports, so your app ships no i18n library
|
|
13
|
+
- **Links inside sentences**: `<terms>the terms of sale</terms>` renders as your own `<a>`, in every language
|
|
14
|
+
- **Ship a language half done**: `de` shows the English text for messages nobody has translated yet
|
|
15
|
+
- **The right language per request**: `matchLocale` reads the `Accept-Language` header
|
|
16
|
+
- **Every problem in one list**: `kizuna-i18n check` prints one line per message and language
|
|
17
|
+
- **Your own targets**: generate code for another language with `defineTarget`
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
pnpm add -D @kizunajs/i18n
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
Declare your languages:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// translations/i18n.ts
|
|
31
|
+
import { defineI18n } from '@kizunajs/i18n';
|
|
32
|
+
|
|
33
|
+
export const i18n = defineI18n({
|
|
34
|
+
base: 'en',
|
|
35
|
+
locales: {
|
|
36
|
+
en: {},
|
|
37
|
+
nb: {},
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Write the messages:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
// translations/cart.ts
|
|
46
|
+
import { i18n } from './i18n';
|
|
47
|
+
|
|
48
|
+
export const cart = i18n.messages({
|
|
49
|
+
title: i18n.message({
|
|
50
|
+
en: 'Your cart',
|
|
51
|
+
nb: 'Handlekurven din',
|
|
52
|
+
}),
|
|
53
|
+
greeting: i18n.message({
|
|
54
|
+
en: 'Welcome back, {firstName}',
|
|
55
|
+
nb: 'Velkommen tilbake, {firstName}',
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Every language must use the base language's `{params}` and `<tags>`:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
nb: 'Velkommen tilbake, {fornavn}',
|
|
64
|
+
// Type '"Velkommen tilbake, {fornavn}"' is not assignable to type
|
|
65
|
+
// '"nb uses {fornavn}, the message has {firstName}"'.
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Configure the generator:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// i18n.config.ts
|
|
72
|
+
import { defineConfig, typescriptTarget } from '@kizunajs/i18n/generate';
|
|
73
|
+
|
|
74
|
+
export default defineConfig({
|
|
75
|
+
messages: './translations',
|
|
76
|
+
targets: [
|
|
77
|
+
typescriptTarget({
|
|
78
|
+
output: './src/translations.generated.ts',
|
|
79
|
+
}),
|
|
80
|
+
],
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
pnpm kizuna-i18n generate
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Import the generated file:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { getTranslations } from './translations.generated';
|
|
92
|
+
|
|
93
|
+
const t = getTranslations('nb');
|
|
94
|
+
|
|
95
|
+
t.cart.title; // 'Handlekurven din'
|
|
96
|
+
t.cart.greeting({
|
|
97
|
+
firstName: 'Ada',
|
|
98
|
+
}); // 'Velkommen tilbake, Ada'
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Picking the language
|
|
102
|
+
|
|
103
|
+
`matchLocale` takes a list of languages or an `Accept-Language` header, and returns the best match or the base language:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { getTranslations, matchLocale } from './translations.generated';
|
|
107
|
+
|
|
108
|
+
const t = getTranslations(matchLocale(navigator.languages));
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
On a server:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
// src/locale.ts
|
|
115
|
+
import { headers } from 'next/headers';
|
|
116
|
+
import { matchLocale } from './translations.generated';
|
|
117
|
+
|
|
118
|
+
export const getLocale = async () => matchLocale((await headers()).get('accept-language') ?? '');
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Length limits
|
|
122
|
+
|
|
123
|
+
`maxLength` sets the most characters a text may have, in every language:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
title: i18n
|
|
127
|
+
.message({
|
|
128
|
+
en: 'Your cart',
|
|
129
|
+
nb: 'Handlekurven din',
|
|
130
|
+
})
|
|
131
|
+
.maxLength(16),
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The compiler checks texts without params. `kizuna-i18n check` checks the rest, with the params filled in from `example`.
|
|
135
|
+
|
|
136
|
+
## Descriptions and examples
|
|
137
|
+
|
|
138
|
+
`describe` and `example` show up in the generated JSDoc:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
greeting: i18n
|
|
142
|
+
.message({
|
|
143
|
+
en: 'Welcome back, {firstName}',
|
|
144
|
+
nb: 'Velkommen tilbake, {firstName}',
|
|
145
|
+
})
|
|
146
|
+
.describe('Shown above the cart to a customer who is logged in')
|
|
147
|
+
.example({
|
|
148
|
+
firstName: 'Ada',
|
|
149
|
+
}),
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Fallback languages
|
|
153
|
+
|
|
154
|
+
A language with a `fallback` may leave messages out:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
export const i18n = defineI18n({
|
|
158
|
+
base: 'en',
|
|
159
|
+
locales: {
|
|
160
|
+
en: {},
|
|
161
|
+
nb: {},
|
|
162
|
+
de: {
|
|
163
|
+
fallback: 'en',
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Tags
|
|
170
|
+
|
|
171
|
+
Pass a function for each `<tag>`. It gets the translated text inside the tag:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
terms: i18n.message({
|
|
175
|
+
en: 'I agree to <terms>the terms of sale</terms>',
|
|
176
|
+
nb: 'Jeg godtar <terms>salgsvilkårene</terms>',
|
|
177
|
+
}),
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
```tsx
|
|
181
|
+
t.cart.terms({
|
|
182
|
+
terms: (text) => <a href="/terms">{text}</a>,
|
|
183
|
+
});
|
|
184
|
+
// ['I agree to ', <a>the terms of sale</a>]
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## Rich values
|
|
188
|
+
|
|
189
|
+
A param can be a React element. The message then returns an array React can render:
|
|
190
|
+
|
|
191
|
+
```tsx
|
|
192
|
+
<p>
|
|
193
|
+
{t.cart.greeting({
|
|
194
|
+
firstName: <strong>Ada</strong>,
|
|
195
|
+
})}
|
|
196
|
+
</p>
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Check and generate
|
|
200
|
+
|
|
201
|
+
```sh
|
|
202
|
+
pnpm kizuna-i18n check # lists every problem, one line each
|
|
203
|
+
pnpm kizuna-i18n generate # writes every target's files
|
|
204
|
+
pnpm kizuna-i18n generate --watch # writes again on every change
|
|
205
|
+
pnpm kizuna-i18n generate --check # fails when a generated file is out of date
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`check` fails on errors, and lists texts that show a fallback:
|
|
209
|
+
|
|
210
|
+
```
|
|
211
|
+
cart.greeting nb uses {fornavn}, the message has {firstName}
|
|
212
|
+
cart.title de has no translation, shows en
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Targets
|
|
216
|
+
|
|
217
|
+
A target generates code for one language:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { z } from 'zod';
|
|
221
|
+
import { defineTarget } from '@kizunajs/i18n/generate';
|
|
222
|
+
|
|
223
|
+
export const csharpTarget = defineTarget({
|
|
224
|
+
language: 'csharp',
|
|
225
|
+
options: z.object({
|
|
226
|
+
namespace: z.string().default('Strings'),
|
|
227
|
+
}),
|
|
228
|
+
generate: ({ options, catalog }) => renderCsharp(catalog, options.namespace),
|
|
229
|
+
});
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
MIT
|
package/dist/bin.cjs
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const require_load = require("./load-dVzjsBK6.cjs");
|
|
3
|
+
let node_fs = require("node:fs");
|
|
4
|
+
let node_path = require("node:path");
|
|
5
|
+
let jiti = require("jiti");
|
|
6
|
+
//#region src/files.ts
|
|
7
|
+
/**
|
|
8
|
+
* Every file the config's targets generate from the messages.
|
|
9
|
+
*/
|
|
10
|
+
function plannedFiles(source, config, root) {
|
|
11
|
+
const catalog = require_load.toCatalog(source);
|
|
12
|
+
const files = [];
|
|
13
|
+
for (const target of config.targets ?? []) {
|
|
14
|
+
const output = (0, node_path.resolve)(root, target.output);
|
|
15
|
+
const rendered = target.render(catalog);
|
|
16
|
+
if (typeof rendered === "string") files.push({
|
|
17
|
+
path: output,
|
|
18
|
+
contents: rendered
|
|
19
|
+
});
|
|
20
|
+
else files.push(...rendered.map((file) => ({
|
|
21
|
+
path: (0, node_path.join)(output, file.path),
|
|
22
|
+
contents: file.contents
|
|
23
|
+
})));
|
|
24
|
+
}
|
|
25
|
+
return files;
|
|
26
|
+
}
|
|
27
|
+
const currentContents = (path) => {
|
|
28
|
+
try {
|
|
29
|
+
return (0, node_fs.readFileSync)(path, "utf8");
|
|
30
|
+
} catch {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Writes every file, leaving one alone when it already matches so watchers see no change. Returns
|
|
36
|
+
* the files it wrote.
|
|
37
|
+
*/
|
|
38
|
+
function writeFiles(files) {
|
|
39
|
+
return files.flatMap((file) => {
|
|
40
|
+
if (currentContents(file.path) === file.contents) return [];
|
|
41
|
+
(0, node_fs.mkdirSync)((0, node_path.dirname)(file.path), { recursive: true });
|
|
42
|
+
(0, node_fs.writeFileSync)(file.path, file.contents);
|
|
43
|
+
return [file.path];
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Every file that no longer matches, without writing anything.
|
|
48
|
+
*/
|
|
49
|
+
function checkFiles(files) {
|
|
50
|
+
return files.flatMap((file) => {
|
|
51
|
+
const current = currentContents(file.path);
|
|
52
|
+
if (current === void 0) return [{
|
|
53
|
+
path: file.path,
|
|
54
|
+
reason: "missing"
|
|
55
|
+
}];
|
|
56
|
+
if (current !== file.contents) return [{
|
|
57
|
+
path: file.path,
|
|
58
|
+
reason: "outdated"
|
|
59
|
+
}];
|
|
60
|
+
return [];
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* What a failed check prints: the stale files, and the command that fixes them.
|
|
65
|
+
*/
|
|
66
|
+
function formatStale(stale, root) {
|
|
67
|
+
const lines = stale.map((file) => {
|
|
68
|
+
const where = (0, node_path.relative)(root, file.path);
|
|
69
|
+
return file.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the messages`;
|
|
70
|
+
});
|
|
71
|
+
return [
|
|
72
|
+
stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
|
|
73
|
+
...lines,
|
|
74
|
+
"",
|
|
75
|
+
"Run `kizuna-i18n generate` and commit the result."
|
|
76
|
+
].join("\n");
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/cli.ts
|
|
80
|
+
const usage = `Usage: kizuna-i18n <command> [--config <path>]
|
|
81
|
+
|
|
82
|
+
check Lists every problem in the messages, one line each.
|
|
83
|
+
generate Writes every target's files.
|
|
84
|
+
generate --check Writes nothing, and fails when a generated file is out of date.
|
|
85
|
+
generate --watch Writes again on every change to the messages.
|
|
86
|
+
--config <path> The config file. Default: i18n.config.ts`;
|
|
87
|
+
async function readConfig(configPath) {
|
|
88
|
+
return await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
|
|
89
|
+
interopDefault: true,
|
|
90
|
+
jsx: true,
|
|
91
|
+
tsconfigPaths: true,
|
|
92
|
+
moduleCache: false,
|
|
93
|
+
fsCache: false
|
|
94
|
+
}).import(configPath, { default: true });
|
|
95
|
+
}
|
|
96
|
+
async function check(configPath) {
|
|
97
|
+
const config = await readConfig(configPath);
|
|
98
|
+
const problems = require_load.problemsOf(await require_load.loadMessages((0, node_path.resolve)((0, node_path.dirname)(configPath), config.messages)));
|
|
99
|
+
const errors = problems.filter((problem) => problem.severity === "error");
|
|
100
|
+
const notices = problems.length - errors.length;
|
|
101
|
+
if (problems.length === 0) {
|
|
102
|
+
console.log("Every message is complete in every language.");
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
const summary = [errors.length > 0 ? `${errors.length} ${errors.length === 1 ? "error" : "errors"}` : "No errors", notices > 0 ? `${notices} ${notices === 1 ? "shows" : "show"} a fallback` : void 0].filter(Boolean).join(", ");
|
|
106
|
+
(errors.length > 0 ? console.error : console.log)(`${require_load.formatProblems(problems)}\n\n${summary}.`);
|
|
107
|
+
return errors.length > 0 ? 1 : 0;
|
|
108
|
+
}
|
|
109
|
+
async function generate(configPath, onlyCheck) {
|
|
110
|
+
const config = await readConfig(configPath);
|
|
111
|
+
const root = (0, node_path.dirname)(configPath);
|
|
112
|
+
const files = plannedFiles(await require_load.loadMessages((0, node_path.resolve)(root, config.messages)), config, root);
|
|
113
|
+
if (onlyCheck) {
|
|
114
|
+
const stale = checkFiles(files);
|
|
115
|
+
if (stale.length > 0) {
|
|
116
|
+
console.error(formatStale(stale, root));
|
|
117
|
+
return 1;
|
|
118
|
+
}
|
|
119
|
+
console.log(`${files.length} generated ${files.length === 1 ? "file is" : "files are"} current.`);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
const written = writeFiles(files);
|
|
123
|
+
console.log(written.length === 0 ? "Everything was already current." : written.map((path) => `Wrote ${(0, node_path.relative)(process.cwd(), path)}`).join("\n"));
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
async function generateOnChange(configPath) {
|
|
127
|
+
const config = await readConfig(configPath);
|
|
128
|
+
const folder = (0, node_path.resolve)((0, node_path.dirname)(configPath), config.messages);
|
|
129
|
+
const write = async () => {
|
|
130
|
+
try {
|
|
131
|
+
await generate(configPath, false);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
console.error(error.message);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
let timer;
|
|
137
|
+
const schedule = () => {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
timer = setTimeout(write, 100);
|
|
140
|
+
};
|
|
141
|
+
await write();
|
|
142
|
+
(0, node_fs.watch)(folder, { recursive: true }, schedule);
|
|
143
|
+
(0, node_fs.watch)(configPath, schedule);
|
|
144
|
+
console.log(`Watching ${(0, node_path.relative)(process.cwd(), folder) || folder} for changes.`);
|
|
145
|
+
return new Promise(() => {});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Runs `kizuna-i18n` with its arguments, and returns the exit code.
|
|
149
|
+
*/
|
|
150
|
+
async function main(args) {
|
|
151
|
+
const [command, ...rest] = args;
|
|
152
|
+
if (command !== "generate" && command !== "check") {
|
|
153
|
+
console.log(usage);
|
|
154
|
+
return command === void 0 || command === "--help" ? 0 : 1;
|
|
155
|
+
}
|
|
156
|
+
const configIndex = rest.indexOf("--config");
|
|
157
|
+
const configPath = (0, node_path.resolve)(configIndex === -1 ? "i18n.config.ts" : rest[configIndex + 1] ?? "");
|
|
158
|
+
if (!(0, node_fs.existsSync)(configPath)) {
|
|
159
|
+
console.error(`No config at ${(0, node_path.relative)(process.cwd(), configPath) || configPath}.`);
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
if (command === "check") return await check(configPath);
|
|
164
|
+
if (rest.includes("--watch")) return await generateOnChange(configPath);
|
|
165
|
+
return await generate(configPath, rest.includes("--check"));
|
|
166
|
+
} catch (error) {
|
|
167
|
+
console.error(error.message);
|
|
168
|
+
return 1;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
//#endregion
|
|
172
|
+
//#region src/bin.ts
|
|
173
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
174
|
+
//#endregion
|
package/dist/bin.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/dist/bin.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/dist/bin.mjs
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { i as problemsOf, o as toCatalog, r as formatProblems, t as loadMessages } from "./load-CE9FYddD.mjs";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
5
|
+
import { createJiti } from "jiti";
|
|
6
|
+
//#region src/files.ts
|
|
7
|
+
/**
|
|
8
|
+
* Every file the config's targets generate from the messages.
|
|
9
|
+
*/
|
|
10
|
+
function plannedFiles(source, config, root) {
|
|
11
|
+
const catalog = toCatalog(source);
|
|
12
|
+
const files = [];
|
|
13
|
+
for (const target of config.targets ?? []) {
|
|
14
|
+
const output = resolve(root, target.output);
|
|
15
|
+
const rendered = target.render(catalog);
|
|
16
|
+
if (typeof rendered === "string") files.push({
|
|
17
|
+
path: output,
|
|
18
|
+
contents: rendered
|
|
19
|
+
});
|
|
20
|
+
else files.push(...rendered.map((file) => ({
|
|
21
|
+
path: join(output, file.path),
|
|
22
|
+
contents: file.contents
|
|
23
|
+
})));
|
|
24
|
+
}
|
|
25
|
+
return files;
|
|
26
|
+
}
|
|
27
|
+
const currentContents = (path) => {
|
|
28
|
+
try {
|
|
29
|
+
return readFileSync(path, "utf8");
|
|
30
|
+
} catch {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Writes every file, leaving one alone when it already matches so watchers see no change. Returns
|
|
36
|
+
* the files it wrote.
|
|
37
|
+
*/
|
|
38
|
+
function writeFiles(files) {
|
|
39
|
+
return files.flatMap((file) => {
|
|
40
|
+
if (currentContents(file.path) === file.contents) return [];
|
|
41
|
+
mkdirSync(dirname(file.path), { recursive: true });
|
|
42
|
+
writeFileSync(file.path, file.contents);
|
|
43
|
+
return [file.path];
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Every file that no longer matches, without writing anything.
|
|
48
|
+
*/
|
|
49
|
+
function checkFiles(files) {
|
|
50
|
+
return files.flatMap((file) => {
|
|
51
|
+
const current = currentContents(file.path);
|
|
52
|
+
if (current === void 0) return [{
|
|
53
|
+
path: file.path,
|
|
54
|
+
reason: "missing"
|
|
55
|
+
}];
|
|
56
|
+
if (current !== file.contents) return [{
|
|
57
|
+
path: file.path,
|
|
58
|
+
reason: "outdated"
|
|
59
|
+
}];
|
|
60
|
+
return [];
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* What a failed check prints: the stale files, and the command that fixes them.
|
|
65
|
+
*/
|
|
66
|
+
function formatStale(stale, root) {
|
|
67
|
+
const lines = stale.map((file) => {
|
|
68
|
+
const where = relative(root, file.path);
|
|
69
|
+
return file.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the messages`;
|
|
70
|
+
});
|
|
71
|
+
return [
|
|
72
|
+
stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
|
|
73
|
+
...lines,
|
|
74
|
+
"",
|
|
75
|
+
"Run `kizuna-i18n generate` and commit the result."
|
|
76
|
+
].join("\n");
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/cli.ts
|
|
80
|
+
const usage = `Usage: kizuna-i18n <command> [--config <path>]
|
|
81
|
+
|
|
82
|
+
check Lists every problem in the messages, one line each.
|
|
83
|
+
generate Writes every target's files.
|
|
84
|
+
generate --check Writes nothing, and fails when a generated file is out of date.
|
|
85
|
+
generate --watch Writes again on every change to the messages.
|
|
86
|
+
--config <path> The config file. Default: i18n.config.ts`;
|
|
87
|
+
async function readConfig(configPath) {
|
|
88
|
+
return await createJiti(import.meta.url, {
|
|
89
|
+
interopDefault: true,
|
|
90
|
+
jsx: true,
|
|
91
|
+
tsconfigPaths: true,
|
|
92
|
+
moduleCache: false,
|
|
93
|
+
fsCache: false
|
|
94
|
+
}).import(configPath, { default: true });
|
|
95
|
+
}
|
|
96
|
+
async function check(configPath) {
|
|
97
|
+
const config = await readConfig(configPath);
|
|
98
|
+
const problems = problemsOf(await loadMessages(resolve(dirname(configPath), config.messages)));
|
|
99
|
+
const errors = problems.filter((problem) => problem.severity === "error");
|
|
100
|
+
const notices = problems.length - errors.length;
|
|
101
|
+
if (problems.length === 0) {
|
|
102
|
+
console.log("Every message is complete in every language.");
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
const summary = [errors.length > 0 ? `${errors.length} ${errors.length === 1 ? "error" : "errors"}` : "No errors", notices > 0 ? `${notices} ${notices === 1 ? "shows" : "show"} a fallback` : void 0].filter(Boolean).join(", ");
|
|
106
|
+
(errors.length > 0 ? console.error : console.log)(`${formatProblems(problems)}\n\n${summary}.`);
|
|
107
|
+
return errors.length > 0 ? 1 : 0;
|
|
108
|
+
}
|
|
109
|
+
async function generate(configPath, onlyCheck) {
|
|
110
|
+
const config = await readConfig(configPath);
|
|
111
|
+
const root = dirname(configPath);
|
|
112
|
+
const files = plannedFiles(await loadMessages(resolve(root, config.messages)), config, root);
|
|
113
|
+
if (onlyCheck) {
|
|
114
|
+
const stale = checkFiles(files);
|
|
115
|
+
if (stale.length > 0) {
|
|
116
|
+
console.error(formatStale(stale, root));
|
|
117
|
+
return 1;
|
|
118
|
+
}
|
|
119
|
+
console.log(`${files.length} generated ${files.length === 1 ? "file is" : "files are"} current.`);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
const written = writeFiles(files);
|
|
123
|
+
console.log(written.length === 0 ? "Everything was already current." : written.map((path) => `Wrote ${relative(process.cwd(), path)}`).join("\n"));
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
async function generateOnChange(configPath) {
|
|
127
|
+
const config = await readConfig(configPath);
|
|
128
|
+
const folder = resolve(dirname(configPath), config.messages);
|
|
129
|
+
const write = async () => {
|
|
130
|
+
try {
|
|
131
|
+
await generate(configPath, false);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
console.error(error.message);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
let timer;
|
|
137
|
+
const schedule = () => {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
timer = setTimeout(write, 100);
|
|
140
|
+
};
|
|
141
|
+
await write();
|
|
142
|
+
watch(folder, { recursive: true }, schedule);
|
|
143
|
+
watch(configPath, schedule);
|
|
144
|
+
console.log(`Watching ${relative(process.cwd(), folder) || folder} for changes.`);
|
|
145
|
+
return new Promise(() => {});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Runs `kizuna-i18n` with its arguments, and returns the exit code.
|
|
149
|
+
*/
|
|
150
|
+
async function main(args) {
|
|
151
|
+
const [command, ...rest] = args;
|
|
152
|
+
if (command !== "generate" && command !== "check") {
|
|
153
|
+
console.log(usage);
|
|
154
|
+
return command === void 0 || command === "--help" ? 0 : 1;
|
|
155
|
+
}
|
|
156
|
+
const configIndex = rest.indexOf("--config");
|
|
157
|
+
const configPath = resolve(configIndex === -1 ? "i18n.config.ts" : rest[configIndex + 1] ?? "");
|
|
158
|
+
if (!existsSync(configPath)) {
|
|
159
|
+
console.error(`No config at ${relative(process.cwd(), configPath) || configPath}.`);
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
if (command === "check") return await check(configPath);
|
|
164
|
+
if (rest.includes("--watch")) return await generateOnChange(configPath);
|
|
165
|
+
return await generate(configPath, rest.includes("--check"));
|
|
166
|
+
} catch (error) {
|
|
167
|
+
console.error(error.message);
|
|
168
|
+
return 1;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
//#endregion
|
|
172
|
+
//#region src/bin.ts
|
|
173
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
174
|
+
//#endregion
|
|
175
|
+
export {};
|