@worldware/msg-cli 0.3.0 → 0.4.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 (37) hide show
  1. package/README.md +49 -12
  2. package/dist/{chunk-6A6JGF7U.mjs → chunk-5VZRQBSH.mjs} +1 -1
  3. package/dist/{chunk-DIY2WO3R.mjs → chunk-77PP26JZ.mjs} +14 -17
  4. package/dist/{chunk-LNCUPVEF.mjs → chunk-JQKAEOL7.mjs} +64 -36
  5. package/dist/{chunk-XHD7F45F.mjs → chunk-KZ47S4SH.mjs} +42 -5
  6. package/dist/{chunk-DPUF7YUH.mjs → chunk-MGHC4AYZ.mjs} +18 -13
  7. package/dist/chunk-Q775ZGC5.mjs +29 -0
  8. package/dist/chunk-XID5J2F7.mjs +135 -0
  9. package/dist/commands/create/project.mjs +2 -2
  10. package/dist/commands/create/resource.cjs +64 -36
  11. package/dist/commands/create/resource.mjs +1 -1
  12. package/dist/commands/export.cjs +142 -16
  13. package/dist/commands/export.mjs +5 -3
  14. package/dist/commands/import.cjs +135 -17
  15. package/dist/commands/import.mjs +5 -3
  16. package/dist/lib/create-project-helpers.mjs +2 -2
  17. package/dist/lib/create-resource-helpers.cjs +64 -36
  18. package/dist/lib/create-resource-helpers.d.mts +4 -0
  19. package/dist/lib/create-resource-helpers.d.ts +4 -0
  20. package/dist/lib/create-resource-helpers.mjs +1 -1
  21. package/dist/lib/export-helpers.cjs +142 -16
  22. package/dist/lib/export-helpers.mjs +5 -3
  23. package/dist/lib/import-helpers.cjs +135 -17
  24. package/dist/lib/import-helpers.mjs +5 -3
  25. package/dist/lib/msg-format.cjs +55 -0
  26. package/dist/lib/msg-format.d.mts +28 -0
  27. package/dist/lib/msg-format.d.ts +28 -0
  28. package/dist/lib/msg-format.mjs +10 -0
  29. package/dist/lib/pgs-mf1.cjs +289 -0
  30. package/dist/lib/pgs-mf1.d.mts +28 -0
  31. package/dist/lib/pgs-mf1.d.ts +28 -0
  32. package/dist/lib/pgs-mf1.mjs +9 -0
  33. package/dist/lib/pgs-mf2.cjs +19 -13
  34. package/dist/lib/pgs-mf2.d.mts +9 -1
  35. package/dist/lib/pgs-mf2.d.ts +9 -1
  36. package/dist/lib/pgs-mf2.mjs +3 -1
  37. package/package.json +13 -3
package/README.md CHANGED
@@ -154,12 +154,39 @@ msg create resource myProject messages --edit
154
154
 
155
155
  **Behavior:**
156
156
 
157
- - Writes the file to `i18n/resources/<title>.msg.js` (always `.js`).
158
- - Uses ES module or CommonJS export syntax based on `package.json` `"type"` or presence of `tsconfig.json`.
157
+ - Writes the file to `i18n/resources/<title>.msg.js` (always `.js`, including TypeScript projects).
158
+ - Uses ES module or CommonJS syntax based on `package.json` `"type"` or presence of `tsconfig.json`.
159
+ - Imports the project via the `#i18n/projects/<projectName>` alias (added by `msg init`).
159
160
  - Sets `lang` from the project's `sourceLocale` and `dir` to `rtl` for Arabic/Hebrew, `ltr` otherwise.
160
- - Includes a minimal example message. Validates that the generated file is importable.
161
+ - 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.
162
+ - Includes sample messages added via chainable `.add()`. Validates that the generated file is importable.
161
163
  - Errors if i18n/projects or i18n/resources does not exist, the project is not found, or the resource file already exists (unless `--force`).
162
164
 
165
+ **Generated file (ESM excerpt):**
166
+
167
+ ```javascript
168
+ import { MsgResource, getLang } from '@worldware/msg';
169
+ import project from '#i18n/projects/myProject';
170
+
171
+ export const resource = MsgResource.create({ /* title, attributes, notes */ }, project);
172
+
173
+ resource
174
+ .add('sampleKey', 'Sample value.', {}, [/* notes */])
175
+ .add('sampleKey2', 'Hi, {name}', { dnt: true }, [/* notes */]);
176
+
177
+ export async function getMessages() {
178
+ return await resource.getTranslation(getLang());
179
+ }
180
+ ```
181
+
182
+ **Usage:**
183
+
184
+ ```javascript
185
+ import { getMessages } from '#i18n/resources/messages.msg.js';
186
+
187
+ const messages = await getMessages();
188
+ ```
189
+
163
190
  ### export
