@worldware/msg 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,11 +33,11 @@ A project configuration that defines:
33
33
 
34
34
  ### MsgResource
35
35
 
36
- A collection of messages (extends `Map<string, MsgMessage>`) representing a resource bundle. Each resource has:
36
+ A collection of messages (extends `Map<K, MsgMessage>`, where `K` defaults to `string`) representing a resource bundle. Each resource has:
37
37
  - A title/name
38
38
  - Attributes (language, text direction, do-not-translate flag)
39
39
  - Notes (descriptions, context, etc.)
40
- - Messages indexed by key
40
+ - Messages indexed by key. Dot-separated keys such as `home.cta.label` can be read as a nested tree with `toTree()`, and opting in with `as const` makes the keys type-checked (see [Typed message keys and the message tree](#typed-message-keys-and-the-message-tree)).
41
41
 
42
42
  ### MsgMessage
43
43
 
@@ -64,7 +64,7 @@ const loader = async (project, title, language) => {
64
64
  const module = await import(path, { with: { type: 'json' } });
65
65
  return module.default;
66
66
  } catch (error) {
67
- console.warn(`Translations for locale ${language} could not be loaded.`, error);
67
+ console.warn(`Translations for locale ${language} could not be loaded.`);
68
68
  return {
69
69
  title,
70
70
  attributes: { lang: language, dir: 'auto' },
@@ -149,6 +149,35 @@ const messages = await getMessages();
149
149
  messages.get('sampleKey2')?.format({ name: 'Alice' });
150
150
  ```
151
151
 
152
+ ### Typed message keys and the message tree
153
+
154
+ Define a resource's messages `as const` and TypeScript infers its keys: `get()`, `has()`, and `toTree()` then reject keys the resource doesn't define. `toTree()` returns a nested view of dot-separated keys.
155
+
156
+ ```typescript
157
+ const resource = MsgResource.create({
158
+ title: 'Home',
159
+ attributes: { lang: 'en', dir: 'ltr' },
160
+ messages: [
161
+ { key: 'home.title', value: 'Welcome' },
162
+ { key: 'home.cta.label', value: 'Hi, {name}' },
163
+ { key: 'footer', value: 'Footer' }
164
+ ] as const
165
+ }, project);
166
+
167
+ resource.get('home.titel'); // compile error: unknown key
168
+ const tree = resource.toTree();
169
+ tree.home.cta.label.format({ name: 'Ada' }); // autocompletes; typos are compile errors
170
+ tree.footer.toString(); // "Footer"
171
+ ```
172
+
173
+ - **Opt-in.** Without `as const`, keys are typed as `string`, so a resource can keep growing with `add()`. `add()` always accepts any string and doesn't change the resource's key type.
174
+ - **JavaScript files** (such as msg-cli's `.msg.js` resources) can't use `as const`. Use the JSDoc form instead, `messages: /** @type {const} */ ([ … ])`, and editors and `tsc --checkJs` give the same key checking.
175
+ - **Typed resources are still `MsgResource`s.** You can pass one anywhere a plain `MsgResource` is expected.
176
+ - **Translations keep the key type.** `translate()` and `getTranslation()` return a resource with the same keys as the source (see [Language fallbacks and translation layering](#language-fallbacks-and-translation-layering)).
177
+ - **No key can be both a message and a branch.** Adding `a` when `a.b` exists, or `a.b` when `a` exists, throws a `TypeError`. Replacing an existing key is fine, and `delete()` / `clear()` free the path again.
178
+ - **The tree is built on each call.** It holds the resource's own `MsgMessage` objects and reflects the resource at the time of the call. Keys such as `constructor` or `__proto__` are ordinary tree keys.
179
+ - **Limits.** One `as const` message list can hold up to about 10,000 messages (TypeScript's tuple limit). Resources loaded from JSON at runtime are untyped (`MsgResource<string>`), because their keys aren't known at compile time.
180
+
152
181
  ### Message Formats (MF1, MF2, NONE)
153
182
 
154
183
  Every message is formatted according to its resolved `format` attribute:
@@ -196,7 +225,8 @@ When serializing, an inherited `format` is omitted to keep output compact: a res
196
225
  const zhResource = await resource.getTranslation('zh');
197
226
 
198
227
  // The translated resource will have Chinese messages where available,
199
- // falling back to the source messages for missing translations
228
+ // falling back to the source messages for missing translations.
229
+ // It has exactly the source's keys: keys only the translation has are ignored.
200
230
 
201
231
  // Or use the scaffolded helper (honors setLang() / getLang())
202
232
  const messages = await getMessages();
@@ -210,7 +240,7 @@ When you call `resource.getTranslation(locale)`:
210
240
 
211
241
  1. The **source resource** (the resource you called it on) is the base.
212
242
  2. For each locale in that locale's chain, the project **loader** is called to load that locale's translation data.
213
- 3. Each loaded dataset is **layered** onto the current result: messages in the new data add or override by key; keys missing in the new layer keep the value from the previous layer.
243
+ 3. Each loaded dataset is **layered** onto the current result: messages in the new data override by key; keys missing in the new layer keep the value from the previous layer. Keys that aren't in the source resource are **ignored**, so a translation can't add messages (stale keys left in translation files are dropped).
214
244
  4. The final resource is the result after all layers have been applied.
215
245
 
216
246
  So for `getTranslation('zh-HK')` with chain `['zh', 'zh-Hant', 'zh-HK']`, you get: source → then zh overlay → then zh-Hant overlay → then zh-HK overlay. Later entries in the chain override earlier ones for the same key; missing keys fall back to the previous layer (and ultimately to the source).
@@ -297,15 +327,17 @@ const data = resource.getData();
297
327
  ### MsgResource
298
328
 
299
329
  **Static Methods:**
300
- - `create(data: MsgResourceData, project: MsgProject): MsgResource` - Create a new resource
330
+ - `create(data: MsgResourceData, project: MsgProject): MsgResource<K>` - Create a new resource. When `messages` is `as const`, `K` is the union of its keys; otherwise `string`. Throws a `TypeError` when one key is a dot-separated prefix of another (e.g. `a` and `a.b`)
301
331
 
302
332
  **Methods:**
303
- - `add(key: string, value: string, attributes?: MsgAttributes, notes?: MsgNote[]): MsgResource` - Add a message
333
+ - `add(key: string, value: string, attributes?: MsgAttributes, notes?: MsgNote[]): MsgResource<K>` - Add a message. Accepts any string key; throws a `TypeError` on a leaf/branch collision
334
+ - `set(key: K, message: MsgMessage)` / `delete(key: K)` / `clear()` - `Map` methods; `set()` also throws on a leaf/branch collision
335
+ - `toTree(): MsgTree<K>` - Nested, read-only view of dot-separated keys (`resource.toTree().home.title`). Built on each call from the resource's own messages
304
336
  - `addNote(type: NoteTypes, content: string): MsgResource` - Add a note (returns `this` for chaining)
305
- - `translate(data: MsgResourceData): MsgResource` - Create a translated version
306
- - `getTranslation(lang?: string): Promise<MsgResource>` - Load and apply translations. When `lang` matches the project's `pseudoLocale`, returns a resource with message values pseudo-localized according to each message's resolved `format` (`MF1` / `MF2` / `NONE`) instead of loading from the loader. When `lang` is omitted, returns a clone of the current resource.
337
+ - `translate(data: MsgResourceData): MsgResource<K>` - Create a translated version. Keys that aren't in this resource are ignored
338
+ - `getTranslation(lang?: string): Promise<MsgResource<K>>` - Load and apply translations. When `lang` matches the project's `pseudoLocale`, returns a resource with message values pseudo-localized according to each message's resolved `format` (`MF1` / `MF2` / `NONE`) instead of loading from the loader. When `lang` is omitted, returns a clone of the current resource.
307
339
  - `getProject(): MsgProject` - Returns the project instance associated with the resource
308
- - `getData(stripNotes?: boolean): MsgResourceData` - Get resource data. Message objects in the output omit `attributes` when they match the resource's attributes (to avoid redundancy). The resource's `format` is omitted when it equals the project's, and a message's `format` is omitted when it equals the resource's
340
+ - `getData(stripNotes?: boolean): MsgResourceData<K>` - Get resource data. Message objects in the output omit `attributes` when they match the resource's attributes (to avoid redundancy). The resource's `format` is omitted when it equals the project's, and a message's `format` is omitted when it equals the resource's
309
341
  - `toJSON(stripNotes?: boolean): string` - Serialize to JSON
310
342
 
311
343
  **Properties:**
@@ -335,6 +367,9 @@ const data = resource.getData();
335
367
 
336
368
  - `MsgFormat` - `'MF1' | 'MF2' | 'NONE'`; the formatting syntax for a message.
337
369
  - `MsgAttributes` - `{ lang?: string; dir?: string; dnt?: boolean; format?: MsgFormat }`. Omitted or empty `dir` resolves to `'auto'`.
370
+ - `MsgResourceData<K = string>` / `MsgMessageData<K = string>` - Plain resource and message data; `K` is the message key type.
371
+ - `MsgTree<K>` - Nested view of keys `K`: for `'home.title' | 'footer'`, `{ home: { title: MsgMessage }; footer: MsgMessage }`. `MsgTree<string>` is `MsgTreeNode`.
372
+ - `MsgTreeNode` - `{ readonly [segment: string]: MsgMessage | MsgTreeNode }`; the tree of an untyped resource.
338
373
 
339
374
  ### Pseudo-localization helpers
340
375
 
@@ -12,16 +12,52 @@ import {
12
12
  } from "./chunk-XQVALCKX.mjs";
13
13
 
14
14
  // src/classes/MsgResource/MsgResource.ts
15
+ function branchPrefixes(key) {
16
+ const prefixes = [];
17
+ for (let i = key.indexOf("."); i !== -1; i = key.indexOf(".", i + 1)) {
18
+ prefixes.push(key.slice(0, i));
19
+ }
20
+ return prefixes;
21
+ }
15
22
  var MsgResource = class _MsgResource extends Map {
16
23
  _attributes = {};
17
24
  _notes = [];
18
25
  _title;
19
26
  _project;
27
+ /**
28
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
29
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
30
+ * proportional to key depth instead of resource size.
31
+ */
32
+ _branches = /* @__PURE__ */ new Map();
20
33
  /**
21
34
  * Builds a resource from {@link MsgResourceData} and an owning project.
22
35
  *
23
36
  * When `messages` is provided, each entry is added to the resource.
24
37
  * When omitted, the resource starts empty.
38
+ *
39
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
40
+ * definition) is `as const`, the resource's key type is the union of its
41
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
42
+ * Without `as const` the key type is `string`, exactly as before, so a
43
+ * resource can keep growing through `add()`.
44
+ *
45
+ * ```ts
46
+ * const typed = MsgResource.create({
47
+ * title: 'Home',
48
+ * attributes: { lang: 'en' },
49
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
50
+ * }, project);
51
+ * typed.get('home.titel'); // compile error
52
+ * ```
53
+ *
54
+ * `as const` data is a tuple, so inference also scales to large resources:
55
+ * up to TypeScript's ~10,000-element tuple limit.
56
+ *
57
+ * @typeParam M - The message list; its `key` types become the resource's
58
+ * key type.
59
+ * @throws {TypeError} When one key is a dot-separated prefix of another
60
+ * (for example `a` and `a.b`).
25
61
  */
26
62
  static create(data, project) {
27
63
  const { title, attributes, notes, messages } = data;
@@ -29,7 +65,7 @@ var MsgResource = class _MsgResource extends Map {
29
65
  if (messages) {
30
66
  messages.forEach((messageData) => {
31
67
  const { key, value, attributes: attributes2, notes: notes2 } = messageData;
32
- res.add(key, value, attributes2, notes2);
68
+ res.add(key, value, attributes2, notes2 && [...notes2]);
33
69
  });
34
70
  } else {
35
71
  res.clear();
@@ -115,7 +151,11 @@ var MsgResource = class _MsgResource extends Map {
115
151
  * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
116
152
  * values on the message win.
117
153
  *
154
+ * Accepts any string key and does not change the resource's key type.
155
+ *
118
156
  * @returns This resource, for chaining.
157
+ * @throws {TypeError} When `key` and an existing key are dot-separated
158
+ * prefixes of one another (for example `a` and `a.b`).
119
159
  */
120
160
  add(key, value, attributes, notes) {
121
161
  const merged = { ...this.attributes, ...attributes };
@@ -128,12 +168,89 @@ var MsgResource = class _MsgResource extends Map {
128
168
  this.set(key, msg);
129
169
  return this;
130
170
  }
171
+ /**
172
+ * Stores a message under `key`.
173
+ *
174
+ * @throws {TypeError} When `key` and an existing key are dot-separated
175
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
176
+ * cannot be both a message and a branch.
177
+ */
178
+ set(key, value) {
179
+ if (!this.has(key)) {
180
+ this.assertNoCollision(key);
181
+ this.updateBranches(key, 1);
182
+ }
183
+ return super.set(key, value);
184
+ }
185
+ /** Removes the message stored under `key`. */
186
+ delete(key) {
187
+ const deleted = super.delete(key);
188
+ if (deleted) {
189
+ this.updateBranches(key, -1);
190
+ }
191
+ return deleted;
192
+ }
193
+ /** Removes every message from this resource. */
194
+ clear() {
195
+ super.clear();
196
+ this._branches.clear();
197
+ }
198
+ /**
199
+ * Throws when `key` would be both a message and a branch in the tree.
200
+ */
201
+ assertNoCollision(key) {
202
+ if (this._branches.has(key)) {
203
+ const descendant = [...this.keys()].find((existing) => existing.startsWith(`${key}.`));
204
+ throw new TypeError(`Message key "${key}" collides with "${descendant}": a key cannot also be a prefix of another key.`);
205
+ }
206
+ const leaf = branchPrefixes(key).find((prefix) => this.has(prefix));
207
+ if (leaf !== void 0) {
208
+ throw new TypeError(`Message key "${key}" collides with "${leaf}": a key cannot also be a prefix of another key.`);
209
+ }
210
+ }
211
+ /**
212
+ * Adds `delta` to the count of every branch `key` passes through,
213
+ * dropping branches that no key uses any more.
214
+ */
215
+ updateBranches(key, delta) {
216
+ for (const prefix of branchPrefixes(key)) {
217
+ const count = (this._branches.get(prefix) ?? 0) + delta;
218
+ if (count > 0) {
219
+ this._branches.set(prefix, count);
220
+ } else {
221
+ this._branches.delete(prefix);
222
+ }
223
+ }
224
+ }
225
+ /**
226
+ * Returns a nested, read-only view of this resource's messages, splitting
227
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
228
+ * under `'home.cta.label'`.
229
+ *
230
+ * The key type comes from `this` rather than the class parameter so that a
231
+ * typed resource stays assignable to a plain `MsgResource`.
232
+ */
233
+ toTree() {
234
+ const root = /* @__PURE__ */ Object.create(null);
235
+ for (const [key, msg] of this) {
236
+ const segments = key.split(".");
237
+ const leaf = segments.pop();
238
+ let node = root;
239
+ for (const segment of segments) {
240
+ node = node[segment] ??= /* @__PURE__ */ Object.create(null);
241
+ }
242
+ node[leaf] = msg;
243
+ }
244
+ return root;
245
+ }
131
246
  /**
132
247
  * Builds a translated copy of this resource from translation data.
133
248
  *
134
249
  * Messages present in the translation replace the source; missing keys keep
135
- * the source message. Notes are carried over from the source. Unspecified
136
- * message `lang`, `dir`, and `dnt` inherit from the translated resource.
250
+ * the source message. Keys that are not in this resource are ignored, so the
251
+ * translated resource has the same keys (and key type) as the source. Notes
252
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
253
+ * `dnt` inherit from the translated resource.
137
254
  *
138
255
  * @throws {TypeError} When the translation title does not match this resource.
139
256
  */
@@ -142,24 +259,28 @@ var MsgResource = class _MsgResource extends Map {
142
259
  if (title !== this.title) {
143
260
  throw new TypeError("Title of resource and translations do not match.");
144
261
  }
145
- const translated = _MsgResource.create({
262
+ const translated = new _MsgResource(
146
263
  title,
147
264
  // preserve the source resource's format unless the translation overrides it
148
- attributes: this.preserveFormat(attributes, this.attributes.format),
149
- notes: this.notes
265
+ this.preserveFormat(attributes, this.attributes.format),
266
+ this._project,
267
+ this.notes
150
268
  // transfer the notes
151
- }, this._project);
152
- this.forEach((msg) => {
153
- translated.set(msg.key, msg);
269
+ );
270
+ this.forEach((msg, key) => {
271
+ translated.set(key, msg);
154
272
  });
155
273
  messages?.forEach((messageData) => {
156
274
  const { key, value, attributes: attributes2 } = messageData;
157
275
  const source = this.get(key);
276
+ if (!source) {
277
+ return;
278
+ }
158
279
  translated.add(
159
280
  key,
160
281
  value,
161
- this.preserveFormat(attributes2, source?.attributes.format),
162
- source?.notes
282
+ this.preserveFormat(attributes2, source.attributes.format),
283
+ source.notes
163
284
  );
164
285
  });
165
286
  return translated;
@@ -189,8 +310,8 @@ var MsgResource = class _MsgResource extends Map {
189
310
  const project = this._project;
190
311
  const pseudoLocale = project.locales.pseudoLocale;
191
312
  if (lang === pseudoLocale) {
192
- const messages = [...this.values()].map((msg) => ({
193
- key: msg.key,
313
+ const messages = [...this.entries()].map(([key, msg]) => ({
314
+ key,
194
315
  value: pseudoLocalize(msg.value, this.resolveFormat(msg.attributes)),
195
316
  attributes: { ...msg.attributes, lang: pseudoLocale }
196
317
  }));
@@ -230,16 +351,16 @@ var MsgResource = class _MsgResource extends Map {
230
351
  const resourceFormat = this.resolveFormat(this.attributes);
231
352
  const projectFormat = this._project.format;
232
353
  const messages = [];
233
- this.forEach((msg) => {
354
+ this.forEach((msg, key) => {
234
355
  if (this.hasMatchingAttributes(msg)) {
235
356
  const data = {
236
- key: msg.key,
357
+ key,
237
358
  value: msg.value,
238
359
  notes: !stripNotes && msg.notes.length > 0 ? msg.notes : void 0
239
360
  };
240
361
  messages.push(data);
241
362
  } else {
242
- const data = msg.getData(stripNotes);
363
+ const data = { ...msg.getData(stripNotes), key };
243
364
  if (data.attributes && this.resolveFormat(data.attributes) === resourceFormat) {
244
365
  const { format, ...rest } = data.attributes;
245
366
  data.attributes = rest;
@@ -4,10 +4,13 @@ import { MsgInterface, MsgAttributes, MsgNote, NoteTypes } from '../MsgInterface
4
4
 
5
5
  /**
6
6
  * Plain data used to create a {@link MsgMessage}.
7
+ *
8
+ * @typeParam K - The message key. Defaults to `string`; `as const` message
9
+ * data lets `MsgResource.create()` infer a resource's key union.
7
10
  */
8
- type MsgMessageData = {
11
+ type MsgMessageData<K extends string = string> = {
9
12
  /** Unique key that identifies this message within a resource. */
10
- key: string;
13
+ key: K;
11
14
  /** The message string, possibly in MessageFormat syntax. */
12
15
  value: string;
13
16
  /** Optional locale and formatting metadata. */
@@ -4,10 +4,13 @@ import { MsgInterface, MsgAttributes, MsgNote, NoteTypes } from '../MsgInterface
4
4
 
5
5
  /**
6
6
  * Plain data used to create a {@link MsgMessage}.
7
+ *
8
+ * @typeParam K - The message key. Defaults to `string`; `as const` message
9
+ * data lets `MsgResource.create()` infer a resource's key union.
7
10
  */
8
- type MsgMessageData = {
11
+ type MsgMessageData<K extends string = string> = {
9
12
  /** Unique key that identifies this message within a resource. */
10
- key: string;
13
+ key: K;
11
14
  /** The message string, possibly in MessageFormat syntax. */
12
15
  value: string;
13
16
  /** Optional locale and formatting metadata. */
@@ -251,16 +251,52 @@ function pseudoLocalize(source, format, options) {
251
251
  }
252
252
 
253
253
  // src/classes/MsgResource/MsgResource.ts
254
+ function branchPrefixes(key) {
255
+ const prefixes = [];
256
+ for (let i = key.indexOf("."); i !== -1; i = key.indexOf(".", i + 1)) {
257
+ prefixes.push(key.slice(0, i));
258
+ }
259
+ return prefixes;
260
+ }
254
261
  var MsgResource = class _MsgResource extends Map {
255
262
  _attributes = {};
256
263
  _notes = [];
257
264
  _title;
258
265
  _project;
266
+ /**
267
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
268
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
269
+ * proportional to key depth instead of resource size.
270
+ */
271
+ _branches = /* @__PURE__ */ new Map();
259
272
  /**
260
273
  * Builds a resource from {@link MsgResourceData} and an owning project.
261
274
  *
262
275
  * When `messages` is provided, each entry is added to the resource.
263
276
  * When omitted, the resource starts empty.
277
+ *
278
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
279
+ * definition) is `as const`, the resource's key type is the union of its
280
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
281
+ * Without `as const` the key type is `string`, exactly as before, so a
282
+ * resource can keep growing through `add()`.
283
+ *
284
+ * ```ts
285
+ * const typed = MsgResource.create({
286
+ * title: 'Home',
287
+ * attributes: { lang: 'en' },
288
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
289
+ * }, project);
290
+ * typed.get('home.titel'); // compile error
291
+ * ```
292
+ *
293
+ * `as const` data is a tuple, so inference also scales to large resources:
294
+ * up to TypeScript's ~10,000-element tuple limit.
295
+ *
296
+ * @typeParam M - The message list; its `key` types become the resource's
297
+ * key type.
298
+ * @throws {TypeError} When one key is a dot-separated prefix of another
299
+ * (for example `a` and `a.b`).
264
300
  */
265
301
  static create(data, project) {
266
302
  const { title, attributes, notes, messages } = data;
@@ -268,7 +304,7 @@ var MsgResource = class _MsgResource extends Map {
268
304
  if (messages) {
269
305
  messages.forEach((messageData) => {
270
306
  const { key, value, attributes: attributes2, notes: notes2 } = messageData;
271
- res.add(key, value, attributes2, notes2);
307
+ res.add(key, value, attributes2, notes2 && [...notes2]);
272
308
  });
273
309
  } else {
274
310
  res.clear();
@@ -354,7 +390,11 @@ var MsgResource = class _MsgResource extends Map {
354
390
  * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
355
391
  * values on the message win.
356
392
  *
393
+ * Accepts any string key and does not change the resource's key type.
394
+ *
357
395
  * @returns This resource, for chaining.
396
+ * @throws {TypeError} When `key` and an existing key are dot-separated
397
+ * prefixes of one another (for example `a` and `a.b`).
358
398
  */
359
399
  add(key, value, attributes, notes) {
360
400
  const merged = { ...this.attributes, ...attributes };
@@ -367,12 +407,89 @@ var MsgResource = class _MsgResource extends Map {
367
407
  this.set(key, msg);
368
408
  return this;
369
409
  }
410
+ /**
411
+ * Stores a message under `key`.
412
+ *
413
+ * @throws {TypeError} When `key` and an existing key are dot-separated
414
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
415
+ * cannot be both a message and a branch.
416
+ */
417
+ set(key, value) {
418
+ if (!this.has(key)) {
419
+ this.assertNoCollision(key);
420
+ this.updateBranches(key, 1);
421
+ }
422
+ return super.set(key, value);
423
+ }
424
+ /** Removes the message stored under `key`. */
425
+ delete(key) {
426
+ const deleted = super.delete(key);
427
+ if (deleted) {
428
+ this.updateBranches(key, -1);
429
+ }
430
+ return deleted;
431
+ }
432
+ /** Removes every message from this resource. */
433
+ clear() {
434
+ super.clear();
435
+ this._branches.clear();
436
+ }
437
+ /**
438
+ * Throws when `key` would be both a message and a branch in the tree.
439
+ */
440
+ assertNoCollision(key) {
441
+ if (this._branches.has(key)) {
442
+ const descendant = [...this.keys()].find((existing) => existing.startsWith(`${key}.`));
443
+ throw new TypeError(`Message key "${key}" collides with "${descendant}": a key cannot also be a prefix of another key.`);
444
+ }
445
+ const leaf = branchPrefixes(key).find((prefix) => this.has(prefix));
446
+ if (leaf !== void 0) {
447
+ throw new TypeError(`Message key "${key}" collides with "${leaf}": a key cannot also be a prefix of another key.`);
448
+ }
449
+ }
450
+ /**
451
+ * Adds `delta` to the count of every branch `key` passes through,
452
+ * dropping branches that no key uses any more.
453
+ */
454
+ updateBranches(key, delta) {
455
+ for (const prefix of branchPrefixes(key)) {
456
+ const count = (this._branches.get(prefix) ?? 0) + delta;
457
+ if (count > 0) {
458
+ this._branches.set(prefix, count);
459
+ } else {
460
+ this._branches.delete(prefix);
461
+ }
462
+ }
463
+ }
464
+ /**
465
+ * Returns a nested, read-only view of this resource's messages, splitting
466
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
467
+ * under `'home.cta.label'`.
468
+ *
469
+ * The key type comes from `this` rather than the class parameter so that a
470
+ * typed resource stays assignable to a plain `MsgResource`.
471
+ */
472
+ toTree() {
473
+ const root = /* @__PURE__ */ Object.create(null);
474
+ for (const [key, msg] of this) {
475
+ const segments = key.split(".");
476
+ const leaf = segments.pop();
477
+ let node = root;
478
+ for (const segment of segments) {
479
+ node = node[segment] ??= /* @__PURE__ */ Object.create(null);
480
+ }
481
+ node[leaf] = msg;
482
+ }
483
+ return root;
484
+ }
370
485
  /**
371
486
  * Builds a translated copy of this resource from translation data.
372
487
  *
373
488
  * Messages present in the translation replace the source; missing keys keep
374
- * the source message. Notes are carried over from the source. Unspecified
375
- * message `lang`, `dir`, and `dnt` inherit from the translated resource.
489
+ * the source message. Keys that are not in this resource are ignored, so the
490
+ * translated resource has the same keys (and key type) as the source. Notes
491
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
492
+ * `dnt` inherit from the translated resource.
376
493
  *
377
494
  * @throws {TypeError} When the translation title does not match this resource.
378
495
  */
@@ -381,24 +498,28 @@ var MsgResource = class _MsgResource extends Map {
381
498
  if (title !== this.title) {
382
499
  throw new TypeError("Title of resource and translations do not match.");
383
500
  }
384
- const translated = _MsgResource.create({
501
+ const translated = new _MsgResource(
385
502
  title,
386
503
  // preserve the source resource's format unless the translation overrides it
387
- attributes: this.preserveFormat(attributes, this.attributes.format),
388
- notes: this.notes
504
+ this.preserveFormat(attributes, this.attributes.format),
505
+ this._project,
506
+ this.notes
389
507
  // transfer the notes
390
- }, this._project);
391
- this.forEach((msg) => {
392
- translated.set(msg.key, msg);
508
+ );
509
+ this.forEach((msg, key) => {
510
+ translated.set(key, msg);
393
511
  });
394
512
  messages?.forEach((messageData) => {
395
513
  const { key, value, attributes: attributes2 } = messageData;
396
514
  const source = this.get(key);
515
+ if (!source) {
516
+ return;
517
+ }
397
518
  translated.add(
398
519
  key,
399
520
  value,
400
- this.preserveFormat(attributes2, source?.attributes.format),
401
- source?.notes
521
+ this.preserveFormat(attributes2, source.attributes.format),
522
+ source.notes
402
523
  );
403
524
  });
404
525
  return translated;
@@ -428,8 +549,8 @@ var MsgResource = class _MsgResource extends Map {
428
549
  const project = this._project;
429
550
  const pseudoLocale = project.locales.pseudoLocale;
430
551
  if (lang === pseudoLocale) {
431
- const messages = [...this.values()].map((msg) => ({
432
- key: msg.key,
552
+ const messages = [...this.entries()].map(([key, msg]) => ({
553
+ key,
433
554
  value: pseudoLocalize(msg.value, this.resolveFormat(msg.attributes)),
434
555
  attributes: { ...msg.attributes, lang: pseudoLocale }
435
556
  }));
@@ -469,16 +590,16 @@ var MsgResource = class _MsgResource extends Map {
469
590
  const resourceFormat = this.resolveFormat(this.attributes);
470
591
  const projectFormat = this._project.format;
471
592
  const messages = [];
472
- this.forEach((msg) => {
593
+ this.forEach((msg, key) => {
473
594
  if (this.hasMatchingAttributes(msg)) {
474
595
  const data = {
475
- key: msg.key,
596
+ key,
476
597
  value: msg.value,
477
598
  notes: !stripNotes && msg.notes.length > 0 ? msg.notes : void 0
478
599
  };
479
600
  messages.push(data);
480
601
  } else {
481
- const data = msg.getData(stripNotes);
602
+ const data = { ...msg.getData(stripNotes), key };
482
603
  if (data.attributes && this.resolveFormat(data.attributes) === resourceFormat) {
483
604
  const { format, ...rest } = data.attributes;
484
605
  data.attributes = rest;
@@ -1,4 +1,4 @@
1
1
  import '../MsgMessage/MsgMessage.cjs';
2
2
  import '../MsgInterface/MsgInterface.cjs';
3
- export { MsgResource, MsgResourceData } from '../index.cjs';
3
+ export { MsgResource, MsgResourceData, MsgTree, MsgTreeNode } from '../index.cjs';
4
4
  import 'messageformat';
@@ -1,4 +1,4 @@
1
1
  import '../MsgMessage/MsgMessage.js';
2
2
  import '../MsgInterface/MsgInterface.js';
3
- export { MsgResource, MsgResourceData } from '../index.js';
3
+ export { MsgResource, MsgResourceData, MsgTree, MsgTreeNode } from '../index.js';
4
4
  import 'messageformat';
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  MsgResource
3
- } from "../../chunk-CRT2A2HP.mjs";
3
+ } from "../../chunk-HQMBNFN5.mjs";
4
4
  import "../../chunk-GHDKBE4P.mjs";
5
5
  import "../../chunk-RMZ42XIY.mjs";
6
6
  import "../../chunk-QU3HGZUN.mjs";