@worldware/msg-cli 0.1.1 → 0.2.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.
Files changed (38) hide show
  1. package/README.md +99 -13
  2. package/dist/{chunk-4Q2252JQ.mjs → chunk-6A6JGF7U.mjs} +2 -2
  3. package/dist/chunk-BM3O7ZJW.mjs +176 -0
  4. package/dist/{chunk-DBC2Y6VQ.mjs → chunk-F7XZRKP7.mjs} +6 -6
  5. package/dist/chunk-KKATA5YE.mjs +324 -0
  6. package/dist/{chunk-KKYCVD5M.mjs → chunk-LNCUPVEF.mjs} +2 -2
  7. package/dist/commands/create/project.cjs +23 -10
  8. package/dist/commands/create/project.mjs +26 -13
  9. package/dist/commands/create/resource.cjs +1 -1
  10. package/dist/commands/create/resource.mjs +2 -2
  11. package/dist/commands/export.cjs +356 -0
  12. package/dist/commands/export.d.mts +16 -0
  13. package/dist/commands/export.d.ts +16 -0
  14. package/dist/commands/export.mjs +91 -0
  15. package/dist/commands/import.cjs +526 -0
  16. package/dist/commands/import.d.mts +17 -0
  17. package/dist/commands/import.d.ts +17 -0
  18. package/dist/commands/import.mjs +116 -0
  19. package/dist/commands/init.cjs +6 -6
  20. package/dist/commands/init.mjs +1 -1
  21. package/dist/lib/create-project-helpers.mjs +3 -3
  22. package/dist/lib/create-resource-helpers.cjs +1 -1
  23. package/dist/lib/create-resource-helpers.mjs +2 -2
  24. package/dist/lib/export-helpers.cjs +229 -0
  25. package/dist/lib/export-helpers.d.mts +55 -0
  26. package/dist/lib/export-helpers.d.ts +55 -0
  27. package/dist/lib/export-helpers.mjs +18 -0
  28. package/dist/lib/import-helpers.cjs +380 -0
  29. package/dist/lib/import-helpers.d.mts +92 -0
  30. package/dist/lib/import-helpers.d.ts +92 -0
  31. package/dist/lib/import-helpers.mjs +24 -0
  32. package/dist/lib/init-helpers.cjs +6 -6
  33. package/dist/lib/init-helpers.mjs +1 -1
  34. package/package.json +2 -2
  35. package/dist/lib/utilities.cjs +0 -203
  36. package/dist/lib/utilities.d.mts +0 -59
  37. package/dist/lib/utilities.d.ts +0 -59
  38. package/dist/lib/utilities.mjs +0 -172
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  msg-cli is a command-line tool for the [msg](https://github.com/worldware-studios/msg) library. It helps you scaffold internationalization (i18n) and localization (l10n) layout and wire up your project for use with msg.
6
6
 
7
- **Current status:** Implemented commands: `init` (scaffold i18n/l10n and config), `create project` (template a new MsgProject file in i18n/projects), and `create resource` (template a new MsgResource file in i18n/resources).
7
+ **Current status:** CLI for the msg library (npm: `@worldware/msg-cli`, v0.2.0). Commands: `init` (scaffold i18n/l10n and config), `create project` (new MsgProject in i18n/projects), `create resource` (new MsgResource in i18n/resources), `export` (serialize MsgResources to XLIFF 2.0 in l10n/xliff), `import` (import translations from XLIFF 2.0 to JSON in l10n/translations).
8
8
 
9
9
  ## Installation
10
10
 
@@ -17,7 +17,7 @@ npm install -g @worldware/msg-cli
17
17
  Or use via `npx`:
18
18
 
19
19
  ```bash
20
- npx @worldware/msg-cli <command>
20
+ npx msg <command>
21
21
  ```
22
22
 
23
23
  For project-local setup, run `msg init` in your project root to add msg and msg-cli as dependencies and scaffold directories and config.
@@ -30,7 +30,7 @@ For project-local setup, run `msg init` in your project root to add msg and msg-
30
30
 
31
31
  ## Usage
32
32
 
33
- **Commands:** `init`, `create project`, `create resource`.
33
+ **Commands:** `init`, `create project`, `create resource`, `export`, `import`.
34
34
 
35
35
  ### init
36
36
 
@@ -44,7 +44,7 @@ msg init
44
44
  |------|-------------|
45
45
  | `-h`, `--help` | Show help for the init command. |
46
46
  | `-i` | Interactive: prompt for i18n and l10n directory paths. |
47
- | `-f`, `--force` | Force a clean run; overwrite or re-apply existing msg setup. |
47
+ | `-f`, `--force` | Force clean install; overwrite existing msg setup. |
48
48
  | `--i18nDir <path>` | Relative path for the i18n directory (default: `src/i18n`). |
49
49
  | `--l10nDir <path>` | Relative path for the l10n directory (default: `res/l10n`). |
50
50
 
@@ -70,7 +70,7 @@ msg init -i
70
70
  2. Adds `.gitkeep` in each leaf directory.
71
71
  3. Adds `directories.i18n`, `directories.l10n`, and `directories.root` to `package.json`.
72
72
  4. Adds import aliases `#i18n/*`, `#l10n/*`, and `#root/*` to `package.json`.
73
- 5. Adds scripts `i18n-export` and `l10n-import` (pointing to `msg export:resources` and `msg import:translations`) for when those commands are available.
73
+ 5. Adds scripts `i18n-export` and `l10n-import` (running `msg export` and `msg import`).
74
74
  6. If `tsconfig.json` exists, adds `compilerOptions.baseUrl` and `compilerOptions.paths` for the aliases.
75
75
  7. Installs the latest `@worldware/msg` as a dependency.
76
76
 
@@ -79,14 +79,16 @@ msg init -i
79
79
  Create a new MsgProject file in the i18n projects directory. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first).