164
191
 
165
192
  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).
@@ -187,7 +214,7 @@ msg export -p myApp
187
214
  **Behavior:**
188
215
 
189
216
  - Recursively finds all `.msg.js` and `.msg.ts` files under `i18n/resources`.
190
- - Imports each file as a MsgResource; errors if any file is invalid.
217
+ - Imports each file as a MsgResource (default export, or named `resource` / `MsgResource`, including CJS `module.exports = { resource }`); errors if any file is invalid.
191
218
  - Groups resources by project name and writes one XLIFF 2.2 file per project to `l10n/xliff` (e.g. `myApp.xliff`).
192
219
  - With `--project`, only that project is exported; existing other files in `l10n/xliff` are not removed.
193
220
  - If no MsgResource files are found, exits with an informational message (no error).
@@ -200,12 +227,22 @@ msg export -p myApp
200
227
  - **Resource attributes** — `dir` → file `srcDir`; `dnt` → file `translate="no"`.
201
228
  - **Message notes** — Emitted as unit-level `<notes>` with category (e.g. `description`, `context`, `parameters`).
202
229
  - **Message attributes** — `dnt` → unit `translate="no"`; message `dir` is serialized as the unit’s `srcDir` attribute (XLIFF text direction for the segment).
230
+ - **Message format** — Resolved `format` (`NONE` / `MF1` / `MF2`, including inheritance from resource/project) is written as the unit `type` attribute using the XLIFF custom form `msg:NONE`, `msg:MF1`, or `msg:MF2`.
203
231
 
204
- **Plural, gender, select (PGS) and MessageFormat 2:** Messages written in Unicode MessageFormat 2 using `.match` are exported to the [XLIFF 2.2 Plural, Gender, and Select module](https://docs.oasis-open.org/xliff/xliff-core/v2.2/xliff-extended-v2.2-part2.html) when the selectors classify as `plural`, `ordinal`, `gender`, or `select` (see implementation in `pgs-mf2`). Such units use `xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0"`, `pgs:switch` on the `<unit>`, and one `<segment>` per variant with `pgs:case`. Other messages stay a single segment with the full MF2 string in `<source>`. Unsupported `.match` shapes fall back to that single-segment form.
232
+ **Plural, gender, select (PGS):** Classifiable plural/select messages are exported to the [XLIFF 2.2 Plural, Gender, and Select module](https://docs.oasis-open.org/xliff/xliff-core/v2.2/xliff-extended-v2.2-part2.html) (`xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0"`): `pgs:switch` on the `<unit>`, and one `<segment>` per variant with `pgs:case`.
233
+
234
+ - **MF2** — Unicode MessageFormat 2 `.match` messages (see `pgs-mf2`). Segment bodies keep MF2 pattern text. Unsupported `.match` shapes fall back to a single segment with the full string in `<source>`.
235
+ - **MF1** — ICU MessageFormat 1 `plural` / `selectordinal` / `select` messages (see `pgs-mf1`). Segment bodies use ICU-friendly text (`#` for the plural/ordinal variable, `{name}` for others).
236
+ - **NONE** — Always a single segment with the raw string (no PGS).
205
237
 
206
238
  ### import
207
239
 
208
- Import translations from bilingual XLIFF 2.0 or 2.2 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). Units with `pgs:switch` are reassembled into a single MessageFormat 2 string per message key from the segment bodies (targets when present).
240
+ Import translations from bilingual XLIFF 2.0 or 2.2 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).
241
+
242
+ **Format and PGS on import:**
243
+
244
+ - Unit `type` of `msg:NONE` / `msg:MF1` / `msg:MF2` (or bare `NONE` / `MF1` / `MF2`) is restored as the message `attributes.format`.
245
+ - Units with `pgs:switch` are reassembled from segment bodies (`<target>` when present): **MF1** → nested ICU MessageFormat 1; otherwise (including missing type) → MessageFormat 2 `.match`. Single-segment units are unchanged.
209
246
 
