@worldware/msg-cli 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -167,7 +167,7 @@ msg create resource myProject messages --edit
167
167
  - Imports the project via the `#i18n/projects/<projectName>.js` alias (added by `msg init`).
168
168
  - Sets `lang` from the project's `sourceLocale` and `dir` to `rtl` for Arabic/Hebrew, `ltr` otherwise.
169
169
  - Exports a named `resource` plus an async `getMessages()` helper that returns `resource.getTranslation(getLang())`, so the resource can be pre-translated for the runtime locale.
170
- - Includes sample messages added via chainable `.add()`. Validates that the generated file is importable.
170
+ - Declares sample messages in `MsgResource.create({ messages })`, wrapped in a JSDoc const assertion (`/** @type {const} */ (…)`, the `.js` form of `as const`), so TypeScript and editors infer the resource's message keys. Validates that the generated file is importable.
171
171
  - Errors if i18n/projects or i18n/resources does not exist, the project is not found, or the resource file already exists (unless `--force`).
172
172
 
173
173
  **Generated file (ESM excerpt):**
@@ -176,11 +176,13 @@ msg create resource myProject messages --edit
176
176
  import { MsgResource, getLang } from '@worldware/msg';
177
177
  import project from '#i18n/projects/myProject.js';
178
178
 
179
- export const resource = MsgResource.create({ /* title, attributes, notes */ }, project);
180
-
181
- resource
182
- .add('sampleKey', 'Sample value.', {}, [/* notes */])
183
- .add('sampleKey2', 'Hi, {name}', { dnt: true }, [/* notes */]);
179
+ export const resource = MsgResource.create({
180
+ /* title, attributes, notes */
181
+ messages: /** @type {const} */ ([
182
+ { key: 'sampleKey', value: 'Sample value.', notes: [/* … */] },
183
+ { key: 'sampleKey2', value: 'Hi, {name}', attributes: { dnt: true }, notes: [/* … */] }
184
+ ])
185
+ }, project);
184
186
 
185
187
  export async function getMessages() {
186
188
  return await resource.getTranslation(getLang());
@@ -195,6 +197,15 @@ import { getMessages } from '#i18n/resources/messages.msg.js';
195
197
  const messages = await getMessages();
196
198
  ```
197
199
 
200
+ **Typed message keys:** with `@worldware/msg` 0.13+, the const assertion makes `resource` a `MsgResource<'sampleKey' | 'sampleKey2'>`. In a TypeScript project, or a JS project with `checkJs` / `// @ts-check`, a misspelled key is a compile error:
201
+
202
+ ```javascript
203
+ resource.get('sampleKey'); // ok
204
+ resource.get('sampleKye'); // error: not assignable to 'sampleKey' | 'sampleKey2'
205
+ ```
206
+
207
+ Add your own messages to the `messages` array to keep them typed. Messages added later with the chainable `resource.add(key, value, attributes, notes)` still work at runtime, but their keys are not part of the inferred type. Remove the `/** @type {const} */` cast to opt out of typed keys.
208
+
198
209
  ### export
199
210
 
200
211
  Serialize all MsgResource files in `i18n/resources` to XLIFF 2.2 files in `l10n/xliff`, one file per project. Does not send files for translation; use your own translation workflow with the generated XLIFF. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first).
@@ -280,7 +291,9 @@ msg import -l zh
280
291
  **Behavior:**
281
292
 
282
293
  - Recursively finds all `.xliff` and `.xlf` files under `l10n/xliff`.
283
- - Project and target locale are taken from the filename (e.g. `myApp.zh.xliff`) or from path segments (e.g. `myApp/zh/messages.xliff`).
294
+ - Project and target locale are taken from the filename (e.g. `myApp.zh.xliff`) or, when the filename has no locale, from a directory under `l10n/xliff` (e.g. `l10n/xliff/zh/myApp.xliff`). Directories above `l10n/xliff` are ignored, so a path like `/var/…` or `/tmp/…` is never read as a locale.
295
+ - `--project` and `--language` match the filename or a directory under `l10n/xliff` the same way.
296
+ - Skips (with a warning) files with no locale in the filename or under `l10n/xliff`, such as the monolingual `myApp.xliff` written by `msg export`.
284
297
  - Dynamically imports `MsgProject` from `i18n/projects` to validate target locales.
285
298
  - Skips monolingual XLIFF files (no `trgLang`).
286
299
  - Skips files whose target locale is not in the project's `targetLocales`.
@@ -383,7 +396,8 @@ The CLI does not expose a programmatic API. For library usage, see [@worldware/m
383
396
  - **Setup:** `npm install`
384
397
  - **Build:** `npm run build`
385
398
  - **Tests:** `npm run test`
386
- - **Coverage:** `npm run coverage`
399
+ - **Type-check:** `npm run typecheck` (source and tests)
400
+ - **Coverage:** `npm run coverage` (fails below 90% lines, branches, functions, or statements)
387
401
 
388
402
  Source layout:
389
403
 
@@ -9,12 +9,12 @@ import {
9
9
  } from "./chunk-HH6ZOHO4.mjs";
10
10
  import {
11
11
  dynamicImportFromUrl
12
- } from "./chunk-PO2Z7EWJ.mjs";
12
+ } from "./chunk-KRQA4FRY.mjs";
13
13
 
14
14
  // src/lib/import-helpers.ts
15
15
  import { MsgResource } from "@worldware/msg";
16
16
  import { readdir, readFile, writeFile, mkdir } from "fs/promises";
17
- import { basename, extname, join } from "path";
17
+ import { basename, extname, isAbsolute, join, relative, sep } from "path";
18
18
  import { pathToFileURL } from "url";
19
19
  import { XMLParser } from "fast-xml-parser";
20
20
  import { existsSync } from "fs";