80
80
 
81
81
  ```bash
82
- msg create project <projectName> <source> <targets...> [--extend <name>]
82
+ msg create project <projectName> [source] [targets...] [--extend <name>]
83
83
  ```
84
84
 
85
85
  | Argument | Required | Description |
86
86
  |-------------|----------|------------------------------------------|
87
87
  | `projectName` | Yes | Name of the project (used as file name). |
88
- | `source` | Yes | Source locale (e.g. `en`). |
89
- | `targets` | Yes (≥1) | Target locale(s), e.g. `fr`, `de`, `es`. |
88
+ | `source` | Yes* | Source locale (e.g. `en`). |
89
+ | `targets` | Yes* (≥1) | Target locale(s), e.g. `fr`, `de`, `es`. |
90
+
91
+ \* `source` and `targets` are optional when `--extend` is passed; they are inherited from the base project.
90
92
 
91
93
  | Flag | Short | Description |
92
94
  |------------|-------|--------------------------------|
@@ -99,7 +101,10 @@ msg create project <projectName> <source> <targets...> [--extend <name>]
99
101
  # Create project myApp with source en and targets fr, de
100
102
  msg create project myApp en fr de
101
103
 
102
- # Extend an existing project
104
+ # Extend an existing project (inherits source and targets from base)
105
+ msg create project extendedApp --extend base
106
+
107
+ # Extend and add/override locales
103
108
  msg create project extendedApp en de --extend base
104
109
 
105
110
  # Help
@@ -111,7 +116,7 @@ msg create project -h
111
116
  - Writes the file to `i18n/projects/<projectName>.js` or `.ts` (TypeScript if `tsconfig.json` exists).
112
117
  - Uses ES module or CommonJS export based on `package.json` `"type"`.
113
118
  - Generates a translation loader that imports from `l10n/translations` using the relative path from `i18n/projects` (from `directories` in package.json).