210
247
  ```bash
211
248
  msg import [-p <projectName>] [-l <locale>]
@@ -246,9 +283,9 @@ msg import -l zh
246
283
 
247
284
  ### Example: plural messages (XLIFF 2.2 PGS)
248
285
 
249
- Plural (and other classifiable `.match`) messages use the [XLIFF 2.2 PGS module](https://docs.oasis-open.org/xliff/xliff-core/v2.2/xliff-extended-v2.2-part2.html): export splits them into one `<segment>` per variant (`pgs:case`), and import merges `<target>` text back into a single MessageFormat 2 string per message key.
286
+ Plural (and other classifiable select) messages use the [XLIFF 2.2 PGS module](https://docs.oasis-open.org/xliff/xliff-core/v2.2/xliff-extended-v2.2-part2.html): export splits them into one `<segment>` per variant (`pgs:case`), and import merges `<target>` text back into a single message string per key. The unit `type` (`msg:MF1` or `msg:MF2`) selects ICU MessageFormat 1 vs MessageFormat 2 reconstruction.
250
287
 
251
- **1. Message in the MsgResource** (Unicode MessageFormat 2 with `.input` / `.match` on a plural):
288
+ **1. Message in the MsgResource** (MF2 `.match`, or MF1 `{count, plural, ...}` with `format: "MF1"`):
252
289
 
253
290
  ```js
254
291
  // i18n/resources/messages.msg.js — excerpt
@@ -271,7 +308,7 @@ The plural becomes a `pgs:switch` unit with one segment per case (abbreviated):
271
308
  <?xml version="1.0" encoding="UTF-8"?>
272
309
  <xliff xmlns="urn:oasis:names:tc:xliff:document:2.2" xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0" version="2.2" srcLang="en">
273
310
  <file id="f1" original="messages.json" srcDir="ltr">
274
- <unit id="itemsCount" name="itemsCount" pgs:switch="plural:n">
311
+ <unit id="itemsCount" name="itemsCount" type="msg:MF2" pgs:switch="plural:n">
275
312
  <segment id="itemsCount_s1" pgs:case="one">
276
313
  <source>One item</source>
277
314
  </segment>
@@ -288,7 +325,7 @@ The plural becomes a `pgs:switch` unit with one segment per case (abbreviated):
288
325
  ```xml
289
326
  <xliff xmlns="urn:oasis:names:tc:xliff:document:2.2" xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0" version="2.2" srcLang="en" trgLang="fr">
290
327
  <file id="f1" original="messages.json" srcDir="ltr">
291
- <unit id="itemsCount" name="itemsCount" pgs:switch="plural:n">
328
+ <unit id="itemsCount" name="itemsCount" type="msg:MF2" pgs:switch="plural:n">
292
329
  <segment id="itemsCount_s1" pgs:case="one">
293
330
  <source>One item</source>
294
331
  <target>Un élément</target>
@@ -302,7 +339,7 @@ The plural becomes a `pgs:switch` unit with one segment per case (abbreviated):
302
339
  </xliff>
303
340
  ```
304
341
 
305
- **4. Import** — writes minimal JSON under `l10n/translations/<project>/<locale>/<resource>.json`, with one MF2 message per key rebuilt from the PGS segments:
342
+ **4. Import** — writes minimal JSON under `l10n/translations/<project>/<locale>/<resource>.json`, with one message per key rebuilt from the PGS segments (MF2 `.match` when `type` is `msg:MF2` or omitted; ICU MF1 when `type` is `msg:MF1`):
306
343
 