@@ -36,52 +36,33 @@ async function findXliffFilePaths(directory) {
36
36
  }
37
37
  return result;
38
38
  }
39
- function filterXliffPathsByProject(filePaths, projectName) {
39
+ function xliffDirSegments(xliffDir, filePath) {
40
+ const rel = relative(xliffDir, filePath);
41
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
42
+ return [];
43
+ }
44
+ return rel.split(/[/\\]/).slice(0, -1);
45
+ }
46
+ function filterXliffPathsByProject(filePaths, projectName, xliffDir) {
40
47
  return filePaths.filter((p) => {
41
48
  const filename = basename(p);
42
49
  if (filename.startsWith(projectName)) return true;
43
- const pathParts = p.split(/[/\\]/);
44
- return pathParts.some((part) => part === projectName);
50
+ return xliffDirSegments(xliffDir, p).some((part) => part === projectName);
45
51
  });
46
52
  }
47
- function filterXliffPathsByLocale(filePaths, locale) {
53
+ function filterXliffPathsByLocale(filePaths, locale, xliffDir) {
48
54
  return filePaths.filter((p) => {
49
55
  const filename = basename(p);
50
56
  if (filename.includes(`.${locale}.`)) return true;
51
- const pathParts = p.split(/[/\\]/);
52
- return pathParts.some((part) => part === locale);
57
+ return xliffDirSegments(xliffDir, p).some((part) => part === locale);
53
58
  });
54
59
  }
55
60
  var LOCALE_PATTERN = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]+)*$/;