114
- - With `--extend <name>`, merges target locales and pseudoLocale from the existing project.
119
+ - With `--extend <name>`, merges target locales and pseudoLocale from the existing project. If `source` and `targets` are omitted, they are inherited from the base project.
115
120
  - Errors if the project name already exists, package.json is missing or invalid, or required directories are not configured.
116
121
 
117
122
  ### create resource
@@ -154,12 +159,94 @@ msg create resource myProject messages --edit
154
159
  - Includes a minimal example message. Validates that the generated file is importable.
155
160
  - Errors if i18n/projects or i18n/resources does not exist, the project is not found, or the resource file already exists (unless `--force`).
156
161
 
162
+ ### export
163
+
164
+ Serialize all MsgResource files in `i18n/resources` to XLIFF 2.0 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).
165
+
166
+ ```bash
167
+ msg export [-p <projectName>]
168
+ ```
169
+
170
+ | Flag | Short | Description |
171
+ |-------------|-------|--------------------------------------------|
172
+ | `--project` | `-p` | Export only the named project. |
173
+ | `--help` | `-h` | Show help for the export command. |
174
+
175
+ **Examples:**
176
+
177
+ ```bash
178
+ # Export all projects to l10n/xliff
179
+ msg export
180
+
181
+ # Export only project "myApp"
182
+ msg export --project myApp
183
+ msg export -p myApp
184
+ ```
185
+
186
+ **Behavior:**
187
+
188
+ - Recursively finds all `.msg.js` and `.msg.ts` files under `i18n/resources`.
189
+ - Imports each file as a MsgResource; errors if any file is invalid.
190
+ - Groups resources by project name and writes one XLIFF 2.0 file per project to `l10n/xliff` (e.g. `myApp.xliff`).
191
+ - With `--project`, only that project is exported; existing other files in `l10n/xliff` are not removed.
192
+ - If no MsgResource files are found, exits with an informational message (no error).
193
+ - Logs each major step (finding files, importing, grouping, writing).
194
+
195
+ **What is preserved in XLIFF 2.0:**
196
+
197
+ - **Message keys** — Stored as unit `id` (sanitized for XML) and `name` (original key).
198
+ - **Resource notes** — Emitted as file-level `<notes>` with category (e.g. `description`, `comment`).
199
+ - **Resource attributes** — `dir` → file `srcDir`; `dnt` → file `translate="no"`.
200
+ - **Message notes** — Emitted as unit-level `<notes>` with category (e.g. `description`, `context`, `parameters`).
201
+ - **Message attributes** — `dnt` → unit `translate="no"`; message `dir` is serialized as the unit’s `srcDir` attribute (XLIFF 2.0 text direction for the segment).
202
+
203
+ ### import
204
+
205
+ Import translations from bilingual XLIFF 2.0 files in `l10n/xliff` to JSON files in `l10n/translations`. Expects XLIFF files with `trgLang` (target language) and translated content in `<target>` elements. Writes JSON files without notes for minimal size. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first).
206
+
207
+ ```bash
208
+ msg import [-p <projectName>] [-l <locale>]
209
+ ```
210
+
211
+ | Flag | Short | Description |
212
+ |-------------|-------|--------------------------------------------|
213
+ | `--project` | `-p` | Import only the named project. |
214
+ | `--language`| `-l` | Import only the specified locale. |
215
+ | `--help` | `-h` | Show help for the import command. |
216
+
217
+ **Examples:**
218
+
219
+ ```bash
220
+ # Import all XLIFF files
221
+ msg import
222
+
223
+ # Import only project "myApp"
224
+ msg import --project myApp
225
+ msg import -p myApp
226
+
227
+ # Import only locale "zh"
228
+ msg import --language zh
229
+ msg import -l zh
230
+ ```
231
+
232
+ **Behavior:**
233
+
234
+ - Recursively finds all `.xliff` and `.xlf` files under `l10n/xliff`.
235
+ - Project and target locale are taken from the filename (e.g. `myApp.zh.xliff`) or from path segments (e.g. `myApp/zh/messages.xliff`).
236
+ - Dynamically imports `MsgProject` from `i18n/projects` to validate target locales.
237
+ - Skips monolingual XLIFF files (no `trgLang`).
238
+ - Skips files whose target locale is not in the project's `targetLocales`.
239
+ - Writes JSON to `l10n/translations/<project>/<locale>/<title>.json`.
240
+ - Preserves existing translation files for other projects or locales when filtering.
241
+ - Errors on malformed XLIFF and logs each step.
242
+
157
243
  ## API Reference