307
344
  ```bash
308
345
  msg import
@@ -343,7 +380,7 @@ The CLI does not expose a programmatic API. For library usage, see [@worldware/m
343
380
  Source layout:
344
381
 
345
382
  - `src/commands/` — CLI commands (init, export, import, create/project, create/resource).
346
- - `src/lib/` — Shared utilities: init-helpers, export-helpers, import-helpers, create-project-helpers, create-resource-helpers.
383
+ - `src/lib/` — Shared utilities: init-helpers, export-helpers, import-helpers, create-project-helpers, create-resource-helpers, msg-format, pgs-mf1, pgs-mf2.
347
384
  - `src/tests/` — Vitest tests and fixtures.
348
385
 
349
386
  ## License
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  dynamicImportFromUrl
3
- } from "./chunk-LNCUPVEF.mjs";
3
+ } from "./chunk-JQKAEOL7.mjs";
4
4
  import {
5
5
  loadPackageJsonForMsg
6
6
  } from "./chunk-F7XZRKP7.mjs";
@@ -1,9 +1,15 @@
1
+ import {
2
+ unitTypeToFormat
3
+ } from "./chunk-Q775ZGC5.mjs";
4
+ import {
5
+ pgsImportToMf1Message
6
+ } from "./chunk-XID5J2F7.mjs";
1
7
  import {
2
8
  pgsImportToSelectMessage
3
- } from "./chunk-DPUF7YUH.mjs";
9
+ } from "./chunk-MGHC4AYZ.mjs";
4
10
  import {
5
11
  dynamicImportFromUrl
6
- } from "./chunk-LNCUPVEF.mjs";
12
+ } from "./chunk-JQKAEOL7.mjs";
7
13
 
8
14
  // src/lib/import-helpers.ts
9
15
  import { MsgResource } from "@worldware/msg";
@@ -186,6 +192,7 @@ function processUnit(unit, fileAttrs) {
186
192
  const trgDir = unit["@_trgDir"] ?? fileAttrs.trgDir;
187
193
  const translate = (unit["@_translate"] ?? "yes").toLowerCase();
188
194
  const dnt = translate === "no" || translate === "false";
195
+ const format = unitTypeToFormat(unit["@_type"]);
189
196
  const fileTranslate = (fileAttrs.translate ?? "yes").toLowerCase();
190
197
  const fileDnt = fileTranslate === "no" || fileTranslate === "false";
191
198
  const notes = [];
@@ -201,6 +208,7 @@ function processUnit(unit, fileAttrs) {
201
208
  }
202
209
  const segments = unit.segment ? Array.isArray(unit.segment) ? unit.segment : [unit.segment] : [];
203
210
  const pgsSwitch = unit["@_pgs:switch"];
211
+ const joinSegmentTexts = () => segments.map((seg) => extractSegmentText(seg)).join("");
204
212
  let value;
205
213
  if (pgsSwitch && segments.length > 0 && segments.every(
206
214
  (seg) => typeof seg["@_pgs:case"] === "string"
@@ -209,27 +217,16 @@ function processUnit(unit, fileAttrs) {
209
217
  caseAttr: seg["@_pgs:case"],
210
218
  body: extractSegmentText(seg)
211
219
  }));
212
- const rebuilt = pgsImportToSelectMessage(pgsSwitch, importSegments);
213
- if (rebuilt) {
214
- value = rebuilt;
215
- } else {
216
- const targetParts = [];
217
- for (const seg of segments) {
218
- targetParts.push(extractSegmentText(seg));
219
- }
220
- value = targetParts.join("");
221
- }
220
+ const rebuilt = format === "MF1" ? pgsImportToMf1Message(pgsSwitch, importSegments) : pgsImportToSelectMessage(pgsSwitch, importSegments);
221
+ value = rebuilt ?? joinSegmentTexts();
222
222
  } else {
223
- const targetParts = [];
224
- for (const seg of segments) {
225
- targetParts.push(extractSegmentText(seg));
226
- }
227
- value = targetParts.join("");
223
+ value = joinSegmentTexts();
228
224
  }
229
225
  const attributes = {};
230
226
  if (trgLang !== fileAttrs.trgLang) attributes.lang = trgLang || void 0;
231
227
  if (trgDir !== fileAttrs.trgDir) attributes.dir = trgDir || void 0;
232
228
  if (dnt !== fileDnt) attributes.dnt = dnt;
229
+ if (format) attributes.format = format;
233
230
  return {
234
231
  key: name,
235
232
  value,
@@ -71,52 +71,80 @@ async function importMsgProjectForResource(projectsDir, projectName) {
71
71
  }
72
72
  return void 0;
73
73
  }
74
+ function escapeSingleQuoted(value) {
75
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
76
+ }
74
77
  function generateMsgResourceContent(params) {
75
78
  const { title, projectName, sourceLocale, dir, isEsm } = params;
76
- const projectImport = isEsm ? `../projects/${projectName}.js` : `../projects/${projectName}`;
77
- const messagesBlock = ` messages: [
78
- {
79
- key: 'example.message',
80
- value: 'Example message.',
81
- notes: [
82
- { type: 'DESCRIPTION', content: 'This is an example message. You can delete it.' }
83
- ]
84
- }
85
- ]`;
86
- const titleStr = `'${title.replace(/'/g, "\\'")}'`;
87
- const langStr = `'${sourceLocale.replace(/'/g, "\\'")}'`;
79
+ const titleStr = `'${escapeSingleQuoted(title)}'`;
80
+ const langStr = `'${escapeSingleQuoted(sourceLocale)}'`;
88
81
  const dirStr = `'${dir}'`;
