@verbaly/compiler 0.67.0 → 0.69.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.js CHANGED
@@ -1,14 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import { basename, dirname, join, relative, resolve } from "node:path";
2
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
- import { pathToFileURL } from "node:url";
7
- import { createHash } from "node:crypto";
8
6
  import { glob } from "tinyglobby";
9
7
  import { parse as parse$1 } from "@babel/parser";
10
- import MagicString from "magic-string";
8
+ import { createHash } from "node:crypto";
9
+ import { pathToFileURL } from "node:url";
10
+ import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
11
11
  import picomatch from "picomatch";
12
+ import MagicString from "magic-string";
13
+ //#region src/eol.ts
14
+ function withLineEndings(text, existing) {
15
+ const first = existing?.indexOf("\n") ?? -1;
16
+ return first > 0 && existing[first - 1] === "\r" ? text.replace(/\r?\n/g, "\r\n") : text;
17
+ }
18
+ //#endregion
12
19
  //#region src/catalog.ts
13
20
  function emptyCatalog() {
14
21
  return Object.create(null);
@@ -128,7 +135,7 @@ function writeCatalog(cfg, locale, catalog) {
128
135
  }
129
136
  const parsed = existing === void 0 ? void 0 : parseTree(existing);
130
137
  const previous = isTree(parsed) ? parsed : void 0;
131
- const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous);
138
+ const serialized = withLineEndings(serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous), existing);
132
139
  if (existing === serialized) return serialized;
133
140
  writeFileSync(path, serialized);
134
141
  return serialized;
@@ -139,594 +146,838 @@ function wantsNesting(cfg, locale, existing, previous) {
139
146
  return isNested(readTree(cfg, cfg.sourceLocale));
140
147
  }
141
148
  //#endregion