158
244
 
159
245
  The CLI does not expose a programmatic API. For library usage, see [@worldware/msg](https://github.com/worldware-studios/msg).
160
246
 
161
247
  ## Development
162
248
 
249
+ - **Repository:** [github.com/worldware-studios/msg-cli](https://github.com/worldware-studios/msg-cli)
163
250
  - **Setup:** `npm install`
164
251
  - **Build:** `npm run build`
165
252
  - **Tests:** `npm run test`
@@ -167,9 +254,8 @@ The CLI does not expose a programmatic API. For library usage, see [@worldware/m
167
254
 
168
255
  Source layout:
169
256
 
170
- - `src/commands/` — CLI commands (init, create/project, create/resource).
171
- - `src/lib/` — Shared utilities, init helpers, create-project helpers, and create-resource helpers.
172
- - `src/specs/` — Feature and command specs.
257
+ - `src/commands/` — CLI commands (init, export, import, create/project, create/resource).
258
+ - `src/lib/` — Shared utilities: init-helpers, export-helpers, import-helpers, create-project-helpers, create-resource-helpers.
173
259
  - `src/tests/` — Vitest tests and fixtures.
174
260
 
175
261
  ## License
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  dynamicImportFromUrl
3
- } from "./chunk-KKYCVD5M.mjs";
3
+ } from "./chunk-LNCUPVEF.mjs";
4
4
  import {
5
5
  loadPackageJsonForMsg
6
- } from "./chunk-DBC2Y6VQ.mjs";
6
+ } from "./chunk-F7XZRKP7.mjs";
7
7
 
8
8
  // src/lib/create-project-helpers.ts
9
9
  import { existsSync, mkdirSync, writeFileSync } from "fs";