82
+ const resourceNote = `This is the ${escapeSingleQuoted(title)} resource.`;
83
+ const projectImport = `#i18n/projects/${escapeSingleQuoted(projectName)}`;
84
+ const createAndAdd = `MsgResource.create({
85
+ title: ${titleStr},
86
+ attributes: {
87
+ lang: ${langStr},
88
+ dir: ${dirStr}
89
+ },
90
+ notes: [
91
+ {type: 'DESCRIPTION', content: '${resourceNote}'}
92
+ ]
93
+ }, project);
94
+
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
+ ]);`;
89
108
  if (isEsm) {
90
- return `import { MsgResource } from '@worldware/msg';
109
+ return `/** ESM module **/
110
+
111
+ import { MsgResource, getLang } from '@worldware/msg';
91
112
  import project from '${projectImport}';
92
113
 
93
- export default MsgResource.create({
94
- title: ${titleStr},
95
- attributes: {
96
- lang: ${langStr},
97
- dir: ${dirStr}
98
- },
99
- notes: [
100
- { type: 'DESCRIPTION', content: 'This is a generated file. Replace this description with your own.' }
101
- ],
102
- ${messagesBlock}
103
- }, project);
114
+ /** Create a MsgResource object */
115
+
116
+ export const resource = ${createAndAdd}
117
+
118
+ /**
119
+ * An async function to get a translated version of the resource
120
+ * If the runtime language has not been set using \`setLang()\`,
121
+ * it will return the original resource
122
+ */
123
+ export async function getMessages() {
124
+ return await resource.getTranslation(getLang());
125
+ }
104
126
  `;
105
127
  }
106
- return `const { MsgResource } = require('@worldware/msg');
128
+ return `/** CJS implementation **/
129
+
130
+ const { MsgResource, getLang } = require('@worldware/msg');
107
131
  const project = require('${projectImport}');
108
132
 
109
- module.exports = MsgResource.create({
110
- title: ${titleStr},
111
- attributes: {
112
- lang: ${langStr},
113
- dir: ${dirStr}
114
- },
115
- notes: [
116
- { type: 'DESCRIPTION', content: 'This is a generated file. Replace this description with your own.' }
117
- ],
118
- ${messagesBlock}
119
- }, project);
133
+ const resource = ${createAndAdd}
134
+
135
+ /**
136
+ * An async function to get a translated version of the resource
137
+ * If a runtime language has not been set using \`setLang()\`,
138
+ * it will return the original resource
139
+ */
140
+ async function getMessages() {
141
+ return await resource.getTranslation(getLang());
142
+ }
143
+
144
+ module.exports = {
145
+ resource,
146
+ getMessages
147
+ }
120
148
  `;
121
149
  }
122
150
  function writeMsgResourceFile(filePath, content) {
@@ -1,11 +1,19 @@
1
+ import {
2
+ formatToUnitType,
3
+ resolveMessageFormat
4
+ } from "./chunk-Q775ZGC5.mjs";
5
+ import {
6
+ mf1MessageToPgsExport
7
+ } from "./chunk-XID5J2F7.mjs";
1
8
  import {
2
9
  selectMessageToPgsExport
3
- } from "./chunk-DPUF7YUH.mjs";
10
+ } from "./chunk-MGHC4AYZ.mjs";
4
11
  import {
5
12
  dynamicImportFromUrl
6
- } from "./chunk-LNCUPVEF.mjs";
13
+ } from "./chunk-JQKAEOL7.mjs";
7
14
 
8
15
  // src/lib/export-helpers.ts
16
+ import { MSG_DEFAULT_FORMAT } from "@worldware/msg";
9
17
  import { readdir, writeFile, mkdir } from "fs/promises";
10
18
  import { join } from "path";
11
19
  import { pathToFileURL } from "url";
@@ -13,6 +21,18 @@ var MSG_PATTERN = /\.msg\.(ts|js)$/i;
13
21
  function isMsgResourceLike(value) {
14
22
  return Boolean(value) && typeof value.getProject === "function";
15
23
  }
