@verbaly/studio 0.75.0 → 0.77.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/dist/cli.d.ts +1 -0
- package/dist/cli.js +4 -849
- package/dist/index.d.ts +1 -4
- package/dist/index.js +1 -848
- package/dist/server-B4FzIf6x.js +837 -0
- package/dist/ui/assets/{index-Dlbt2o7i.js → index-BLZUYeP_.js} +2 -2
- package/dist/ui/index.html +1 -1
- package/package.json +10 -6
- package/dist/cli.js.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,850 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
import { createServer } from "node:http";
|
|
7
|
-
import { execFile, spawn } from "node:child_process";
|
|
8
|
-
import { fileURLToPath } from "node:url";
|
|
9
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
10
|
-
//#region src/http.ts
|
|
11
|
-
var HttpError = class extends Error {
|
|
12
|
-
status;
|
|
13
|
-
constructor(status, message) {
|
|
14
|
-
super(message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`);
|
|
15
|
-
this.status = status;
|
|
16
|
-
this.name = "HttpError";
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
const badRequest = (message) => new HttpError(400, message);
|
|
20
|
-
function scrub(message, root) {
|
|
21
|
-
return root ? message.split(root).join(".") : message;
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
24
|
-
//#region src/triage.ts
|
|
25
|
-
const DIGITS = /\d[\d.,]*/g;
|
|
26
|
-
const URLS = /https?:\/\/[^\s<)"']+/g;
|
|
27
|
-
const CODE = /<code>([^<]+)<\/code>/g;
|
|
28
|
-
function bag(text, re, normalize) {
|
|
29
|
-
const found = text.match(re) ?? [];
|
|
30
|
-
return (normalize ? found.map(normalize) : found).sort();
|
|
31
|
-
}
|
|
32
|
-
function same(a, b) {
|
|
33
|
-
return a.length === b.length && a.every((v, i) => v === b[i]);
|
|
34
|
-
}
|
|
35
|
-
const trimPunct = (v) => v.replace(/[.,;:!?)\]]+$/, "");
|
|
36
|
-
const bareDigits = (v) => trimPunct(v).replaceAll(/[.,]/g, ".");
|
|
37
|
-
function push(out, key, reason) {
|
|
38
|
-
(out[key] ??= []).push(reason);
|
|
39
|
-
}
|
|
40
|
-
function clip(text, max = 42) {
|
|
41
|
-
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
42
|
-
}
|
|
43
|
-
const quote = (text, max) => `"${clip(text, max)}"`;
|
|
44
|
-
function lost(from, to) {
|
|
45
|
-
const rest = [...to];
|
|
46
|
-
const out = [];
|
|
47
|
-
for (const item of from) {
|
|
48
|
-
const at = rest.indexOf(item);
|
|
49
|
-
if (at < 0) out.push(item);
|
|
50
|
-
else rest.splice(at, 1);
|
|
51
|
-
}
|
|
52
|
-
return out;
|
|
53
|
-
}
|
|
54
|
-
function movedText(kind, from, to) {
|
|
55
|
-
const gone = lost(from, to);
|
|
56
|
-
const added = lost(to, from);
|
|
57
|
-
if (gone.length && added.length) return `the source ${kind} ${quote(gone[0])}, this one ${kind} ${quote(added[0])}`;
|
|
58
|
-
if (gone.length) return `the source ${kind} ${quote(gone[0])} and this one does not`;
|
|
59
|
-
return `this one ${kind} ${quote(added[0])} and the source does not`;
|
|
60
|
-
}
|
|
61
|
-
function triage({ source, target, reviewed }) {
|
|
62
|
-
const out = Object.create(null);
|
|
63
|
-
const keys = Object.keys(source);
|
|
64
|
-
const bySource = Object.create(null);
|
|
65
|
-
for (const key of keys) {
|
|
66
|
-
const text = source[key]?.trim();
|
|
67
|
-
if (text) (bySource[text] ??= []).push(key);
|
|
68
|
-
}
|
|
69
|
-
for (const [text, group] of Object.entries(bySource)) {
|
|
70
|
-
if (group.length < 2) continue;
|
|
71
|
-
let split;
|
|
72
|
-
for (const { locale, catalog } of reviewed) {
|
|
73
|
-
const seen = [...new Set(group.map((k) => catalog[k]?.trim() ?? "").filter(Boolean))];
|
|
74
|
-
if (seen.length > 1) {
|
|
75
|
-
split = {
|
|
76
|
-
locale,
|
|
77
|
-
first: seen[0],
|
|
78
|
-
second: seen[1]
|
|
79
|
-
};
|
|
80
|
-
break;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
if (split) for (const key of group) push(out, key, {
|
|
84
|
-
signal: "divergent",
|
|
85
|
-
text: `${split.locale} already says this two ways: ${quote(split.first, 32)} and ${quote(split.second, 32)}`
|
|
86
|
-
});
|
|
87
|
-
const targets = new Set(group.map((key) => target[key]?.trim() ?? "").filter(Boolean));
|
|
88
|
-
if (!split && targets.size > 1) for (const key of group) {
|
|
89
|
-
const mine = target[key]?.trim() ?? "";
|
|
90
|
-
const other = group.find((k) => k !== key && (target[k]?.trim() ?? "") !== mine && target[k]?.trim());
|
|
91
|
-
push(out, key, {
|
|
92
|
-
signal: "collision",
|
|
93
|
-
text: other ? `${other} has the same source text and says ${quote(target[other].trim())}` : `${quote(text)} came back as two different translations`
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
for (const key of keys) {
|
|
98
|
-
const src = source[key]?.trim() ?? "";
|
|
99
|
-
const trg = target[key]?.trim() ?? "";
|
|
100
|
-
if (!src || !trg) continue;
|
|
101
|
-
const voters = reviewed.filter(({ catalog }) => {
|
|
102
|
-
const value = catalog[key]?.trim();
|
|
103
|
-
return value !== void 0 && value !== "";
|
|
104
|
-
});
|
|
105
|
-
if (trg === src && voters.length > 0 && voters.every(({ catalog }) => catalog[key]?.trim() !== src)) push(out, key, {
|
|
106
|
-
signal: "echo",
|
|
107
|
-
text: `still the source text, and ${voters.map(({ locale }) => locale).join(" and ")} did translate it`
|
|
108
|
-
});
|
|
109
|
-
const srcDigits = bag(src, DIGITS, bareDigits);
|
|
110
|
-
const trgDigits = bag(trg, DIGITS, bareDigits);
|
|
111
|
-
if (srcDigits.length > 0 && !same(srcDigits, trgDigits)) push(out, key, {
|
|
112
|
-
signal: "digits",
|
|
113
|
-
text: movedText("says", srcDigits, trgDigits)
|
|
114
|
-
});
|
|
115
|
-
const srcUrls = bag(src, URLS, trimPunct);
|
|
116
|
-
const trgUrls = bag(trg, URLS, trimPunct);
|
|
117
|
-
if (!same(srcUrls, trgUrls)) push(out, key, {
|
|
118
|
-
signal: "url",
|
|
119
|
-
text: movedText("links to", srcUrls, trgUrls)
|
|
120
|
-
});
|
|
121
|
-
const srcCode = bag(src, CODE);
|
|
122
|
-
const trgCode = bag(trg, CODE);
|
|
123
|
-
if (!same(srcCode, trgCode)) push(out, key, {
|
|
124
|
-
signal: "code",
|
|
125
|
-
text: movedText("shows the code", srcCode, trgCode)
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
return out;
|
|
129
|
-
}
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region src/api.ts
|
|
132
|
-
function readAll(cfg) {
|
|
133
|
-
const catalogs = {};
|
|
134
|
-
const problems = [];
|
|
135
|
-
if (!existsSync(cfg.dir)) {
|
|
136
|
-
const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
|
|
137
|
-
problems.push({
|
|
138
|
-
scope: dir,
|
|
139
|
-
message: "[verbaly] no catalogs here, run npx verbaly init or check --root"
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
for (const locale of cfg.locales) try {
|
|
143
|
-
catalogs[locale] = readCatalog(cfg, locale);
|
|
144
|
-
} catch (error) {
|
|
145
|
-
catalogs[locale] = {};
|
|
146
|
-
problems.push({
|
|
147
|
-
scope: locale,
|
|
148
|
-
message: error instanceof Error ? error.message : String(error)
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
return {
|
|
152
|
-
catalogs,
|
|
153
|
-
problems
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
function relativize(cfg, result) {
|
|
157
|
-
const rel = (file) => relative(cfg.root, file).replaceAll("\\", "/");
|
|
158
|
-
return {
|
|
159
|
-
...result,
|
|
160
|
-
unknown: result.unknown.map((entry) => ({
|
|
161
|
-
...entry,
|
|
162
|
-
files: entry.files.map(rel)
|
|
163
|
-
})),
|
|
164
|
-
extra: result.extra.map((entry) => ({
|
|
165
|
-
...entry,
|
|
166
|
-
files: entry.files.map(rel)
|
|
167
|
-
})),
|
|
168
|
-
collisions: result.collisions.map((entry) => ({
|
|
169
|
-
...entry,
|
|
170
|
-
sites: entry.sites.map((at) => ({
|
|
171
|
-
...at,
|
|
172
|
-
file: rel(at.file)
|
|
173
|
-
}))
|
|
174
|
-
})),
|
|
175
|
-
divergent: result.divergent.map((entry) => ({
|
|
176
|
-
...entry,
|
|
177
|
-
code: {
|
|
178
|
-
...entry.code,
|
|
179
|
-
file: rel(entry.code.file)
|
|
180
|
-
}
|
|
181
|
-
}))
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
async function buildState(cfg) {
|
|
185
|
-
const { catalogs, problems } = readAll(cfg);
|
|
186
|
-
const registry = await extractProject(cfg);
|
|
187
|
-
const { state: sidecar, problem } = readState(cfg);
|
|
188
|
-
if (problem) problems.push({
|
|
189
|
-
scope: STATE_FILE,
|
|
190
|
-
message: problem
|
|
191
|
-
});
|
|
192
|
-
const live = effectiveDrafts(sidecar.drafts, catalogs);
|
|
193
|
-
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
194
|
-
const targets = targetLocales(cfg);
|
|
195
|
-
for (const { file, message } of registry.parseErrors()) problems.push({
|
|
196
|
-
scope: relative(cfg.root, file).replaceAll("\\", "/"),
|
|
197
|
-
message
|
|
198
|
-
});
|
|
199
|
-
const perLocale = {};
|
|
200
|
-
for (const locale of targets) perLocale[locale] = triage({
|
|
201
|
-
source,
|
|
202
|
-
target: catalogs[locale] ?? {},
|
|
203
|
-
reviewed: targets.filter((other) => other !== locale && !(live[other] ?? []).length).map((other) => ({
|
|
204
|
-
locale: other,
|
|
205
|
-
catalog: catalogs[other] ?? {}
|
|
206
|
-
}))
|
|
207
|
-
});
|
|
208
|
-
return {
|
|
209
|
-
root: cfg.root,
|
|
210
|
-
dir: cfg.dir,
|
|
211
|
-
sourceLocale: cfg.sourceLocale,
|
|
212
|
-
locales: cfg.locales,
|
|
213
|
-
scanning: cfg.include.length > 0,
|
|
214
|
-
catalogs,
|
|
215
|
-
origins: await collectOrigins(cfg, registry),
|
|
216
|
-
status: status(cfg, catalogs, registry, live, sidecar.fingerprints),
|
|
217
|
-
check: relativize(cfg, check(cfg, catalogs, registry, sidecar.fingerprints)),
|
|
218
|
-
drafts: live,
|
|
219
|
-
triage: perLocale,
|
|
220
|
-
problems
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
function health(cfg) {
|
|
224
|
-
return doctor(cfg);
|
|
225
|
-
}
|
|
226
|
-
async function writeMessage(cfg, locale, key, text) {
|
|
227
|
-
if (locale === cfg.sourceLocale) throw badRequest("the source text lives in your code, Studio never edits it");
|
|
228
|
-
if (!cfg.locales.includes(locale)) throw badRequest(`${locale} is not one of this project's locales`);
|
|
229
|
-
const before = loadState(cfg);
|
|
230
|
-
const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
|
|
231
|
-
const registry = await extractProject(cfg);
|
|
232
|
-
const source = shippedCatalogs(cfg, catalogs, registry, { newKeys: false })[cfg.sourceLocale];
|
|
233
|
-
if (!Object.hasOwn(source, key)) throw badRequest(`"${key}" is not in the source catalog, so Studio will not create it`);
|
|
234
|
-
const value = text.trim() ? text : "";
|
|
235
|
-
const errors = (value ? [...validateMessage(value, locale), ...validatePair(source[key], value)] : []).filter((issue) => issue.severity === "error");
|
|
236
|
-
if (errors.length) throw badRequest(`${errors.map((issue) => issue.message).join("; ")}`);
|
|
237
|
-
const catalog = {
|
|
238
|
-
...readCatalog(cfg, locale),
|
|
239
|
-
[key]: value
|
|
240
|
-
};
|
|
241
|
-
writeCatalog(cfg, locale, catalog);
|
|
242
|
-
const clearedDraft = (before.drafts[locale] ?? []).includes(key);
|
|
243
|
-
recordTranslations(cfg, source, [{
|
|
244
|
-
locale,
|
|
245
|
-
entries: [{
|
|
246
|
-
key,
|
|
247
|
-
text: value
|
|
248
|
-
}],
|
|
249
|
-
draft: false
|
|
250
|
-
}]);
|
|
251
|
-
return {
|
|
252
|
-
locale,
|
|
253
|
-
key,
|
|
254
|
-
clearedDraft
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
function approve(cfg, locale, keys) {
|
|
258
|
-
if (!cfg.locales.includes(locale)) throw badRequest(`${locale} is not one of this project's locales`);
|
|
259
|
-
const drafts = loadDrafts(cfg);
|
|
260
|
-
const had = drafts[locale] ?? [];
|
|
261
|
-
const cleared = keys ? had.filter((key) => keys.includes(key)) : [...had];
|
|
262
|
-
clearDrafts(drafts, locale, keys);
|
|
263
|
-
saveDrafts(cfg, drafts);
|
|
264
|
-
return {
|
|
265
|
-
locale,
|
|
266
|
-
approved: cleared.length,
|
|
267
|
-
keys: cleared
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
function unapprove(cfg, locale, keys) {
|
|
271
|
-
if (!cfg.locales.includes(locale)) throw badRequest(`${locale} is not one of this project's locales`);
|
|
272
|
-
const drafts = loadDrafts(cfg);
|
|
273
|
-
markDrafts(drafts, locale, keys);
|
|
274
|
-
saveDrafts(cfg, drafts);
|
|
275
|
-
return {
|
|
276
|
-
locale,
|
|
277
|
-
approved: keys.length,
|
|
278
|
-
keys
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
//#endregion
|
|
282
|
-
//#region src/jobs.ts
|
|
283
|
-
let current = null;
|
|
284
|
-
let counter = 0;
|
|
285
|
-
function running() {
|
|
286
|
-
return current?.state === "running" ? current : null;
|
|
287
|
-
}
|
|
288
|
-
function read(id) {
|
|
289
|
-
if (!current || current.id !== id) throw new HttpError(404, `no job called "${id}"`);
|
|
290
|
-
return current;
|
|
291
|
-
}
|
|
292
|
-
function start(kind, total) {
|
|
293
|
-
if (running()) throw badRequest("a job is already running, wait for it or read its progress");
|
|
294
|
-
counter += 1;
|
|
295
|
-
current = {
|
|
296
|
-
id: `${kind}-${counter}`,
|
|
297
|
-
kind,
|
|
298
|
-
state: "running",
|
|
299
|
-
total,
|
|
300
|
-
done: 0
|
|
301
|
-
};
|
|
302
|
-
return current;
|
|
303
|
-
}
|
|
304
|
-
function advance(id, keys, locale, error) {
|
|
305
|
-
if (current?.id !== id) return;
|
|
306
|
-
current.done = Math.min(current.done + keys, current.total);
|
|
307
|
-
current.locale = locale;
|
|
308
|
-
if (error) current.message = error;
|
|
309
|
-
}
|
|
310
|
-
function finish(id, state, patch = {}) {
|
|
311
|
-
if (current?.id === id) Object.assign(current, patch, { state });
|
|
312
|
-
}
|
|
313
|
-
//#endregion
|
|
314
|
-
//#region src/actions.ts
|
|
315
|
-
async function runExtract(cfg) {
|
|
316
|
-
if (!cfg.include.length) throw badRequest("source scanning is off (include: []), so there is nothing to extract");
|
|
317
|
-
const result = await syncProject(cfg);
|
|
318
|
-
return {
|
|
319
|
-
added: result.added,
|
|
320
|
-
found: result.added[cfg.sourceLocale]?.length ?? 0,
|
|
321
|
-
replaced: result.replaced.length,
|
|
322
|
-
messages: result.registry.messages().size,
|
|
323
|
-
...result.stateProblem && { stateProblem: result.stateProblem }
|
|
324
|
-
};
|
|
325
|
-
}
|
|
326
|
-
async function planTranslate(cfg, locales) {
|
|
327
|
-
const provider = await resolveProvider(cfg);
|
|
328
|
-
const catalogs = loadCatalogs(cfg);
|
|
329
|
-
const result = await translateCatalogs(cfg, catalogs, provider, {
|
|
330
|
-
locales,
|
|
331
|
-
dryRun: true
|
|
332
|
-
});
|
|
333
|
-
const total = Object.values(result.pending).reduce((n, keys) => n + keys.length, 0);
|
|
334
|
-
return {
|
|
335
|
-
pending: result.pending,
|
|
336
|
-
total
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
async function startTranslate(cfg, locales) {
|
|
340
|
-
loadState(cfg);
|
|
341
|
-
const provider = await resolveProvider(cfg);
|
|
342
|
-
const job = start("translate", (await planTranslate(cfg, locales)).total);
|
|
343
|
-
const id = job.id;
|
|
344
|
-
(async () => {
|
|
345
|
-
try {
|
|
346
|
-
const registry = await extractProject(cfg);
|
|
347
|
-
const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
|
|
348
|
-
const result = await translateCatalogs(cfg, catalogs, provider, {
|
|
349
|
-
locales,
|
|
350
|
-
batchSize: cfg.translate.batchSize,
|
|
351
|
-
concurrency: cfg.translate.concurrency,
|
|
352
|
-
retries: cfg.translate.retries,
|
|
353
|
-
origins: await collectOrigins(cfg, registry),
|
|
354
|
-
onProgress: (p) => advance(id, p.keys, p.locale, p.error)
|
|
355
|
-
});
|
|
356
|
-
const writes = [];
|
|
357
|
-
let written = 0;
|
|
358
|
-
let kept = 0;
|
|
359
|
-
for (const [locale, keys] of Object.entries(result.translated)) {
|
|
360
|
-
const catalog = catalogs[locale] ?? {};
|
|
361
|
-
const landed = mergeTranslations(cfg, locale, catalog, keys);
|
|
362
|
-
writes.push({
|
|
363
|
-
locale,
|
|
364
|
-
draft: true,
|
|
365
|
-
entries: landed.map((key) => ({
|
|
366
|
-
key,
|
|
367
|
-
text: catalog[key]
|
|
368
|
-
}))
|
|
369
|
-
});
|
|
370
|
-
written += landed.length;
|
|
371
|
-
kept += keys.length - landed.length;
|
|
372
|
-
}
|
|
373
|
-
recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
|
|
374
|
-
const failed = result.failed[0];
|
|
375
|
-
finish(id, failed ? "failed" : "done", {
|
|
376
|
-
result,
|
|
377
|
-
written,
|
|
378
|
-
kept,
|
|
379
|
-
message: failed ? `${counted(written, "message")} translated, but ${counted(result.failed.length, "batch", "batches")} did not answer (${failed.error}): run it again for the rest` : void 0
|
|
380
|
-
});
|
|
381
|
-
} catch (error) {
|
|
382
|
-
finish(id, "failed", { message: error instanceof Error ? error.message : String(error) });
|
|
383
|
-
}
|
|
384
|
-
})();
|
|
385
|
-
return job;
|
|
386
|
-
}
|
|
387
|
-
//#endregion
|
|
388
|
-
//#region src/history.ts
|
|
389
|
-
const run = promisify(execFile);
|
|
390
|
-
const FIELD = "";
|
|
391
|
-
const FORMAT = `--format=%H${FIELD}%an${FIELD}%aI${FIELD}%s`;
|
|
392
|
-
function parseFullLog(stdout) {
|
|
393
|
-
const commits = [];
|
|
394
|
-
for (const line of stdout.split("\n")) {
|
|
395
|
-
const [sha, author, date, ...rest] = line.split(FIELD);
|
|
396
|
-
if (!sha || !author || !date || !rest.length) continue;
|
|
397
|
-
commits.push({
|
|
398
|
-
sha,
|
|
399
|
-
author,
|
|
400
|
-
date,
|
|
401
|
-
subject: rest.join(FIELD)
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
return commits;
|
|
405
|
-
}
|
|
406
|
-
function parseLog(stdout) {
|
|
407
|
-
return parseFullLog(stdout).map((commit) => ({
|
|
408
|
-
...commit,
|
|
409
|
-
sha: commit.sha.slice(0, 7)
|
|
410
|
-
}));
|
|
411
|
-
}
|
|
412
|
-
async function catalogHistory(cfg, limit = 5) {
|
|
413
|
-
const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/") || ".";
|
|
414
|
-
try {
|
|
415
|
-
const { stdout } = await run("git", [
|
|
416
|
-
"log",
|
|
417
|
-
`-n${limit}`,
|
|
418
|
-
FORMAT,
|
|
419
|
-
"--",
|
|
420
|
-
dir
|
|
421
|
-
], {
|
|
422
|
-
cwd: cfg.root,
|
|
423
|
-
timeout: 3e3,
|
|
424
|
-
windowsHide: true
|
|
425
|
-
});
|
|
426
|
-
return parseLog(stdout);
|
|
427
|
-
} catch {
|
|
428
|
-
return [];
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
function attribute(revisions, owners = /* @__PURE__ */ new Map()) {
|
|
432
|
-
for (const { commit, now, before } of revisions) {
|
|
433
|
-
if (!now || !before) continue;
|
|
434
|
-
for (const key of /* @__PURE__ */ new Set([...Object.keys(now), ...Object.keys(before)])) if (!owners.has(key) && now[key] !== before[key]) owners.set(key, commit);
|
|
435
|
-
}
|
|
436
|
-
return owners;
|
|
437
|
-
}
|
|
438
|
-
function mergeOwners(maps) {
|
|
439
|
-
const merged = /* @__PURE__ */ new Map();
|
|
440
|
-
for (const map of maps) for (const [key, commit] of map) {
|
|
441
|
-
const held = merged.get(key);
|
|
442
|
-
if (!held || Date.parse(commit.date) > Date.parse(held.date)) merged.set(key, commit);
|
|
443
|
-
}
|
|
444
|
-
return merged;
|
|
445
|
-
}
|
|
446
|
-
const BLOB = /^[0-9a-f]{40} \w+ (\d+)$/;
|
|
447
|
-
function readBlobs(root, requests, take) {
|
|
448
|
-
return new Promise((resolve) => {
|
|
449
|
-
const child = spawn("git", ["cat-file", "--batch"], {
|
|
450
|
-
cwd: root,
|
|
451
|
-
windowsHide: true
|
|
452
|
-
});
|
|
453
|
-
const stop = setTimeout(() => {
|
|
454
|
-
ok = false;
|
|
455
|
-
child.kill();
|
|
456
|
-
}, 2e4);
|
|
457
|
-
let pending = Buffer.alloc(0);
|
|
458
|
-
let index = 0;
|
|
459
|
-
let ok = true;
|
|
460
|
-
const fail = () => {
|
|
461
|
-
ok = false;
|
|
462
|
-
};
|
|
463
|
-
child.on("error", fail);
|
|
464
|
-
child.stdin.on("error", fail);
|
|
465
|
-
child.stdout.on("data", (chunk) => {
|
|
466
|
-
pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
467
|
-
for (;;) {
|
|
468
|
-
const end = pending.indexOf(10);
|
|
469
|
-
if (end < 0) break;
|
|
470
|
-
const header = pending.toString("utf8", 0, end);
|
|
471
|
-
const blob = BLOB.exec(header);
|
|
472
|
-
if (!blob) {
|
|
473
|
-
take(index++, null, "");
|
|
474
|
-
pending = pending.subarray(end + 1);
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
const size = Number(blob[1]);
|
|
478
|
-
if (pending.length < end + size + 2) break;
|
|
479
|
-
take(index++, pending.toString("utf8", end + 1, end + 1 + size), header.slice(0, 40));
|
|
480
|
-
pending = pending.subarray(end + size + 2);
|
|
481
|
-
}
|
|
482
|
-
});
|
|
483
|
-
child.on("close", () => {
|
|
484
|
-
clearTimeout(stop);
|
|
485
|
-
resolve(ok);
|
|
486
|
-
});
|
|
487
|
-
child.stdin.end(requests.join("\n") + "\n");
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
const WINDOW = 200;
|
|
491
|
-
async function walkFile(root, file, limit) {
|
|
492
|
-
const { stdout } = await run("git", [
|
|
493
|
-
"log",
|
|
494
|
-
`-n${limit}`,
|
|
495
|
-
FORMAT,
|
|
496
|
-
"--",
|
|
497
|
-
file
|
|
498
|
-
], {
|
|
499
|
-
cwd: root,
|
|
500
|
-
timeout: 5e3,
|
|
501
|
-
windowsHide: true,
|
|
502
|
-
maxBuffer: 8e6
|
|
503
|
-
});
|
|
504
|
-
const commits = parseFullLog(stdout);
|
|
505
|
-
if (!commits.length) return {
|
|
506
|
-
owners: /* @__PURE__ */ new Map(),
|
|
507
|
-
head: []
|
|
508
|
-
};
|
|
509
|
-
const owners = /* @__PURE__ */ new Map();
|
|
510
|
-
let head = [];
|
|
511
|
-
let waiting;
|
|
512
|
-
let last = null;
|
|
513
|
-
const parse = (body, blob) => {
|
|
514
|
-
if (body === null) return {};
|
|
515
|
-
if (last && last.blob === blob) return last.flat;
|
|
516
|
-
const flat = parseCatalog(body);
|
|
517
|
-
last = {
|
|
518
|
-
blob,
|
|
519
|
-
flat
|
|
520
|
-
};
|
|
521
|
-
return flat;
|
|
522
|
-
};
|
|
523
|
-
if (!await readBlobs(root, commits.flatMap((commit) => [`${commit.sha}:${file}`, `${commit.sha}^:${file}`]), (index, body, blob) => {
|
|
524
|
-
const flat = parse(body, blob);
|
|
525
|
-
if (index % 2 === 0) {
|
|
526
|
-
waiting = flat;
|
|
527
|
-
if (index === 0 && flat) head = Object.keys(flat);
|
|
528
|
-
return;
|
|
529
|
-
}
|
|
530
|
-
const commit = commits[(index - 1) / 2];
|
|
531
|
-
if (commit) attribute([{
|
|
532
|
-
commit,
|
|
533
|
-
now: waiting,
|
|
534
|
-
before: flat
|
|
535
|
-
}], owners);
|
|
536
|
-
waiting = void 0;
|
|
537
|
-
})) throw new Error("[verbaly] git could not read every revision of this catalog");
|
|
538
|
-
return {
|
|
539
|
-
owners,
|
|
540
|
-
head
|
|
541
|
-
};
|
|
542
|
-
}
|
|
543
|
-
async function catalogKeyHistory(cfg, limit = WINDOW) {
|
|
544
|
-
const maps = [];
|
|
545
|
-
const committed = /* @__PURE__ */ new Set();
|
|
546
|
-
let ok = false;
|
|
547
|
-
for (const locale of cfg.locales) {
|
|
548
|
-
const file = relative(cfg.root, join(cfg.dir, `${locale}.json`)).replaceAll("\\", "/");
|
|
549
|
-
try {
|
|
550
|
-
const walked = await walkFile(cfg.root, file, limit);
|
|
551
|
-
maps.push(walked.owners);
|
|
552
|
-
for (const key of walked.head) committed.add(key);
|
|
553
|
-
ok = true;
|
|
554
|
-
} catch {}
|
|
555
|
-
}
|
|
556
|
-
return {
|
|
557
|
-
owners: mergeOwners(maps),
|
|
558
|
-
committed,
|
|
559
|
-
ok
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
const walked = /* @__PURE__ */ new Map();
|
|
563
|
-
async function headSha(root) {
|
|
564
|
-
try {
|
|
565
|
-
const { stdout } = await run("git", ["rev-parse", "HEAD"], {
|
|
566
|
-
cwd: root,
|
|
567
|
-
timeout: 3e3,
|
|
568
|
-
windowsHide: true
|
|
569
|
-
});
|
|
570
|
-
return stdout.trim();
|
|
571
|
-
} catch {
|
|
572
|
-
return "";
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
async function keyHistory(cfg) {
|
|
576
|
-
const head = await headSha(cfg.root);
|
|
577
|
-
const held = walked.get(cfg.root);
|
|
578
|
-
if (held && held.head === head) return held.history;
|
|
579
|
-
const history = await catalogKeyHistory(cfg);
|
|
580
|
-
walked.set(cfg.root, {
|
|
581
|
-
head,
|
|
582
|
-
history
|
|
583
|
-
});
|
|
584
|
-
return history;
|
|
585
|
-
}
|
|
586
|
-
async function keyCommit(cfg, key) {
|
|
587
|
-
const history = await keyHistory(cfg);
|
|
588
|
-
if (!history.ok) return {
|
|
589
|
-
key,
|
|
590
|
-
commit: null,
|
|
591
|
-
reason: "nogit"
|
|
592
|
-
};
|
|
593
|
-
const commit = history.owners.get(key);
|
|
594
|
-
if (commit) return {
|
|
595
|
-
key,
|
|
596
|
-
commit: {
|
|
597
|
-
...commit,
|
|
598
|
-
sha: commit.sha.slice(0, 7)
|
|
599
|
-
}
|
|
600
|
-
};
|
|
601
|
-
return {
|
|
602
|
-
key,
|
|
603
|
-
commit: null,
|
|
604
|
-
reason: history.committed.has(key) ? "older" : "uncommitted"
|
|
605
|
-
};
|
|
606
|
-
}
|
|
607
|
-
//#endregion
|
|
608
|
-
//#region src/assets.ts
|
|
609
|
-
const UI = resolve(fileURLToPath(new URL(".", import.meta.url)), "ui");
|
|
610
|
-
const TYPES = {
|
|
611
|
-
".html": "text/html; charset=utf-8",
|
|
612
|
-
".js": "text/javascript; charset=utf-8",
|
|
613
|
-
".css": "text/css; charset=utf-8",
|
|
614
|
-
".svg": "image/svg+xml",
|
|
615
|
-
".woff2": "font/woff2",
|
|
616
|
-
".json": "application/json; charset=utf-8",
|
|
617
|
-
".ico": "image/x-icon"
|
|
618
|
-
};
|
|
619
|
-
const uiBuilt = () => existsSync(join(UI, "index.html"));
|
|
620
|
-
function readAsset(pathname) {
|
|
621
|
-
const target = resolve(join(UI, normalize(pathname === "/" ? "/index.html" : pathname)));
|
|
622
|
-
if (target !== UI && !target.startsWith(UI + (process.platform === "win32" ? "\\" : "/"))) return;
|
|
623
|
-
if (!existsSync(target) || !statSync(target).isFile()) return void 0;
|
|
624
|
-
const dot = target.lastIndexOf(".");
|
|
625
|
-
return {
|
|
626
|
-
body: readFileSync(target),
|
|
627
|
-
type: TYPES[target.slice(dot).toLowerCase()] ?? "application/octet-stream"
|
|
628
|
-
};
|
|
629
|
-
}
|
|
630
|
-
//#endregion
|
|
631
|
-
//#region src/guard.ts
|
|
632
|
-
function newToken() {
|
|
633
|
-
return randomBytes(9).toString("base64url");
|
|
634
|
-
}
|
|
635
|
-
function hostAllowed(host, port) {
|
|
636
|
-
const names = port === 80 ? ["127.0.0.1", "localhost"] : [];
|
|
637
|
-
return [
|
|
638
|
-
`127.0.0.1:${port}`,
|
|
639
|
-
`localhost:${port}`,
|
|
640
|
-
...names
|
|
641
|
-
].includes(host ?? "");
|
|
642
|
-
}
|
|
643
|
-
function originAllowed(origin, port) {
|
|
644
|
-
if (origin === void 0) return true;
|
|
645
|
-
return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;
|
|
646
|
-
}
|
|
647
|
-
function tokenMatches(given, expected) {
|
|
648
|
-
if (given === null) return false;
|
|
649
|
-
const a = Buffer.from(given);
|
|
650
|
-
const b = Buffer.from(expected);
|
|
651
|
-
return a.length === b.length && timingSafeEqual(a, b);
|
|
652
|
-
}
|
|
653
|
-
const PASS = {
|
|
654
|
-
ok: true,
|
|
655
|
-
status: 200,
|
|
656
|
-
reason: ""
|
|
657
|
-
};
|
|
658
|
-
function guardRequest(headers, url, { port, token }) {
|
|
659
|
-
if (!hostAllowed(headers.host, port)) return {
|
|
660
|
-
ok: false,
|
|
661
|
-
status: 403,
|
|
662
|
-
reason: "[verbaly] unexpected Host header"
|
|
663
|
-
};
|
|
664
|
-
if (!originAllowed(headers.origin, port)) return {
|
|
665
|
-
ok: false,
|
|
666
|
-
status: 403,
|
|
667
|
-
reason: "[verbaly] cross-origin request"
|
|
668
|
-
};
|
|
669
|
-
if (!tokenMatches(url.searchParams.get("t"), token)) return {
|
|
670
|
-
ok: false,
|
|
671
|
-
status: 401,
|
|
672
|
-
reason: "[verbaly] missing or wrong token, open the printed url"
|
|
673
|
-
};
|
|
674
|
-
return PASS;
|
|
675
|
-
}
|
|
676
|
-
//#endregion
|
|
677
|
-
//#region src/server.ts
|
|
678
|
-
const DEFAULT_PORT = 4747;
|
|
679
|
-
const MAX_BODY = 1e6;
|
|
680
|
-
function send(res, status, body) {
|
|
681
|
-
res.writeHead(status, {
|
|
682
|
-
"content-type": "application/json; charset=utf-8",
|
|
683
|
-
"cache-control": "no-store"
|
|
684
|
-
});
|
|
685
|
-
res.end(JSON.stringify(body));
|
|
686
|
-
}
|
|
687
|
-
async function readJson(req) {
|
|
688
|
-
const chunks = [];
|
|
689
|
-
let size = 0;
|
|
690
|
-
for await (const chunk of req) {
|
|
691
|
-
size += chunk.length;
|
|
692
|
-
if (size > MAX_BODY) throw new HttpError(413, "request body too large");
|
|
693
|
-
chunks.push(chunk);
|
|
694
|
-
}
|
|
695
|
-
if (!chunks.length) return {};
|
|
696
|
-
let parsed;
|
|
697
|
-
try {
|
|
698
|
-
parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
699
|
-
} catch {
|
|
700
|
-
throw badRequest("body is not valid JSON");
|
|
701
|
-
}
|
|
702
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw badRequest("body must be a JSON object");
|
|
703
|
-
return parsed;
|
|
704
|
-
}
|
|
705
|
-
function segment(raw, what) {
|
|
706
|
-
let value;
|
|
707
|
-
try {
|
|
708
|
-
value = decodeURIComponent(raw ?? "");
|
|
709
|
-
} catch {
|
|
710
|
-
throw badRequest(`the ${what} in the url is not valid percent-encoding`);
|
|
711
|
-
}
|
|
712
|
-
if (!value) throw badRequest(`the url is missing a ${what}`);
|
|
713
|
-
return value;
|
|
714
|
-
}
|
|
715
|
-
function createStudioApp(cfg, port, token) {
|
|
716
|
-
return async function handle(req, res) {
|
|
717
|
-
try {
|
|
718
|
-
let url;
|
|
719
|
-
try {
|
|
720
|
-
url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
|
|
721
|
-
} catch {
|
|
722
|
-
throw badRequest("the request target is not a valid url");
|
|
723
|
-
}
|
|
724
|
-
const api = url.pathname.startsWith("/api/");
|
|
725
|
-
const verdict = guardRequest({
|
|
726
|
-
host: req.headers.host,
|
|
727
|
-
origin: req.headers.origin
|
|
728
|
-
}, url, {
|
|
729
|
-
port,
|
|
730
|
-
token
|
|
731
|
-
});
|
|
732
|
-
if (!verdict.ok && (api || verdict.status !== 401)) {
|
|
733
|
-
send(res, verdict.status, { error: verdict.reason });
|
|
734
|
-
return;
|
|
735
|
-
}
|
|
736
|
-
if (!api && req.method === "GET") {
|
|
737
|
-
const asset = readAsset(url.pathname);
|
|
738
|
-
if (asset) {
|
|
739
|
-
res.writeHead(200, {
|
|
740
|
-
"content-type": asset.type,
|
|
741
|
-
"cache-control": "no-store"
|
|
742
|
-
});
|
|
743
|
-
res.end(asset.body);
|
|
744
|
-
return;
|
|
745
|
-
}
|
|
746
|
-
if (url.pathname === "/" && !uiBuilt()) throw new HttpError(500, "the panel is not in this install, so only /api/* answers here");
|
|
747
|
-
}
|
|
748
|
-
if (req.method === "GET" && url.pathname === "/api/state") {
|
|
749
|
-
send(res, 200, await buildState(cfg));
|
|
750
|
-
return;
|
|
751
|
-
}
|
|
752
|
-
if (req.method === "GET" && url.pathname === "/api/history") {
|
|
753
|
-
send(res, 200, { commits: await catalogHistory(cfg) });
|
|
754
|
-
return;
|
|
755
|
-
}
|
|
756
|
-
if (req.method === "GET" && url.pathname.startsWith("/api/commit/")) {
|
|
757
|
-
send(res, 200, await keyCommit(cfg, segment(url.pathname.slice(12), "key")));
|
|
758
|
-
return;
|
|
759
|
-
}
|
|
760
|
-
if (req.method === "GET" && url.pathname === "/api/health") {
|
|
761
|
-
send(res, 200, await health(cfg));
|
|
762
|
-
return;
|
|
763
|
-
}
|
|
764
|
-
if (req.method === "PUT" && url.pathname.startsWith("/api/message/")) {
|
|
765
|
-
const rest = url.pathname.slice(13).split("/");
|
|
766
|
-
const locale = segment(rest[0], "locale");
|
|
767
|
-
const key = segment(rest.slice(1).join("/"), "key");
|
|
768
|
-
const body = await readJson(req);
|
|
769
|
-
if (typeof body.text !== "string") throw badRequest("body needs a \"text\" string");
|
|
770
|
-
send(res, 200, await writeMessage(cfg, locale, key, body.text));
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
if (req.method === "POST" && url.pathname === "/api/approve") {
|
|
774
|
-
const body = await readJson(req);
|
|
775
|
-
if (typeof body.locale !== "string") throw badRequest("body needs a \"locale\" string");
|
|
776
|
-
const keys = Array.isArray(body.keys) ? body.keys.filter((k) => typeof k === "string") : void 0;
|
|
777
|
-
if (body.undo === true) {
|
|
778
|
-
if (!keys?.length) throw badRequest("undoing needs the \"keys\" it should put back");
|
|
779
|
-
send(res, 200, unapprove(cfg, body.locale, keys));
|
|
780
|
-
return;
|
|
781
|
-
}
|
|
782
|
-
send(res, 200, approve(cfg, body.locale, keys));
|
|
783
|
-
return;
|
|
784
|
-
}
|
|
785
|
-
if (req.method === "POST" && url.pathname === "/api/extract") {
|
|
786
|
-
send(res, 200, await runExtract(cfg));
|
|
787
|
-
return;
|
|
788
|
-
}
|
|
789
|
-
if (req.method === "GET" && url.pathname === "/api/translate") {
|
|
790
|
-
const locales = url.searchParams.getAll("locale");
|
|
791
|
-
send(res, 200, await planTranslate(cfg, locales.length ? locales : void 0));
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
if (req.method === "POST" && url.pathname === "/api/translate") {
|
|
795
|
-
const body = await readJson(req);
|
|
796
|
-
const locales = Array.isArray(body.locales) ? body.locales.filter((l) => typeof l === "string") : void 0;
|
|
797
|
-
send(res, 200, await startTranslate(cfg, locales?.length ? locales : void 0));
|
|
798
|
-
return;
|
|
799
|
-
}
|
|
800
|
-
if (req.method === "GET" && url.pathname === "/api/job") {
|
|
801
|
-
send(res, 200, running());
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
if (req.method === "GET" && url.pathname.startsWith("/api/job/")) {
|
|
805
|
-
send(res, 200, read(segment(url.pathname.slice(9), "job id")));
|
|
806
|
-
return;
|
|
807
|
-
}
|
|
808
|
-
send(res, 404, { error: `[verbaly] no route for ${req.method} ${url.pathname}` });
|
|
809
|
-
} catch (error) {
|
|
810
|
-
send(res, error instanceof HttpError ? error.status : 500, { error: scrub(error instanceof Error ? error.message : String(error), cfg.root) });
|
|
811
|
-
}
|
|
812
|
-
};
|
|
813
|
-
}
|
|
814
|
-
function listen(server, port, attemptsLeft) {
|
|
815
|
-
return new Promise((resolve, reject) => {
|
|
816
|
-
const onError = (error) => {
|
|
817
|
-
if (error.code === "EADDRINUSE" && attemptsLeft > 0) {
|
|
818
|
-
server.removeListener("error", onError);
|
|
819
|
-
resolve(listen(server, port + 1, attemptsLeft - 1));
|
|
820
|
-
return;
|
|
821
|
-
}
|
|
822
|
-
reject(error);
|
|
823
|
-
};
|
|
824
|
-
server.once("error", onError);
|
|
825
|
-
server.listen(port, "127.0.0.1", () => {
|
|
826
|
-
server.removeListener("error", onError);
|
|
827
|
-
const bound = server.address();
|
|
828
|
-
resolve(typeof bound === "object" && bound !== null ? bound.port : port);
|
|
829
|
-
});
|
|
830
|
-
});
|
|
831
|
-
}
|
|
832
|
-
async function startStudio(cfg, options = {}) {
|
|
833
|
-
const token = options.token ?? newToken();
|
|
834
|
-
const server = createServer();
|
|
835
|
-
let port = options.port ?? DEFAULT_PORT;
|
|
836
|
-
server.on("request", (req, res) => void createStudioApp(cfg, port, token)(req, res));
|
|
837
|
-
port = await listen(server, port, 20);
|
|
838
|
-
return {
|
|
839
|
-
server,
|
|
840
|
-
port,
|
|
841
|
-
token,
|
|
842
|
-
url: `http://127.0.0.1:${port}/?t=${token}`,
|
|
843
|
-
close: () => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
|
|
844
|
-
};
|
|
845
|
-
}
|
|
846
|
-
//#endregion
|
|
847
|
-
//#region src/cli.ts
|
|
2
|
+
import { n as startStudio, r as buildState } from "./server-B4FzIf6x.js";
|
|
3
|
+
import { counted, formatCliError, loadConfig } from "@verbaly/compiler";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
// src/cli.ts
|
|
848
6
|
try {
|
|
849
7
|
const { values } = parseArgs({ options: {
|
|
850
8
|
root: { type: "string" },
|
|
@@ -870,7 +28,4 @@ try {
|
|
|
870
28
|
console.error(formatCliError(error));
|
|
871
29
|
process.exitCode = 1;
|
|
872
30
|
}
|
|
873
|
-
//#endregion
|
|
874
31
|
export {};
|
|
875
|
-
|
|
876
|
-
//# sourceMappingURL=cli.js.map
|