142
- //#region src/pseudo.ts
143
- const PSEUDO_LOCALE = "en-XA";
144
- const ACCENTS = {
145
- a: "á",
146
- b: "ƀ",
147
- c: "ç",
148
- d: "đ",
149
- e: "é",
150
- f: "ƒ",
151
- g: "ğ",
152
- h: "ĥ",
153
- i: "í",
154
- j: "ĵ",
155
- k: "ķ",
156
- l: "ĺ",
157
- m: "ɱ",
158
- n: "ñ",
159
- o: "ó",
160
- p: "þ",
161
- q: "ǫ",
162
- r: "ŕ",
163
- s: "š",
164
- t: "ţ",
165
- u: "ú",
166
- v: "ṽ",
167
- w: "ŵ",
168
- x: "ẋ",
169
- y: "ý",
170
- z: "ž",
171
- A: "Á",
172
- B: "Ɓ",
173
- C: "Ç",
174
- D: "Đ",
175
- E: "É",
176
- F: "Ƒ",
177
- G: "Ğ",
178
- H: "Ĥ",
179
- I: "Í",
180
- J: "Ĵ",
181
- K: "Ķ",
182
- L: "Ĺ",
183
- M: "Ḿ",
184
- N: "Ñ",
185
- O: "Ó",
186
- P: "Þ",
187
- Q: "Ǫ",
188
- R: "Ŕ",
189
- S: "Š",
190
- T: "Ţ",
191
- U: "Ú",
192
- V: "Ṽ",
193
- W: "Ŵ",
194
- X: "Ẍ",
195
- Y: "Ý",
196
- Z: "Ž"
197
- };
198
- const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
199
- function pseudoLocalize(message) {
200
- let out = "";
201
- let letters = 0;
202
- let i = 0;
203
- while (i < message.length) {
204
- const two = message.slice(i, i + 2);
205
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
206
- out += two;
207
- i += 2;
208
- continue;
209
- }
210
- const ch = message[i];
211
- if (ch === "{") {
212
- const end = matchBrace$1(message, i);
213
- out += message.slice(i, end);
214
- i = end;
215
- continue;
216
- }
217
- if (ch === "<") {
218
- TAG_AT.lastIndex = i;
219
- const m = TAG_AT.exec(message);
220
- if (m) {
221
- out += m[0];
222
- i += m[0].length;
223
- continue;
224
- }
149
+ //#region src/registry.ts
150
+ var MessageRegistry = class {
151
+ files = /* @__PURE__ */ new Map();
152
+ update(file, analysis) {
153
+ this.files.set(file, analysis);
154
+ }
155
+ remove(file) {
156
+ this.files.delete(file);
157
+ }
158
+ messages() {
159
+ const out = /* @__PURE__ */ new Map();
160
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
161
+ const held = out.get(msg.key);
162
+ if (!held || earlier(msg, held)) out.set(msg.key, msg);
225
163
  }
226
- const mapped = ACCENTS[ch];
227
- if (mapped) {
228
- out += mapped;
229
- letters += 1;
230
- } else out += ch;
231
- i += 1;
164
+ return out;
232
165
  }
233
- const pad = "~".repeat(Math.ceil(letters / 3));
234
- return `⟦${out}${pad ? " " + pad : ""}⟧`;
235
- }
236
- function matchBrace$1(message, start) {
237
- let depth = 0;
238
- for (let i = start; i < message.length; i++) {
239
- const two = message.slice(i, i + 2);
240
- if (two === "{{" || two === "}}") {
241
- i += 1;
242
- continue;
166
+ collisions() {
167
+ const winners = this.messages();
168
+ const dropped = /* @__PURE__ */ new Map();
169
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
170
+ if (msg.message === winners.get(msg.key).message) continue;
171
+ dropped.set(msg.key, [...dropped.get(msg.key) ?? [], msg]);
243
172
  }
244
- const ch = message[i];
245
- if (ch === "{") depth += 1;
246
- else if (ch === "}") {
247
- depth -= 1;
248
- if (depth === 0) return i + 1;
173
+ return [...dropped].map(([key, others]) => ({
174
+ key,
175
+ kept: winners.get(key),
176
+ dropped: others.sort((a, b) => earlier(a, b) ? -1 : 1)
177
+ }));
178
+ }
179
+ usedKeys(strict = false) {
180
+ const out = /* @__PURE__ */ new Map();
181
+ for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
182
+ if (strict && used.loose) continue;
183
+ const files = out.get(used.key) ?? [];
184
+ if (!files.includes(used.file)) files.push(used.file);
185
+ out.set(used.key, files);
249
186
  }
187
+ return out;
250
188
  }
251
- return message.length;
252
- }
253
- function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
254
- const source = catalogs[cfg.sourceLocale] ?? {};
255
- const target = emptyCatalog();
256
- for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
257
- catalogs[locale] = target;
258
- return Object.keys(target).filter((key) => target[key]);
259
- }
260
- //#endregion
261
- //#region src/config.ts
262
- function resolveConfig(config = {}) {
263
- const root = resolve(config.root ?? process.cwd());
264
- const dir = resolve(root, config.dir ?? "locales");
265
- const sourceLocale = config.sourceLocale ?? "en";
266
- const localesDeclared = config.locales !== void 0;
267
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
268
- if (!localesDeclared && existsSync(dir)) {
269
- for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
189
+ strayImports() {
190
+ return this.inOrder().flatMap((analysis) => analysis.strayImports);
270
191
  }
271
- return {
272
- root,
273
- dir,
274
- sourceLocale,
275
- localesDeclared,
276
- routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
277
- icu: config.icu,
278
- relative: config.relative,
279
- locales: [...locales],
280
- include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
281
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
282
- dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
283
- translate: config.translate ?? {},
284
- render: config.render ?? {},
285
- bundle: config.bundle ?? {}
286
- };
287
- }
288
- const CONFIG_FILES = [
289
- "verbaly.config.js",
290
- "verbaly.config.mjs",
291
- "verbaly.config.ts",
292
- "verbaly.config.mts",
293
- "verbaly.config.json"
294
- ];
295
- function findConfigFile(root) {
296
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
297
- }
298
- async function loadConfigFile(root) {
299
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
300
- const path = join(root, name);
301
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
192
+ missed() {
193
+ return this.inOrder().flatMap((analysis) => analysis.missed);
302
194
  }
303
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
304
- const path = join(root, name);
305
- if (existsSync(path)) return loadTsConfig(path);
195
+ parseErrors() {
196
+ const out = [];
197
+ for (const file of [...this.files.keys()].sort()) {
198
+ const { parseError } = this.files.get(file);
199
+ if (parseError) out.push({
200
+ file,
201
+ message: parseError
202
+ });
203
+ }
204
+ return out;
306
205
  }
307
- const jsonPath = join(root, "verbaly.config.json");
308
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
309
- return {};
310
- }
311
- function readJsonConfig(path) {
312
- const content = readFileSync(path, "utf8");
313
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
314
- try {
315
- return JSON.parse(body);
316
- } catch (error) {
317
- throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
206
+ origins() {
207
+ const out = this.usedKeys();
208
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
209
+ const files = out.get(msg.key) ?? [];
210
+ if (!files.includes(msg.file)) files.push(msg.file);
211
+ out.set(msg.key, files);
212
+ }
213
+ return out;
318
214
  }
319
- }
320
- async function loadTsConfig(path) {
321
- try {
322
- const { bundleRequire } = await import("bundle-require");
323
- const { mod } = await bundleRequire({ filepath: path });
324
- return mod.default ?? {};
325
- } catch (error) {
326
- if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
327
- throw error;
215
+ inOrder() {
216
+ return [...this.files.keys()].sort().map((file) => this.files.get(file));
328
217
  }
329
- }
330
- function isModuleNotFound(error, name) {
331
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
332
- }
333
- function targetLocales(cfg, override) {
334
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
335
- }
336
- async function loadConfig(root, overrides = {}) {
337
- return resolveConfig({
338
- ...await loadConfigFile(root),
339
- ...definedOnly(overrides),
340
- root
341
- });
342
- }
343
- function definedOnly(config) {
344
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
218
+ };
219
+ function earlier(a, b) {
220
+ return a.file === b.file ? a.start < b.start : a.file < b.file;
345
221
  }
346
222
  //#endregion
347
- //#region src/tag.ts
348
- function isLocaleTag(tag) {
349
- try {
350
- Intl.getCanonicalLocales(tag);
351
- return true;
352
- } catch {
353
- return false;
354
- }
223
+ //#region src/key.ts
224
+ function stableKey(message) {
225
+ return createHash("sha256").update(message).digest("base64url").slice(0, 8);
355
226
  }
356
- function suggestTag(tag) {
357
- const near = tag.replace(/_/g, "-");
358
- return near !== tag && isLocaleTag(near) ? near : void 0;
227
+ //#endregion
228
+ //#region src/analyze.ts
229
+ function parseErrorMessage(error) {
230
+ return error instanceof Error ? error.message : String(error);
359
231
  }
360
- function projectLocale(tag, locales) {
361
- if (locales.includes(tag)) return tag;
362
- const plain = (value) => value.replace(/_/g, "-").toLowerCase();
363
- return locales.find((locale) => plain(locale) === plain(tag));
232
+ const SKIP_KEYS = /* @__PURE__ */ new Set([
233
+ "loc",
234
+ "leadingComments",
235
+ "trailingComments",
236
+ "innerComments",
237
+ "extra"
238
+ ]);
239
+ const DEFAULT_T_NAMES = ["t"];
240
+ const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
241
+ const DEFINE_KEYS = "defineKeys";
242
+ function analyze(code, file, options = {}) {
243
+ return analyzeScript(code, file, options).analysis;
364
244
  }
365
- //#endregion
366
- //#region src/init.ts
367
- const HOSTS = [
368
- {
369
- name: "nuxt",
370
- dep: "nuxt",
371
- pkg: "@verbaly/nuxt",
372
- wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
373
- },
374
- {
375
- name: "next",
376
- dep: "next",
377
- pkg: "@verbaly/next",
378
- wire: "wrap the export of next.config with withVerbaly"
379
- },
380
- {
381
- name: "sveltekit",
382
- dep: "@sveltejs/kit",
383
- pkg: "@verbaly/vite",
384
- wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
385
- },
386
- {
387
- name: "astro",
388
- dep: "astro",
389
- pkg: "@verbaly/astro",
390
- wire: "add verbaly() to the integrations in astro.config"
391
- },
392
- {
393
- name: "vite",
394
- dep: "vite",
395
- pkg: "@verbaly/vite",
396
- wire: "add verbaly() to the plugins in vite.config"
397
- },
398
- {
399
- name: "webpack",
400
- dep: "webpack",
401
- pkg: "@verbaly/unplugin",
402
- wire: "add the verbaly webpack plugin to your build config"
403
- },
404
- {
405
- name: "rspack",
406
- dep: "@rspack/core",
407
- pkg: "@verbaly/unplugin",
408
- wire: "add the verbaly rspack plugin to your build config"
409
- },
410
- {
411
- name: "rollup",
412
- dep: "rollup",
413
- pkg: "@verbaly/unplugin",
414
- wire: "add the verbaly rollup plugin to your build config"
415
- },
416
- {
417
- name: "esbuild",
418
- dep: "esbuild",
419
- pkg: "@verbaly/unplugin",
420
- wire: "add the verbaly esbuild plugin to your build config"
245
+ function analyzeScript(code, file, options = {}) {
246
+ const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
247
+ const ast = parse$1(code, {
248
+ sourceType: "module",
249
+ errorRecovery: true,
250
+ plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
251
+ });
252
+ const tagged = [];
253
+ const usedKeys = [];
254
+ const strayImports = [];
255
+ const bindings = new Bindings(names);
256
+ const candidates = [];
257
+ walk$1(ast.program, (node) => {
258
+ if (node.type === "ImportDeclaration") {
259
+ collectStrayImports(node, file, strayImports);
260
+ bindings.addImport(node);
261
+ } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
262
+ else if (node.type === "TaggedTemplateExpression") {
263
+ const tag = node.tag;
264
+ const explicit = explicitId(tag, names);
265
+ if (!explicit && !isTReference(tag, names)) {
266
+ candidates.push({
267
+ kind: "tag",
268
+ node
269
+ });
270
+ return;
271
+ }
272
+ const quasi = node.quasi;
273
+ const message = buildMessage(code, quasi, names);
274
+ if (!message) return;
275
+ tagged.push({
276
+ key: explicit ? explicit.key : stableKey(message.text),
277
+ message: message.text,
278
+ params: message.params,
279
+ start: node.start,
280
+ end: node.end,
281
+ line: lineOf(node),
282
+ tagStart: explicit ? explicit.refStart : tag.start,
283
+ tagEnd: explicit ? explicit.refEnd : tag.end,
284
+ file
285
+ });
286
+ } else if (node.type === "CallExpression") {
287
+ const callee = node.callee;
288
+ const args = node.arguments;
289
+ if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
290
+ collectDeclaredKeys(args[0], file, usedKeys);
291
+ return;
292
+ }
293
+ if (!isTReference(callee, names)) {
294
+ const key = callee.type === "Identifier" ? staticString(args[0]) : void 0;
295
+ if (key !== void 0) candidates.push({
296
+ kind: "call",
297
+ name: callee.name,
298
+ key
299
+ });
300
+ return;
301
+ }
302
+ const key = staticString(args[0]);
303
+ if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
304
+ } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
305
+ });
306
+ const renamed = bindings.renamed(options.renamed);
307
+ const missed = [];
308
+ for (const candidate of candidates) {
309
+ if (candidate.kind === "call") {
310
+ if (renamed.has(candidate.name)) usedKeys.push({
311
+ key: candidate.key,
312
+ file,
313
+ loose: true
314
+ });
315
+ continue;
316
+ }
317
+ const { node } = candidate;
318
+ const name = renamedTag(node.tag, renamed);
319
+ if (!name) continue;
320
+ missed.push({
321
+ name,
322
+ file,
323
+ start: node.start,
324
+ line: lineOf(node)
325
+ });
326
+ const key = missedKey(code, node, names);
327
+ if (key !== void 0) usedKeys.push({
328
+ key,
329
+ file,
330
+ loose: true
331
+ });
421
332
  }
422
- ];
423
- const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
424
- function readDependencies(root) {
425
- const path = join(root, "package.json");
426
- if (!existsSync(path)) return {};
427
- try {
428
- const pkg = JSON.parse(readFileSync(path, "utf8"));
333
+ return {
334
+ analysis: {
335
+ tagged,
336
+ usedKeys,
337
+ strayImports,
338
+ missed
339
+ },
340
+ renamed: [...renamed]
341
+ };
342
+ }
343
+ function lineOf(node) {
344
+ return node.loc?.start.line ?? 1;
345
+ }
346
+ const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
347
+ const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
348
+ const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
349
+ var Bindings = class {
350
+ names;
351
+ imports = /* @__PURE__ */ new Map();
352
+ direct = /* @__PURE__ */ new Set();
353
+ declared = [];
354
+ destructured = [];
355
+ constructor(names) {
356
+ this.names = names;
357
+ }
358
+ addImport(node) {
359
+ const source = node.source.value;
360
+ if (typeof source !== "string") return;
361
+ for (const spec of node.specifiers) {
362
+ const local = identifierName(spec.local);
363
+ if (!local) continue;
364
+ const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
365
+ this.imports.set(local, {
366
+ source,
367
+ imported
368
+ });
369
+ if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
370
+ }
371
+ }
372
+ addDeclarator(node) {
373
+ const id = node.id;
374
+ const init = node.init;
375
+ if (!init) return;
376
+ if (id.type === "Identifier") {
377
+ this.declared.push({
378
+ name: id.name,
379
+ init
380
+ });
381
+ return;
382
+ }
383
+ if (id.type !== "ObjectPattern") return;
384
+ for (const property of id.properties) {
385
+ if (property.type !== "ObjectProperty" || property.computed) continue;
386
+ if (identifierName(property.key) !== "t") continue;
387
+ const value = property.value;
388
+ const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
389
+ if (name) this.destructured.push({
390
+ name,
391
+ init
392
+ });
393
+ }
394
+ }
395
+ renamed(seed = []) {
396
+ const out = new Set(seed);
397
+ const add = (name) => {
398
+ if (this.names.has(name)) return;
399
+ out.add(name);
400
+ if (this.names.has("$t")) out.add(`$${name}`);
401
+ };
402
+ for (const name of this.direct) add(name);
403
+ for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
404
+ for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
405
+ return out;
406
+ }
407
+ handsOutT(init) {
408
+ const awaited = init.type === "AwaitExpression";
409
+ const call = awaited ? init.argument : init;
410
+ if (call.type !== "CallExpression") return false;
411
+ const origin = this.origin(identifierName(call.callee));
412
+ if (origin.verbaly === false) return false;
413
+ const how = T_FACTORIES.get(origin.imported);
414
+ return how !== void 0 && how === "await" === awaited;
415
+ }
416
+ carriesT(init) {
417
+ const inner = init.type === "AwaitExpression" ? init.argument : init;
418
+ const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
419
+ if (!name) return false;
420
+ return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
421
+ }
422
+ origin(local) {
423
+ const found = this.imports.get(local);
424
+ if (!found) return {
425
+ verbaly: void 0,
426
+ imported: local
427
+ };
429
428
  return {
430
- ...pkg.dependencies,
431
- ...pkg.devDependencies
429
+ verbaly: VERBALY_SOURCE.test(found.source),
430
+ imported: found.imported
432
431
  };
433
- } catch {
434
- return {};
435
432
  }
433
+ };
434
+ function importedName(node) {
435
+ return node.type === "StringLiteral" ? node.value : identifierName(node);
436
436
  }
437
- function cliReachable(root) {
438
- const bin = join(root, "node_modules", ".bin");
439
- return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
437
+ function identifierName(node) {
438
+ return node?.type === "Identifier" ? node.name : "";
440
439
  }
441
- const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
442
- function detectHost(root) {
443
- const deps = readDependencies(root);
444
- return HOSTS.find((host) => deps[host.dep]);
440
+ function renamedTag(tag, renamed) {
441
+ if (renamed.size === 0) return void 0;
442
+ const name = identifierName(tag);
443
+ if (renamed.has(name)) return name;
444
+ if (tag.type !== "CallExpression") return void 0;
445
+ const callee = tag.callee;
446
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
447
+ if (identifierName(callee.property) !== "id") return void 0;
448
+ const object = identifierName(callee.object);
449
+ return renamed.has(object) ? object : void 0;
445
450
  }
446
- function configSource(options, typescript) {
447
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
448
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
449
- if (options.dir) fields.push(` dir: '${options.dir}',`);
450
- const body = `export default {\n${fields.join("\n")}\n}`;
451
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
452
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
451
+ function missedKey(code, node, names) {
452
+ const tag = node.tag;
453
+ if (tag.type === "CallExpression") {
454
+ const args = tag.arguments;
455
+ const first = args[0];
456
+ return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
457
+ }
458
+ const message = buildMessage(code, node.quasi, names);
459
+ return message ? stableKey(message.text) : void 0;
453
460
  }
454
- async function init(input = {}) {
455
- const root = input.root ?? process.cwd();
456
- const created = [];
457
- const skipped = [];
458
- const renamed = [];
459
- const refused = [];
460
- const typed = input.locales?.flatMap((locale) => {
461
- if (isLocaleTag(locale)) return [locale];
462
- const near = suggestTag(locale);
463
- if (near) renamed.push({
464
- from: locale,
465
- to: near
461
+ function collectDeclaredKeys(node, file, out) {
462
+ if (node?.type !== "ObjectExpression") return;
463
+ for (const property of node.properties) {
464
+ if (property.type !== "ObjectProperty") continue;
465
+ const value = property.value;
466
+ const key = staticString(value);
467
+ if (key !== void 0) {
468
+ if (key !== "") out.push(usedKey(key, file, value));
469
+ } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
470
+ }
471
+ }
472
+ function usedKey(key, file, node) {
473
+ return node?.type === "StringLiteral" ? {
474
+ key,
475
+ file
476
+ } : {
477
+ key,
478
+ file,
479
+ loose: true
480
+ };
481
+ }
482
+ function staticString(node) {
483
+ if (!node) return void 0;
484
+ if (node.type === "StringLiteral") return node.value;
485
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
486
+ if (node.type === "JSXExpressionContainer") return staticString(node.expression);
487
+ }
488
+ const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
489
+ function collectStrayImports(node, file, out) {
490
+ const source = node.source;
491
+ if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
492
+ for (const spec of node.specifiers) {
493
+ if (spec.type !== "ImportSpecifier") continue;
494
+ const imported = spec.imported;
495
+ if (imported.type !== "Identifier") continue;
496
+ const name = imported.name;
497
+ if (name === "t" || name === DEFINE_KEYS) out.push({
498
+ name,
499
+ source: source.value,
500
+ file
466
501
  });
467
- else refused.push(locale);
468
- return near ? [near] : [];
502
+ }
503
+ }
504
+ function handleTrans(code, node, file, tagged, usedKeys, names) {
505
+ const opening = node.openingElement;
506
+ const nameNode = opening.name;
507
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
508
+ const attrs = opening.attributes;
509
+ const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
510
+ const children = node.children;
511
+ const push = (key, built) => tagged.push({
512
+ key,
513
+ message: built.text,
514
+ params: built.params,
515
+ start: node.start,
516
+ end: node.end,
517
+ line: lineOf(node),
518
+ tagStart: nameNode.start,
519
+ tagEnd: nameNode.end,
520
+ file,
521
+ jsx: {
522
+ name: nameNode.name,
523
+ components: built.components
524
+ }
469
525
  });
470
- const locales = typed && [...new Set(typed)];
471
- let sourceLocale = input.sourceLocale;
472
- if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
473
- const near = suggestTag(sourceLocale);
474
- if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
475
- renamed.push({
476
- from: sourceLocale,
477
- to: near
478
- });
479
- sourceLocale = near;
526
+ if (idAttr) {
527
+ const value = idAttr.value;
528
+ const id = staticString(value);
529
+ if (id === void 0) return;
530
+ if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
531
+ const built = buildTransMessage(code, children, names);
532
+ if (built?.text.trim()) {
533
+ push(id, built);
534
+ return;
535
+ }
536
+ }
537
+ usedKeys.push(usedKey(id, file, value));
538
+ return;
480
539
  }
481
- const options = {
482
- ...input,
483
- locales,
484
- sourceLocale
540
+ if (attrs.length > 0) return;
541
+ if (!children?.length) return;
542
+ const built = buildTransMessage(code, children, names);
543
+ if (!built || !built.text.trim()) return;
544
+ push(stableKey(built.text), built);
545
+ }
546
+ function explicitId(tag, names) {
547
+ if (tag.type !== "CallExpression") return void 0;
548
+ const callee = tag.callee;
549
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
550
+ const prop = callee.property;
551
+ if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
552
+ const obj = callee.object;
553
+ if (!isTReference(obj, names)) return void 0;
554
+ const args = tag.arguments;
555
+ const first = args[0];
556
+ if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
557
+ return {
558
+ key: first.value,
559
+ refStart: obj.start,
560
+ refEnd: obj.end
485
561
  };
486
- const existing = findConfigFile(root);
487
- const typescript = existsSync(join(root, "tsconfig.json"));
488
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
489
- if (existing) skipped.push(existing);
490
- else {
491
- writeFileSync(join(root, configFile), configSource(options, typescript));
492
- created.push(configFile);
562
+ }
563
+ function buildTransMessage(code, children, names) {
564
+ const params = [];
565
+ const components = [];
566
+ const takenParams = /* @__PURE__ */ new Map();
567
+ const takenTags = /* @__PURE__ */ new Map();
568
+ function walkChildren(nodes) {
569
+ let text = "";
570
+ for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
571
+ else if (child.type === "JSXExpressionContainer") {
572
+ const expr = child.expression;
573
+ if (expr.type === "JSXEmptyExpression") continue;
574
+ if (expr.type === "StringLiteral") {
575
+ text += escapeText(expr.value);
576
+ continue;
577
+ }
578
+ if (containsTaggedT(expr, names)) return void 0;
579
+ const source = code.slice(expr.start, expr.end);
580
+ const name = uniqueName(deriveName(expr, params.length), source, takenParams);
581
+ params.push({
582
+ name,
583
+ start: expr.start,
584
+ end: expr.end
585
+ });
586
+ text += `{${name}}`;
587
+ } else if (child.type === "JSXElement") {
588
+ const opening = child.openingElement;
589
+ const nameNode = opening.name;
590
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
591
+ const source = selfClosedSource(code, opening);
592
+ const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
593
+ if (!components.some((c) => c.name === tag)) components.push({
594
+ name: tag,
595
+ source
596
+ });
597
+ if (!child.closingElement) text += `<${tag}/>`;
598
+ else {
599
+ const inner = walkChildren(child.children);
600
+ if (inner === void 0) return void 0;
601
+ text += `<${tag}>${inner}</${tag}>`;
602
+ }
603
+ } else return;
604
+ return text;
493
605
  }
494
- const fromFile = existing ? await loadConfigFile(root) : {};
495
- const scaffold = {
496
- dir: options.dir ?? fromFile.dir,
497
- sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
498
- locales: options.locales ?? fromFile.locales
606
+ const text = walkChildren(children);
607
+ if (text === void 0) return void 0;
608
+ return {
609
+ text,
610
+ params,
611
+ components
499
612
  };
500
- const dir = join(root, scaffold.dir ?? "locales");
501
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
502
- for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
503
- const file = join(dir, `${locale}.json`);
504
- const label = relative(root, file).replaceAll("\\", "/");
505
- if (existsSync(file)) skipped.push(label);
506
- else {
507
- writeFileSync(file, "{}\n");
508
- created.push(label);
509
- }
613
+ }
614
+ function cleanJsxText(raw) {
615
+ const lines = raw.split(/\r\n|[\r\n]/);
616
+ let out = "";
617
+ for (let i = 0; i < lines.length; i++) {
618
+ let line = lines[i].replace(/\t/g, " ");
619
+ if (i !== 0) line = line.replace(/^ +/, "");
620
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
621
+ if (!line) continue;
622
+ if (out && i !== 0) out += " ";
623
+ out += line;
624
+ }
625
+ return out;
626
+ }
627
+ function selfClosedSource(code, opening) {
628
+ const src = code.slice(opening.start, opening.end);
629
+ return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
630
+ }
631
+ function containsTaggedT(node, names) {
632
+ let found = false;
633
+ walk$1(node, (n) => {
634
+ if (n.type !== "TaggedTemplateExpression") return;
635
+ const tag = n.tag;
636
+ if (isTReference(tag, names) || explicitId(tag, names)) found = true;
637
+ });
638
+ return found;
639
+ }
640
+ function isTReference(node, names) {
641
+ if (node.type === "Identifier") return names.has(node.name);
642
+ if (node.type === "MemberExpression" && !node.computed) {
643
+ const prop = node.property;
644
+ return prop.type === "Identifier" && names.has(prop.name);
645
+ }
646
+ return false;
647
+ }
648
+ function buildMessage(code, quasi, names) {
649
+ const quasis = quasi.quasis;
650
+ const expressions = quasi.expressions;
651
+ const params = [];
652
+ const taken = /* @__PURE__ */ new Map();
653
+ let text = escapeText(cookedValue(quasis[0]));
654
+ for (let i = 0; i < expressions.length; i++) {
655
+ const expr = expressions[i];
656
+ if (!expr) return void 0;
657
+ if (containsTaggedT(expr, names)) return void 0;
658
+ const source = code.slice(expr.start, expr.end);
659
+ const name = uniqueName(deriveName(expr, i), source, taken);
660
+ params.push({
661
+ name,
662
+ start: expr.start,
663
+ end: expr.end
664
+ });
665
+ text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
510
666
  }
511
- const host = detectHost(root);
512
- const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
513
667
  return {
514
- created,
515
- skipped,
516
- host: host?.name,
517
- configFile,
518
- next,
519
- renamed,
520
- refused
668
+ text,
669
+ params
521
670
  };
522
671
  }
523
- //#endregion
524
- //#region src/location.ts
525
- function lineAt(content, offset) {
526
- let line = 1;
527
- const end = Math.min(offset, content.length);
528
- for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
529
- return line;
530
- }
531
- function createLocator() {
532
- const contents = /* @__PURE__ */ new Map();
533
- return (file, offset) => {
534
- if (!contents.has(file)) try {
535
- contents.set(file, readFileSync(file, "utf8"));
536
- } catch {
537
- contents.set(file, void 0);
538
- }
539
- const content = contents.get(file);
540
- return content === void 0 ? void 0 : lineAt(content, offset);
541
- };
672
+ function cookedValue(element) {
673
+ if (!element) return "";
674
+ const value = element.value;
675
+ return value.cooked ?? value.raw;
542
676
  }
543
- //#endregion
544
- //#region src/key.ts
545
- function stableKey(message) {
546
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
677
+ function escapeText(text) {
678
+ return text.replace(/[{}]/g, (m) => m + m);
547
679
  }
548
- //#endregion
549
- //#region src/state.ts
550
- const STATE_FILE = ".verbaly-state.json";
551
- const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
552
- function statePath(cfg, file = STATE_FILE) {
553
- return join(cfg.dir, file);
680
+ function deriveName(expr, index) {
681
+ if (expr.type === "Identifier") return expr.name;
682
+ if (expr.type === "MemberExpression" && !expr.computed) {
683
+ const prop = expr.property;
684
+ if (prop.type === "Identifier") return prop.name;
685
+ }
686
+ return `_${index}`;
554
687
  }
555
- function loadState(cfg) {
556
- const current = readJson(statePath(cfg));
557
- if (current !== void 0) {
558
- if (!isObject(current)) throw corrupt(statePath(cfg));
688
+ function uniqueName(base, source, taken) {
689
+ let name = base;
690
+ let n = 2;
691
+ while (taken.has(name) && taken.get(name) !== source) {
692
+ name = `${base}${n}`;
693
+ n += 1;
694
+ }
695
+ taken.set(name, source);
696
+ return name;
697
+ }
698
+ function walk$1(node, visit) {
699
+ visit(node);
700
+ for (const key in node) {
701
+ if (SKIP_KEYS.has(key)) continue;
702
+ const value = node[key];
703
+ if (Array.isArray(value)) {
704
+ for (const item of value) if (isNode(item)) walk$1(item, visit);
705
+ } else if (isNode(value)) walk$1(value, visit);
706
+ }
707
+ }
708
+ function isNode(value) {
709
+ return typeof value === "object" && value !== null && typeof value.type === "string";
710
+ }
711
+ //#endregion
712
+ //#region src/sfc.ts
713
+ const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
714
+ function analyzeFile(code, file) {
715
+ if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
716
+ try {
717
+ return analyze(code, file);
718
+ } catch (error) {
559
719
  return {
560
- drafts: readDrafts(current.drafts),
561
- fingerprints: readFingerprints(current.fingerprints)
720
+ tagged: [],
721
+ usedKeys: [],
722
+ strayImports: [],
723
+ missed: [],
724
+ parseError: parseErrorMessage(error)
562
725
  };
563
726
  }
564
- const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
565
- if (legacy === void 0) return {
566
- drafts: {},
567
- fingerprints: {}
727
+ }
728
+ const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
729
+ const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
730
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
731
+ const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
732
+ const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
733
+ const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
734
+ function analyzeSfc(code, file) {
735
+ const svelte = file.endsWith(".svelte");
736
+ const tNames = svelte ? ["t", "$t"] : ["t"];
737
+ const tagged = [];
738
+ const usedKeys = [];
739
+ const strayImports = [];
740
+ const missed = [];
741
+ const renamed = /* @__PURE__ */ new Set();
742
+ const lineAt = lineCounter(code);
743
+ let parseError;
744
+ const block = (content, offset) => {
745
+ const segment = analyzeSegment(content, file, { tNames });
746
+ parseError ??= segment.error;
747
+ for (const name of segment.renamed) renamed.add(name);
748
+ merge(segment.analysis, offset, false);
568
749
  };
569
- if (!isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
570
- return {
571
- drafts: readDrafts(legacy),
572
- fingerprints: {}
750
+ const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
751
+ if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
752
+ for (const match of code.matchAll(SCRIPT_RE)) {
753
+ const content = match[2];
754
+ if (content) block(content, match.index + match[1].length);
755
+ }
756
+ const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
757
+ const markupOptions = {
758
+ tNames,
759
+ renamed: [...renamed]
573
760
  };
574
- }
575
- function saveState(cfg, state) {
576
- const serialized = serializeState(state);
577
- const path = statePath(cfg);
578
- const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
579
- if (serialized === void 0) {
580
- rmSync(path, { force: true });
581
- rmSync(legacy, { force: true });
582
- return;
761
+ const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
762
+ let range = 0;
763
+ let consumedTo = 0;
764
+ for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
765
+ const start = match.index;
766
+ if (start < consumedTo) continue;
767
+ while (range < ranges.length && ranges[range][1] <= start) range += 1;
768
+ if (range >= ranges.length || start < ranges[range][0]) continue;
769
+ const end = expressionExtent(markup, start, match[0].length);
770
+ if (end === void 0) continue;
771
+ merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
772
+ consumedTo = end;
583
773
  }
584
- let existing;
585
- try {
586
- existing = readFileSync(path, "utf8");
587
- } catch {
588
- mkdirSync(cfg.dir, { recursive: true });
774
+ return {
775
+ tagged,
776
+ usedKeys,
777
+ strayImports,
778
+ missed,
779
+ ...parseError && { parseError }
780
+ };
781
+ function merge(analysis, offset, markupSegment) {
782
+ if (!analysis) return;
783
+ const lines = lineAt(offset) - 1;
784
+ for (const msg of analysis.tagged) tagged.push({
785
+ ...msg,
786
+ start: msg.start + offset,
787
+ end: msg.end + offset,
788
+ line: msg.line + lines,
789
+ tagStart: msg.tagStart + offset,
790
+ tagEnd: msg.tagEnd + offset,
791
+ params: msg.params.map((p) => ({
792
+ ...p,
793
+ start: p.start + offset,
794
+ end: p.end + offset
795
+ })),
796
+ ...markupSegment && { singleQuote: true }
797
+ });
798
+ for (const call of analysis.missed) missed.push({
799
+ ...call,
800
+ start: call.start + offset,
801
+ line: call.line + lines
802
+ });
803
+ usedKeys.push(...analysis.usedKeys);
804
+ strayImports.push(...analysis.strayImports);
589
805
  }
590
- if (existing !== serialized) writeFileSync(path, serialized);
591
- if (existsSync(legacy)) rmSync(legacy);
592
806
  }
593
- function updateState(cfg, catalogs) {
594
- const state = loadState(cfg);
595
- const next = {
596
- drafts: effectiveDrafts(state.drafts, catalogs),
597
- fingerprints: refreshFingerprints(cfg, catalogs, state.fingerprints)
807
+ function candidatePattern(svelte, renamed) {
808
+ const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
809
+ return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
810
+ }
811
+ function lineCounter(code) {
812
+ const breaks = [];
813
+ for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
814
+ return (offset) => {
815
+ let low = 0;
816
+ let high = breaks.length;
817
+ while (low < high) {
818
+ const mid = low + high >> 1;
819
+ if (breaks[mid] < offset) low = mid + 1;
820
+ else high = mid;
821
+ }
822
+ return low + 1;
598
823
  };
599
- saveState(cfg, next);
600
- return next;
601
824
  }
602
- function effectiveDrafts(drafts, catalogs) {
603
- const out = {};
604
- for (const [locale, keys] of Object.entries(drafts)) {
605
- const catalog = catalogs[locale] ?? {};
606
- const live = keys.filter((key) => own(catalog, key));
607
- if (live.length) out[locale] = live;
825
+ function analyzeSegment(code, file, options) {
826
+ try {
827
+ return analyzeScript(code, file, options);
828
+ } catch (error) {
829
+ return {
830
+ renamed: [],
831
+ error: parseErrorMessage(error)
832
+ };
608
833
  }
609
- return out;
610
- }
611
- function fingerprint(text) {
612
- return stableKey(text);
613
834
  }
614
- function tracked(key, text) {
615
- return stableKey(text) !== key;
616
- }
617
- function stamp(source, translated) {
618
- return `${fingerprint(source)}.${fingerprint(translated)}`;
835
+ function blank(source, re) {
836
+ return source.replace(re, (m) => " ".repeat(m.length));
619
837
  }
620
- function refreshFingerprints(cfg, catalogs, previous) {
621
- const source = catalogs[cfg.sourceLocale] ?? {};
622
- const out = {};
623
- for (const locale of targetLocales(cfg)) {
624
- const catalog = catalogs[locale] ?? {};
625
- const before = previous[locale] ?? {};
626
- const after = emptyCatalog();
627
- for (const [key, text] of Object.entries(source)) {
628
- const translated = own(catalog, key);
629
- if (!text || !translated || !tracked(key, text)) continue;
630
- const was = own(before, key);
631
- after[key] = was !== void 0 && translationOf(was) === fingerprint(translated) ? was : stamp(text, translated);
838
+ function braceRanges(markup) {
839
+ const ranges = [];
840
+ let i = 0;
841
+ while (i < markup.length) {
842
+ if (markup[i] === "{") {
843
+ const end = balancedEnd(markup, i);
844
+ if (end !== void 0) {
845
+ ranges.push([i + 1, end - 1]);
846
+ i = end;
847
+ continue;
848
+ }
632
849
  }
633
- if (Object.keys(after).length) out[locale] = after;
850
+ i += 1;
634
851
  }
635
- return out;
852
+ return ranges;
636
853
  }
637
- function outdatedTranslations(cfg, catalogs, fingerprints) {
638
- const source = catalogs[cfg.sourceLocale] ?? {};
639
- const out = [];
640
- for (const locale of targetLocales(cfg)) {
641
- const catalog = catalogs[locale] ?? {};
642
- for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
643
- const text = own(source, key);
644
- const translated = own(catalog, key);
645
- if (!text || !translated) continue;
646
- if (translationOf(was) !== fingerprint(translated)) continue;
647
- if (sourceOf(was) !== fingerprint(text)) out.push({
648
- locale,
649
- key
650
- });
651
- }
854
+ function vueExpressionRanges(markup) {
855
+ const ranges = [];
856
+ for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
857
+ for (const match of markup.matchAll(DIRECTIVE_RE)) {
858
+ const valueStart = match.index + match[0].length - match[1].length + 1;
859
+ ranges.push([valueStart, valueStart + match[1].length - 2]);
652
860
  }
653
- return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
861
+ return ranges.sort((a, b) => a[0] - b[0]);
654
862
  }
655
- function acceptOutdated(cfg, catalogs, fingerprints, entries) {
656
- const source = catalogs[cfg.sourceLocale] ?? {};
657
- for (const { locale, key } of entries) {
658
- const text = own(source, key);
659
- const translated = own(catalogs[locale] ?? {}, key);
660
- if (!text || !translated) continue;
661
- (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
863
+ function expressionExtent(code, start, nameLength) {
864
+ const i = start + nameLength;
865
+ if (code.startsWith(".id(", i)) {
866
+ const close = balancedEnd(code, i + 3);
867
+ if (close === void 0 || code[close] !== "`") return void 0;
868
+ return balancedEnd(code, close);
662
869
  }
870
+ if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
663
871
  }
664
- function sourceOf(stamped) {
665
- return stamped.slice(0, stamped.indexOf("."));
666
- }
667
- function translationOf(stamped) {
668
- return stamped.slice(stamped.indexOf(".") + 1);
669
- }
670
- function serializeState(state) {
671
- const drafts = {};
672
- for (const locale of Object.keys(state.drafts).sort()) {
673
- const keys = [...new Set(state.drafts[locale])].sort();
674
- if (keys.length) drafts[locale] = keys;
675
- }
676
- const fingerprints = {};
677
- for (const locale of Object.keys(state.fingerprints).sort()) {
678
- const entries = state.fingerprints[locale] ?? {};
679
- const keys = Object.keys(entries).sort();
680
- if (!keys.length) continue;
681
- fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
872
+ function balancedEnd(code, open) {
873
+ const stack = [];
874
+ let i = open;
875
+ while (i < code.length) {
876
+ const ch = code[i];
877
+ if (stack[stack.length - 1] === "`") {
878
+ if (ch === "\\") i += 1;
879
+ else if (ch === "`") stack.pop();
880
+ else if (ch === "$" && code[i + 1] === "{") {
881
+ stack.push("{");
882
+ i += 1;
883
+ }
884
+ } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
885
+ else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
886
+ else if (ch === ")" || ch === "}") {
887
+ if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
888
+ stack.pop();
889
+ }
890
+ i += 1;
891
+ if (stack.length === 0) return i;
682
892
  }
683
- const out = {};
684
- if (Object.keys(drafts).length) out.drafts = drafts;
685
- if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
686
- if (!out.drafts && !out.fingerprints) return void 0;
687
- return JSON.stringify(out, null, 2) + "\n";
688
893
  }
689
- function readJson(path) {
690
- let content;
691
- try {
692
- content = readFileSync(path, "utf8");
693
- } catch {
694
- return;
695
- }
696
- try {
697
- return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
698
- } catch (error) {
699
- throw corrupt(path, error);
700
- }
894
+ function stringEnd(code, start) {
895
+ const quote = code[start];
896
+ let i = start + 1;
897
+ while (i < code.length) if (code[i] === "\\") i += 2;
898
+ else if (code[i] === quote) return i;
899
+ else i += 1;
900
+ return code.length;
701
901
  }
702
- function corrupt(path, cause) {
703
- return new Error(`[verbaly] ${path} is not valid JSON, fix or delete the file`, { cause });
902
+ //#endregion
903
+ //#region src/extract.ts
904
+ async function extractProject(cfg) {
905
+ const files = await glob(cfg.include, {
906
+ cwd: cfg.root,
907
+ ignore: cfg.exclude,
908
+ absolute: true
909
+ });
910
+ const registry = new MessageRegistry();
911
+ for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
912
+ return registry;
704
913
  }
705
- function isObject(value) {
706
- return typeof value === "object" && value !== null && !Array.isArray(value);
914
+ async function collectOrigins(cfg, reuse) {
915
+ const registry = reuse ?? await extractProject(cfg);
916
+ const origins = Object.create(null);
917
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
918
+ return origins;
919
+ }
920
+ function syncCatalogs(cfg, catalogs, registry) {
921
+ const added = {};
922
+ const replaced = [];
923
+ const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
924
+ for (const [key, msg] of registry.messages()) {
925
+ const before = own(source, key);
926
+ if (before === msg.message) continue;
927
+ source[key] = msg.message;
928
+ if (before) replaced.push({
929
+ key,
930
+ before
931
+ });
932
+ else (added[cfg.sourceLocale] ??= []).push(key);
933
+ }
934
+ const needed = Object.keys(source);
935
+ for (const locale of cfg.locales) {
936
+ if (locale === cfg.sourceLocale) continue;
937
+ const catalog = catalogs[locale] ??= emptyCatalog();
938
+ for (const key of needed) if (own(catalog, key) === void 0) {
939
+ catalog[key] = "";
940
+ (added[locale] ??= []).push(key);
941
+ }
942
+ }
943
+ return {
944
+ added,
945
+ replaced
946
+ };
707
947
  }
708
- function readDrafts(value) {
709
- const out = {};
710
- if (!isObject(value)) return out;
711
- for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
712
- return out;
948
+ function shippedCatalogs(cfg, catalogs, registry, options = {}) {
949
+ const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
950
+ for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
951
+ return {
952
+ ...catalogs,
953
+ [cfg.sourceLocale]: source
954
+ };
713
955
  }
714
- function readFingerprints(value) {
715
- const out = {};
716
- if (!isObject(value)) return out;
717
- for (const [locale, entries] of Object.entries(value)) {
718
- if (!isObject(entries)) continue;
719
- const kept = emptyCatalog();
720
- for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
721
- out[locale] = kept;
956
+ function pruneCatalogs(cfg, catalogs, registry) {
957
+ const removed = {};
958
+ if (registry.parseErrors().length > 0) return removed;
959
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
960
+ for (const locale of cfg.locales) {
961
+ const catalog = catalogs[locale];
962
+ if (!catalog) continue;
963
+ for (const key of Object.keys(catalog)) if (!keep.has(key)) {
964
+ delete catalog[key];
965
+ (removed[locale] ??= []).push(key);
966
+ }
722
967
  }
723
- return out;
968
+ return removed;
724
969
  }
725
970
  //#endregion
726
971
  //#region src/text.ts
727
972
  function counted(count, noun, many = `${noun}s`) {
728
973
  return `${count} ${count === 1 ? noun : many}`;
729
974
  }
975
+ function truncate(text, max) {
976
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
977
+ }
978
+ function byCodeUnit(a, b) {
979
+ return a < b ? -1 : a > b ? 1 : 0;
980
+ }
730
981
  //#endregion
731
982
  //#region src/validate.ts
732
983
  const read = (message) => parse(message, parseIcu);
@@ -740,10 +991,10 @@ const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
740
991
  const EXACT = /^=\d+$/;
741
992
  function shapes(message) {
742
993
  const out = /* @__PURE__ */ new Map();
743
- walk$1(read(message), out);
994
+ walk(read(message), out);
744
995
  return out;
745
996
  }
746
- function walk$1(nodes, out) {
997
+ function walk(nodes, out) {
747
998
  for (const node of nodes) {
748
999
  if (node.kind !== "param" || !node.variants) continue;
749
1000
  const selectors = node.variants.map(([key]) => key);
@@ -752,7 +1003,7 @@ function walk$1(nodes, out) {
752
1003
  plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),
753
1004
  ordinal: node.ordinal === true
754
1005
  });
755
- for (const [, body] of node.variants) walk$1(body, out);
1006
+ for (const [, body] of node.variants) walk(body, out);
756
1007
  }
757
1008
  }
758
1009
  function paramNames(message) {
@@ -891,1056 +1142,1322 @@ function reachableCategories(locale, ordinal) {
891
1142
  return out;
892
1143
  }
893
1144
  //#endregion
894
- //#region src/check.ts
895
- function gatePasses(result) {
896
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
897
- }
898
- function check(cfg, catalogs, registry, fingerprints = {}) {
899
- const extracted = registry.messages();
900
- const locate = createLocator();
901
- const site = (msg) => ({
1145
+ //#region src/findings.ts
1146
+ function siteOf(msg) {
1147
+ return {
902
1148
  file: msg.file,
903
- line: locate(msg.file, msg.start),
1149
+ line: msg.line,
904
1150
  message: msg.message
905
- });
906
- const flat = {};
907
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
908
- const source = flat[cfg.sourceLocale] ?? {};
909
- const used = registry.usedKeys();
910
- const unknown = [];
911
- for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
912
- key,
913
- files
914
- });
915
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
916
- const missing = [];
917
- for (const key of extracted.keys()) if (!source[key]) missing.push({
918
- locale: cfg.sourceLocale,
1151
+ };
1152
+ }
1153
+ function collisionEntries(registry) {
1154
+ return registry.collisions().map(({ key, kept, dropped }) => ({
919
1155
  key,
920
- source: extracted.get(key)?.message
921
- });
922
- for (const locale of cfg.locales) {
923
- if (locale === cfg.sourceLocale) continue;
924
- for (const key of needed) if (!flat[locale]?.[key]) missing.push({
925
- locale,
1156
+ sites: [kept, ...dropped].map(siteOf)
1157
+ }));
1158
+ }
1159
+ function scanFindings(cfg, registry, replaced = []) {
1160
+ const messages = registry.messages();
1161
+ const out = [];
1162
+ for (const { key, before } of replaced) {
1163
+ const msg = messages.get(key);
1164
+ if (msg) out.push({
1165
+ kind: "replaced",
1166
+ locale: cfg.sourceLocale,
926
1167
  key,
927
- source: source[key] ?? extracted.get(key)?.message
1168
+ before,
1169
+ site: siteOf(msg)
928
1170
  });
929
1171
  }
930
- const broken = [];
931
- const add = (locale, key, issues) => {
932
- for (const issue of issues) broken.push({
933
- locale,
934
- key,
935
- severity: issue.severity,
936
- issue: issue.message
1172
+ for (const entry of collisionEntries(registry)) out.push({
1173
+ kind: "collision",
1174
+ ...entry
1175
+ });
1176
+ for (const { name, file, line } of registry.missed()) out.push({
1177
+ kind: "renamed",
1178
+ name,
1179
+ file,
1180
+ line
1181
+ });
1182
+ for (const msg of messages.values()) {
1183
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
1184
+ if (params.length > 0) out.push({
1185
+ kind: "positional",
1186
+ params,
1187
+ site: siteOf(msg)
937
1188
  });
938
- };
939
- const sourceText = Object.assign(emptyCatalog(), source);
940
- const divergent = [];
941
- for (const [key, entry] of extracted) {
942
- const written = sourceText[key];
943
- if (written && written !== entry.message) divergent.push({
944
- key,
945
- catalog: written,
946
- code: site(entry)
1189
+ const slice = escapedSyntax(msg.message);
1190
+ if (slice) out.push({
1191
+ kind: "escaped",
1192
+ slice,
1193
+ site: siteOf(msg)
947
1194
  });
948
- sourceText[key] = entry.message;
949
1195
  }
950
- for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
951
- for (const locale of cfg.locales) {
952
- if (locale === cfg.sourceLocale) continue;
953
- for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
954
- if (!translated) continue;
955
- add(locale, key, validateMessage(translated, locale));
956
- const text = sourceText[key];
957
- if (text) add(locale, key, validatePair(text, translated));
1196
+ for (const { file, message } of registry.parseErrors()) out.push({
1197
+ kind: "unparsed",
1198
+ file,
1199
+ message
1200
+ });
1201
+ return out;
1202
+ }
1203
+ function sourcePlace(at, root) {
1204
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1205
+ return at.line ? `${file}:${at.line}` : file;
1206
+ }
1207
+ function quoted(at, root) {
1208
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1209
+ }
1210
+ function formatCollision({ key, sites }, root) {
1211
+ const [kept, ...others] = sites;
1212
+ const texts = new Set(sites.map((at) => at.message)).size;
1213
+ return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1214
+ }
1215
+ function formatFinding(finding, root) {
1216
+ switch (finding.kind) {
1217
+ case "collision": return formatCollision(finding, root);
1218
+ case "replaced": {
1219
+ const place = sourcePlace(finding.site, root);
1220
+ return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
1221
+ }
1222
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
1223
+ case "positional": {
1224
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
1225
+ return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
1226
+ }
1227
+ case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \${…} value)`;
1228
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1229
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1230
+ }
1231
+ }
1232
+ function findingId(finding) {
1233
+ switch (finding.kind) {
1234
+ case "collision":
1235
+ case "replaced": return `${finding.kind}:${finding.key}`;
1236
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
1237
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
1238
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1239
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1240
+ case "unparsed": return `unparsed:${finding.file}`;
1241
+ }
1242
+ }
1243
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
1244
+ const shown = /* @__PURE__ */ new Map();
1245
+ return { report(channel, findings) {
1246
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
1247
+ const now = /* @__PURE__ */ new Set();
1248
+ const fresh = [];
1249
+ for (const finding of findings) {
1250
+ const id = findingId(finding);
1251
+ if (now.has(id)) continue;
1252
+ now.add(id);
1253
+ if (!before.has(id)) fresh.push(finding);
1254
+ }
1255
+ shown.set(channel, now);
1256
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
1257
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
1258
+ } };
1259
+ }
1260
+ //#endregion
1261
+ //#region src/host.ts
1262
+ const HOSTS = [
1263
+ {
1264
+ name: "nuxt",
1265
+ dep: "nuxt",
1266
+ pkg: "@verbaly/nuxt",
1267
+ install: [
1268
+ "verbaly",
1269
+ "@verbaly/nuxt",
1270
+ "@verbaly/vue"
1271
+ ],
1272
+ wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1273
+ },
1274
+ {
1275
+ name: "next",
1276
+ dep: "next",
1277
+ pkg: "@verbaly/next",
1278
+ install: [
1279
+ "verbaly",
1280
+ "@verbaly/next",
1281
+ "@verbaly/react"
1282
+ ],
1283
+ wire: "wrap the export of next.config with withVerbaly"
1284
+ },
1285
+ {
1286
+ name: "sveltekit",
1287
+ dep: "@sveltejs/kit",
1288
+ pkg: "@verbaly/vite",
1289
+ install: [
1290
+ "verbaly",
1291
+ "@verbaly/sveltekit",
1292
+ "@verbaly/svelte",
1293
+ "@verbaly/vite"
1294
+ ],
1295
+ wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1296
+ },
1297
+ {
1298
+ name: "astro",
1299
+ dep: "astro",
1300
+ pkg: "@verbaly/astro",
1301
+ install: ["verbaly", "@verbaly/astro"],
1302
+ wire: "add verbaly() to the integrations in astro.config"
1303
+ },
1304
+ {
1305
+ name: "vite",
1306
+ dep: "vite",
1307
+ pkg: "@verbaly/vite",
1308
+ install: ["verbaly", "@verbaly/vite"],
1309
+ wire: "add verbaly() to the plugins in vite.config"
1310
+ },
1311
+ {
1312
+ name: "webpack",
1313
+ dep: "webpack",
1314
+ pkg: "@verbaly/unplugin",
1315
+ install: ["verbaly", "@verbaly/unplugin"],
1316
+ wire: "add the verbaly webpack plugin to your build config"
1317
+ },
1318
+ {
1319
+ name: "rspack",
1320
+ dep: "@rspack/core",
1321
+ pkg: "@verbaly/unplugin",
1322
+ install: ["verbaly", "@verbaly/unplugin"],
1323
+ wire: "add the verbaly rspack plugin to your build config"
1324
+ },
1325
+ {
1326
+ name: "rollup",
1327
+ dep: "rollup",
1328
+ pkg: "@verbaly/unplugin",
1329
+ install: ["verbaly", "@verbaly/unplugin"],
1330
+ wire: "add the verbaly rollup plugin to your build config"
1331
+ },
1332
+ {
1333
+ name: "esbuild",
1334
+ dep: "esbuild",
1335
+ pkg: "@verbaly/unplugin",
1336
+ install: ["verbaly", "@verbaly/unplugin"],
1337
+ wire: "add the verbaly esbuild plugin to your build config"
1338
+ }
1339
+ ];
1340
+ const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1341
+ function readDependencies(root) {
1342
+ const path = join(root, "package.json");
1343
+ if (!existsSync(path)) return {};
1344
+ try {
1345
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
1346
+ return {
1347
+ ...pkg.dependencies,
1348
+ ...pkg.devDependencies
1349
+ };
1350
+ } catch {
1351
+ return {};
1352
+ }
1353
+ }
1354
+ function detectHost(root) {
1355
+ const deps = readDependencies(root);
1356
+ return HOSTS.find((host) => deps[host.dep]);
1357
+ }
1358
+ const LOCKFILES = [
1359
+ ["pnpm-lock.yaml", "pnpm"],
1360
+ ["yarn.lock", "yarn"],
1361
+ ["bun.lock", "bun"],
1362
+ ["bun.lockb", "bun"],
1363
+ ["package-lock.json", "npm"]
1364
+ ];
1365
+ function packageManager(root) {
1366
+ try {
1367
+ const declared = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).packageManager;
1368
+ const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
1369
+ if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
1370
+ } catch {}
1371
+ for (let dir = root;; dir = dirname(dir)) {
1372
+ const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
1373
+ if (found) return found[1];
1374
+ if (dirname(dir) === dir) return "npm";
1375
+ }
1376
+ }
1377
+ function installCommand(root, packages, dev = false) {
1378
+ const manager = packageManager(root);
1379
+ return `${manager} ${manager === "npm" ? "install" : "add"}${dev ? manager === "bun" ? " -d" : " -D" : ""} ${packages.join(" ")}`;
1380
+ }
1381
+ const TYPE_SLOTS = {
1382
+ next: [".verbaly", "types.d.ts"],
1383
+ astro: [
1384
+ ".astro",
1385
+ "integrations",
1386
+ "_verbaly_astro",
1387
+ "verbaly.d.ts"
1388
+ ],
1389
+ nuxt: [".nuxt", "verbaly.d.ts"]
1390
+ };
1391
+ function defaultTypesPath(root, host = detectHost(root)?.name) {
1392
+ const slot = host && TYPE_SLOTS[host];
1393
+ if (slot) return join(root, ...slot);
1394
+ return existsSync(join(root, "src")) ? join(root, "src", "verbaly.d.ts") : join(root, "verbaly.d.ts");
1395
+ }
1396
+ //#endregion
1397
+ //#region src/pseudo.ts
1398
+ const PSEUDO_LOCALE = "en-XA";
1399
+ const ACCENTS = {
1400
+ a: "á",
1401
+ b: "ƀ",
1402
+ c: "ç",
1403
+ d: "đ",
1404
+ e: "é",
1405
+ f: "ƒ",
1406
+ g: "ğ",
1407
+ h: "ĥ",
1408
+ i: "í",
1409
+ j: "ĵ",
1410
+ k: "ķ",
1411
+ l: "ĺ",
1412
+ m: "ɱ",
1413
+ n: "ñ",
1414
+ o: "ó",
1415
+ p: "þ",
1416
+ q: "ǫ",
1417
+ r: "ŕ",
1418
+ s: "š",
1419
+ t: "ţ",
1420
+ u: "ú",
1421
+ v: "ṽ",
1422
+ w: "ŵ",
1423
+ x: "ẋ",
1424
+ y: "ý",
1425
+ z: "ž",
1426
+ A: "Á",
1427
+ B: "Ɓ",
1428
+ C: "Ç",
1429
+ D: "Đ",
1430
+ E: "É",
1431
+ F: "Ƒ",
1432
+ G: "Ğ",
1433
+ H: "Ĥ",
1434
+ I: "Í",
1435
+ J: "Ĵ",
1436
+ K: "Ķ",
1437
+ L: "Ĺ",
1438
+ M: "Ḿ",
1439
+ N: "Ñ",
1440
+ O: "Ó",
1441
+ P: "Þ",
1442
+ Q: "Ǫ",
1443
+ R: "Ŕ",
1444
+ S: "Š",
1445
+ T: "Ţ",
1446
+ U: "Ú",
1447
+ V: "Ṽ",
1448
+ W: "Ŵ",
1449
+ X: "Ẍ",
1450
+ Y: "Ý",
1451
+ Z: "Ž"
1452
+ };
1453
+ const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
1454
+ function pseudoLocalize(message) {
1455
+ let out = "";
1456
+ let letters = 0;
1457
+ let i = 0;
1458
+ while (i < message.length) {
1459
+ const two = message.slice(i, i + 2);
1460
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
1461
+ out += two;
1462
+ i += 2;
1463
+ continue;
1464
+ }
1465
+ const ch = message[i];
1466
+ if (ch === "{") {
1467
+ const end = matchBrace$1(message, i);
1468
+ out += message.slice(i, end);
1469
+ i = end;
1470
+ continue;
1471
+ }
1472
+ if (ch === "<") {
1473
+ TAG_AT.lastIndex = i;
1474
+ const m = TAG_AT.exec(message);
1475
+ if (m) {
1476
+ out += m[0];
1477
+ i += m[0].length;
1478
+ continue;
1479
+ }
958
1480
  }
1481
+ const mapped = ACCENTS[ch];
1482
+ if (mapped) {
1483
+ out += mapped;
1484
+ letters += 1;
1485
+ } else out += ch;
1486
+ i += 1;
959
1487
  }
960
- const extra = [];
961
- for (const locale of cfg.locales) {
962
- if (locale === cfg.sourceLocale) continue;
963
- for (const key of Object.keys(flat[locale] ?? {})) {
964
- if (source[key] !== void 0 || extracted.has(key)) continue;
965
- extra.push({
966
- locale,
967
- key,
968
- files: used.get(key) ?? []
969
- });
1488
+ const pad = "~".repeat(Math.ceil(letters / 3));
1489
+ return `⟦${out}${pad ? " " + pad : ""}⟧`;
1490
+ }
1491
+ function matchBrace$1(message, start) {
1492
+ let depth = 0;
1493
+ for (let i = start; i < message.length; i++) {
1494
+ const two = message.slice(i, i + 2);
1495
+ if (two === "{{" || two === "}}") {
1496
+ i += 1;
1497
+ continue;
1498
+ }
1499
+ const ch = message[i];
1500
+ if (ch === "{") depth += 1;
1501
+ else if (ch === "}") {
1502
+ depth -= 1;
1503
+ if (depth === 0) return i + 1;
970
1504
  }
971
1505
  }
972
- const collisions = collisionEntries(registry, locate);
973
- const outdated = outdatedTranslations(cfg, flat, fingerprints);
1506
+ return message.length;
1507
+ }
1508
+ function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
1509
+ const source = catalogs[cfg.sourceLocale] ?? {};
1510
+ const target = emptyCatalog();
1511
+ for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
1512
+ catalogs[locale] = target;
1513
+ return Object.keys(target).filter((key) => target[key]);
1514
+ }
1515
+ //#endregion
1516
+ //#region src/config.ts
1517
+ const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
1518
+ function resolveConfig(config = {}) {
1519
+ const root = resolve(config.root ?? process.cwd());
1520
+ const dir = resolve(root, config.dir ?? "locales");
1521
+ const sourceLocale = config.sourceLocale ?? "en";
1522
+ const localesDeclared = config.locales !== void 0;
1523
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
1524
+ if (!localesDeclared && existsSync(dir)) {
1525
+ for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
1526
+ }
974
1527
  return {
975
- ok: gatePasses({
976
- missing,
977
- unknown,
978
- broken
979
- }),
980
- missing,
981
- unknown,
982
- broken,
983
- extra,
984
- collisions,
985
- divergent,
986
- outdated
1528
+ root,
1529
+ dir,
1530
+ sourceLocale,
1531
+ localesDeclared,
1532
+ routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
1533
+ icu: config.icu,
1534
+ relative: config.relative,
1535
+ locales: [...locales],
1536
+ include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}`],
1537
+ exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
1538
+ dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts === false ? false : defaultTypesPath(root),
1539
+ translate: config.translate ?? {},
1540
+ render: config.render ?? {},
1541
+ bundle: config.bundle ?? {}
987
1542
  };
988
1543
  }
989
- function formatCheckResult(result, root) {
990
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
991
- const lines = [];
992
- if (result.missing.length > 0) {
993
- lines.push("missing translations:");
994
- for (const entry of result.missing) {
995
- const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
996
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
997
- }
1544
+ const CONFIG_FILES = [
1545
+ "verbaly.config.js",
1546
+ "verbaly.config.mjs",
1547
+ "verbaly.config.ts",
1548
+ "verbaly.config.mts",
1549
+ "verbaly.config.json"
1550
+ ];
1551
+ function findConfigFile(root) {
1552
+ return CONFIG_FILES.find((name) => existsSync(join(root, name)));
1553
+ }
1554
+ async function loadConfigFile(root) {
1555
+ for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1556
+ const path = join(root, name);
1557
+ if (existsSync(path)) return (await import(`${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`)).default ?? {};
998
1558
  }
999
- if (result.unknown.length > 0) {
1000
- lines.push("unknown keys (not in any catalog):");
1001
- for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
1559
+ for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1560
+ const path = join(root, name);
1561
+ if (existsSync(path)) return loadTsConfig(path);
1002
1562
  }
1003
- const errors = result.broken.filter((entry) => entry.severity === "error");
1004
- if (errors.length > 0) {
1005
- lines.push("broken translations:");
1006
- for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1563
+ const jsonPath = join(root, "verbaly.config.json");
1564
+ if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
1565
+ return {};
1566
+ }
1567
+ function readJsonConfig(path) {
1568
+ const content = readFileSync(path, "utf8");
1569
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
1570
+ try {
1571
+ return JSON.parse(body);
1572
+ } catch (error) {
1573
+ throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
1007
1574
  }
1008
- return lines.join("\n");
1009
1575
  }
1010
- function checkNextSteps(result, cliReachable = true) {
1011
- const steps = [];
1012
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
1013
- if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
1014
- if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
1015
- if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1016
- return steps.join("\n");
1576
+ async function loadTsConfig(path) {
1577
+ try {
1578
+ const { bundleRequire } = await import("bundle-require");
1579
+ const { mod } = await bundleRequire({ filepath: path });
1580
+ return mod.default ?? {};
1581
+ } catch (error) {
1582
+ if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
1583
+ throw error;
1584
+ }
1017
1585
  }
1018
- function collisionEntries(registry, locate = createLocator()) {
1019
- return registry.collisions().map(({ key, kept, dropped }) => ({
1020
- key,
1021
- sites: [kept, ...dropped].map((msg) => ({
1022
- file: msg.file,
1023
- line: locate(msg.file, msg.start),
1024
- message: msg.message
1025
- }))
1026
- }));
1586
+ function isModuleNotFound(error, name) {
1587
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
1027
1588
  }
1028
- function sourcePlace(at, root) {
1029
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1030
- return at.line ? `${file}:${at.line}` : file;
1589
+ function targetLocales(cfg, override) {
1590
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
1031
1591
  }
1032
- function quoted(at, root) {
1033
- return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1592
+ async function loadConfig(root, overrides = {}) {
1593
+ return resolveConfig({
1594
+ ...await loadConfigFile(root),
1595
+ ...definedOnly(overrides),
1596
+ root
1597
+ });
1034
1598
  }
1035
- function formatCollision({ key, sites }, root) {
1036
- const [kept, ...others] = sites;
1037
- return ` ${key}: one key with ${counted(sites.length, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1599
+ function definedOnly(config) {
1600
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
1038
1601
  }
1039
- function formatCheckWarnings(result, root) {
1040
- const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1041
- for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
1042
- for (const entry of result.collisions) lines.push(formatCollision(entry, root));
1043
- for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says ${quoted(code, root)}: the code wins, so edit the text there (extract writes it into the catalog)`);
1044
- for (const { locale, key } of result.outdated) lines.push(` [${locale}] ${key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``);
1045
- return lines.join("\n");
1602
+ //#endregion
1603
+ //#region src/tag.ts
1604
+ function isLocaleTag(tag) {
1605
+ try {
1606
+ Intl.getCanonicalLocales(tag);
1607
+ return true;
1608
+ } catch {
1609
+ return false;
1610
+ }
1046
1611
  }
1047
- function truncate(text, max) {
1048
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
1612
+ function suggestTag(tag) {
1613
+ const near = tag.replace(/_/g, "-");
1614
+ return near !== tag && isLocaleTag(near) ? near : void 0;
1049
1615
  }
1050
- function githubCheckAnnotations(result, registry, root) {
1051
- const messages = registry.messages();
1052
- const locate = createLocator();
1053
- const rel = (file) => escapeProperty(relative(root, file).replaceAll("\\", "/"));
1054
- const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
1055
- const lines = [];
1056
- const byKey = /* @__PURE__ */ new Map();
1057
- for (const entry of result.missing) {
1058
- const grouped = byKey.get(entry.key);
1059
- if (grouped) grouped.locales.push(entry.locale);
1060
- else byKey.set(entry.key, {
1061
- ...entry,
1062
- locales: [entry.locale]
1616
+ function projectLocale(tag, locales) {
1617
+ if (locales.includes(tag)) return tag;
1618
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
1619
+ return locales.find((locale) => plain(locale) === plain(tag));
1620
+ }
1621
+ //#endregion
1622
+ //#region src/init.ts
1623
+ function cliReachable(root) {
1624
+ const bin = join(root, "node_modules", ".bin");
1625
+ return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
1626
+ }
1627
+ const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
1628
+ function configSource(options, typescript) {
1629
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1630
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1631
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
1632
+ const body = `export default {\n${fields.join("\n")}\n}`;
1633
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1634
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1635
+ }
1636
+ async function init(input = {}) {
1637
+ const root = input.root ?? process.cwd();
1638
+ const created = [];
1639
+ const skipped = [];
1640
+ const renamed = [];
1641
+ const refused = [];
1642
+ const typed = input.locales?.flatMap((locale) => {
1643
+ if (isLocaleTag(locale)) return [locale];
1644
+ const near = suggestTag(locale);
1645
+ if (near) renamed.push({
1646
+ from: locale,
1647
+ to: near
1063
1648
  });
1649
+ else refused.push(locale);
1650
+ return near ? [near] : [];
1651
+ });
1652
+ const locales = typed && [...new Set(typed)];
1653
+ let sourceLocale = input.sourceLocale;
1654
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
1655
+ const near = suggestTag(sourceLocale);
1656
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
1657
+ renamed.push({
1658
+ from: sourceLocale,
1659
+ to: near
1660
+ });
1661
+ sourceLocale = near;
1064
1662
  }
1065
- for (const entry of byKey.values()) {
1066
- const origin = messages.get(entry.key);
1067
- const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
1068
- const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
1069
- if (origin) lines.push(`::error ${at(origin.file, locate(origin.file, origin.start))}::${text}`);
1070
- else lines.push(`::error::${text}`);
1071
- }
1072
- for (const entry of result.unknown) {
1073
- const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
1074
- const file = entry.files[0];
1075
- lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);
1663
+ const options = {
1664
+ ...input,
1665
+ locales,
1666
+ sourceLocale
1667
+ };
1668
+ const existing = findConfigFile(root);
1669
+ const typescript = existsSync(join(root, "tsconfig.json"));
1670
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1671
+ if (existing) skipped.push(existing);
1672
+ else {
1673
+ writeFileSync(join(root, configFile), configSource(options, typescript));
1674
+ created.push(configFile);
1076
1675
  }
1077
- for (const entry of result.broken) {
1078
- const origin = messages.get(entry.key);
1079
- const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
1080
- const command = entry.severity === "error" ? "error" : "warning";
1081
- if (!origin) {
1082
- lines.push(`::${command}::${text}`);
1083
- continue;
1676
+ const fromFile = existing ? await loadConfigFile(root) : {};
1677
+ const scaffold = {
1678
+ dir: options.dir ?? fromFile.dir,
1679
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
1680
+ locales: options.locales ?? fromFile.locales
1681
+ };
1682
+ const dir = join(root, scaffold.dir ?? "locales");
1683
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1684
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
1685
+ const file = join(dir, `${locale}.json`);
1686
+ const label = relative(root, file).replaceAll("\\", "/");
1687
+ if (existsSync(file)) skipped.push(label);
1688
+ else {
1689
+ writeFileSync(file, "{}\n");
1690
+ created.push(label);
1084
1691
  }
1085
- lines.push(`::${command} ${at(origin.file, locate(origin.file, origin.start))}::${text}`);
1086
- }
1087
- for (const entry of result.extra) {
1088
- const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
1089
- const file = entry.files[0];
1090
- lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);
1091
1692
  }
1092
- for (const { key, sites } of result.collisions) {
1093
- const text = escapeData(`"${key}" has ${counted(sites.length, "text")}, and every place shows the first one`);
1094
- for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);
1095
- }
1096
- for (const { key, code } of result.divergent) {
1097
- const text = escapeData(`"${key}": the source catalog has another text, the code's one ships`);
1098
- lines.push(`::warning ${at(code.file, code.line)}::${text}`);
1099
- }
1100
- for (const { locale, key } of result.outdated) {
1101
- const text = escapeData(`[${locale}] ${key}: translated from an older source text`);
1102
- lines.push(`::warning::${text}`);
1103
- }
1104
- return lines;
1693
+ const host = detectHost(root);
1694
+ const next = host ? [installCommand(root, host.install), host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1695
+ return {
1696
+ created,
1697
+ skipped,
1698
+ host: host?.name,
1699
+ configFile,
1700
+ next,
1701
+ renamed,
1702
+ refused
1703
+ };
1105
1704
  }
1106
- function escapeData(text) {
1107
- return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1705
+ //#endregion
1706
+ //#region src/state.ts
1707
+ const STATE_FILE = ".verbaly-state.json";
1708
+ const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1709
+ function statePath(cfg, file = STATE_FILE) {
1710
+ return join(cfg.dir, file);
1108
1711
  }
1109
- function escapeProperty(text) {
1110
- return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
1712
+ function loadState(cfg) {
1713
+ const current = readJson(statePath(cfg));
1714
+ if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1715
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1716
+ if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1717
+ const state = isObject(current) ? {
1718
+ drafts: readDrafts(current.drafts),
1719
+ fingerprints: readFingerprints(current.fingerprints)
1720
+ } : {
1721
+ drafts: {},
1722
+ fingerprints: {}
1723
+ };
1724
+ if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1725
+ return state;
1111
1726
  }
1112
- //#endregion
1113
- //#region src/params.ts
1114
- const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1115
- "number",
1116
- "integer",
1117
- "percent",
1118
- "currency"
1119
- ]);
1120
- const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
1121
- function collectParams(message) {
1122
- const out = /* @__PURE__ */ new Map();
1123
- visit(parse(message, parseIcu), out);
1124
- return out;
1727
+ function readState(cfg) {
1728
+ try {
1729
+ return { state: loadState(cfg) };
1730
+ } catch (error) {
1731
+ return {
1732
+ state: {
1733
+ drafts: {},
1734
+ fingerprints: {}
1735
+ },
1736
+ problem: error.message.replace(/^\[verbaly\] /, "")
1737
+ };
1738
+ }
1125
1739
  }
1126
- function visit(nodes, out) {
1127
- for (const node of nodes) {
1128
- if (node.kind !== "param") continue;
1129
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
1130
- out.set(node.name, types);
1131
- if (node.variants) {
1132
- for (const [key, body] of node.variants) {
1133
- if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
1134
- else if (key !== "other") types.add("string");
1135
- visit(body, out);
1136
- }
1137
- if (types.size === 0) types.add("string");
1138
- } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
1139
- else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
1140
- else types.add("unknown");
1740
+ function saveState(cfg, state) {
1741
+ const fresh = serializeState(state);
1742
+ const path = statePath(cfg);
1743
+ const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1744
+ if (fresh === void 0) {
1745
+ rmSync(path, { force: true });
1746
+ rmSync(legacy, { force: true });
1747
+ return;
1748
+ }
1749
+ let existing;
1750
+ try {
1751
+ existing = readFileSync(path, "utf8");
1752
+ } catch {
1753
+ mkdirSync(cfg.dir, { recursive: true });
1141
1754
  }
1755
+ const serialized = withLineEndings(fresh, existing);
1756
+ if (existing !== serialized) writeFileSync(path, serialized);
1757
+ if (existsSync(legacy)) rmSync(legacy);
1142
1758
  }
1143
- function renderParamType(types) {
1144
- if (types.has("unknown") || types.size === 0) return "unknown";
1145
- const members = /* @__PURE__ */ new Set();
1146
- if (types.has("number")) members.add("number");
1147
- if (types.has("string")) members.add("string");
1148
- if (types.has("date")) for (const m of [
1149
- "Date",
1150
- "number",
1151
- "string"
1152
- ]) members.add(m);
1153
- return [...members].join(" | ");
1759
+ function updateState(cfg, catalogs) {
1760
+ const next = refreshState(cfg, catalogs, loadState(cfg));
1761
+ saveState(cfg, next);
1762
+ return next;
1154
1763
  }
1155
- function generateDts(catalog, options = {}) {
1156
- const lines = [];
1157
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
1158
- const params = collectParams(message);
1159
- if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
1160
- else {
1161
- const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
1162
- lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
1764
+ function refreshState(cfg, catalogs, previous) {
1765
+ const flat = flatCatalogs(catalogs);
1766
+ const source = flat[cfg.sourceLocale] ?? {};
1767
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
1768
+ const drafts = {};
1769
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
1770
+ if (!shown.has(locale)) {
1771
+ drafts[locale] = keys;
1772
+ continue;
1163
1773
  }
1774
+ const live = keys.filter((key) => own(flat[locale], key));
1775
+ if (live.length) drafts[locale] = live;
1164
1776
  }
1165
- return `// generated by verbaly: do not edit
1166
- declare module 'virtual:verbaly' {
1167
- export interface VerbalyMessages {
1168
- ${lines.join("\n")}
1169
- }
1170
- export type VerbalyKey = keyof VerbalyMessages & string;
1171
-
1172
- export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
1173
- export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
1174
-
1175
- export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
1176
-
1177
- export const sourceLocale: string;
1178
- export const locales: string[];
1179
- export const routing: import('verbaly').Routing;
1180
- export function localePath(
1181
- locale: string,
1182
- options?: { path?: string; base?: string },
1183
- ): string;
1184
- export function localeFromPath(options?: {
1185
- path?: string;
1186
- base?: string;
1187
- }): string | undefined;
1188
- export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
1189
- export function createInstance(
1190
- options?: import('verbaly').VerbalyOptions<VerbalyKey>,
1191
- ): import('verbaly').Verbaly<VerbalyKey>;
1192
- export function createRequestInstance(
1193
- locale: string,
1194
- ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
1195
-
1196
- export function t<K extends VerbalyKey>(
1197
- key: K,
1198
- ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
1199
- ): string;
1200
- export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
1201
- export namespace t {
1202
- export function id(
1203
- key: string,
1204
- ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
1205
- }
1206
-
1207
- export function setLocale(locale: string): Promise<void>;
1208
- export function switchLocale(
1209
- locale: string,
1210
- options?: Omit<
1211
- import('verbaly').SwitchLocaleOptions,
1212
- 'routing' | 'supported' | 'sourceLocale'
1213
- >,
1214
- ): Promise<void>;
1215
- export function getLocale(): string;
1216
- export function subscribe(listener: () => void): () => void;
1217
- }
1218
-
1219
- declare module 'virtual:verbaly/locale/*' {
1220
- const messages: Record<string, string>;
1221
- export default messages;
1777
+ const fingerprints = {};
1778
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
1779
+ for (const locale of shown) {
1780
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
1781
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
1782
+ }
1783
+ return {
1784
+ drafts,
1785
+ fingerprints
1786
+ };
1222
1787
  }
1223
- `;
1788
+ function refreshStamps(source, catalog, before) {
1789
+ const after = emptyCatalog();
1790
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
1791
+ const translated = own(catalog, key);
1792
+ if (!translated) continue;
1793
+ const was = own(before, key);
1794
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
1795
+ after[key] = was;
1796
+ continue;
1797
+ }
1798
+ const text = own(source, key);
1799
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
1800
+ else if (was !== void 0) after[key] = was;
1801
+ }
1802
+ return after;
1224
1803
  }
1225
- function writeDts(cfg, catalog, file) {
1226
- const target = file === void 0 ? cfg.dts : file;
1227
- if (target === false) return;
1228
- file = target ?? join(cfg.root, "verbaly.d.ts");
1229
- const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
1230
- try {
1231
- if (readFileSync(file, "utf8") === content) return;
1232
- } catch {}
1233
- mkdirSync(dirname(file), { recursive: true });
1234
- writeFileSync(file, content);
1804
+ function recordTranslations(cfg, source, writes) {
1805
+ const state = loadState(cfg);
1806
+ for (const { locale, entries, draft } of writes) {
1807
+ if (entries.length === 0) continue;
1808
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
1809
+ for (const entry of entries) {
1810
+ const from = entry.source || own(source, entry.key);
1811
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
1812
+ }
1813
+ const keys = entries.map((entry) => entry.key);
1814
+ if (draft === true) markDrafts(state.drafts, locale, keys);
1815
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
1816
+ }
1817
+ saveState(cfg, state);
1818
+ return state;
1235
1819
  }
1236
- //#endregion
1237
- //#region src/bundle.ts
1238
- function isExcluded(key, prefixes) {
1239
- return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
1820
+ function effectiveDrafts(drafts, catalogs) {
1821
+ const out = {};
1822
+ for (const [locale, keys] of Object.entries(drafts)) {
1823
+ const catalog = catalogs[locale] ?? {};
1824
+ const live = keys.filter((key) => own(catalog, key));
1825
+ if (live.length) out[locale] = live;
1826
+ }
1827
+ return out;
1240
1828
  }
1241
- function auditBundle(cfg, catalogs, registry) {
1242
- const prefixes = cfg.bundle.exclude ?? [];
1243
- if (prefixes.length === 0) return [];
1244
- const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
1245
- const used = registry.usedKeys();
1246
- const issues = [];
1247
- for (const prefix of prefixes) {
1248
- if (!source.some((key) => isExcluded(key, [prefix]))) {
1249
- issues.push({
1250
- prefix,
1251
- problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
1252
- fix: "check the spelling against your catalog, or drop it from bundle.exclude"
1253
- });
1254
- continue;
1255
- }
1256
- const files = /* @__PURE__ */ new Set();
1257
- for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
1258
- if (files.size > 0) issues.push({
1259
- prefix,
1260
- problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
1261
- fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
1262
- });
1829
+ function markDrafts(drafts, locale, keys) {
1830
+ if (!keys.length) return;
1831
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1832
+ }
1833
+ function clearDrafts(drafts, locale, keys) {
1834
+ if (!drafts[locale]) return;
1835
+ if (!keys) {
1836
+ delete drafts[locale];
1837
+ return;
1263
1838
  }
1264
- return issues;
1839
+ const drop = new Set(keys);
1840
+ drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1841
+ if (!drafts[locale].length) delete drafts[locale];
1265
1842
  }
1266
- function formatBundleIssue(issue) {
1267
- return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1843
+ function fingerprint(text) {
1844
+ return stableKey(text);
1268
1845
  }
1269
- //#endregion
1270
- //#region src/registry.ts
1271
- var MessageRegistry = class {
1272
- files = /* @__PURE__ */ new Map();
1273
- update(file, analysis) {
1274
- this.files.set(file, analysis);
1275
- }
1276
- remove(file) {
1277
- this.files.delete(file);
1278
- }
1279
- messages() {
1280
- const out = /* @__PURE__ */ new Map();
1281
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) if (!out.has(msg.key)) out.set(msg.key, msg);
1282
- return out;
1283
- }
1284
- collisions() {
1285
- const seen = /* @__PURE__ */ new Map();
1286
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1287
- const found = seen.get(msg.key);
1288
- if (!found) seen.set(msg.key, {
1289
- key: msg.key,
1290
- kept: msg,
1291
- dropped: []
1846
+ function tracked(key, text) {
1847
+ return stableKey(text) !== key;
1848
+ }
1849
+ function stamp(source, translated) {
1850
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
1851
+ }
1852
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
1853
+ const source = catalogs[cfg.sourceLocale] ?? {};
1854
+ const out = [];
1855
+ for (const locale of targetLocales(cfg)) {
1856
+ const catalog = catalogs[locale] ?? {};
1857
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1858
+ const text = own(source, key);
1859
+ const translated = own(catalog, key);
1860
+ if (!text || !translated) continue;
1861
+ if (translationOf(was) !== fingerprint(translated)) continue;
1862
+ if (sourceOf(was) !== fingerprint(text)) out.push({
1863
+ locale,
1864
+ key
1292
1865
  });
1293
- else if (msg.message !== found.kept.message && !found.dropped.some((other) => other.message === msg.message)) found.dropped.push(msg);
1294
1866
  }
1295
- return [...seen.values()].filter((entry) => entry.dropped.length > 0);
1296
1867
  }
1297
- usedKeys(strict = false) {
1298
- const out = /* @__PURE__ */ new Map();
1299
- for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
1300
- if (strict && used.loose) continue;
1301
- const files = out.get(used.key) ?? [];
1302
- if (!files.includes(used.file)) files.push(used.file);
1303
- out.set(used.key, files);
1304
- }
1305
- return out;
1868
+ return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
1869
+ }
1870
+ function acceptOutdated(cfg, catalogs, fingerprints, entries) {
1871
+ const source = catalogs[cfg.sourceLocale] ?? {};
1872
+ for (const { locale, key } of entries) {
1873
+ const text = own(source, key);
1874
+ const translated = own(catalogs[locale] ?? {}, key);
1875
+ if (!text || !translated) continue;
1876
+ (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
1306
1877
  }
1307
- strayImports() {
1308
- return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
1878
+ }
1879
+ function sourceOf(stamped) {
1880
+ return stamped.slice(0, stamped.indexOf("."));
1881
+ }
1882
+ function translationOf(stamped) {
1883
+ return stamped.slice(stamped.indexOf(".") + 1);
1884
+ }
1885
+ function flatCatalogs(catalogs) {
1886
+ const out = {};
1887
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
1888
+ return out;
1889
+ }
1890
+ function serializeState(state) {
1891
+ const drafts = {};
1892
+ for (const locale of Object.keys(state.drafts).sort()) {
1893
+ const keys = [...new Set(state.drafts[locale])].sort();
1894
+ if (keys.length) drafts[locale] = keys;
1309
1895
  }
1310
- missed() {
1311
- return [...this.files.values()].flatMap((analysis) => analysis.missed ?? []);
1896
+ const fingerprints = {};
1897
+ for (const locale of Object.keys(state.fingerprints).sort()) {
1898
+ const entries = state.fingerprints[locale] ?? {};
1899
+ const keys = Object.keys(entries).sort();
1900
+ if (!keys.length) continue;
1901
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1312
1902
  }
1313
- parseErrors() {
1314
- const out = [];
1315
- for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
1316
- file,
1317
- message: analysis.parseError
1318
- });
1319
- return out;
1903
+ const out = {};
1904
+ if (Object.keys(drafts).length) out.drafts = drafts;
1905
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1906
+ if (!out.drafts && !out.fingerprints) return void 0;
1907
+ return JSON.stringify(out, null, 2) + "\n";
1908
+ }
1909
+ function readJson(path) {
1910
+ let content;
1911
+ try {
1912
+ content = readFileSync(path, "utf8");
1913
+ } catch {
1914
+ return;
1320
1915
  }
1321
- origins() {
1322
- const out = this.usedKeys();
1323
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1324
- const files = out.get(msg.key) ?? [];
1325
- if (!files.includes(msg.file)) files.push(msg.file);
1326
- out.set(msg.key, files);
1327
- }
1328
- return out;
1916
+ try {
1917
+ return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1918
+ } catch (error) {
1919
+ throw corrupt(path, error);
1329
1920
  }
1330
- };
1921
+ }
1922
+ function corrupt(path, cause) {
1923
+ return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1924
+ }
1925
+ function isObject(value) {
1926
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1927
+ }
1928
+ function readDrafts(value) {
1929
+ const out = {};
1930
+ if (!isObject(value)) return out;
1931
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1932
+ return out;
1933
+ }
1934
+ function readFingerprints(value) {
1935
+ const out = {};
1936
+ if (!isObject(value)) return out;
1937
+ for (const [locale, entries] of Object.entries(value)) {
1938
+ if (!isObject(entries)) continue;
1939
+ const kept = emptyCatalog();
1940
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1941
+ out[locale] = kept;
1942
+ }
1943
+ return out;
1944
+ }
1331
1945
  //#endregion
1332
- //#region src/analyze.ts
1333
- function parseErrorMessage(error) {
1334
- return error instanceof Error ? error.message : String(error);
1946
+ //#region src/check.ts
1947
+ function gatePasses(result) {
1948
+ return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1335
1949
  }
1336
- const SKIP_KEYS = /* @__PURE__ */ new Set([
1337
- "loc",
1338
- "leadingComments",
1339
- "trailingComments",
1340
- "innerComments",
1341
- "extra"
1342
- ]);
1343
- const DEFAULT_T_NAMES = ["t"];
1344
- const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
1345
- const DEFINE_KEYS = "defineKeys";
1346
- function analyze(code, file, options = {}) {
1347
- const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
1348
- const ast = parse$1(code, {
1349
- sourceType: "module",
1350
- errorRecovery: true,
1351
- plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
1950
+ function check(cfg, catalogs, registry, fingerprints = {}) {
1951
+ const extracted = registry.messages();
1952
+ const flat = {};
1953
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1954
+ const source = flat[cfg.sourceLocale] ?? {};
1955
+ const shipped = shippedCatalogs(cfg, flat, registry);
1956
+ const sourceText = shipped[cfg.sourceLocale];
1957
+ const used = registry.usedKeys();
1958
+ const unknown = [];
1959
+ for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
1960
+ key,
1961
+ files
1352
1962
  });
1353
- const tagged = [];
1354
- const usedKeys = [];
1355
- const strayImports = [];
1356
- const missed = [];
1357
- const renamed = renamedBindings(ast.program, names);
1358
- walk(ast.program, (node) => {
1359
- if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
1360
- else if (node.type === "TaggedTemplateExpression") {
1361
- const tag = node.tag;
1362
- const explicit = explicitId(tag, names);
1363
- if (!explicit && !isTReference(tag, names)) {
1364
- const name = renamedTag(tag, renamed);
1365
- if (name) missed.push({
1366
- name,
1367
- file,
1368
- start: node.start
1369
- });
1370
- return;
1371
- }
1372
- const quasi = node.quasi;
1373
- const message = buildMessage(code, quasi, names);
1374
- if (!message) return;
1375
- tagged.push({
1376
- key: explicit ? explicit.key : stableKey(message.text),
1377
- message: message.text,
1378
- params: message.params,
1379
- start: node.start,
1380
- end: node.end,
1381
- tagStart: explicit ? explicit.refStart : tag.start,
1382
- tagEnd: explicit ? explicit.refEnd : tag.end,
1383
- file
1384
- });
1385
- } else if (node.type === "CallExpression") {
1386
- const callee = node.callee;
1387
- const args = node.arguments;
1388
- if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
1389
- collectDeclaredKeys(args[0], file, usedKeys);
1390
- return;
1391
- }
1392
- if (!isTReference(callee, names)) {
1393
- const key = renamed.has(identifierName(callee)) ? staticString(args[0]) : void 0;
1394
- if (key !== void 0) usedKeys.push({
1395
- key,
1396
- file,
1397
- loose: true
1398
- });
1399
- return;
1400
- }
1401
- const key = staticString(args[0]);
1402
- if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
1403
- } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
1963
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1964
+ const missing = [];
1965
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
1966
+ locale: cfg.sourceLocale,
1967
+ key,
1968
+ source: extracted.get(key)?.message
1404
1969
  });
1970
+ for (const locale of cfg.locales) {
1971
+ if (locale === cfg.sourceLocale) continue;
1972
+ for (const key of needed) if (!flat[locale]?.[key]) missing.push({
1973
+ locale,
1974
+ key,
1975
+ source: source[key] ?? extracted.get(key)?.message
1976
+ });
1977
+ }
1978
+ const broken = [];
1979
+ const add = (locale, key, issues) => {
1980
+ for (const issue of issues) broken.push({
1981
+ locale,
1982
+ key,
1983
+ severity: issue.severity,
1984
+ issue: issue.message
1985
+ });
1986
+ };
1987
+ const divergent = [];
1988
+ for (const [key, entry] of extracted) {
1989
+ const written = source[key];
1990
+ if (written && written !== entry.message) divergent.push({
1991
+ key,
1992
+ catalog: written,
1993
+ code: siteOf(entry)
1994
+ });
1995
+ }
1996
+ for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1997
+ for (const locale of cfg.locales) {
1998
+ if (locale === cfg.sourceLocale) continue;
1999
+ for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
2000
+ if (!translated) continue;
2001
+ add(locale, key, validateMessage(translated, locale));
2002
+ const text = sourceText[key];
2003
+ if (text) add(locale, key, validatePair(text, translated));
2004
+ }
2005
+ }
2006
+ const extra = [];
2007
+ for (const locale of cfg.locales) {
2008
+ if (locale === cfg.sourceLocale) continue;
2009
+ for (const key of Object.keys(flat[locale] ?? {})) {
2010
+ if (source[key] !== void 0 || extracted.has(key)) continue;
2011
+ extra.push({
2012
+ locale,
2013
+ key,
2014
+ files: used.get(key) ?? []
2015
+ });
2016
+ }
2017
+ }
1405
2018
  return {
1406
- tagged,
1407
- usedKeys,
1408
- strayImports,
1409
- ...missed.length > 0 && { missed }
2019
+ ok: gatePasses({
2020
+ missing,
2021
+ unknown,
2022
+ broken
2023
+ }),
2024
+ missing,
2025
+ unknown,
2026
+ broken,
2027
+ extra,
2028
+ collisions: collisionEntries(registry),
2029
+ divergent,
2030
+ outdated: outdatedTranslations(cfg, shipped, fingerprints)
1410
2031
  };
1411
2032
  }
1412
- function renamedBindings(program, names) {
1413
- const out = /* @__PURE__ */ new Set();
1414
- const add = (node) => {
1415
- const name = identifierName(node);
1416
- if (name && !names.has(name)) out.add(name);
1417
- };
1418
- walk(program, (node) => {
1419
- if (node.type === "ImportDeclaration") {
1420
- if (node.source.value !== "virtual:verbaly") return;
1421
- for (const spec of node.specifiers) if (spec.type === "ImportSpecifier" && identifierName(spec.imported) === "t") add(spec.local);
1422
- } else if (node.type === "VariableDeclarator") {
1423
- const id = node.id;
1424
- const init = node.init;
1425
- if (id.type === "Identifier" && init && handsOutT(init)) add(id);
1426
- if (id.type !== "ObjectPattern") return;
1427
- for (const property of id.properties) {
1428
- if (property.type !== "ObjectProperty" || property.computed) continue;
1429
- if (identifierName(property.key) === "t") add(property.value);
1430
- }
2033
+ function formatCheckResult(result, root) {
2034
+ const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
2035
+ const lines = [];
2036
+ if (result.missing.length > 0) {
2037
+ lines.push("missing translations:");
2038
+ for (const entry of result.missing) {
2039
+ const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
2040
+ lines.push(` [${entry.locale}] ${entry.key}${hint}`);
1431
2041
  }
1432
- });
1433
- return out;
1434
- }
1435
- function handsOutT(init) {
1436
- const call = init.type === "AwaitExpression" ? init.argument : init;
1437
- if (call.type !== "CallExpression") return false;
1438
- const callee = identifierName(call.callee);
1439
- return init.type === "AwaitExpression" ? callee === "getT" : callee === "useT";
1440
- }
1441
- function identifierName(node) {
1442
- return node?.type === "Identifier" ? node.name : "";
1443
- }
1444
- function renamedTag(tag, renamed) {
1445
- if (renamed.size === 0) return void 0;
1446
- const name = identifierName(tag);
1447
- if (renamed.has(name)) return name;
1448
- if (tag.type !== "CallExpression") return void 0;
1449
- const callee = tag.callee;
1450
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1451
- if (identifierName(callee.property) !== "id") return void 0;
1452
- const object = identifierName(callee.object);
1453
- return renamed.has(object) ? object : void 0;
1454
- }
1455
- function collectDeclaredKeys(node, file, out) {
1456
- if (node?.type !== "ObjectExpression") return;
1457
- for (const property of node.properties) {
1458
- if (property.type !== "ObjectProperty") continue;
1459
- const value = property.value;
1460
- const key = staticString(value);
1461
- if (key !== void 0) {
1462
- if (key !== "") out.push(usedKey(key, file, value));
1463
- } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
1464
2042
  }
2043
+ if (result.unknown.length > 0) {
2044
+ lines.push("unknown keys (not in any catalog):");
2045
+ for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
2046
+ }
2047
+ const errors = result.broken.filter((entry) => entry.severity === "error");
2048
+ if (errors.length > 0) {
2049
+ lines.push("broken translations:");
2050
+ for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2051
+ }
2052
+ return lines.join("\n");
1465
2053
  }
1466
- function usedKey(key, file, node) {
1467
- return node?.type === "StringLiteral" ? {
1468
- key,
1469
- file
1470
- } : {
1471
- key,
1472
- file,
1473
- loose: true
1474
- };
2054
+ function checkNextSteps(result, cliReachable = true) {
2055
+ const steps = [];
2056
+ if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
2057
+ if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
2058
+ if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
2059
+ if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
2060
+ return steps.join("\n");
1475
2061
  }
1476
- function staticString(node) {
1477
- if (!node) return void 0;
1478
- if (node.type === "StringLiteral") return node.value;
1479
- if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
1480
- if (node.type === "JSXExpressionContainer") return staticString(node.expression);
2062
+ function formatCheckWarnings(result, root, options = {}) {
2063
+ const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2064
+ for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
2065
+ for (const entry of result.collisions) lines.push(` ${formatFinding({
2066
+ kind: "collision",
2067
+ ...entry
2068
+ }, root)}`);
2069
+ for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says "${truncate(code.message, 40)}" (${sourcePlace(code, root)}): the code wins, so edit the text there (extract writes it into the catalog)`);
2070
+ if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2071
+ kind: "outdated",
2072
+ ...entry
2073
+ }, root)}`);
2074
+ return lines.join("\n");
1481
2075
  }
1482
- const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
1483
- function collectStrayImports(node, file, out) {
1484
- const source = node.source;
1485
- if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
1486
- for (const spec of node.specifiers) {
1487
- if (spec.type !== "ImportSpecifier") continue;
1488
- const imported = spec.imported;
1489
- if (imported.type !== "Identifier") continue;
1490
- const name = imported.name;
1491
- if (name === "t" || name === DEFINE_KEYS) out.push({
1492
- name,
1493
- source: source.value,
1494
- file
2076
+ function githubCheckAnnotations(result, registry, cfg, options = {}) {
2077
+ const messages = registry.messages();
2078
+ const rel = (file) => escapeProperty(relative(cfg.root, file).replaceAll("\\", "/"));
2079
+ const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
2080
+ const lines = [];
2081
+ const byKey = /* @__PURE__ */ new Map();
2082
+ for (const entry of result.missing) {
2083
+ const grouped = byKey.get(entry.key);
2084
+ if (grouped) grouped.locales.push(entry.locale);
2085
+ else byKey.set(entry.key, {
2086
+ ...entry,
2087
+ locales: [entry.locale]
1495
2088
  });
1496
2089
  }
1497
- }
1498
- function handleTrans(code, node, file, tagged, usedKeys, names) {
1499
- const opening = node.openingElement;
1500
- const nameNode = opening.name;
1501
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
1502
- const attrs = opening.attributes;
1503
- const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
1504
- const children = node.children;
1505
- const push = (key, built) => tagged.push({
1506
- key,
1507
- message: built.text,
1508
- params: built.params,
1509
- start: node.start,
1510
- end: node.end,
1511
- tagStart: nameNode.start,
1512
- tagEnd: nameNode.end,
1513
- file,
1514
- jsx: {
1515
- name: nameNode.name,
1516
- components: built.components
1517
- }
1518
- });
1519
- if (idAttr) {
1520
- const value = idAttr.value;
1521
- const id = staticString(value);
1522
- if (id === void 0) return;
1523
- if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
1524
- const built = buildTransMessage(code, children, names);
1525
- if (built?.text.trim()) {
1526
- push(id, built);
1527
- return;
1528
- }
2090
+ for (const entry of byKey.values()) {
2091
+ const origin = messages.get(entry.key);
2092
+ const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
2093
+ const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
2094
+ if (origin) lines.push(`::error ${at(origin.file, origin.line)}::${text}`);
2095
+ else lines.push(`::error::${text}`);
2096
+ }
2097
+ for (const entry of result.unknown) {
2098
+ const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
2099
+ const file = entry.files[0];
2100
+ lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);
2101
+ }
2102
+ for (const entry of result.broken) {
2103
+ const origin = messages.get(entry.key);
2104
+ const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
2105
+ const command = entry.severity === "error" ? "error" : "warning";
2106
+ if (!origin) {
2107
+ lines.push(`::${command}::${text}`);
2108
+ continue;
1529
2109
  }
1530
- usedKeys.push(usedKey(id, file, value));
1531
- return;
2110
+ lines.push(`::${command} ${at(origin.file, origin.line)}::${text}`);
1532
2111
  }
1533
- if (attrs.length > 0) return;
1534
- if (!children?.length) return;
1535
- const built = buildTransMessage(code, children, names);
1536
- if (!built || !built.text.trim()) return;
1537
- push(stableKey(built.text), built);
1538
- }
1539
- function explicitId(tag, names) {
1540
- if (tag.type !== "CallExpression") return void 0;
1541
- const callee = tag.callee;
1542
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1543
- const prop = callee.property;
1544
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
1545
- const obj = callee.object;
1546
- if (!isTReference(obj, names)) return void 0;
1547
- const args = tag.arguments;
1548
- const first = args[0];
1549
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
1550
- return {
1551
- key: first.value,
1552
- refStart: obj.start,
1553
- refEnd: obj.end
1554
- };
1555
- }
1556
- function buildTransMessage(code, children, names) {
1557
- const params = [];
1558
- const components = [];
1559
- const takenParams = /* @__PURE__ */ new Map();
1560
- const takenTags = /* @__PURE__ */ new Map();
1561
- function walkChildren(nodes) {
1562
- let text = "";
1563
- for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
1564
- else if (child.type === "JSXExpressionContainer") {
1565
- const expr = child.expression;
1566
- if (expr.type === "JSXEmptyExpression") continue;
1567
- if (expr.type === "StringLiteral") {
1568
- text += escapeText(expr.value);
1569
- continue;
1570
- }
1571
- if (containsTaggedT(expr, names)) return void 0;
1572
- const source = code.slice(expr.start, expr.end);
1573
- const name = uniqueName(deriveName(expr, params.length), source, takenParams);
1574
- params.push({
1575
- name,
1576
- start: expr.start,
1577
- end: expr.end
1578
- });
1579
- text += `{${name}}`;
1580
- } else if (child.type === "JSXElement") {
1581
- const opening = child.openingElement;
1582
- const nameNode = opening.name;
1583
- if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
1584
- const source = selfClosedSource(code, opening);
1585
- const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
1586
- if (!components.some((c) => c.name === tag)) components.push({
1587
- name: tag,
1588
- source
1589
- });
1590
- if (!child.closingElement) text += `<${tag}/>`;
1591
- else {
1592
- const inner = walkChildren(child.children);
1593
- if (inner === void 0) return void 0;
1594
- text += `<${tag}>${inner}</${tag}>`;
1595
- }
1596
- } else return;
1597
- return text;
2112
+ for (const entry of result.extra) {
2113
+ const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
2114
+ const file = entry.files[0];
2115
+ lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);
1598
2116
  }
1599
- const text = walkChildren(children);
1600
- if (text === void 0) return void 0;
1601
- return {
1602
- text,
1603
- params,
1604
- components
1605
- };
1606
- }
1607
- function cleanJsxText(raw) {
1608
- const lines = raw.split(/\r\n|[\r\n]/);
1609
- let out = "";
1610
- for (let i = 0; i < lines.length; i++) {
1611
- let line = lines[i].replace(/\t/g, " ");
1612
- if (i !== 0) line = line.replace(/^ +/, "");
1613
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
1614
- if (!line) continue;
1615
- if (out && i !== 0) out += " ";
1616
- out += line;
2117
+ for (const { key, sites } of result.collisions) {
2118
+ const texts = new Set(sites.map((place) => place.message)).size;
2119
+ const text = escapeData(`"${key}" has ${counted(texts, "text")}, and every place shows the first one`);
2120
+ for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);
1617
2121
  }
1618
- return out;
1619
- }
1620
- function selfClosedSource(code, opening) {
1621
- const src = code.slice(opening.start, opening.end);
1622
- return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
1623
- }
1624
- function containsTaggedT(node, names) {
1625
- let found = false;
1626
- walk(node, (n) => {
1627
- if (n.type !== "TaggedTemplateExpression") return;
1628
- const tag = n.tag;
1629
- if (isTReference(tag, names) || explicitId(tag, names)) found = true;
1630
- });
1631
- return found;
1632
- }
1633
- function isTReference(node, names) {
1634
- if (node.type === "Identifier") return names.has(node.name);
1635
- if (node.type === "MemberExpression" && !node.computed) {
1636
- const prop = node.property;
1637
- return prop.type === "Identifier" && names.has(prop.name);
2122
+ for (const { key, code } of result.divergent) {
2123
+ const text = escapeData(`"${key}": the source catalog has another text, the code's one ships`);
2124
+ lines.push(`::warning ${at(code.file, code.line)}::${text}`);
1638
2125
  }
1639
- return false;
1640
- }
1641
- function buildMessage(code, quasi, names) {
1642
- const quasis = quasi.quasis;
1643
- const expressions = quasi.expressions;
1644
- const params = [];
1645
- const taken = /* @__PURE__ */ new Map();
1646
- let text = escapeText(cookedValue(quasis[0]));
1647
- for (let i = 0; i < expressions.length; i++) {
1648
- const expr = expressions[i];
1649
- if (!expr) return void 0;
1650
- if (containsTaggedT(expr, names)) return void 0;
1651
- const source = code.slice(expr.start, expr.end);
1652
- const name = uniqueName(deriveName(expr, i), source, taken);
1653
- params.push({
1654
- name,
1655
- start: expr.start,
1656
- end: expr.end
1657
- });
1658
- text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
2126
+ const outdated = options.outdatedFails ? "error" : "warning";
2127
+ for (const { locale, key } of result.outdated) {
2128
+ const text = escapeData(`[${locale}] ${key}: translated from an older source text`);
2129
+ lines.push(`::${outdated} file=${rel(catalogPath(cfg, locale))}::${text}`);
1659
2130
  }
1660
- return {
1661
- text,
1662
- params
1663
- };
1664
- }
1665
- function cookedValue(element) {
1666
- if (!element) return "";
1667
- const value = element.value;
1668
- return value.cooked ?? value.raw;
2131
+ return lines;
1669
2132
  }
1670
- function escapeText(text) {
1671
- return text.replace(/[{}]/g, (m) => m + m);
2133
+ function escapeData(text) {
2134
+ return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1672
2135
  }
1673
- function deriveName(expr, index) {
1674
- if (expr.type === "Identifier") return expr.name;
1675
- if (expr.type === "MemberExpression" && !expr.computed) {
1676
- const prop = expr.property;
1677
- if (prop.type === "Identifier") return prop.name;
1678
- }
1679
- return `_${index}`;
2136
+ function escapeProperty(text) {
2137
+ return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
1680
2138
  }
1681
- function uniqueName(base, source, taken) {
1682
- let name = base;
1683
- let n = 2;
1684
- while (taken.has(name) && taken.get(name) !== source) {
1685
- name = `${base}${n}`;
1686
- n += 1;
1687
- }
1688
- taken.set(name, source);
1689
- return name;
2139
+ //#endregion
2140
+ //#region src/params.ts
2141
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
2142
+ "number",
2143
+ "integer",
2144
+ "percent",
2145
+ "currency"
2146
+ ]);
2147
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
2148
+ function collectParams(message) {
2149
+ const out = /* @__PURE__ */ new Map();
2150
+ visit(parse(message, parseIcu), out);
2151
+ return out;
1690
2152
  }
1691
- function walk(node, visit) {
1692
- visit(node);
1693
- for (const key in node) {
1694
- if (SKIP_KEYS.has(key)) continue;
1695
- const value = node[key];
1696
- if (Array.isArray(value)) {
1697
- for (const item of value) if (isNode(item)) walk(item, visit);
1698
- } else if (isNode(value)) walk(value, visit);
2153
+ function visit(nodes, out) {
2154
+ for (const node of nodes) {
2155
+ if (node.kind !== "param") continue;
2156
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
2157
+ out.set(node.name, types);
2158
+ if (node.variants) {
2159
+ for (const [key, body] of node.variants) {
2160
+ if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
2161
+ else if (key !== "other") types.add("string");
2162
+ visit(body, out);
2163
+ }
2164
+ if (types.size === 0) types.add("string");
2165
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
2166
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
2167
+ else types.add("unknown");
1699
2168
  }
1700
2169
  }
1701
- function isNode(value) {
1702
- return typeof value === "object" && value !== null && typeof value.type === "string";
2170
+ function renderParamType(types) {
2171
+ if (types.has("unknown") || types.size === 0) return "unknown";
2172
+ const members = /* @__PURE__ */ new Set();
2173
+ if (types.has("number")) members.add("number");
2174
+ if (types.has("string")) members.add("string");
2175
+ if (types.has("date")) for (const m of [
2176
+ "Date",
2177
+ "number",
2178
+ "string"
2179
+ ]) members.add(m);
2180
+ return [...members].join(" | ");
1703
2181
  }
1704
2182
  //#endregion
1705
- //#region src/sfc.ts
1706
- const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
1707
- function analyzeFile(code, file) {
1708
- if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
2183
+ //#region src/tsconfig.ts
2184
+ function readTsconfig(root) {
2185
+ const path = join(root, "tsconfig.json");
2186
+ let text;
1709
2187
  try {
1710
- return analyze(code, file);
1711
- } catch (error) {
1712
- return {
1713
- tagged: [],
1714
- usedKeys: [],
1715
- strayImports: [],
1716
- parseError: parseErrorMessage(error)
1717
- };
2188
+ text = readFileSync(path, "utf8");
2189
+ } catch {
2190
+ return "no-tsconfig";
1718
2191
  }
1719
- }
1720
- const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
1721
- const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
1722
- const COMMENT_RE = /<!--[\s\S]*?-->/g;
1723
- const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
1724
- const CANDIDATE_SVELTE = /(?<![\w$])\$?t(?=[`(]|\.id\()/g;
1725
- const CANDIDATE_VUE = /(?<![\w$])t(?=[`(]|\.id\()/g;
1726
- const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
1727
- const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
1728
- function analyzeSfc(code, file) {
1729
- const svelte = file.endsWith(".svelte");
1730
- const options = svelte ? { tNames: ["t", "$t"] } : void 0;
1731
- const tagged = [];
1732
- const usedKeys = [];
1733
- const strayImports = [];
1734
- let parseError;
1735
- const block = (segment, offset) => {
1736
- parseError ??= segment.error;
1737
- merge(segment.analysis, offset, false);
2192
+ const errors = [];
2193
+ const json = parse$2(text, errors, { allowTrailingComma: true });
2194
+ if (errors.length > 0 || typeof json !== "object" || json === null || Array.isArray(json)) return "unreadable";
2195
+ return {
2196
+ path,
2197
+ text,
2198
+ json
1738
2199
  };
1739
- const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
1740
- if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
1741
- for (const match of code.matchAll(SCRIPT_RE)) {
1742
- const content = match[2];
1743
- if (!content) continue;
1744
- block(analyzeSegment(content, file, options), match.index + match[1].length);
1745
- }
1746
- const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
1747
- const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
1748
- const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
1749
- let range = 0;
1750
- let consumedTo = 0;
1751
- for (const match of markup.matchAll(candidates)) {
1752
- const start = match.index;
1753
- if (start < consumedTo) continue;
1754
- while (range < ranges.length && ranges[range][1] <= start) range += 1;
1755
- if (range >= ranges.length || start < ranges[range][0]) continue;
1756
- const end = expressionExtent(markup, start);
1757
- if (end === void 0) continue;
1758
- merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
1759
- consumedTo = end;
1760
- }
2200
+ }
2201
+ function covered(list, entry) {
2202
+ if (!Array.isArray(list)) return false;
2203
+ return list.some((item) => {
2204
+ if (typeof item !== "string") return false;
2205
+ const pattern = item.replace(/^\.\//, "").replace(/\/+$/, "");
2206
+ return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);
2207
+ });
2208
+ }
2209
+ function formatting(text) {
2210
+ const indent = /\n([ \t]+)\S/.exec(text)?.[1] ?? " ";
1761
2211
  return {
1762
- tagged,
1763
- usedKeys,
1764
- strayImports,
1765
- ...parseError && { parseError }
2212
+ insertSpaces: !indent.startsWith(" "),
2213
+ tabSize: indent.startsWith(" ") ? 1 : indent.length,
2214
+ eol: text.includes("\r\n") ? "\r\n" : "\n"
1766
2215
  };
1767
- function merge(analysis, offset, markupSegment) {
1768
- if (!analysis) return;
1769
- for (const msg of analysis.tagged) tagged.push({
1770
- ...msg,
1771
- start: msg.start + offset,
1772
- end: msg.end + offset,
1773
- tagStart: msg.tagStart + offset,
1774
- tagEnd: msg.tagEnd + offset,
1775
- params: msg.params.map((p) => ({
1776
- ...p,
1777
- start: p.start + offset,
1778
- end: p.end + offset
1779
- })),
1780
- ...markupSegment && { singleQuote: true }
1781
- });
1782
- usedKeys.push(...analysis.usedKeys);
1783
- strayImports.push(...analysis.strayImports);
2216
+ }
2217
+ function typesIncluded(root, file) {
2218
+ const read = readTsconfig(root);
2219
+ if (typeof read === "string") return read;
2220
+ const entry = relative(root, file).replaceAll("\\", "/");
2221
+ const { include, files } = read.json;
2222
+ if (covered(include, entry) || covered(files, entry)) return "present";
2223
+ return "missing";
2224
+ }
2225
+ function includeTypes(root, file) {
2226
+ const read = readTsconfig(root);
2227
+ if (typeof read === "string") return read;
2228
+ const entry = relative(root, file).replaceAll("\\", "/");
2229
+ const { include, files } = read.json;
2230
+ if (covered(include, entry) || covered(files, entry)) return "present";
2231
+ const options = { formattingOptions: formatting(read.text) };
2232
+ const edits = Array.isArray(include) ? modify(read.text, ["include", -1], entry, {
2233
+ ...options,
2234
+ isArrayInsertion: true
2235
+ }) : Array.isArray(files) && include === void 0 ? modify(read.text, ["files", -1], entry, {
2236
+ ...options,
2237
+ isArrayInsertion: true
2238
+ }) : modify(read.text, ["include"], ["**/*", entry], options);
2239
+ writeFileSync(read.path, applyEdits(read.text, edits));
2240
+ return "added";
2241
+ }
2242
+ //#endregion
2243
+ //#region src/warn.ts
2244
+ const warned = /* @__PURE__ */ new Set();
2245
+ function warnOnce(message, dedupeKey = message) {
2246
+ if (warned.has(dedupeKey)) return;
2247
+ warned.add(dedupeKey);
2248
+ console.warn(`[verbaly] ${message}`);
2249
+ }
2250
+ const DTS_HEADER = "// generated by verbaly: do not edit";
2251
+ function generateDts(catalog, options = {}) {
2252
+ const lines = [];
2253
+ const locales = options.locales?.length ? [...options.locales].sort(byCodeUnit).map((locale) => JSON.stringify(locale)).join(" | ") : "string";
2254
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
2255
+ const params = collectParams(message);
2256
+ if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
2257
+ else {
2258
+ const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
2259
+ lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
2260
+ }
1784
2261
  }
2262
+ return `${DTS_HEADER}
2263
+ declare module 'virtual:verbaly' {
2264
+ export interface VerbalyMessages {
2265
+ ${lines.join("\n")}
2266
+ }
2267
+ export type VerbalyKey = keyof VerbalyMessages & string;
2268
+ export type VerbalyLocale = ${locales};
2269
+
2270
+ export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
2271
+ export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
2272
+
2273
+ export const verbaly: import('verbaly').Verbaly;
2274
+
2275
+ export const sourceLocale: VerbalyLocale;
2276
+ export const locales: string[];
2277
+ export const routing: import('verbaly').Routing;
2278
+ export function localePath(
2279
+ locale: string,
2280
+ options?: { path?: string; base?: string },
2281
+ ): string;
2282
+ export function localeFromPath(options?: {
2283
+ path?: string;
2284
+ base?: string;
2285
+ }): string | undefined;
2286
+ export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
2287
+ export function createInstance(
2288
+ options?: import('verbaly').VerbalyOptions,
2289
+ ): import('verbaly').Verbaly;
2290
+ export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
2291
+
2292
+ export function t<K extends VerbalyKey | TemplateStringsArray>(
2293
+ first: K,
2294
+ ...rest: K extends VerbalyKey
2295
+ ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2296
+ : unknown[]
2297
+ ): string;
2298
+ export namespace t {
2299
+ export function id(
2300
+ key: string,
2301
+ ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2302
+ }
2303
+
2304
+ export function setLocale(locale: string): Promise<void>;
2305
+ export function switchLocale(
2306
+ locale: string,
2307
+ options?: Omit<
2308
+ import('verbaly').SwitchLocaleOptions,
2309
+ 'routing' | 'supported' | 'sourceLocale'
2310
+ >,
2311
+ ): Promise<void>;
2312
+ export function getLocale(): string;
2313
+ export function subscribe(listener: () => void): () => void;
2314
+
2315
+ // nested, so it augments verbaly: at the top of a script it would replace the real module
2316
+ module 'verbaly' {
2317
+ interface Register {
2318
+ t: typeof t;
2319
+ locale: VerbalyLocale;
2320
+ }
2321
+ }
2322
+ }
2323
+
2324
+ declare module 'virtual:verbaly/locale/*' {
2325
+ const messages: Record<string, string>;
2326
+ export default messages;
1785
2327
  }
1786
- function analyzeSegment(code, file, options) {
1787
- try {
1788
- return { analysis: analyze(code, file, options) };
1789
- } catch (error) {
1790
- return { error: parseErrorMessage(error) };
1791
- }
2328
+ `;
1792
2329
  }
1793
- function blank(source, re) {
1794
- return source.replace(re, (m) => " ".repeat(m.length));
2330
+ function projectDtsOptions(cfg) {
2331
+ return {
2332
+ inlineCatalog: cfg.render.inlineCatalog === true,
2333
+ locales: cfg.locales
2334
+ };
1795
2335
  }
1796
- function braceRanges(markup) {
1797
- const ranges = [];
1798
- let i = 0;
1799
- while (i < markup.length) {
1800
- if (markup[i] === "{") {
1801
- const end = balancedEnd(markup, i);
1802
- if (end !== void 0) {
1803
- ranges.push([i + 1, end - 1]);
1804
- i = end;
1805
- continue;
1806
- }
1807
- }
1808
- i += 1;
2336
+ function writeDts(cfg, catalog, file) {
2337
+ const target = file === void 0 ? cfg.dts : file;
2338
+ if (target === false) return void 0;
2339
+ let existing;
2340
+ try {
2341
+ existing = readFileSync(target, "utf8");
2342
+ } catch {}
2343
+ const content = withLineEndings(generateDts(catalog, projectDtsOptions(cfg)), existing);
2344
+ const changed = existing !== content;
2345
+ if (changed) {
2346
+ mkdirSync(dirname(target), { recursive: true });
2347
+ writeFileSync(target, content);
2348
+ }
2349
+ removeRootDts(cfg, target);
2350
+ if (resolve(target).startsWith(resolve(cfg.root, ".verbaly") + sep)) {
2351
+ const ignore = join(cfg.root, ".verbaly", ".gitignore");
2352
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
2353
+ const state = includeTypes(cfg.root, target);
2354
+ const entry = relative(cfg.root, target).replaceAll("\\", "/");
2355
+ if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
2356
+ else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
1809
2357
  }
1810
- return ranges;
2358
+ return {
2359
+ file: target,
2360
+ changed
2361
+ };
1811
2362
  }
1812
- function vueExpressionRanges(markup) {
1813
- const ranges = [];
1814
- for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
1815
- for (const match of markup.matchAll(DIRECTIVE_RE)) {
1816
- const valueStart = match.index + match[0].length - match[1].length + 1;
1817
- ranges.push([valueStart, valueStart + match[1].length - 2]);
2363
+ function removeRootDts(cfg, target) {
2364
+ const old = join(cfg.root, "verbaly.d.ts");
2365
+ if (resolve(target) === resolve(old)) return;
2366
+ let head;
2367
+ try {
2368
+ head = readFileSync(old, "utf8").slice(0, 36);
2369
+ } catch {
2370
+ return;
1818
2371
  }
1819
- return ranges.sort((a, b) => a[0] - b[0]);
2372
+ if (head !== "// generated by verbaly: do not edit") return;
2373
+ rmSync(old);
2374
+ warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
1820
2375
  }
1821
- function expressionExtent(code, start) {
1822
- let i = start;
1823
- if (code[i] === "$") i += 1;
1824
- i += 1;
1825
- if (code.startsWith(".id(", i)) {
1826
- const close = balancedEnd(code, i + 3);
1827
- if (close === void 0 || code[close] !== "`") return void 0;
1828
- return balancedEnd(code, close);
1829
- }
1830
- if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
2376
+ //#endregion
2377
+ //#region src/bundle.ts
2378
+ function isExcluded(key, prefixes) {
2379
+ return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
1831
2380
  }
1832
- function balancedEnd(code, open) {
1833
- const stack = [];
1834
- let i = open;
1835
- while (i < code.length) {
1836
- const ch = code[i];
1837
- if (stack[stack.length - 1] === "`") {
1838
- if (ch === "\\") i += 1;
1839
- else if (ch === "`") stack.pop();
1840
- else if (ch === "$" && code[i + 1] === "{") {
1841
- stack.push("{");
1842
- i += 1;
1843
- }
1844
- } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
1845
- else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
1846
- else if (ch === ")" || ch === "}") {
1847
- if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
1848
- stack.pop();
2381
+ function auditBundle(cfg, catalogs, registry) {
2382
+ const prefixes = cfg.bundle.exclude ?? [];
2383
+ if (prefixes.length === 0) return [];
2384
+ const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
2385
+ const used = registry.usedKeys();
2386
+ const issues = [];
2387
+ for (const prefix of prefixes) {
2388
+ if (!source.some((key) => isExcluded(key, [prefix]))) {
2389
+ issues.push({
2390
+ prefix,
2391
+ problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
2392
+ fix: "check the spelling against your catalog, or drop it from bundle.exclude"
2393
+ });
2394
+ continue;
1849
2395
  }
1850
- i += 1;
1851
- if (stack.length === 0) return i;
2396
+ const files = /* @__PURE__ */ new Set();
2397
+ for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
2398
+ if (files.size > 0) issues.push({
2399
+ prefix,
2400
+ problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
2401
+ fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
2402
+ });
1852
2403
  }
2404
+ return issues;
1853
2405
  }
1854
- function stringEnd(code, start) {
1855
- const quote = code[start];
1856
- let i = start + 1;
1857
- while (i < code.length) if (code[i] === "\\") i += 2;
1858
- else if (code[i] === quote) return i;
1859
- else i += 1;
1860
- return code.length;
2406
+ function formatBundleIssue(issue) {
2407
+ return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1861
2408
  }
1862
2409
  //#endregion
1863
- //#region src/extract.ts
1864
- async function extractProject(cfg) {
1865
- const files = await glob(cfg.include, {
2410
+ //#region src/scope.ts
2411
+ const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
2412
+ const NOT_SOURCE = [
2413
+ "**/node_modules/**",
2414
+ "**/dist/**",
2415
+ "**/build/**",
2416
+ "**/out/**",
2417
+ "**/coverage/**"
2418
+ ];
2419
+ function relativeId(cfg, id) {
2420
+ return relative(cfg.root, id).replaceAll("\\", "/");
2421
+ }
2422
+ function suggestedPattern(rel) {
2423
+ const slash = rel.indexOf("/");
2424
+ return slash < 0 ? rel : `${rel.slice(0, slash)}/**/*.${SOURCE_EXTENSIONS}`;
2425
+ }
2426
+ function createOutsideCheck(cfg) {
2427
+ if (cfg.include.length === 0) return () => void 0;
2428
+ const included = picomatch(cfg.include);
2429
+ const excluded = picomatch(cfg.exclude);
2430
+ return (code, id) => {
2431
+ const rel = relativeId(cfg, id);
2432
+ if (rel.startsWith("..") || included(rel) || excluded(rel)) return void 0;
2433
+ if (!TAGGED_HINT.test(code)) return void 0;
2434
+ if (analyzeFile(code, id).tagged.length === 0) return void 0;
2435
+ return {
2436
+ file: id,
2437
+ pattern: suggestedPattern(rel)
2438
+ };
2439
+ };
2440
+ }
2441
+ async function filesOutsideInclude(cfg) {
2442
+ if (cfg.include.length === 0) return [];
2443
+ const check = createOutsideCheck(cfg);
2444
+ const files = await glob([`**/*.${SOURCE_EXTENSIONS}`], {
1866
2445
  cwd: cfg.root,
1867
- ignore: cfg.exclude,
2446
+ ignore: [...NOT_SOURCE, ...cfg.exclude],
1868
2447
  absolute: true
1869
2448
  });
1870
- const registry = new MessageRegistry();
1871
- for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
1872
- return registry;
1873
- }
1874
- async function collectOrigins(cfg, reuse) {
1875
- const registry = reuse ?? await extractProject(cfg);
1876
- const origins = Object.create(null);
1877
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1878
- return origins;
1879
- }
1880
- function syncCatalogs(cfg, catalogs, registry) {
1881
- const added = {};
1882
- const replaced = [];
1883
- const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1884
- for (const [key, msg] of registry.messages()) {
1885
- const before = own(source, key);
1886
- if (before !== msg.message) {
1887
- if (before) replaced.push(key);
1888
- source[key] = msg.message;
1889
- (added[cfg.sourceLocale] ??= []).push(key);
1890
- }
1891
- }
1892
- const needed = Object.keys(source);
1893
- for (const locale of cfg.locales) {
1894
- if (locale === cfg.sourceLocale) continue;
1895
- const catalog = catalogs[locale] ??= emptyCatalog();
1896
- for (const key of needed) if (own(catalog, key) === void 0) {
1897
- catalog[key] = "";
1898
- (added[locale] ??= []).push(key);
1899
- }
1900
- }
1901
- return {
1902
- added,
1903
- replaced
1904
- };
1905
- }
1906
- function pruneCatalogs(cfg, catalogs, registry) {
1907
- const removed = {};
1908
- if (registry.parseErrors().length > 0) return removed;
1909
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1910
- for (const locale of cfg.locales) {
1911
- const catalog = catalogs[locale];
1912
- if (!catalog) continue;
1913
- for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1914
- delete catalog[key];
1915
- (removed[locale] ??= []).push(key);
2449
+ const found = [];
2450
+ for (const file of files.sort()) {
2451
+ let code;
2452
+ try {
2453
+ code = readFileSync(file, "utf8");
2454
+ } catch {
2455
+ continue;
1916
2456
  }
2457
+ const outside = check(code, file);
2458
+ if (outside) found.push(outside);
1917
2459
  }
1918
- return removed;
1919
- }
1920
- //#endregion
1921
- //#region src/drafts.ts
1922
- function loadDrafts(cfg) {
1923
- return loadState(cfg).drafts;
1924
- }
1925
- function saveDrafts(cfg, drafts) {
1926
- saveState(cfg, {
1927
- ...loadState(cfg),
1928
- drafts
1929
- });
1930
- }
1931
- function markDrafts(drafts, locale, keys) {
1932
- if (!keys.length) return;
1933
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1934
- }
1935
- function clearDrafts(drafts, locale, keys) {
1936
- if (!drafts[locale]) return;
1937
- if (!keys) {
1938
- delete drafts[locale];
1939
- return;
1940
- }
1941
- const drop = new Set(keys);
1942
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1943
- if (!drafts[locale].length) delete drafts[locale];
2460
+ return found;
1944
2461
  }
1945
2462
  //#endregion
1946
2463
  //#region src/doctor.ts
@@ -2047,14 +2564,23 @@ async function doctor(cfg) {
2047
2564
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
2048
2565
  if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
2049
2566
  else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
2050
- else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
2567
+ else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
2051
2568
  const scanning = cfg.include.length > 0;
2052
2569
  if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
2053
2570
  if (source && scanning && cfg.dts !== false) {
2054
- const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
2055
- if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
2056
- else if (readFileSync(dtsPath, "utf8") !== generateDts(source, { inlineCatalog: cfg.render.inlineCatalog === true })) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
2057
- else ok("types", "verbaly.d.ts is up to date");
2571
+ const dtsPath = cfg.dts;
2572
+ const shown = rel(dtsPath);
2573
+ const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
2574
+ const expected = generateDts(source, projectDtsOptions(cfg));
2575
+ if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
2576
+ else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
2577
+ else ok("types", `${shown} is up to date`);
2578
+ if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
2579
+ const state = typesIncluded(cfg.root, dtsPath);
2580
+ if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
2581
+ }
2582
+ const old = join(cfg.root, "verbaly.d.ts");
2583
+ if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
2058
2584
  }
2059
2585
  const registry = await extractProject(cfg);
2060
2586
  if (scanning) {
@@ -2063,6 +2589,12 @@ async function doctor(cfg) {
2063
2589
  const first = unreadable[0];
2064
2590
  warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
2065
2591
  }
2592
+ const outside = await filesOutsideInclude(cfg);
2593
+ if (outside.length > 0) {
2594
+ const files = outside.map((entry) => rel(entry.file));
2595
+ const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
2596
+ warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
2597
+ }
2066
2598
  const stray = registry.strayImports();
2067
2599
  if (stray.length > 0) {
2068
2600
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
@@ -2070,15 +2602,13 @@ async function doctor(cfg) {
2070
2602
  }
2071
2603
  const missed = registry.missed();
2072
2604
  if (missed.length > 0) {
2073
- const locate = createLocator();
2074
2605
  const first = missed[0];
2075
- const line = locate(first.file, first.start);
2076
- warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${rel(first.file)}${line ? `:${line}` : ""}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2606
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2077
2607
  }
2078
2608
  const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2079
2609
  if (positional.length > 0) {
2080
2610
  const first = positional[0];
2081
- warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${rel(first.file)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2611
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2082
2612
  }
2083
2613
  const escaped = [...registry.messages().values()].map((msg) => ({
2084
2614
  file: rel(msg.file),
@@ -2100,15 +2630,8 @@ async function doctor(cfg) {
2100
2630
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
2101
2631
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
2102
2632
  }
2103
- let state = {
2104
- drafts: {},
2105
- fingerprints: {}
2106
- };
2107
- try {
2108
- state = loadState(cfg);
2109
- } catch (error) {
2110
- warn("state", error.message.replace(/^\[verbaly\] /, ""), `delete ${STATE_FILE}: drafts and outdated tracking start again from the catalogs`);
2111
- }
2633
+ const { state, problem } = readState(cfg);
2634
+ if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2112
2635
  if (catalogsHealthy) {
2113
2636
  const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2114
2637
  const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
@@ -2437,6 +2960,7 @@ function toPo(sourceLocale, locale, entries) {
2437
2960
  }
2438
2961
  function parsePo(content) {
2439
2962
  const entries = Object.create(null);
2963
+ const sources = Object.create(null);
2440
2964
  let locale;
2441
2965
  let msgctxt;
2442
2966
  let msgid;
@@ -2447,7 +2971,10 @@ function parsePo(content) {
2447
2971
  if (msgid === "" && msgctxt === void 0) {
2448
2972
  const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
2449
2973
  if (lang) locale = lang;
2450
- } else if (msgctxt !== void 0 && msgid !== void 0) entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
2974
+ } else if (msgctxt !== void 0 && msgid !== void 0) {
2975
+ entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
2976
+ sources[msgctxt] = msgid;
2977
+ }
2451
2978
  msgctxt = msgid = msgstr = field = void 0;
2452
2979
  fuzzy = false;
2453
2980
  };
@@ -2487,7 +3014,8 @@ function parsePo(content) {
2487
3014
  finish();
2488
3015
  return {
2489
3016
  locale,
2490
- entries
3017
+ entries,
3018
+ sources
2491
3019
  };
2492
3020
  }
2493
3021
  function poString(text) {
@@ -2613,11 +3141,11 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2613
3141
  });
2614
3142
  for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
2615
3143
  for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
2616
- result.failed.sort((a, b) => a.locale.localeCompare(b.locale) || compare(a.keys, b.keys));
3144
+ result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
2617
3145
  return result;
2618
3146
  }
2619
3147
  function compare(a, b) {
2620
- return (a[0] ?? "").localeCompare(b[0] ?? "");
3148
+ return byCodeUnit(a[0] ?? "", b[0] ?? "");
2621
3149
  }
2622
3150
  function mergeTranslations(cfg, locale, translated, keys) {
2623
3151
  const source = readCatalog(cfg, cfg.sourceLocale);
@@ -2647,7 +3175,7 @@ function formatTranslateFailures(failed) {
2647
3175
  async function resolveProvider(cfg, model) {
2648
3176
  const configured = cfg.translate.provider;
2649
3177
  if (typeof configured === "function") return configured;
2650
- const { claudeProvider } = await import("./claude-BmD8W9uW.js");
3178
+ const { claudeProvider } = await import("./claude-DmnZ1cvR.js");
2651
3179
  return claudeProvider({ model: model ?? cfg.translate.model });
2652
3180
  }
2653
3181
  function structureMatches(source, translated) {
@@ -2751,7 +3279,8 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2751
3279
  skipped: {},
2752
3280
  unknown: {},
2753
3281
  unmatched: [],
2754
- mapped: []
3282
+ mapped: [],
3283
+ sources: {}
2755
3284
  };
2756
3285
  for (const file of files) {
2757
3286
  const parsed = parseExchangeFile(file, options.locale);
@@ -2795,6 +3324,8 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2795
3324
  }
2796
3325
  if (!options.dryRun) catalog[key] = text;
2797
3326
  (result.imported[locale] ??= []).push(key);
3327
+ const seen = parsed.sources[key];
3328
+ if (seen) (result.sources[locale] ??= {})[key] = seen;
2798
3329
  }
2799
3330
  }
2800
3331
  return result;
@@ -2807,18 +3338,20 @@ function parseExchangeFile(file, localeOverride) {
2807
3338
  if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
2808
3339
  return {
2809
3340
  locale,
2810
- entries: parsed.entries
3341
+ entries: parsed.entries,
3342
+ sources: parsed.sources
2811
3343
  };
2812
3344
  }
2813
3345
  if (/\.csv$/i.test(file)) return {
2814
3346
  locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
2815
- entries: parseCsv(content)
3347
+ ...parseCsv(content)
2816
3348
  };
2817
3349
  if (/\.po$/i.test(file)) {
2818
3350
  const parsed = parsePo(content);
2819
3351
  return {
2820
3352
  locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
2821
- entries: parsed.entries
3353
+ entries: parsed.entries,
3354
+ sources: parsed.sources
2822
3355
  };
2823
3356
  }
2824
3357
  throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
@@ -2854,15 +3387,19 @@ function newLocale(cfg, detected) {
2854
3387
  function parseXliff(content) {
2855
3388
  const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
2856
3389
  const entries = Object.create(null);
3390
+ const sources = Object.create(null);
2857
3391
  for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
2858
3392
  const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
2859
3393
  if (!id) continue;
2860
3394
  const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
2861
3395
  entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
3396
+ const source = /<source\b[^>]*>([\s\S]*?)<\/source>/.exec(match[2])?.[1];
3397
+ if (source !== void 0) sources[unescapeXml(id)] = inlineToMessage(stripCdata(source));
2862
3398
  }
2863
3399
  return {
2864
3400
  locale,
2865
- entries
3401
+ entries,
3402
+ sources
2866
3403
  };
2867
3404
  }
2868
3405
  function stripCdata(text) {
@@ -2883,13 +3420,21 @@ function parseCsv(content) {
2883
3420
  const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
2884
3421
  const keyCol = header.indexOf("key");
2885
3422
  const targetCol = header.indexOf("target");
3423
+ const sourceCol = header.indexOf("source");
2886
3424
  if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
2887
3425
  const entries = Object.create(null);
3426
+ const sources = Object.create(null);
2888
3427
  for (const row of rows.slice(1)) {
2889
3428
  const key = row[keyCol];
2890
- if (key) entries[key] = row[targetCol] ?? "";
3429
+ if (!key) continue;
3430
+ entries[key] = row[targetCol] ?? "";
3431
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
3432
+ if (source) sources[key] = source;
2891
3433
  }
2892
- return entries;
3434
+ return {
3435
+ entries,
3436
+ sources
3437
+ };
2893
3438
  }
2894
3439
  function csvRows(content) {
2895
3440
  const rows = [];
@@ -3085,12 +3630,53 @@ function migrateCatalogs(cfg, options = {}) {
3085
3630
  };
3086
3631
  }
3087
3632
  //#endregion
3088
- //#region src/warn.ts
3089
- const warned = /* @__PURE__ */ new Set();
3090
- function warnOnce(message, dedupeKey = message) {
3091
- if (warned.has(dedupeKey)) return;
3092
- warned.add(dedupeKey);
3093
- console.warn(`[verbaly] ${message}`);
3633
+ //#region src/project.ts
3634
+ async function syncProject(cfg, options = {}) {
3635
+ const registry = options.registry ?? await extractProject(cfg);
3636
+ const catalogs = options.catalogs ?? loadCatalogs(cfg);
3637
+ if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
3638
+ const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
3639
+ const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
3640
+ const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
3641
+ const result = {
3642
+ registry,
3643
+ catalogs,
3644
+ added,
3645
+ replaced,
3646
+ pruned,
3647
+ pruneBlocked,
3648
+ findings: scanFindings(cfg, registry, replaced),
3649
+ written: {}
3650
+ };
3651
+ if (options.dryRun) return result;
3652
+ const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
3653
+ if (replaced.length > 0) changed.add(cfg.sourceLocale);
3654
+ for (const locale of cfg.locales) {
3655
+ if (options.write === "changed" && !changed.has(locale)) continue;
3656
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
3657
+ }
3658
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
3659
+ try {
3660
+ result.state = updateState(cfg, catalogs);
3661
+ } catch (error) {
3662
+ result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
3663
+ }
3664
+ return result;
3665
+ }
3666
+ function confirmFromDisk(cfg, catalogs, registry) {
3667
+ const source = catalogs[cfg.sourceLocale] ?? {};
3668
+ const stale = /* @__PURE__ */ new Set();
3669
+ for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
3670
+ for (const file of stale) {
3671
+ let code;
3672
+ try {
3673
+ code = readFileSync(file, "utf8");
3674
+ } catch {
3675
+ registry.remove(file);
3676
+ continue;
3677
+ }
3678
+ registry.update(file, analyzeFile(code, file));
3679
+ }
3094
3680
  }
3095
3681
  //#endregion
3096
3682
  //#region src/render.ts
@@ -3371,7 +3957,7 @@ async function renderSite(cfg, options = {}) {
3371
3957
  base,
3372
3958
  storageKey: redirect.storageKey
3373
3959
  };
3374
- const catalogs = loadCatalogs(cfg);
3960
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg));
3375
3961
  const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
3376
3962
  if (clean) {
3377
3963
  for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
@@ -3543,7 +4129,9 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3543
4129
  const source = flat[cfg.sourceLocale] ?? {};
3544
4130
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3545
4131
  const live = effectiveDrafts(drafts, flat);
3546
- const outdated = outdatedTranslations(cfg, flat, fingerprints);
4132
+ const shipped = shippedCatalogs(cfg, flat, registry);
4133
+ const sourceText = shipped[cfg.sourceLocale];
4134
+ const outdated = outdatedTranslations(cfg, shipped, fingerprints);
3547
4135
  const locales = [];
3548
4136
  for (const locale of cfg.locales) {
3549
4137
  if (locale === cfg.sourceLocale) continue;
@@ -3553,7 +4141,7 @@ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3553
4141
  let broken = 0;
3554
4142
  for (const [key, text] of Object.entries(catalog)) {
3555
4143
  if (!text) continue;
3556
- const from = source[key] ?? extracted.get(key)?.message;
4144
+ const from = sourceText[key];
3557
4145
  if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
3558
4146
  }
3559
4147
  locales.push({
@@ -3751,7 +4339,7 @@ function wrapCode(code, file) {
3751
4339
  const s = new MagicString(code);
3752
4340
  const visited = /* @__PURE__ */ new Set();
3753
4341
  let changed = false;
3754
- walk(ast, (node) => {
4342
+ walk$1(ast, (node) => {
3755
4343
  if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
3756
4344
  if (visited.has(node)) return;
3757
4345
  processElement(node);
@@ -3880,7 +4468,7 @@ function wrapCode(code, file) {
3880
4468
  return text.length > 60 ? text.slice(0, 59) + "…" : text;
3881
4469
  }
3882
4470
  function markSubtree(node) {
3883
- walk(node, (n) => {
4471
+ walk$1(node, (n) => {
3884
4472
  if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
3885
4473
  });
3886
4474
  }
@@ -3896,7 +4484,7 @@ function hasDirective(program, value) {
3896
4484
  }
3897
4485
  function declaresT(program) {
3898
4486
  let found = false;
3899
- walk(program, (node) => {
4487
+ walk$1(program, (node) => {
3900
4488
  if (found) return;
3901
4489
  if (node.type === "ImportDeclaration") {
3902
4490
  for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
@@ -3928,7 +4516,7 @@ function hasVerbalyAttr(opening) {
3928
4516
  }
3929
4517
  function usesT(node) {
3930
4518
  let found = false;
3931
- walk(node, (n) => {
4519
+ walk$1(node, (n) => {
3932
4520
  if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
3933
4521
  if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
3934
4522
  });
@@ -3936,7 +4524,7 @@ function usesT(node) {
3936
4524
  }
3937
4525
  function containsJsx(node) {
3938
4526
  let found = false;
3939
- walk(node, (n) => {
4527
+ walk$1(node, (n) => {
3940
4528
  if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
3941
4529
  });
3942
4530
  return found;
@@ -3963,10 +4551,11 @@ Usage:
3963
4551
  verbaly wrap find hardcoded JSX text and wrap it in t\`…\` (report; --write applies)
3964
4552
  verbaly migrate port catalogs from another i18n library (report; --write applies)
3965
4553
  verbaly extract scan sources, update catalogs and types
4554
+ verbaly typegen write the TypeScript types only (CI: run it before tsc)
3966
4555
  verbaly status translation coverage per locale, at a glance
3967
4556
  verbaly check verify translations are complete (CI)
3968
4557
  verbaly translate fill missing translations via a provider (default: claude)
3969
- verbaly review list translations awaiting review: machine drafts and outdated ones (--approve accepts them)
4558
+ verbaly review [keys…] list translations awaiting review: machine drafts and outdated ones (--approve accepts them)
3970
4559
  verbaly export write translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)
3971
4560
  verbaly import <files…> fill catalogs back from translated XLIFF/CSV/PO files
3972
4561
  verbaly pseudo generate a pseudo-locale catalog for i18n QA (default: en-XA)
@@ -3984,7 +4573,7 @@ Options:
3984
4573
  --json machine-readable output (status)
3985
4574
  --drafts also fail on unreviewed machine translations (check)
3986
4575
  --outdated also fail on translations written for an older source text (check)
3987
- --approve mark listed drafts as reviewed (review)
4576
+ --approve accept what review lists, drafts and outdated, or only the keys given (review)
3988
4577
  --reporter <name> failure format: text (default) or github annotations (check)
3989
4578
  --model <id> model override for the claude provider (translate)
3990
4579
  --dry-run list what would happen, write nothing (translate, import, extract)
@@ -4094,30 +4683,28 @@ async function runCli(args = process.argv.slice(2)) {
4094
4683
  process.exitCode = 1;
4095
4684
  return;
4096
4685
  }
4686
+ const reporter = values.watch ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`)) : void 0;
4097
4687
  async function runExtract() {
4098
- const registry = await extractProject(cfg);
4099
- const catalogs = loadCatalogs(cfg);
4100
- if (values.prune) {
4101
- const removed = pruneCatalogs(cfg, catalogs, registry);
4102
- const unread = registry.parseErrors().length;
4103
- if (unread > 0) console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
4104
- for (const [locale, keys] of Object.entries(removed)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
4105
- }
4106
- const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
4107
- if (!dryRun) {
4108
- for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
4109
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
4110
- updateState(cfg, catalogs);
4688
+ const result = await syncProject(cfg, {
4689
+ prune: values.prune,
4690
+ dryRun
4691
+ });
4692
+ if (result.pruneBlocked) {
4693
+ const unread = result.registry.parseErrors().length;
4694
+ console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
4111
4695
  }
4112
- const total = registry.messages().size;
4696
+ for (const [locale, keys] of Object.entries(result.pruned)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
4697
+ const total = result.registry.messages().size;
4113
4698
  console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
4114
- for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4115
- reportReplaced(cfg, registry, replaced, dryRun);
4116
- for (const entry of collisionEntries(registry)) console.warn(formatCollision(entry, cfg.root));
4117
- reportParseErrors(cfg, registry);
4118
- reportEscapedSyntax(cfg, registry);
4119
- reportMissed(cfg, registry);
4120
- reportPositional(cfg, registry);
4699
+ for (const [locale, keys] of Object.entries(result.added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4700
+ const warnings = result.findings.filter((finding) => {
4701
+ if (finding.kind !== "replaced") return true;
4702
+ console.log(` ${formatFinding(finding, cfg.root)}`);
4703
+ return false;
4704
+ });
4705
+ if (reporter) reporter.report("extract", warnings);
4706
+ else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);
4707
+ if (result.stateProblem) console.warn(` ${result.stateProblem}, so drafts and outdated translations were not updated`);
4121
4708
  }
4122
4709
  await runExtract();
4123
4710
  if (values.watch) {
@@ -4126,6 +4713,19 @@ async function runCli(args = process.argv.slice(2)) {
4126
4713
  }
4127
4714
  return;
4128
4715
  }
4716
+ if (command === "typegen") {
4717
+ const registry = await extractProject(cfg);
4718
+ const source = shippedCatalogs(cfg, loadCatalogs(cfg), registry)[cfg.sourceLocale] ?? {};
4719
+ const written = writeDts(cfg, source);
4720
+ if (!written) {
4721
+ console.log("[verbaly] no types written: dts is false in your verbaly config");
4722
+ return;
4723
+ }
4724
+ const where = relative(cfg.root, written.file).replaceAll("\\", "/");
4725
+ const how = written.changed ? "written to" : "up to date in";
4726
+ console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
4727
+ return;
4728
+ }
4129
4729
  if (command === "migrate") {
4130
4730
  const result = migrateCatalogs(cfg, {
4131
4731
  write: values.write,
@@ -4183,7 +4783,8 @@ async function runCli(args = process.argv.slice(2)) {
4183
4783
  }
4184
4784
  if (command === "status") {
4185
4785
  const registry = await extractProject(cfg);
4186
- const state = loadState(cfg);
4786
+ const { state, problem } = readState(cfg);
4787
+ if (problem) console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);
4187
4788
  const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
4188
4789
  console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));
4189
4790
  return;
@@ -4200,39 +4801,41 @@ async function runCli(args = process.argv.slice(2)) {
4200
4801
  const state = checkState(cfg, values.drafts === true || values.outdated === true);
4201
4802
  const result = check(cfg, catalogs, registry, state.fingerprints);
4202
4803
  const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
4203
- const draftKeys = Object.entries(unreviewed);
4204
4804
  const outdated = values.outdated ? result.outdated : [];
4205
- if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg.root)) console.error(line);
4805
+ const gated = { outdatedFails: values.outdated === true };
4806
+ if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg, gated)) console.error(line);
4206
4807
  else {
4207
- const warnings = formatCheckWarnings(result, cfg.root);
4808
+ const warnings = formatCheckWarnings(result, cfg.root, gated);
4208
4809
  if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\n${warnings}`);
4209
4810
  }
4210
- if (result.ok && draftKeys.length === 0 && outdated.length === 0) {
4811
+ const awaiting = [...Object.entries(unreviewed).map(([locale, keys]) => ` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`), ...byLocale(outdated).map(([locale, keys]) => ` [${locale}] ${keys.length} outdated: ${keys.join(", ")}`)];
4812
+ if (result.ok && awaiting.length === 0) {
4211
4813
  console.log("[verbaly] all translations complete ✓");
4212
4814
  return;
4213
4815
  }
4214
- if (result.ok) {
4215
- for (const [locale, keys] of draftKeys) console.error(` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`);
4216
- for (const [locale, keys] of byLocale(outdated)) console.error(` [${locale}] ${keys.length} outdated: ${keys.join(", ")}`);
4816
+ if (!result.ok) {
4817
+ const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
4818
+ const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4819
+ console.error(`${report}\n${checkNextSteps(result)}`);
4820
+ }
4821
+ if (awaiting.length > 0) {
4822
+ for (const line of awaiting) console.error(line);
4217
4823
  console.error("[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)");
4218
- process.exitCode = 1;
4219
- return;
4220
4824
  }
4221
- const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
4222
- const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4223
- console.error(`${report}\n${checkNextSteps(result)}`);
4224
4825
  process.exitCode = 1;
4225
4826
  return;
4226
4827
  }
4227
4828
  if (command === "translate") {
4228
- const catalogs = loadCatalogs(cfg);
4829
+ if (!values["dry-run"]) loadState(cfg);
4830
+ const registry = await extractProject(cfg);
4831
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
4229
4832
  const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
4230
4833
  locales: csv(values.locales),
4231
4834
  batchSize: cfg.translate.batchSize,
4232
4835
  concurrency: cfg.translate.concurrency,
4233
4836
  retries: cfg.translate.retries,
4234
4837
  dryRun: values["dry-run"],
4235
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg),
4838
+ origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
4236
4839
  onProgress: values["dry-run"] ? void 0 : reportProgress
4237
4840
  });
4238
4841
  if (values["dry-run"]) {
@@ -4244,15 +4847,24 @@ async function runCli(args = process.argv.slice(2)) {
4244
4847
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
4245
4848
  return;
4246
4849
  }
4247
- const drafts = loadDrafts(cfg);
4850
+ const source = catalogs[cfg.sourceLocale] ?? {};
4851
+ const writes = [];
4248
4852
  for (const [locale, keys] of Object.entries(result.translated)) {
4249
- const written = mergeTranslations(cfg, locale, catalogs[locale] ?? {}, keys);
4250
- markDrafts(drafts, locale, written);
4853
+ const catalog = catalogs[locale] ?? {};
4854
+ const written = mergeTranslations(cfg, locale, catalog, keys);
4855
+ writes.push({
4856
+ locale,
4857
+ draft: true,
4858
+ entries: written.map((key) => ({
4859
+ key,
4860
+ text: catalog[key]
4861
+ }))
4862
+ });
4251
4863
  console.log(` ${locale}: +${written.length} translated (draft)`);
4252
4864
  const kept = keys.length - written.length;
4253
4865
  if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
4254
4866
  }
4255
- if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
4867
+ if (writes.length > 0) recordTranslations(cfg, source, writes);
4256
4868
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4257
4869
  for (const line of formatTranslateFailures(result.failed)) console.error(line);
4258
4870
  if (result.failed.length > 0) process.exitCode = 1;
@@ -4260,40 +4872,48 @@ async function runCli(args = process.argv.slice(2)) {
4260
4872
  return;
4261
4873
  }
4262
4874
  if (command === "review") {
4875
+ const registry = await extractProject(cfg);
4263
4876
  const catalogs = loadCatalogs(cfg);
4877
+ const shipped = shippedCatalogs(cfg, catalogs, registry);
4264
4878
  const state = loadState(cfg);
4265
- const live = effectiveDrafts(state.drafts, catalogs);
4266
- const targets = values.locale ? { [values.locale]: live[values.locale] ?? [] } : live;
4267
- const entries = Object.entries(targets).filter(([, keys]) => keys.length);
4268
- const outdated = outdatedTranslations(cfg, catalogs, state.fingerprints).filter((entry) => !values.locale || entry.locale === values.locale);
4269
- if (entries.length === 0 && outdated.length === 0) {
4879
+ const only = new Set(positionals.slice(1));
4880
+ const wanted = ({ locale, key }) => (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));
4881
+ const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs)).flatMap(([locale, keys]) => keys.map((key) => ({
4882
+ locale,
4883
+ key
4884
+ }))).filter(wanted);
4885
+ const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);
4886
+ if (drafts.length === 0 && outdated.length === 0) {
4270
4887
  console.log("[verbaly] nothing awaiting review ✓");
4271
4888
  return;
4272
4889
  }
4273
4890
  if (values.approve) {
4274
- let count = 0;
4275
- for (const [locale, keys] of entries) {
4891
+ for (const [locale, keys] of byLocale(drafts)) {
4276
4892
  clearDrafts(state.drafts, locale, keys);
4277
- count += keys.length;
4278
4893
  console.log(` ${locale}: ${keys.length} approved`);
4279
4894
  }
4280
- acceptOutdated(cfg, catalogs, state.fingerprints, outdated);
4281
- for (const [locale, keys] of byLocale(outdated)) {
4282
- console.log(` ${locale}: ${keys.length} kept for the new source text`);
4283
- count += keys.length;
4284
- }
4895
+ acceptOutdated(cfg, shipped, state.fingerprints, outdated);
4896
+ for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.length} kept for the new source text`);
4285
4897
  saveState(cfg, state);
4286
- console.log(`[verbaly] ${counted(count, "translation")} marked reviewed ✓`);
4898
+ const reviewed = new Set([...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`));
4899
+ console.log(`[verbaly] ${counted(reviewed.size, "translation")} marked reviewed ✓`);
4287
4900
  return;
4288
4901
  }
4289
- if (entries.length > 0) {
4290
- const total = entries.reduce((sum, [, keys]) => sum + keys.length, 0);
4291
- console.log(`[verbaly] ${counted(total, "machine translation")} awaiting review (--approve to accept)`);
4292
- for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.join(", ")}`);
4902
+ const source = shipped[cfg.sourceLocale] ?? {};
4903
+ const show = (locale, keys) => {
4904
+ console.log(` ${locale}:`);
4905
+ for (const key of keys) {
4906
+ const translated = catalogs[locale]?.[key] ?? "";
4907
+ console.log(` ${key}: "${truncate(source[key] ?? "", 60)}" → "${truncate(translated, 60)}"`);
4908
+ }
4909
+ };
4910
+ if (drafts.length > 0) {
4911
+ console.log(`[verbaly] ${counted(drafts.length, "machine translation")} awaiting review (--approve to accept)`);
4912
+ for (const [locale, keys] of byLocale(drafts)) show(locale, keys);
4293
4913
  }
4294
4914
  if (outdated.length > 0) {
4295
4915
  console.log(`[verbaly] ${counted(outdated.length, "translation")} written for an older source text (update them, or --approve keeps them)`);
4296
- for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.join(", ")}`);
4916
+ for (const [locale, keys] of byLocale(outdated)) show(locale, keys);
4297
4917
  }
4298
4918
  return;
4299
4919
  }
@@ -4315,12 +4935,13 @@ async function runCli(args = process.argv.slice(2)) {
4315
4935
  process.exitCode = 1;
4316
4936
  return;
4317
4937
  }
4318
- const result = exportCatalogs(cfg, loadCatalogs(cfg), {
4938
+ const registry = await extractProject(cfg);
4939
+ const result = exportCatalogs(cfg, shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false }), {
4319
4940
  locales: csv(values.locales),
4320
4941
  format,
4321
4942
  out: values.out,
4322
4943
  missing: values.missing,
4323
- origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg)
4944
+ origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg, registry)
4324
4945
  });
4325
4946
  if (result.files.length === 0) {
4326
4947
  console.log("[verbaly] no target locales to export (add locales to your config)");
@@ -4338,7 +4959,9 @@ async function runCli(args = process.argv.slice(2)) {
4338
4959
  process.exitCode = 1;
4339
4960
  return;
4340
4961
  }
4341
- const catalogs = loadCatalogs(cfg);
4962
+ if (!values["dry-run"]) loadState(cfg);
4963
+ const registry = await extractProject(cfg);
4964
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
4342
4965
  const result = importCatalogs(cfg, catalogs, files, {
4343
4966
  locale: values.locale,
4344
4967
  overwrite: values.overwrite,
@@ -4355,19 +4978,27 @@ async function runCli(args = process.argv.slice(2)) {
4355
4978
  }
4356
4979
  process.exitCode = 1;
4357
4980
  }
4358
- const drafts = loadDrafts(cfg);
4359
- let draftsChanged = false;
4981
+ const writes = [];
4360
4982
  for (const [locale, keys] of Object.entries(result.imported)) {
4361
4983
  if (!values["dry-run"]) {
4362
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
4363
- if (values.draft) markDrafts(drafts, locale, keys);
4364
- else clearDrafts(drafts, locale, keys);
4365
- draftsChanged = true;
4984
+ const catalog = catalogs[locale] ?? {};
4985
+ writeCatalog(cfg, locale, catalog);
4986
+ const seen = result.sources[locale] ?? {};
4987
+ const entries = keys.map((key) => ({
4988
+ key,
4989
+ text: catalog[key],
4990
+ source: seen[key]
4991
+ }));
4992
+ writes.push({
4993
+ locale,
4994
+ entries,
4995
+ draft: values.draft === true
4996
+ });
4366
4997
  }
4367
4998
  const verb = values["dry-run"] ? "would import" : "imported";
4368
4999
  console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4369
5000
  }
4370
- if (draftsChanged) saveDrafts(cfg, drafts);
5001
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
4371
5002
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
4372
5003
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4373
5004
  for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${counted(keys.length, "unknown key")} ignored (not in the source catalog): ${keys.join(", ")}`);
@@ -4390,7 +5021,7 @@ async function runCli(args = process.argv.slice(2)) {
4390
5021
  return;
4391
5022
  }
4392
5023
  if (command === "pseudo") {
4393
- const catalogs = loadCatalogs(cfg);
5024
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg), { newKeys: false });
4394
5025
  const locale = values.locale ?? "en-XA";
4395
5026
  const keys = pseudoCatalogs(cfg, catalogs, locale);
4396
5027
  writeCatalog(cfg, locale, catalogs[locale] ?? {});
@@ -4412,67 +5043,20 @@ function formatCliError(error) {
4412
5043
  const message = error instanceof Error ? error.message : String(error);
4413
5044
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
4414
5045
  }
4415
- function reportParseErrors(cfg, registry) {
4416
- for (const { file, message } of registry.parseErrors()) {
4417
- const rel = relative(cfg.root, file).replaceAll("\\", "/");
4418
- console.warn(` ${rel}: could not be parsed (${message}), its messages were not extracted`);
4419
- }
4420
- }
4421
- function reportReplaced(cfg, registry, replaced, dryRun) {
4422
- if (replaced.length === 0) return;
4423
- const messages = registry.messages();
4424
- const locate = createLocator();
4425
- const verb = dryRun ? "would get" : "got";
4426
- for (const key of replaced) {
4427
- const msg = messages.get(key);
4428
- if (!msg) continue;
4429
- const line = locate(msg.file, msg.start);
4430
- const place = `${relative(cfg.root, msg.file).replaceAll("\\", "/")}${line ? `:${line}` : ""}`;
4431
- console.warn(` ${cfg.sourceLocale}: ${key} ${verb} the text written in ${place}, the code owns it: edit it there`);
4432
- }
4433
- }
4434
- function reportMissed(cfg, registry) {
4435
- const locate = createLocator();
4436
- for (const { name, file, start } of registry.missed()) {
4437
- const line = locate(file, start);
4438
- const place = `${relative(cfg.root, file).replaceAll("\\", "/")}${line ? `:${line}` : ""}`;
4439
- console.warn(` ${place}: ${name}\`…\` is never extracted, so it stays in the source language: name it t`);
4440
- }
4441
- }
4442
- function reportPositional(cfg, registry) {
4443
- for (const msg of registry.messages().values()) {
4444
- const nameless = msg.params.filter((param) => /^_\d+$/.test(param.name));
4445
- if (nameless.length === 0) continue;
4446
- const file = relative(cfg.root, msg.file).replaceAll("\\", "/");
4447
- const names = nameless.map((param) => `{${param.name}}`).join(", ");
4448
- console.warn(` ${file}: ${names} in "${msg.message}" reaches the translator without a name, put the value in a named variable first`);
4449
- }
4450
- }
4451
5046
  function checkState(cfg, gating) {
4452
- try {
4453
- return loadState(cfg);
4454
- } catch (error) {
4455
- if (gating) throw error;
4456
- console.warn(`${formatCliError(error)}, so outdated translations are not reported`);
4457
- return {
4458
- drafts: {},
4459
- fingerprints: {}
4460
- };
4461
- }
5047
+ if (gating) return loadState(cfg);
5048
+ const { state, problem } = readState(cfg);
5049
+ if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
5050
+ return state;
4462
5051
  }
4463
5052
  function byLocale(entries) {
4464
5053
  const out = /* @__PURE__ */ new Map();
4465
- for (const { locale, key } of entries) out.set(locale, [...out.get(locale) ?? [], key]);
4466
- return [...out];
4467
- }
4468
- function reportEscapedSyntax(cfg, registry) {
4469
- for (const msg of registry.messages().values()) {
4470
- const slice = escapedSyntax(msg.message);
4471
- if (!slice) continue;
4472
- const file = relative(cfg.root, msg.file).replaceAll("\\", "/");
4473
- console.warn(` ${file}: ${slice} renders as literal text, a tagged template has no params`);
4474
- console.warn(" use t(key, params) for a plural or format block, or pass a ${…} value");
5054
+ for (const { locale, key } of entries) {
5055
+ const keys = out.get(locale);
5056
+ if (keys) keys.push(key);
5057
+ else out.set(locale, [key]);
4475
5058
  }
5059
+ return [...out];
4476
5060
  }
4477
5061
  const COMMON_FLAGS = /* @__PURE__ */ new Set([
4478
5062
  "root",
@@ -4489,6 +5073,7 @@ const COMMAND_FLAGS = {
4489
5073
  "dry-run",
4490
5074
  "watch"
4491
5075
  ],
5076
+ typegen: [],
4492
5077
  wrap: ["write"],
4493
5078
  migrate: ["write", "plurals"],
4494
5079
  status: ["json"],
@@ -4538,6 +5123,6 @@ runCli().catch((error) => {
4538
5123
  process.exitCode = 1;
4539
5124
  });
4540
5125
  //#endregion
4541
- export { isModuleNotFound as n, counted as t };
5126
+ export { counted as n, isModuleNotFound as t };
4542
5127
 
4543
5128
  //# sourceMappingURL=cli.js.map