24
+ function resolveMsgResourceExport(mod) {
25
+ const defaultExport = mod.default;
26
+ const defaultRecord = defaultExport && typeof defaultExport === "object" ? defaultExport : void 0;
27
+ const candidates = [
28
+ defaultExport,
29
+ mod.resource,
30
+ mod.MsgResource,
31
+ defaultRecord?.resource,
32
+ defaultRecord?.MsgResource
33
+ ];
34
+ return candidates.find(isMsgResourceLike);
35
+ }
16
36
  var XLIFF22_NS = "urn:oasis:names:tc:xliff:document:2.2";
17
37
  var PGS_NS = "urn:oasis:names:tc:xliff:pgs:1.0";
18
38
  async function findMsgResourceFilePaths(directory) {
@@ -36,8 +56,8 @@ async function importMsgResourcesFromPaths(filePaths) {
36
56
  }
37
57
  const url = pathToFileURL(filePath).href;
38
58
  const mod = await dynamicImportFromUrl(url);
39
- const resource = mod.default ?? mod.resource ?? mod.MsgResource;
40
- if (!isMsgResourceLike(resource)) {
59
+ const resource = resolveMsgResourceExport(mod);
60
+ if (!resource) {
41
61
  throw new Error(
42
62
  `Failed to import MsgResource from ${filePath}: no valid export found`
43
63
  );
@@ -97,6 +117,11 @@ function renderNotes(notes, idPrefix, indent = " ") {
97
117
  parts.push(`${indent}</notes>`);
98
118
  return parts;
99
119
  }
120
+ function pgsExportForFormat(format, value) {
121
+ if (format === "MF1") return mf1MessageToPgsExport(value);
122
+ if (format === "MF2") return selectMessageToPgsExport(value);
123
+ return null;
124
+ }
100
125
  function resourceGroupToXliff22(group) {
101
126
  const srcLang = group.resources[0]?.attributes?.lang ?? "en";
102
127
  const parts = [
@@ -109,6 +134,12 @@ function resourceGroupToXliff22(group) {
109
134
  fileIndex += 1;
110
135
  const fileId = `f${fileIndex}`;
111
136
  const attrs = resource.attributes ?? {};
137
+ const projectFormat = resource.getProject().format ?? MSG_DEFAULT_FORMAT;
138
+ const resourceFormat = resolveMessageFormat(
139
+ void 0,
140
+ attrs.format,
141
+ projectFormat
142
+ );
112
143
  const fileAttrs = [
113
144
  `id="${fileId}"`,
114
145
  `original="${escapeXml(orig)}"`
@@ -139,7 +170,13 @@ function resourceGroupToXliff22(group) {
139
170
  if (msgAttr?.dir) {
140
171
  msgAttrs.push(`srcDir="${escapeXml(msgAttr.dir)}"`);
141
172
  }
142
- const pgsExport = selectMessageToPgsExport(msg.value);
173
+ const msgFormat = resolveMessageFormat(
174
+ msgAttr?.format,
175
+ resourceFormat,
176
+ projectFormat
177
+ );
178
+ msgAttrs.push(`type="${escapeXml(formatToUnitType(msgFormat))}"`);
179
+ const pgsExport = pgsExportForFormat(msgFormat, msg.value);
143
180
  if (pgsExport) {
144
181
  msgAttrs.push(`pgs:switch="${escapeXml(pgsExport.switchAttr)}"`);
145
182
  }
@@ -38,10 +38,13 @@ function findInputDeclaration(msg, varName) {
38
38
  function getFunctionName(expr) {
39
39
  return expr.functionRef?.name;
40
40
  }
41
+ function getOption(opts, key) {
42
+ if (!opts) return void 0;
43
+ if (opts instanceof Map) return opts.get(key);
44
+ return opts[key];
45
+ }
41
46
  function getSelectOptionOrdinal(expr) {
42
- const opts = expr.functionRef?.options;
43
- if (!opts || !(opts instanceof Map)) return false;
44
- const sel = opts.get("select");
47
+ const sel = getOption(expr.functionRef?.options, "select");
45
48
  if (!sel || typeof sel !== "object" || sel === null) return false;
46
49
  if (sel.type !== "literal") return false;
47
50
  return sel.value === "ordinal";
@@ -118,13 +121,7 @@ function stringifyPattern(pattern) {
118
121
  wrap
119
122
  );
120
123
  }
121
- function selectMessageToPgsExport(source) {
122
- let msg;
123
- try {
124
- msg = parseMessage(source);
125
- } catch {
126
- return null;
127
- }
124
+ function selectMessageDataToPgsExport(msg) {
128
125
  if (!isSelectMessage(msg)) return null;
129
126
  const classification = classifySelectMessageForPgs(
130
127
  msg
@@ -139,9 +136,7 @@ function selectMessageToPgsExport(source) {
139
136
  for (let ki = 0; ki < classification.length; ki++) {
140
137
  const key = variant.keys[ki];
141
138
  if (!key) return null;
142
- caseParts.push(
143
- mf2KeyToPgsToken(key, classification[ki].kind)
144
- );
139
+ caseParts.push(mf2KeyToPgsToken(key, classification[ki].kind));
145
140
  }
146
141
  segments.push({
147
142
  caseAttr: caseParts.join(" "),
@@ -150,6 +145,15 @@ function selectMessageToPgsExport(source) {
150
145
  }
151
146
  return { switchAttr, segments };
152
147
  }
148
+ function selectMessageToPgsExport(source) {
149
+ let msg;
150
+ try {
151
+ msg = parseMessage(source);
152
+ } catch {
153
+ return null;
154
+ }
155
+ return selectMessageDataToPgsExport(msg);
156
+ }
153
157
  function parsePatternFromSegmentBody(body) {
154
158
  const trimmed = body.trim();
155
159
  if (!trimmed) return [];
@@ -263,6 +267,7 @@ export {
263
267
  classifySelectMessageForPgs,
264
268
  mf2KeyToPgsToken,
265
269
  pgsTokenToMf2Key,
270
+ selectMessageDataToPgsExport,
266
271
  selectMessageToPgsExport,
267
272
  pgsImportToSelectMessage,
268
273
  messagesStructurallyEqual
@@ -0,0 +1,29 @@
1
+ // src/lib/msg-format.ts
2
+ import { MSG_DEFAULT_FORMAT } from "@worldware/msg";
3
+ var MSG_TYPE_PREFIX = "msg";
4
+ var FORMAT_VALUES = /* @__PURE__ */ new Set(["NONE", "MF1", "MF2"]);
5
+ function formatToUnitType(format) {
6
+ return `${MSG_TYPE_PREFIX}:${format}`;
7
+ }
8
+ function unitTypeToFormat(type) {
9
+ if (type == null || type === "") return void 0;
10
+ if (FORMAT_VALUES.has(type)) {
11
+ return type;
12
+ }
13
+ const prefixed = new RegExp(
14
+ `^${MSG_TYPE_PREFIX}:(NONE|MF1|MF2)$`
15
+ ).exec(type);
16
+ if (prefixed?.[1] && FORMAT_VALUES.has(prefixed[1])) {
17
+ return prefixed[1];
18
+ }
19
+ return void 0;
20
+ }
21
+ function resolveMessageFormat(messageFormat, resourceFormat, projectFormat) {
22
+ return messageFormat ?? resourceFormat ?? projectFormat ?? MSG_DEFAULT_FORMAT;
23
+ }
24
+
25
+ export {
26
+ formatToUnitType,
27
+ unitTypeToFormat,
28
+ resolveMessageFormat
29
+ };
@@ -0,0 +1,135 @@
1
+ import {
2
+ parsePgsSwitch,
3
+ selectMessageDataToPgsExport
4
+ } from "./chunk-MGHC4AYZ.mjs";
5
+
6
+ // src/lib/pgs-mf1.ts
7
+ import { parse } from "@messageformat/parser";
8
+ import { mf1ToMessageData } from "@messageformat/icu-messageformat-1";
9
+ import { parseMessage } from "messageformat";
10
+ function mf1MessageToPgsExport(source) {
11
+ try {
12
+ const data = mf1ToMessageData(parse(source));
13
+ const exp = selectMessageDataToPgsExport(data);
14
+ if (!exp) return null;
15
+ const parsedSwitch = parsePgsSwitch(exp.switchAttr);
16
+ if (!parsedSwitch) return null;
17
+ const hashVars = pluralVarNames(parsedSwitch);
18
+ return {
19
+ switchAttr: exp.switchAttr,
20
+ segments: exp.segments.map((seg) => ({
21
+ caseAttr: seg.caseAttr,
22
+ sourcePattern: segmentBodyToMf1(seg.sourcePattern, hashVars)
23
+ }))
24
+ };
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ function kindToIcuType(kind) {
30
+ if (kind === "plural") return "plural";
31
+ if (kind === "ordinal") return "selectordinal";
32
+ return "select";
33
+ }
34
+ function pluralVarNames(parsedSwitch) {
35
+ const names = /* @__PURE__ */ new Set();
36
+ for (const { kind, name } of parsedSwitch) {
37
+ if (kind === "plural" || kind === "ordinal") names.add(name);
38
+ }
39
+ return names;
40
+ }
41
+ function segmentBodyToMf1(body, hashVars) {
42
+ const trimmed = body.trim();
43
+ if (!trimmed) return "";
44
+ try {
45
+ const msg = parseMessage(trimmed);
46
+ if (msg.type !== "message") {
47
+ return escapeIcuLiteral(trimmed);
48
+ }
49
+ return patternPartsToMf1(
50
+ msg.pattern,
51
+ hashVars
52
+ );
53
+ } catch {
54
+ return escapeIcuLiteral(trimmed);
55
+ }
56
+ }
57
+ function patternPartsToMf1(pattern, hashVars) {
58
+ let out = "";
59
+ for (const part of pattern) {
60
+ if (typeof part === "string") {
61
+ out += escapeIcuLiteral(part);
62
+ continue;
63
+ }
64
+ if (!part || typeof part !== "object") continue;
65
+ const expr = part;
66
+ if (expr.type === "expression" && expr.arg?.type === "variable" && expr.arg.name) {
67
+ const name = expr.arg.name;
68
+ out += hashVars.has(name) ? "#" : `{${name}}`;
69
+ continue;
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+ function escapeIcuLiteral(s) {
75
+ return s.replace(/'/g, "''").replace(/([{}])/g, "'$1'");
76
+ }
77
+ function insertCase(tree, tokens, body, depth) {
78
+ if (tokens.length === 0) return false;
79
+ const token = tokens[depth];
80
+ if (token === void 0) return false;
81
+ if (depth === tokens.length - 1) {
82
+ tree.set(token, body);
83
+ return true;
84
+ }
85
+ let child = tree.get(token);
86
+ if (typeof child === "string") return false;
87
+ if (!child) {
88
+ child = /* @__PURE__ */ new Map();
89
+ tree.set(token, child);
90
+ }
91
+ return insertCase(child, tokens, body, depth + 1);
92
+ }
93
+ function serializeCaseTree(tree, parsedSwitch, depth, hashVars) {
94
+ const item = parsedSwitch[depth];
95
+ if (!item) return null;
96
+ const icuType = kindToIcuType(item.kind);
97
+ const parts = [];
98
+ for (const [key, child] of tree) {
99
+ let content;
100
+ if (typeof child === "string") {
101
+ content = segmentBodyToMf1(child, hashVars);
102
+ } else {
103
+ const nested = serializeCaseTree(
104
+ child,
105
+ parsedSwitch,
106
+ depth + 1,
107
+ hashVars
108
+ );
109
+ if (nested == null) return null;
110
+ content = nested;
111
+ }
112
+ parts.push(`${key} {${content}}`);
113
+ }
114
+ if (parts.length === 0) return null;
115
+ return `{${item.name}, ${icuType}, ${parts.join(" ")}}`;
116
+ }
117
+ function pgsImportToMf1Message(switchAttr, segments) {
118
+ const parsedSwitch = parsePgsSwitch(switchAttr);
119
+ if (!parsedSwitch || parsedSwitch.length === 0) return null;
120
+ const n = parsedSwitch.length;
121
+ if (segments.length === 0) return null;
122
+ const hashVars = pluralVarNames(parsedSwitch);
123
+ const tree = /* @__PURE__ */ new Map();
124
+ for (const seg of segments) {
125
+ const tokens = seg.caseAttr.trim().split(/\s+/).filter(Boolean);
126
+ if (tokens.length !== n) return null;
127
+ if (!insertCase(tree, tokens, seg.body, 0)) return null;
128
+ }
129
+ return serializeCaseTree(tree, parsedSwitch, 0, hashVars);
130
+ }
131
+
132
+ export {
133
+ mf1MessageToPgsExport,
134
+ pgsImportToMf1Message
135
+ };
@@ -3,8 +3,8 @@ import {
3
3
  importMsgProjectFile,
4
4
  loadPackageJsonForCreateProject,
5
5
  writeMsgProjectFile
6
- } from "../../chunk-6A6JGF7U.mjs";
7
- import "../../chunk-LNCUPVEF.mjs";
6
+ } from "../../chunk-5VZRQBSH.mjs";
7
+ import "../../chunk-JQKAEOL7.mjs";
8
8
  import {
9
9
  findPackageJsonPath
10
10
  } from "../../chunk-F7XZRKP7.mjs";