@@ -0,0 +1,176 @@
1
+ import {
2
+ dynamicImportFromUrl
3
+ } from "./chunk-LNCUPVEF.mjs";
4
+
5
+ // src/lib/export-helpers.ts
6
+ import { readdir, writeFile, mkdir } from "fs/promises";
7
+ import { join } from "path";
8
+ import { pathToFileURL } from "url";
9
+ var MSG_PATTERN = /\.msg\.(ts|js)$/i;
10
+ function isMsgResourceLike(value) {
11
+ return Boolean(value) && typeof value.getProject === "function";
12
+ }
13
+ var XLIFF20_NS = "urn:oasis:names:tc:xliff:document:2.0";
14
+ async function findMsgResourceFilePaths(directory) {
15
+ const result = [];
16
+ const entries = await readdir(directory, { withFileTypes: true });
17
+ for (const entry of entries) {
18
+ const fullPath = join(directory, entry.name);
19
+ if (entry.isFile() && MSG_PATTERN.test(entry.name)) {
20
+ result.push(fullPath);
21
+ } else if (entry.isDirectory()) {
22
+ result.push(...await findMsgResourceFilePaths(fullPath));
23
+ }
24
+ }
25
+ return result;
26
+ }
27
+ async function importMsgResourcesFromPaths(filePaths) {
28
+ const result = [];
29
+ for (const filePath of filePaths) {
30
+ if (!MSG_PATTERN.test(filePath)) {
31
+ throw new Error(`File does not have .msg. in filename: ${filePath}`);
32
+ }
33
+ const url = pathToFileURL(filePath).href;
34
+ const mod = await dynamicImportFromUrl(url);
35
+ const resource = mod.default ?? mod.resource ?? mod.MsgResource;
36
+ if (!isMsgResourceLike(resource)) {
37
+ throw new Error(
38
+ `Failed to import MsgResource from ${filePath}: no valid export found`
39
+ );
40
+ }
41
+ result.push(resource);
42
+ }
43
+ return result;
44
+ }
45
+ function groupResourcesByProject(resources) {
46
+ const byProject = /* @__PURE__ */ new Map();
47
+ for (const resource of resources) {
48
+ const projectName = resource.getProject().project.name;
49
+ let arr = byProject.get(projectName);
50
+ if (!arr) {
51
+ arr = [];
52
+ byProject.set(projectName, arr);
53
+ }
54
+ arr.push(resource);
55
+ }
56
+ return Array.from(byProject.entries(), ([project, resources2]) => ({
57
+ project,
58
+ resources: resources2
59
+ }));
60
+ }
61
+ function filterResourceGroupsByProject(groups, projectName) {
62
+ return groups.filter((g) => g.project === projectName);
63
+ }
64
+ function escapeXml(s) {
65
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
66
+ }
67
+ function sanitizeForXmlId(s) {
68
+ const sanitized = s.replace(/[^a-zA-Z0-9._:-]/g, "_").replace(/_+/g, "_");
69
+ if (/^[0-9]/.test(sanitized) || sanitized === "") {
70
+ return `k${sanitized}`;
71
+ }
72
+ return sanitized;
73
+ }
74
+ function noteTypeToCategory(type) {
75
+ const lower = type.toLowerCase();
76
+ if (lower.startsWith("x-")) return lower;
77
+ return ["description", "authorship", "parameters", "context", "comment"].includes(
78
+ lower
79
+ ) ? lower : `x-${lower}`;
80
+ }
81
+ function renderNotes(notes, idPrefix, indent = " ") {
82
+ const parts = [];
83
+ if (notes.length === 0) return parts;
84
+ const noteIndent = indent + " ";
85
+ parts.push(`${indent}<notes>`);
86
+ notes.forEach((n, i) => {
87
+ const cat = noteTypeToCategory(n.type);
88
+ const id = `${idPrefix}-n${i + 1}`;
89
+ parts.push(
90
+ `${noteIndent}<note id="${escapeXml(id)}" category="${escapeXml(cat)}">${escapeXml(n.content)}</note>`
91
+ );
92
+ });
93
+ parts.push(`${indent}</notes>`);
94
+ return parts;
95
+ }
96
+ function resourceGroupToXliff20(group) {
97
+ const srcLang = group.resources[0]?.attributes?.lang ?? "en";
98
+ const parts = [
99
+ '<?xml version="1.0" encoding="UTF-8"?>',
100
+ `<xliff xmlns="${XLIFF20_NS}" version="2.0" srcLang="${escapeXml(srcLang)}">`
101
+ ];
102
+ let fileIndex = 0;
103
+ for (const resource of group.resources) {
104
+ const orig = `${resource.title}.json`;
105
+ fileIndex += 1;
106
+ const fileId = `f${fileIndex}`;
107
+ const attrs = resource.attributes ?? {};
108
+ const fileAttrs = [
109
+ `id="${fileId}"`,
110
+ `original="${escapeXml(orig)}"`
111
+ ];
112
+ if (attrs.dir) {
113
+ fileAttrs.push(`srcDir="${escapeXml(attrs.dir)}"`);
114
+ }
115
+ if (attrs.dnt === true) {
116
+ fileAttrs.push('translate="no"');
117
+ }
118
+ parts.push(` <file ${fileAttrs.join(" ")}>`);
119
+ const data = resource.getData(false);
120
+ const resourceNotes = data.notes ?? [];
121
+ if (resourceNotes.length > 0) {
122
+ parts.push(...renderNotes(resourceNotes, fileId, " "));
123
+ }
124
+ const messages = data.messages ?? [];
125
+ messages.forEach((msg, idx) => {
126
+ const unitId = sanitizeForXmlId(msg.key) || `u${fileIndex}-${idx + 1}`;
127
+ const msgAttrs = [`id="${escapeXml(unitId)}"`];
128
+ if (msg.key) {
129
+ msgAttrs.push(`name="${escapeXml(msg.key)}"`);
130
+ }
131
+ const msgAttr = msg.attributes;
132
+ if (msgAttr?.dnt === true) {
133
+ msgAttrs.push('translate="no"');
134
+ }
135
+ if (msgAttr?.dir) {
136
+ msgAttrs.push(`srcDir="${escapeXml(msgAttr.dir)}"`);
137
+ }
138
+ parts.push(` <unit ${msgAttrs.join(" ")}>`);
139
+ const msgNotes = msg.notes ?? [];
140
+ if (msgNotes.length > 0) {
141
+ parts.push(
142
+ ...renderNotes(msgNotes, `${fileId}-${unitId}`, " ")
143
+ );
144
+ }
145
+ parts.push(" <segment>");
146
+ parts.push(` <source>${escapeXml(msg.value)}</source>`);
147
+ parts.push(" </segment>");
148
+ parts.push(" </unit>");
149
+ });
150
+ parts.push(" </file>");
151
+ }
152
+ parts.push("</xliff>");
153
+ return parts.join("\n");
154
+ }
155
+ function serializeResourceGroupsToXliff(groups) {
156
+ return groups.map((group) => ({
157
+ project: group.project,
158
+ xliff: resourceGroupToXliff20(group)
159
+ }));
160
+ }
161
+ async function writeXliffFiles(xliffDir, xliffGroups) {
162
+ await mkdir(xliffDir, { recursive: true });
163
+ for (const { project, xliff } of xliffGroups) {
164
+ const filePath = join(xliffDir, `${project}.xliff`);
165
+ await writeFile(filePath, xliff, "utf-8");
166
+ }
167
+ }
168
+
169
+ export {
170
+ findMsgResourceFilePaths,
171
+ importMsgResourcesFromPaths,
172
+ groupResourcesByProject,
173
+ filterResourceGroupsByProject,
174
+ serializeResourceGroupsToXliff,
175
+ writeXliffFiles
176
+ };
@@ -116,8 +116,8 @@ function addDirectoriesToPackageJson(pkg, i18nDir, l10nDir) {
116
116
  function addImportAliasesToPackageJson(pkg, i18nDir, l10nDir) {
117
117
  const imports = {
118
118
  ...pkg.imports,
119
- "#i18n/*": `${i18nDir}/*`,
120
- "#l10n/*": `${l10nDir}/*`,
119
+ "#i18n/*": `./${i18nDir}/*`,
120
+ "#l10n/*": `./${l10nDir}/*`,
121
121
  "#root/*": "./*"
122
122
  };
123
123
  return { ...pkg, imports };
@@ -125,8 +125,8 @@ function addImportAliasesToPackageJson(pkg, i18nDir, l10nDir) {
125
125
  function addScriptsToPackageJson(pkg) {
126
126
  const scripts = {
127
127
  ...pkg.scripts,
128
- "i18n-export": "msg export:resources",
129
- "l10n-import": "msg import:translations"
128
+ "i18n-export": "msg export",
129
+ "l10n-import": "msg import"
130
130
  };
131
131
  return { ...pkg, scripts };
132
132
  }
@@ -143,8 +143,8 @@ function addTsconfigPaths(tsconfigPath, i18nDir, l10nDir) {
143
143
  co.baseUrl = co.baseUrl ?? ".";
144
144
  co.paths = {
145
145
  ...co.paths,
146
- "#i18n/*": [`${i18nDir}/*`],
147
- "#l10n/*": [`${l10nDir}/*`],
146
+ "#i18n/*": [`./${i18nDir}/*`],
147
+ "#l10n/*": [`./${l10nDir}/*`],
148
148
  "#root/*": ["./*"]
149
149
  };
150
150
  writeFileSync(tsconfigPath, JSON.stringify(config, null, 2) + "\n", "utf-8");