56
- function parseXliffFilename(filePath) {
61
+ function parseXliffFilename(filePath, xliffDir) {
57
62
  const filename = basename(filePath);
58
63
  const match = filename.match(XLIFF_FILENAME_PATTERN);
59
- const pathParts = filePath.split(/[/\\]/);
60
- let project;
61
- let locale;
62
- if (match) {
63
- const [, proj, loc] = match;
64
- project = proj ?? basename(filename, extname(filename));
65
- locale = loc;
66
- } else {
67
- project = basename(filename, extname(filename));
68
- }
69
- if (!locale) {
70
- for (const part of pathParts) {
71
- if (LOCALE_PATTERN.test(part) && part.length >= 2) {
72
- locale = part;
73
- break;
74
- }
75
- }
76
- }
77
- if (!project && pathParts.length >= 2) {
78
- for (const part of pathParts) {
79
- if (part && !XLIFF_EXTENSIONS.some((e) => part.endsWith(e))) {
80
- project = part;
81
- break;
82
- }
83
- }
84
- }
64
+ const project = match?.[1] ?? basename(filename, extname(filename));
65
+ const locale = match?.[2] ?? xliffDirSegments(xliffDir, filePath).find((part) => LOCALE_PATTERN.test(part));
85
66
  return { project, locale };
86
67
  }
87
68
  function isMsgProjectLike(value) {
@@ -334,6 +315,7 @@ async function writeTranslationFiles(translationsDir, result) {
334
315
 
335
316
  export {
336
317
  findXliffFilePaths,
318
+ xliffDirSegments,
337
319
  filterXliffPathsByProject,
338
320
  filterXliffPathsByLocale,
339
321
  parseXliffFilename,
@@ -81,7 +81,7 @@ function generateMsgResourceContent(params) {
81
81
  const dirStr = `'${dir}'`;
82
82
  const resourceNote = `This is the ${escapeSingleQuoted(title)} resource.`;
83
83
  const projectImport = `#i18n/projects/${escapeSingleQuoted(projectName)}.js`;
84
- const createAndAdd = `MsgResource.create({
84
+ const createWithMessages = `MsgResource.create({
85
85
  title: ${titleStr},
86
86
  attributes: {
87
87
  lang: ${langStr},
@@ -89,22 +89,35 @@ function generateMsgResourceContent(params) {
89
89
  },
90
90
  notes: [
91
91
  {type: 'DESCRIPTION', content: '${resourceNote}'}
92
- ]
92
+ ],
93
+ /**
94
+ * The JSDoc const assertion lets TypeScript infer the message keys, so
95
+ * resource.get('unknownKey') is a compile error. Remove it to opt out.
96
+ */
97
+ messages: /** @type {const} */ ([
98
+ {
99
+ key: 'sampleKey',
100
+ value: 'Sample value.',
101
+ notes: [
102
+ { type: 'DESCRIPTION', content: 'This is first message.' }
103
+ ]
104
+ },
105
+ {
106
+ key: 'sampleKey2',
107
+ value: 'Hi, {name}',
108
+ attributes: { dnt: true },
109
+ notes: [
110
+ { type: 'DESCRIPTION', content: 'This is the second message.' },
111
+ { type: 'PARAMETERS', content: 'The {name} parameter holds the user name.' }
112
+ ]
113
+ }
114
+ ])
93
115
  }, project);
94
116
 
95
- /**
96
- * Add messages to the resource using add(key, value, attributes, notes)
97
- * The add method is chainable.
98
- */
99
-
100
- resource
101
- .add('sampleKey', 'Sample value.', {}, [
102
- { type: 'DESCRIPTION', content: 'This is first message.' }
103
- ])
104
- .add('sampleKey2', 'Hi, {name}', { dnt: true }, [
105
- { type: 'DESCRIPTION', content: 'This is the second message.' },
106
- { type: 'PARAMETERS', content: 'The {name} parameter holds the user name.' }
107
- ]);`;
117
+ /**
118
+ * More messages can be added with the chainable add(key, value, attributes, notes),
119
+ * but keys added that way are not part of the inferred key type.
120
+ */`;
108
121
  if (isEsm) {
109
122
  return `/** ESM module **/
110
123
 
@@ -113,7 +126,7 @@ import project from '${projectImport}';
113
126
 
114
127
  /** Create a MsgResource object */
115
128
 
116
- export const resource = ${createAndAdd}
129
+ export const resource = ${createWithMessages}
117
130
 
118
131
  /**
119
132
  * An async function to get a translated version of the resource
@@ -130,7 +143,7 @@ export async function getMessages() {
130
143
  const { MsgResource, getLang } = require('@worldware/msg');
131
144
  const project = require('${projectImport}');
132
145
 
133
- const resource = ${createAndAdd}
146
+ const resource = ${createWithMessages}
134
147
 
135
148
  /**
136
149
  * An async function to get a translated version of the resource
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  dynamicImportFromUrl
3
- } from "./chunk-PO2Z7EWJ.mjs";
3
+ } from "./chunk-KRQA4FRY.mjs";
4
4
  import {
5
5
  loadPackageJsonForMsg
6
6
  } from "./chunk-F7XZRKP7.mjs";
@@ -10,7 +10,7 @@ import {
10
10
  } from "./chunk-HH6ZOHO4.mjs";
11
11
  import {
12
12
  dynamicImportFromUrl
13
- } from "./chunk-PO2Z7EWJ.mjs";
13
+ } from "./chunk-KRQA4FRY.mjs";
14
14
 
15
15
  // src/lib/export-helpers.ts
16
16
  import { MSG_DEFAULT_FORMAT } from "@worldware/msg";
@@ -5,8 +5,8 @@ import {
5
5
  loadPackageJsonForCreateProject,
6
6
  resolveCreateProjectFormat,
7
7
  writeMsgProjectFile
8
- } from "../../chunk-QOEKYM6W.mjs";
9
- import "../../chunk-PO2Z7EWJ.mjs";
8
+ } from "../../chunk-W33MA4DJ.mjs";
9
+ import "../../chunk-KRQA4FRY.mjs";
10
10
  import {
11
11
  findPackageJsonPath
12
12
  } from "../../chunk-F7XZRKP7.mjs";
@@ -182,7 +182,7 @@ function generateMsgResourceContent(params) {
182
182
  const dirStr = `'${dir}'`;
183
183
  const resourceNote = `This is the ${escapeSingleQuoted(title)} resource.`;
184
184
  const projectImport = `#i18n/projects/${escapeSingleQuoted(projectName)}.js`;
185
- const createAndAdd = `MsgResource.create({
185
+ const createWithMessages = `MsgResource.create({
186
186
  title: ${titleStr},
187
187
  attributes: {
188
188
  lang: ${langStr},
@@ -190,22 +190,35 @@ function generateMsgResourceContent(params) {
190
190
  },
191
191
  notes: [
192
192
  {type: 'DESCRIPTION', content: '${resourceNote}'}
193
- ]
193
+ ],
194
+ /**
195
+ * The JSDoc const assertion lets TypeScript infer the message keys, so
196
+ * resource.get('unknownKey') is a compile error. Remove it to opt out.
197
+ */
198
+ messages: /** @type {const} */ ([
199
+ {
200
+ key: 'sampleKey',
201
+ value: 'Sample value.',
202
+ notes: [
203
+ { type: 'DESCRIPTION', content: 'This is first message.' }
204
+ ]
205
+ },
206
+ {
207
+ key: 'sampleKey2',
208
+ value: 'Hi, {name}',
209
+ attributes: { dnt: true },
210
+ notes: [
211
+ { type: 'DESCRIPTION', content: 'This is the second message.' },
212
+ { type: 'PARAMETERS', content: 'The {name} parameter holds the user name.' }
213
+ ]
214
+ }
215
+ ])
194
216
  }, project);
195
217
 
196
- /**
197
- * Add messages to the resource using add(key, value, attributes, notes)
198
- * The add method is chainable.
199
- */
200
-
201
- resource
202
- .add('sampleKey', 'Sample value.', {}, [
203
- { type: 'DESCRIPTION', content: 'This is first message.' }
204
- ])
205
- .add('sampleKey2', 'Hi, {name}', { dnt: true }, [
206
- { type: 'DESCRIPTION', content: 'This is the second message.' },
207
- { type: 'PARAMETERS', content: 'The {name} parameter holds the user name.' }
208
- ]);`;
218
+ /**
219
+ * More messages can be added with the chainable add(key, value, attributes, notes),
220
+ * but keys added that way are not part of the inferred key type.
221
+ */`;
209
222
  if (isEsm) {
210
223
  return `/** ESM module **/
211
224
 
@@ -214,7 +227,7 @@ import project from '${projectImport}';
214
227
 
215
228
  /** Create a MsgResource object */
216
229
 
217
- export const resource = ${createAndAdd}
230
+ export const resource = ${createWithMessages}
218
231
 
219
232
  /**
220
233
  * An async function to get a translated version of the resource
@@ -231,7 +244,7 @@ export async function getMessages() {
231
244
  const { MsgResource, getLang } = require('@worldware/msg');
232
245
  const project = require('${projectImport}');
233
246
 
234
- const resource = ${createAndAdd}
247
+ const resource = ${createWithMessages}
235
248
 
236
249
  /**
237
250
  * An async function to get a translated version of the resource
@@ -4,7 +4,7 @@ import {
4
4
  importMsgProjectForResource,
5
5
  readPackageJsonForCreateResource,
6
6
  writeMsgResourceFile
7
- } from "../../chunk-PO2Z7EWJ.mjs";
7
+ } from "../../chunk-KRQA4FRY.mjs";
8
8
  import {
9
9
  findPackageJsonPath
10
10
  } from "../../chunk-F7XZRKP7.mjs";
@@ -5,11 +5,11 @@ import {
5
5
  importMsgResourcesFromPaths,
6
6
  serializeResourceGroupsToXliff,
7
7
  writeXliffFiles
8
- } from "../chunk-ZAU52MSA.mjs";
8
+ } from "../chunk-WGI2EFOS.mjs";
9
9
  import "../chunk-Q775ZGC5.mjs";
10
10
  import "../chunk-PQJA3H4Z.mjs";
11
11
  import "../chunk-HH6ZOHO4.mjs";
12
- import "../chunk-PO2Z7EWJ.mjs";
12
+ import "../chunk-KRQA4FRY.mjs";
13
13
  import {
14
14
  loadPackageJsonForMsg
15
15
  } from "../chunk-F7XZRKP7.mjs";
@@ -390,52 +390,33 @@ async function findXliffFilePaths(directory) {
390
390
  }
391
391
  return result;
392
392
  }
393
- function filterXliffPathsByProject(filePaths, projectName) {
393
+ function xliffDirSegments(xliffDir, filePath) {
394
+ const rel = (0, import_path2.relative)(xliffDir, filePath);
395
+ if (!rel || rel === ".." || rel.startsWith(`..${import_path2.sep}`) || (0, import_path2.isAbsolute)(rel)) {
396
+ return [];
397
+ }
398
+ return rel.split(/[/\\]/).slice(0, -1);
399
+ }
400
+ function filterXliffPathsByProject(filePaths, projectName, xliffDir) {
394
401
  return filePaths.filter((p) => {
395
402
  const filename = (0, import_path2.basename)(p);
396
403
  if (filename.startsWith(projectName)) return true;
397
- const pathParts = p.split(/[/\\]/);
398
- return pathParts.some((part) => part === projectName);
404
+ return xliffDirSegments(xliffDir, p).some((part) => part === projectName);
399
405
  });
400
406
  }
401
- function filterXliffPathsByLocale(filePaths, locale) {
407
+ function filterXliffPathsByLocale(filePaths, locale, xliffDir) {
402
408
  return filePaths.filter((p) => {
403
409
  const filename = (0, import_path2.basename)(p);
404
410
  if (filename.includes(`.${locale}.`)) return true;
405
- const pathParts = p.split(/[/\\]/);
406
- return pathParts.some((part) => part === locale);
411
+ return xliffDirSegments(xliffDir, p).some((part) => part === locale);
407
412
  });
408
413
  }
409
414
  var LOCALE_PATTERN = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]+)*$/;
410
- function parseXliffFilename(filePath) {
415
+ function parseXliffFilename(filePath, xliffDir) {
411
416
  const filename = (0, import_path2.basename)(filePath);
412
417
  const match = filename.match(XLIFF_FILENAME_PATTERN);
413
- const pathParts = filePath.split(/[/\\]/);
414
- let project;
415
- let locale;
416
- if (match) {
417
- const [, proj, loc] = match;
418
- project = proj ?? (0, import_path2.basename)(filename, (0, import_path2.extname)(filename));
419
- locale = loc;
420
- } else {
421
- project = (0, import_path2.basename)(filename, (0, import_path2.extname)(filename));
422
- }
423
- if (!locale) {
424
- for (const part of pathParts) {
425
- if (LOCALE_PATTERN.test(part) && part.length >= 2) {
426
- locale = part;
427
- break;
428
- }
429
- }
430
- }
431
- if (!project && pathParts.length >= 2) {
432
- for (const part of pathParts) {
433
- if (part && !XLIFF_EXTENSIONS.some((e) => part.endsWith(e))) {
434
- project = part;
435
- break;
436
- }
437
- }
438
- }
418
+ const project = match?.[1] ?? (0, import_path2.basename)(filename, (0, import_path2.extname)(filename));
419
+ const locale = match?.[2] ?? xliffDirSegments(xliffDir, filePath).find((part) => LOCALE_PATTERN.test(part));
439
420
  return { project, locale };
440
421
  }
441
422
  function isMsgProjectLike(value) {
@@ -733,7 +714,7 @@ var Import = class _Import extends import_core.Command {
733
714
  }
734
715
  this.log(`Found ${filePaths.length} XLIFF file(s).`);
735
716
  if (flags.project) {
736
- filePaths = filterXliffPathsByProject(filePaths, flags.project);
717
+ filePaths = filterXliffPathsByProject(filePaths, flags.project, xliffDir);
737
718
  if (filePaths.length === 0) {
738
719
  this.log(`No XLIFF files found for project '${flags.project}'. Nothing to import.`);
739
720
  return;
@@ -741,7 +722,7 @@ var Import = class _Import extends import_core.Command {
741
722
  this.log(`Filtered to project '${flags.project}'.`);
742
723
  }
743
724
  if (flags.language) {
744
- filePaths = filterXliffPathsByLocale(filePaths, flags.language);
725
+ filePaths = filterXliffPathsByLocale(filePaths, flags.language, xliffDir);
745
726
  if (filePaths.length === 0) {
746
727
  this.log(`No XLIFF files found for language '${flags.language}'. Nothing to import.`);
747
728
  return;
@@ -751,7 +732,7 @@ var Import = class _Import extends import_core.Command {
751
732
  let wroteCount = 0;
752
733
  let errorCount = 0;
753
734
  for (const xliffPath of filePaths) {
754
- const { project: projectName, locale } = parseXliffFilename(xliffPath);
735
+ const { project: projectName, locale } = parseXliffFilename(xliffPath, xliffDir);
755
736
  if (!locale) {
756
737
  this.warn(`Skipping monolingual file (no target locale): ${xliffPath}`);
757
738
  continue;
@@ -5,11 +5,11 @@ import {
5
5
  parseXliffFilename,
6
6
  processXliffFile,
7
7
  writeTranslationFiles
8
- } from "../chunk-NJKP7C5U.mjs";
8
+ } from "../chunk-3MCULZ7L.mjs";
9
9
  import "../chunk-Q775ZGC5.mjs";
10
10
  import "../chunk-PQJA3H4Z.mjs";
11
11
  import "../chunk-HH6ZOHO4.mjs";
12
- import "../chunk-PO2Z7EWJ.mjs";
12
+ import "../chunk-KRQA4FRY.mjs";
13
13
  import {
14
14
  loadPackageJsonForMsg
15
15
  } from "../chunk-F7XZRKP7.mjs";
@@ -64,7 +64,7 @@ var Import = class _Import extends Command {
64
64
  }
65
65
  this.log(`Found ${filePaths.length} XLIFF file(s).`);
66
66
  if (flags.project) {
67
- filePaths = filterXliffPathsByProject(filePaths, flags.project);
67
+ filePaths = filterXliffPathsByProject(filePaths, flags.project, xliffDir);
68
68
  if (filePaths.length === 0) {
69
69
  this.log(`No XLIFF files found for project '${flags.project}'. Nothing to import.`);
70
70
  return;
@@ -72,7 +72,7 @@ var Import = class _Import extends Command {
72
72
  this.log(`Filtered to project '${flags.project}'.`);
73
73
  }
74
74
  if (flags.language) {
75
- filePaths = filterXliffPathsByLocale(filePaths, flags.language);
75
+ filePaths = filterXliffPathsByLocale(filePaths, flags.language, xliffDir);
76
76
  if (filePaths.length === 0) {
77
77
  this.log(`No XLIFF files found for language '${flags.language}'. Nothing to import.`);
78
78
  return;
@@ -82,7 +82,7 @@ var Import = class _Import extends Command {
82
82
  let wroteCount = 0;
83
83
  let errorCount = 0;
84
84
  for (const xliffPath of filePaths) {
85
- const { project: projectName, locale } = parseXliffFilename(xliffPath);
85
+ const { project: projectName, locale } = parseXliffFilename(xliffPath, xliffDir);
86
86
  if (!locale) {
87
87
  this.warn(`Skipping monolingual file (no target locale): ${xliffPath}`);
88
88
  continue;
@@ -5,8 +5,8 @@ import {
5
5
  loadPackageJsonForCreateProject,
6
6
  resolveCreateProjectFormat,
7
7
  writeMsgProjectFile
8
- } from "../chunk-QOEKYM6W.mjs";
9
- import "../chunk-PO2Z7EWJ.mjs";
8
+ } from "../chunk-W33MA4DJ.mjs";
9
+ import "../chunk-KRQA4FRY.mjs";
10
10
  import "../chunk-F7XZRKP7.mjs";
11
11
  export {
12
12
  CREATE_PROJECT_FORMATS,
@@ -170,7 +170,7 @@ function generateMsgResourceContent(params) {
170
170
  const dirStr = `'${dir}'`;
171
171
  const resourceNote = `This is the ${escapeSingleQuoted(title)} resource.`;
172
172
  const projectImport = `#i18n/projects/${escapeSingleQuoted(projectName)}.js`;
173
- const createAndAdd = `MsgResource.create({
173
+ const createWithMessages = `MsgResource.create({
174
174
  title: ${titleStr},
175
175
  attributes: {
176
176
  lang: ${langStr},
@@ -178,22 +178,35 @@ function generateMsgResourceContent(params) {
178
178
  },
179
179
  notes: [
180
180
  {type: 'DESCRIPTION', content: '${resourceNote}'}
181
- ]
181
+ ],
182
+ /**
183
+ * The JSDoc const assertion lets TypeScript infer the message keys, so
184
+ * resource.get('unknownKey') is a compile error. Remove it to opt out.
185
+ */
186
+ messages: /** @type {const} */ ([
187
+ {
188
+ key: 'sampleKey',
189
+ value: 'Sample value.',
190
+ notes: [
191
+ { type: 'DESCRIPTION', content: 'This is first message.' }
192
+ ]
193
+ },
194
+ {
195
+ key: 'sampleKey2',
196
+ value: 'Hi, {name}',
197
+ attributes: { dnt: true },
198
+ notes: [
199
+ { type: 'DESCRIPTION', content: 'This is the second message.' },
200
+ { type: 'PARAMETERS', content: 'The {name} parameter holds the user name.' }
201
+ ]
202
+ }
203
+ ])
182
204
  }, project);
183
205
 
184
- /**
185
- * Add messages to the resource using add(key, value, attributes, notes)
186
- * The add method is chainable.
187
- */
188
-
189
- resource
190
- .add('sampleKey', 'Sample value.', {}, [
191
- { type: 'DESCRIPTION', content: 'This is first message.' }
192
- ])
193
- .add('sampleKey2', 'Hi, {name}', { dnt: true }, [
194
- { type: 'DESCRIPTION', content: 'This is the second message.' },
195
- { type: 'PARAMETERS', content: 'The {name} parameter holds the user name.' }
196
- ]);`;
206
+ /**
207
+ * More messages can be added with the chainable add(key, value, attributes, notes),
208
+ * but keys added that way are not part of the inferred key type.
209
+ */`;
197
210
  if (isEsm) {
198
211
  return `/** ESM module **/
199
212
 
@@ -202,7 +215,7 @@ import project from '${projectImport}';
202
215
 
203
216
  /** Create a MsgResource object */
204
217
 
205
- export const resource = ${createAndAdd}
218
+ export const resource = ${createWithMessages}
206
219
 
207
220
  /**
208
221
  * An async function to get a translated version of the resource
@@ -219,7 +232,7 @@ export async function getMessages() {
219
232
  const { MsgResource, getLang } = require('@worldware/msg');
220
233
  const project = require('${projectImport}');
221
234
 
222
- const resource = ${createAndAdd}
235
+ const resource = ${createWithMessages}
223
236
 
224
237
  /**
225
238
  * An async function to get a translated version of the resource
@@ -35,9 +35,11 @@ declare function importMsgProjectForResource(projectsDir: string, projectName: s
35
35
  } | undefined>;
36
36
  /**
37
37
  * Generates the MsgResource file content as a string.
38
- * Emits ESM or CJS boilerplate that creates a MsgResource, adds sample
39
- * messages via chainable `.add()`, and exports `resource` plus an async
40
- * `getMessages` loader that calls `resource.getTranslation(getLang())`.
38
+ * Emits ESM or CJS boilerplate that creates a MsgResource with sample
39
+ * messages passed to `create()` inside a JSDoc `@type {const}` assertion
40
+ * (the `.js` form of `as const`), so TypeScript infers the message key union for
41
+ * `.msg.js` files. Exports `resource` plus an async `getMessages` loader that
42
+ * calls `resource.getTranslation(getLang())`.
41
43
  * Project import uses the `#i18n/projects/<name>.js` alias from `msg init`.
42
44
  * @param params - Title, projectName, sourceLocale, dir, and isEsm
43
45
  * @returns The generated file content
@@ -35,9 +35,11 @@ declare function importMsgProjectForResource(projectsDir: string, projectName: s
35
35
  } | undefined>;
36
36
  /**
37
37
  * Generates the MsgResource file content as a string.
38
- * Emits ESM or CJS boilerplate that creates a MsgResource, adds sample
39
- * messages via chainable `.add()`, and exports `resource` plus an async
40
- * `getMessages` loader that calls `resource.getTranslation(getLang())`.
38
+ * Emits ESM or CJS boilerplate that creates a MsgResource with sample
39
+ * messages passed to `create()` inside a JSDoc `@type {const}` assertion
40
+ * (the `.js` form of `as const`), so TypeScript infers the message key union for
41
+ * `.msg.js` files. Exports `resource` plus an async `getMessages` loader that
42
+ * calls `resource.getTranslation(getLang())`.
41
43
  * Project import uses the `#i18n/projects/<name>.js` alias from `msg init`.
42
44
  * @param params - Title, projectName, sourceLocale, dir, and isEsm
43
45
  * @returns The generated file content
@@ -4,7 +4,7 @@ import {
4
4
  importMsgProjectForResource,
5
5
  readPackageJsonForCreateResource,
6
6
  writeMsgResourceFile
7
- } from "../chunk-PO2Z7EWJ.mjs";
7
+ } from "../chunk-KRQA4FRY.mjs";
8
8
  import "../chunk-F7XZRKP7.mjs";
9
9
  export {
10
10
  dynamicImportFromUrl,
@@ -5,11 +5,11 @@ import {
5
5
  importMsgResourcesFromPaths,
6
6
  serializeResourceGroupsToXliff,
7
7
  writeXliffFiles
8
- } from "../chunk-ZAU52MSA.mjs";
8
+ } from "../chunk-WGI2EFOS.mjs";
9
9
  import "../chunk-Q775ZGC5.mjs";
10
10
  import "../chunk-PQJA3H4Z.mjs";
11
11
  import "../chunk-HH6ZOHO4.mjs";
12
- import "../chunk-PO2Z7EWJ.mjs";
12
+ import "../chunk-KRQA4FRY.mjs";
13
13
  import "../chunk-F7XZRKP7.mjs";
14
14
  export {
15
15
  filterResourceGroupsByProject,
@@ -28,7 +28,8 @@ __export(import_helpers_exports, {
28
28
  parseXliff20: () => parseXliff20,
29
29
  parseXliffFilename: () => parseXliffFilename,
30
30
  processXliffFile: () => processXliffFile,
31
- writeTranslationFiles: () => writeTranslationFiles
31
+ writeTranslationFiles: () => writeTranslationFiles,
32
+ xliffDirSegments: () => xliffDirSegments
32
33
  });
33
34
  module.exports = __toCommonJS(import_helpers_exports);
34
35
  var import_msg2 = require("@worldware/msg");
@@ -330,52 +331,33 @@ async function findXliffFilePaths(directory) {
330
331
  }
331
332
  return result;
332
333
  }
333
- function filterXliffPathsByProject(filePaths, projectName) {
334
+ function xliffDirSegments(xliffDir, filePath) {
335
+ const rel = (0, import_path.relative)(xliffDir, filePath);
336
+ if (!rel || rel === ".." || rel.startsWith(`..${import_path.sep}`) || (0, import_path.isAbsolute)(rel)) {
337
+ return [];
338
+ }
339
+ return rel.split(/[/\\]/).slice(0, -1);
340
+ }
341
+ function filterXliffPathsByProject(filePaths, projectName, xliffDir) {
334
342
  return filePaths.filter((p) => {
335
343
  const filename = (0, import_path.basename)(p);
336
344
  if (filename.startsWith(projectName)) return true;
337
- const pathParts = p.split(/[/\\]/);
338
- return pathParts.some((part) => part === projectName);
345
+ return xliffDirSegments(xliffDir, p).some((part) => part === projectName);
339
346
  });
340
347
  }
341
- function filterXliffPathsByLocale(filePaths, locale) {
348
+ function filterXliffPathsByLocale(filePaths, locale, xliffDir) {
342
349
  return filePaths.filter((p) => {
343
350
  const filename = (0, import_path.basename)(p);
344
351
  if (filename.includes(`.${locale}.`)) return true;
345
- const pathParts = p.split(/[/\\]/);
346
- return pathParts.some((part) => part === locale);
352
+ return xliffDirSegments(xliffDir, p).some((part) => part === locale);
347
353
  });
348
354
  }
349
355
  var LOCALE_PATTERN = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]+)*$/;
350
- function parseXliffFilename(filePath) {
356
+ function parseXliffFilename(filePath, xliffDir) {
351
357
  const filename = (0, import_path.basename)(filePath);
352
358
  const match = filename.match(XLIFF_FILENAME_PATTERN);
353
- const pathParts = filePath.split(/[/\\]/);
354
- let project;
355
- let locale;
356
- if (match) {
357
- const [, proj, loc] = match;
358
- project = proj ?? (0, import_path.basename)(filename, (0, import_path.extname)(filename));
359
- locale = loc;
360
- } else {
361
- project = (0, import_path.basename)(filename, (0, import_path.extname)(filename));
362
- }
363
- if (!locale) {
364
- for (const part of pathParts) {
365
- if (LOCALE_PATTERN.test(part) && part.length >= 2) {
366
- locale = part;
367
- break;
368
- }
369
- }
370
- }
371
- if (!project && pathParts.length >= 2) {
372
- for (const part of pathParts) {
373
- if (part && !XLIFF_EXTENSIONS.some((e) => part.endsWith(e))) {
374
- project = part;
375
- break;
376
- }
377
- }
378
- }
359
+ const project = match?.[1] ?? (0, import_path.basename)(filename, (0, import_path.extname)(filename));
360
+ const locale = match?.[2] ?? xliffDirSegments(xliffDir, filePath).find((part) => LOCALE_PATTERN.test(part));
379
361
  return { project, locale };
380
362
  }
381
363
  function isMsgProjectLike(value) {
@@ -635,5 +617,6 @@ async function writeTranslationFiles(translationsDir, result) {
635
617
  parseXliff20,
636
618
  parseXliffFilename,
637
619
  processXliffFile,
638
- writeTranslationFiles
620
+ writeTranslationFiles,
621
+ xliffDirSegments
639
622
  });
@@ -6,29 +6,45 @@ import { MsgResource } from '@worldware/msg';
6
6
  * @returns Promise resolving to array of absolute file paths
7
7
  */
8
8
  declare function findXliffFilePaths(directory: string): Promise<string[]>;
9
+ /**
10
+ * Returns the directory names between the xliff root and an XLIFF file.
11
+ *
12
+ * Path-based project/locale detection must only look below the xliff root:
13
+ * directories above it (`/var`, `/tmp`, `src`, ...) belong to the machine,
14
+ * not to the msg layout, and many of them look like locale codes.
15
+ * @param xliffDir - Absolute path to the xliff directory (e.g. l10n/xliff)
16
+ * @param filePath - Absolute path to an XLIFF file
17
+ * @returns Directory segments under xliffDir, excluding the file name; empty
18
+ * when the file is directly in xliffDir or outside it
19
+ */
20
+ declare function xliffDirSegments(xliffDir: string, filePath: string): string[];
9
21
  /**
10
22
  * Filters XLIFF file paths by project name.
11
- * Keeps paths where filename starts with projectName or projectName is a directory in the path.
23
+ * Keeps paths where filename starts with projectName or projectName is a directory under xliffDir.
12
24
  * @param filePaths - Array of absolute XLIFF file paths
13
25
  * @param projectName - Project name to filter by
26
+ * @param xliffDir - Absolute path to the xliff directory the paths were found in
14
27
  * @returns Filtered array of paths
15
28
  */
16
- declare function filterXliffPathsByProject(filePaths: string[], projectName: string): string[];
29
+ declare function filterXliffPathsByProject(filePaths: string[], projectName: string, xliffDir: string): string[];
17
30
  /**
18
31
  * Filters XLIFF file paths by locale.
19
- * Keeps paths that have .[locale]. in the filename or locale as a directory in the path.
32
+ * Keeps paths that have .[locale]. in the filename or locale as a directory under xliffDir.
20
33
  * @param filePaths - Array of absolute XLIFF file paths
21
34
  * @param locale - Locale code to filter by
35
+ * @param xliffDir - Absolute path to the xliff directory the paths were found in
22
36
  * @returns Filtered array of paths
23
37
  */
24
- declare function filterXliffPathsByLocale(filePaths: string[], locale: string): string[];
38
+ declare function filterXliffPathsByLocale(filePaths: string[], locale: string, xliffDir: string): string[];
25
39
  /**
26
40
  * Extracts project name and locale from an XLIFF file path.
27
- * Filename patterns: project.locale.xliff, project.xliff. Path segments may also indicate project/locale.
41
+ * Filename patterns: project.locale.xliff, project.xliff. Directories under
42
+ * xliffDir may also indicate project/locale (e.g. xliff/zh/project.xliff).
28
43
  * @param filePath - Absolute path to XLIFF file
44
+ * @param xliffDir - Absolute path to the xliff directory the file was found in
29
45
  * @returns Object with project and locale (locale may be undefined for monolingual)
30
46
  */
31
- declare function parseXliffFilename(filePath: string): {
47
+ declare function parseXliffFilename(filePath: string, xliffDir: string): {
32
48
  project: string;
33
49
  locale?: string;
34
50
  };
@@ -89,4 +105,4 @@ declare function processXliffFile(xliffPath: string, projectsDir: string, projec
89
105
  */
90
106
  declare function writeTranslationFiles(translationsDir: string, result: ImportResult): Promise<void>;
91
107
 
92
- export { type ImportResult, extractResourceFromXliffFile, filterXliffPathsByLocale, filterXliffPathsByProject, findXliffFilePaths, importMsgProject, parseXliff20, parseXliffFilename, processXliffFile, writeTranslationFiles };
108
+ export { type ImportResult, extractResourceFromXliffFile, filterXliffPathsByLocale, filterXliffPathsByProject, findXliffFilePaths, importMsgProject, parseXliff20, parseXliffFilename, processXliffFile, writeTranslationFiles, xliffDirSegments };
@@ -6,29 +6,45 @@ import { MsgResource } from '@worldware/msg';
6
6
  * @returns Promise resolving to array of absolute file paths
7
7
  */
8
8
  declare function findXliffFilePaths(directory: string): Promise<string[]>;
9
+ /**
10
+ * Returns the directory names between the xliff root and an XLIFF file.
11
+ *
12
+ * Path-based project/locale detection must only look below the xliff root:
13
+ * directories above it (`/var`, `/tmp`, `src`, ...) belong to the machine,
14
+ * not to the msg layout, and many of them look like locale codes.
15
+ * @param xliffDir - Absolute path to the xliff directory (e.g. l10n/xliff)
16
+ * @param filePath - Absolute path to an XLIFF file
17
+ * @returns Directory segments under xliffDir, excluding the file name; empty
18
+ * when the file is directly in xliffDir or outside it
19
+ */
20
+ declare function xliffDirSegments(xliffDir: string, filePath: string): string[];
9
21
  /**
10
22
  * Filters XLIFF file paths by project name.
11
- * Keeps paths where filename starts with projectName or projectName is a directory in the path.
23
+ * Keeps paths where filename starts with projectName or projectName is a directory under xliffDir.
12
24
  * @param filePaths - Array of absolute XLIFF file paths
13
25
  * @param projectName - Project name to filter by
26
+ * @param xliffDir - Absolute path to the xliff directory the paths were found in
14
27
  * @returns Filtered array of paths
15
28
  */
16
- declare function filterXliffPathsByProject(filePaths: string[], projectName: string): string[];
29
+ declare function filterXliffPathsByProject(filePaths: string[], projectName: string, xliffDir: string): string[];
17
30
  /**
18
31
  * Filters XLIFF file paths by locale.
19
- * Keeps paths that have .[locale]. in the filename or locale as a directory in the path.
32
+ * Keeps paths that have .[locale]. in the filename or locale as a directory under xliffDir.
20
33
  * @param filePaths - Array of absolute XLIFF file paths
21
34
  * @param locale - Locale code to filter by
35
+ * @param xliffDir - Absolute path to the xliff directory the paths were found in
22
36
  * @returns Filtered array of paths
23
37
  */
24
- declare function filterXliffPathsByLocale(filePaths: string[], locale: string): string[];
38
+ declare function filterXliffPathsByLocale(filePaths: string[], locale: string, xliffDir: string): string[];
25
39
  /**
26
40
  * Extracts project name and locale from an XLIFF file path.
27
- * Filename patterns: project.locale.xliff, project.xliff. Path segments may also indicate project/locale.
41
+ * Filename patterns: project.locale.xliff, project.xliff. Directories under
42
+ * xliffDir may also indicate project/locale (e.g. xliff/zh/project.xliff).
28
43
  * @param filePath - Absolute path to XLIFF file
44
+ * @param xliffDir - Absolute path to the xliff directory the file was found in
29
45
  * @returns Object with project and locale (locale may be undefined for monolingual)
30
46
  */
31
- declare function parseXliffFilename(filePath: string): {
47
+ declare function parseXliffFilename(filePath: string, xliffDir: string): {
32
48
  project: string;
33
49
  locale?: string;
34
50
  };
@@ -89,4 +105,4 @@ declare function processXliffFile(xliffPath: string, projectsDir: string, projec
89
105
  */
90
106
  declare function writeTranslationFiles(translationsDir: string, result: ImportResult): Promise<void>;
91
107
 
92
- export { type ImportResult, extractResourceFromXliffFile, filterXliffPathsByLocale, filterXliffPathsByProject, findXliffFilePaths, importMsgProject, parseXliff20, parseXliffFilename, processXliffFile, writeTranslationFiles };
108
+ export { type ImportResult, extractResourceFromXliffFile, filterXliffPathsByLocale, filterXliffPathsByProject, findXliffFilePaths, importMsgProject, parseXliff20, parseXliffFilename, processXliffFile, writeTranslationFiles, xliffDirSegments };
@@ -7,12 +7,13 @@ import {
7
7
  parseXliff20,
8
8
  parseXliffFilename,
9
9
  processXliffFile,
10
- writeTranslationFiles
11
- } from "../chunk-NJKP7C5U.mjs";
10
+ writeTranslationFiles,
11
+ xliffDirSegments
12
+ } from "../chunk-3MCULZ7L.mjs";
12
13
  import "../chunk-Q775ZGC5.mjs";
13
14
  import "../chunk-PQJA3H4Z.mjs";
14
15
  import "../chunk-HH6ZOHO4.mjs";
15
- import "../chunk-PO2Z7EWJ.mjs";
16
+ import "../chunk-KRQA4FRY.mjs";
16
17
  import "../chunk-F7XZRKP7.mjs";
17
18
  export {
18
19
  extractResourceFromXliffFile,
@@ -23,5 +24,6 @@ export {
23
24
  parseXliff20,
24
25
  parseXliffFilename,
25
26
  processXliffFile,
26
- writeTranslationFiles
27
+ writeTranslationFiles,
28
+ xliffDirSegments
27
29
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@worldware/msg-cli",
3
- "version": "0.5.2",
3
+ "version": "0.6.1",
4
4
  "description": "CLI for msg library",
5
5
  "main": "dist/commands/init.cjs",
6
6
  "module": "dist/commands/init.mjs",
@@ -10,6 +10,7 @@
10
10
  "build": "tsup",
11
11
  "prepack": "npm run build",
12
12
  "coverage": "vitest run --coverage",
13
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
13
14
  "docs": "typedoc --entryPointStrategy expand src/commands src/lib"
14
15
  },
15
16
  "repository": {
@@ -39,7 +40,7 @@
39
40
  "@messageformat/icu-messageformat-1": "^0.12.0",
40
41
  "@messageformat/parser": "^5.1.1",
41
42
  "@oclif/core": "^3.21.2",
42
- "@worldware/msg": "^0.12.0",
43
+ "@worldware/msg": "^0.13.0",
43
44
  "fast-xml-parser": "^5.3.4",
44
45
  "messageformat": "^4.0.0-10"
45
46
  },