@worldware/msg-cli 0.1.3 → 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-BRZS5LYD.mjs → chunk-6A6JGF7U.mjs} +2 -2
  3. package/dist/chunk-BM3O7ZJW.mjs +176 -0
  4. package/dist/{chunk-AT7DHQF7.mjs → chunk-F7XZRKP7.mjs} +2 -2
  5. package/dist/chunk-KKATA5YE.mjs +324 -0
  6. package/dist/{chunk-T4ENP5TS.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 +2 -2
  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 +2 -2
  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
@@ -3,9 +3,9 @@ import {
3
3
  importMsgProjectFile,
4
4
  loadPackageJsonForCreateProject,
5
5
  writeMsgProjectFile
6
- } from "../chunk-BRZS5LYD.mjs";
7
- import "../chunk-T4ENP5TS.mjs";
8
- import "../chunk-AT7DHQF7.mjs";
6
+ } from "../chunk-6A6JGF7U.mjs";
7
+ import "../chunk-LNCUPVEF.mjs";
8
+ import "../chunk-F7XZRKP7.mjs";
9
9
  export {
10
10
  calculateRelativePath,
11
11
  importMsgProjectFile,
@@ -168,7 +168,7 @@ function generateMsgResourceContent(params) {
168
168
  key: 'example.message',
169
169
  value: 'Example message.',
170
170
  notes: [
171
- { type: 'description', content: 'This is an example message. You can delete it.' }
171
+ { type: 'DESCRIPTION', content: 'This is an example message. You can delete it.' }
172
172
  ]
173
173
  }
174
174
  ]`;
@@ -4,8 +4,8 @@ import {
4
4
  importMsgProjectForResource,
5
5
  readPackageJsonForCreateResource,
6
6
  writeMsgResourceFile
7
- } from "../chunk-T4ENP5TS.mjs";
8
- import "../chunk-AT7DHQF7.mjs";
7
+ } from "../chunk-LNCUPVEF.mjs";
8
+ import "../chunk-F7XZRKP7.mjs";
9
9
  export {
10
10
  dynamicImportFromUrl,
11
11
  generateMsgResourceContent,
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/lib/export-helpers.ts
21
+ var export_helpers_exports = {};
22
+ __export(export_helpers_exports, {
23
+ filterResourceGroupsByProject: () => filterResourceGroupsByProject,
24
+ findMsgResourceFilePaths: () => findMsgResourceFilePaths,
25
+ groupResourcesByProject: () => groupResourcesByProject,
26
+ importMsgResourcesFromPaths: () => importMsgResourcesFromPaths,
27
+ serializeResourceGroupsToXliff: () => serializeResourceGroupsToXliff,
28
+ writeXliffFiles: () => writeXliffFiles
29
+ });
30
+ module.exports = __toCommonJS(export_helpers_exports);
31
+ var import_promises = require("fs/promises");
32
+ var import_path = require("path");
33
+ var import_url2 = require("url");
34
+
35
+ // src/lib/create-resource-helpers.ts
36
+ var import_module = require("module");
37
+ var import_url = require("url");
38
+ async function dynamicImportFromUrl(url) {
39
+ try {
40
+ return await import(
41
+ /* @vite-ignore */
42
+ url
43
+ );
44
+ } catch (err) {
45
+ const msg = err instanceof Error ? err.message : String(err);
46
+ const useRequire = msg.includes("dynamic import callback") || msg.includes("ERR_VM_DYNAMIC_IMPORT");
47
+ if (useRequire) {
48
+ try {
49
+ const path = url.startsWith("file:") ? (0, import_url.fileURLToPath)(url) : url;
50
+ const base = (0, import_url.pathToFileURL)(process.cwd()).href;
51
+ const req = (0, import_module.createRequire)(base);
52
+ const mod = req(path);
53
+ return Promise.resolve(mod ?? {});
54
+ } catch {
55
+ }
56
+ }
57
+ throw err;
58
+ }
59
+ }
60
+
61
+ // src/lib/export-helpers.ts
62
+ var MSG_PATTERN = /\.msg\.(ts|js)$/i;
63
+ function isMsgResourceLike(value) {
64
+ return Boolean(value) && typeof value.getProject === "function";
65
+ }
66
+ var XLIFF20_NS = "urn:oasis:names:tc:xliff:document:2.0";
67
+ async function findMsgResourceFilePaths(directory) {
68
+ const result = [];
69
+ const entries = await (0, import_promises.readdir)(directory, { withFileTypes: true });
70
+ for (const entry of entries) {
71
+ const fullPath = (0, import_path.join)(directory, entry.name);
72
+ if (entry.isFile() && MSG_PATTERN.test(entry.name)) {
73
+ result.push(fullPath);
74
+ } else if (entry.isDirectory()) {
75
+ result.push(...await findMsgResourceFilePaths(fullPath));
76
+ }
77
+ }
78
+ return result;
79
+ }
80
+ async function importMsgResourcesFromPaths(filePaths) {
81
+ const result = [];
82
+ for (const filePath of filePaths) {
83
+ if (!MSG_PATTERN.test(filePath)) {
84
+ throw new Error(`File does not have .msg. in filename: ${filePath}`);
85
+ }
86
+ const url = (0, import_url2.pathToFileURL)(filePath).href;
87
+ const mod = await dynamicImportFromUrl(url);
88
+ const resource = mod.default ?? mod.resource ?? mod.MsgResource;
89
+ if (!isMsgResourceLike(resource)) {
90
+ throw new Error(
91
+ `Failed to import MsgResource from ${filePath}: no valid export found`
92
+ );
93
+ }
94
+ result.push(resource);
95
+ }
96
+ return result;
97
+ }
98
+ function groupResourcesByProject(resources) {
99
+ const byProject = /* @__PURE__ */ new Map();
100
+ for (const resource of resources) {
101
+ const projectName = resource.getProject().project.name;
102
+ let arr = byProject.get(projectName);
103
+ if (!arr) {
104
+ arr = [];
105
+ byProject.set(projectName, arr);
106
+ }
107
+ arr.push(resource);
108
+ }
109
+ return Array.from(byProject.entries(), ([project, resources2]) => ({
110
+ project,
111
+ resources: resources2
112
+ }));
113
+ }
114
+ function filterResourceGroupsByProject(groups, projectName) {
115
+ return groups.filter((g) => g.project === projectName);
116
+ }
117
+ function escapeXml(s) {
118
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
119
+ }
120
+ function sanitizeForXmlId(s) {
121
+ const sanitized = s.replace(/[^a-zA-Z0-9._:-]/g, "_").replace(/_+/g, "_");
122
+ if (/^[0-9]/.test(sanitized) || sanitized === "") {
123
+ return `k${sanitized}`;
124
+ }
125
+ return sanitized;
126
+ }
127
+ function noteTypeToCategory(type) {
128
+ const lower = type.toLowerCase();
129
+ if (lower.startsWith("x-")) return lower;
130
+ return ["description", "authorship", "parameters", "context", "comment"].includes(
131
+ lower
132
+ ) ? lower : `x-${lower}`;
133
+ }
134
+ function renderNotes(notes, idPrefix, indent = " ") {
135
+ const parts = [];
136
+ if (notes.length === 0) return parts;
137
+ const noteIndent = indent + " ";
138
+ parts.push(`${indent}<notes>`);
139
+ notes.forEach((n, i) => {
140
+ const cat = noteTypeToCategory(n.type);
141
+ const id = `${idPrefix}-n${i + 1}`;
142
+ parts.push(
143
+ `${noteIndent}<note id="${escapeXml(id)}" category="${escapeXml(cat)}">${escapeXml(n.content)}</note>`
144
+ );
145
+ });
146
+ parts.push(`${indent}</notes>`);
147
+ return parts;
148
+ }
149
+ function resourceGroupToXliff20(group) {
150
+ const srcLang = group.resources[0]?.attributes?.lang ?? "en";
151
+ const parts = [
152
+ '<?xml version="1.0" encoding="UTF-8"?>',
153
+ `<xliff xmlns="${XLIFF20_NS}" version="2.0" srcLang="${escapeXml(srcLang)}">`
154
+ ];
155
+ let fileIndex = 0;
156
+ for (const resource of group.resources) {
157
+ const orig = `${resource.title}.json`;
158
+ fileIndex += 1;
159
+ const fileId = `f${fileIndex}`;
160
+ const attrs = resource.attributes ?? {};
161
+ const fileAttrs = [
162
+ `id="${fileId}"`,
163
+ `original="${escapeXml(orig)}"`
164
+ ];
165
+ if (attrs.dir) {
166
+ fileAttrs.push(`srcDir="${escapeXml(attrs.dir)}"`);
167
+ }
168
+ if (attrs.dnt === true) {
169
+ fileAttrs.push('translate="no"');
170
+ }
171
+ parts.push(` <file ${fileAttrs.join(" ")}>`);
172
+ const data = resource.getData(false);
173
+ const resourceNotes = data.notes ?? [];
174
+ if (resourceNotes.length > 0) {
175
+ parts.push(...renderNotes(resourceNotes, fileId, " "));
176
+ }
177
+ const messages = data.messages ?? [];
178
+ messages.forEach((msg, idx) => {
179
+ const unitId = sanitizeForXmlId(msg.key) || `u${fileIndex}-${idx + 1}`;
180
+ const msgAttrs = [`id="${escapeXml(unitId)}"`];
181
+ if (msg.key) {
182
+ msgAttrs.push(`name="${escapeXml(msg.key)}"`);
183
+ }
184
+ const msgAttr = msg.attributes;
185
+ if (msgAttr?.dnt === true) {
186
+ msgAttrs.push('translate="no"');
187
+ }
188
+ if (msgAttr?.dir) {
189
+ msgAttrs.push(`srcDir="${escapeXml(msgAttr.dir)}"`);
190
+ }
191
+ parts.push(` <unit ${msgAttrs.join(" ")}>`);
192
+ const msgNotes = msg.notes ?? [];
193
+ if (msgNotes.length > 0) {
194
+ parts.push(
195
+ ...renderNotes(msgNotes, `${fileId}-${unitId}`, " ")
196
+ );
197
+ }
198
+ parts.push(" <segment>");
199
+ parts.push(` <source>${escapeXml(msg.value)}</source>`);
200
+ parts.push(" </segment>");
201
+ parts.push(" </unit>");
202
+ });
203
+ parts.push(" </file>");
204
+ }
205
+ parts.push("</xliff>");
206
+ return parts.join("\n");
207
+ }
208
+ function serializeResourceGroupsToXliff(groups) {
209
+ return groups.map((group) => ({
210
+ project: group.project,
211
+ xliff: resourceGroupToXliff20(group)
212
+ }));
213
+ }
214
+ async function writeXliffFiles(xliffDir, xliffGroups) {
215
+ await (0, import_promises.mkdir)(xliffDir, { recursive: true });
216
+ for (const { project, xliff } of xliffGroups) {
217
+ const filePath = (0, import_path.join)(xliffDir, `${project}.xliff`);
218
+ await (0, import_promises.writeFile)(filePath, xliff, "utf-8");
219
+ }
220
+ }
221
+ // Annotate the CommonJS export names for ESM import in node:
222
+ 0 && (module.exports = {
223
+ filterResourceGroupsByProject,
224
+ findMsgResourceFilePaths,
225
+ groupResourcesByProject,
226
+ importMsgResourcesFromPaths,
227
+ serializeResourceGroupsToXliff,
228
+ writeXliffFiles
229
+ });
@@ -0,0 +1,55 @@
1
+ import { MsgResource } from '@worldware/msg';
2
+
3
+ /** Object grouping resources with their project name (spec: resource group object). */
4
+ interface ResourceGroup {
5
+ project: string;
6
+ resources: MsgResource[];
7
+ }
8
+ /** Object grouping an XLIFF string with project name for filename (spec: xliff group object). */
9
+ interface XliffGroup {
10
+ project: string;
11
+ xliff: string;
12
+ }
13
+ /**
14
+ * Recursively finds all MsgResource files inside a directory (e.g. i18n/resources).
15
+ * Files must match .msg.(ts|js) in the filename.
16
+ * @param directory - Absolute path to the resources directory
17
+ * @returns Promise resolving to array of file paths
18
+ * @throws Error if directory cannot be read (e.g. does not exist)
19
+ */
20
+ declare function findMsgResourceFilePaths(directory: string): Promise<string[]>;
21
+ /**
22
+ * Dynamically imports MsgResource objects from an array of file paths.
23
+ * @param filePaths - Array of absolute paths to .msg.(ts|js) files
24
+ * @returns Promise resolving to array of MsgResource instances
25
+ * @throws Error if any file cannot be imported as a valid MsgResource
26
+ */
27
+ declare function importMsgResourcesFromPaths(filePaths: string[]): Promise<MsgResource[]>;
28
+ /**
29
+ * Groups MsgResource objects by their associated project name.
30
+ * @param resources - Array of MsgResource instances
31
+ * @returns Array of resource group objects { project, resources }
32
+ */
33
+ declare function groupResourcesByProject(resources: MsgResource[]): ResourceGroup[];
34
+ /**
35
+ * Filters resource groups to a single project by name.
36
+ * @param groups - Array of resource group objects
37
+ * @param projectName - Project name to keep
38
+ * @returns Filtered array (empty if no match)
39
+ */
40
+ declare function filterResourceGroupsByProject(groups: ResourceGroup[], projectName: string): ResourceGroup[];
41
+ /**
42
+ * Serializes each resource group to an XLIFF 2.0 string.
43
+ * @param groups - Array of resource group objects
44
+ * @returns Array of xliff group objects { project, xliff }
45
+ */
46
+ declare function serializeResourceGroupsToXliff(groups: ResourceGroup[]): XliffGroup[];
47
+ /**
48
+ * Writes each XLIFF string to a file in the given directory; filename is project name.
49
+ * Ensures the output directory exists.
50
+ * @param xliffDir - Absolute path to l10n/xliff directory
51
+ * @param xliffGroups - Array of { project, xliff } objects
52
+ */
53
+ declare function writeXliffFiles(xliffDir: string, xliffGroups: XliffGroup[]): Promise<void>;
54
+
55
+ export { type ResourceGroup, type XliffGroup, filterResourceGroupsByProject, findMsgResourceFilePaths, groupResourcesByProject, importMsgResourcesFromPaths, serializeResourceGroupsToXliff, writeXliffFiles };
@@ -0,0 +1,55 @@
1
+ import { MsgResource } from '@worldware/msg';
2
+
3
+ /** Object grouping resources with their project name (spec: resource group object). */
4
+ interface ResourceGroup {
5
+ project: string;
6
+ resources: MsgResource[];
7
+ }
8
+ /** Object grouping an XLIFF string with project name for filename (spec: xliff group object). */
9
+ interface XliffGroup {
10
+ project: string;
11
+ xliff: string;
12
+ }
13
+ /**
14
+ * Recursively finds all MsgResource files inside a directory (e.g. i18n/resources).
15
+ * Files must match .msg.(ts|js) in the filename.
16
+ * @param directory - Absolute path to the resources directory
17
+ * @returns Promise resolving to array of file paths
18
+ * @throws Error if directory cannot be read (e.g. does not exist)
19
+ */
20
+ declare function findMsgResourceFilePaths(directory: string): Promise<string[]>;
21
+ /**
22
+ * Dynamically imports MsgResource objects from an array of file paths.
23
+ * @param filePaths - Array of absolute paths to .msg.(ts|js) files
24
+ * @returns Promise resolving to array of MsgResource instances
25
+ * @throws Error if any file cannot be imported as a valid MsgResource
26
+ */
27
+ declare function importMsgResourcesFromPaths(filePaths: string[]): Promise<MsgResource[]>;
28
+ /**
29
+ * Groups MsgResource objects by their associated project name.
30
+ * @param resources - Array of MsgResource instances
31
+ * @returns Array of resource group objects { project, resources }
32
+ */
33
+ declare function groupResourcesByProject(resources: MsgResource[]): ResourceGroup[];
34
+ /**
35
+ * Filters resource groups to a single project by name.
36
+ * @param groups - Array of resource group objects
37
+ * @param projectName - Project name to keep
38
+ * @returns Filtered array (empty if no match)
39
+ */
40
+ declare function filterResourceGroupsByProject(groups: ResourceGroup[], projectName: string): ResourceGroup[];
41
+ /**
42
+ * Serializes each resource group to an XLIFF 2.0 string.
43
+ * @param groups - Array of resource group objects
44
+ * @returns Array of xliff group objects { project, xliff }
45
+ */
46
+ declare function serializeResourceGroupsToXliff(groups: ResourceGroup[]): XliffGroup[];
47
+ /**
48
+ * Writes each XLIFF string to a file in the given directory; filename is project name.
49
+ * Ensures the output directory exists.
50
+ * @param xliffDir - Absolute path to l10n/xliff directory
51
+ * @param xliffGroups - Array of { project, xliff } objects
52
+ */
53
+ declare function writeXliffFiles(xliffDir: string, xliffGroups: XliffGroup[]): Promise<void>;
54
+
55
+ export { type ResourceGroup, type XliffGroup, filterResourceGroupsByProject, findMsgResourceFilePaths, groupResourcesByProject, importMsgResourcesFromPaths, serializeResourceGroupsToXliff, writeXliffFiles };
@@ -0,0 +1,18 @@
1
+ import {
2
+ filterResourceGroupsByProject,
3
+ findMsgResourceFilePaths,
4
+ groupResourcesByProject,
5
+ importMsgResourcesFromPaths,
6
+ serializeResourceGroupsToXliff,
7
+ writeXliffFiles
8
+ } from "../chunk-BM3O7ZJW.mjs";
9
+ import "../chunk-LNCUPVEF.mjs";
10
+ import "../chunk-F7XZRKP7.mjs";
11
+ export {
12
+ filterResourceGroupsByProject,
13
+ findMsgResourceFilePaths,
14
+ groupResourcesByProject,
15
+ importMsgResourcesFromPaths,
16
+ serializeResourceGroupsToXliff,
17
+ writeXliffFiles
18
+ };