@worldware/msg 0.11.1 → 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.
@@ -255,16 +255,52 @@ function pseudoLocalize(source, format, options) {
255
255
  }
256
256
 
257
257
  // src/classes/MsgResource/MsgResource.ts
258
+ function branchPrefixes(key) {
259
+ const prefixes = [];
260
+ for (let i = key.indexOf("."); i !== -1; i = key.indexOf(".", i + 1)) {
261
+ prefixes.push(key.slice(0, i));
262
+ }
263
+ return prefixes;
264
+ }
258
265
  var MsgResource = class _MsgResource extends Map {
259
266
  _attributes = {};
260
267
  _notes = [];
261
268
  _title;
262
269
  _project;
270
+ /**
271
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
272
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
273
+ * proportional to key depth instead of resource size.
274
+ */
275
+ _branches = /* @__PURE__ */ new Map();
263
276
  /**
264
277
  * Builds a resource from {@link MsgResourceData} and an owning project.
265
278
  *
266
279
  * When `messages` is provided, each entry is added to the resource.
267
280
  * When omitted, the resource starts empty.
281
+ *
282
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
283
+ * definition) is `as const`, the resource's key type is the union of its
284
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
285
+ * Without `as const` the key type is `string`, exactly as before, so a
286
+ * resource can keep growing through `add()`.
287
+ *
288
+ * ```ts
289
+ * const typed = MsgResource.create({
290
+ * title: 'Home',
291
+ * attributes: { lang: 'en' },
292
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
293
+ * }, project);
294
+ * typed.get('home.titel'); // compile error
295
+ * ```
296
+ *
297
+ * `as const` data is a tuple, so inference also scales to large resources:
298
+ * up to TypeScript's ~10,000-element tuple limit.
299
+ *
300
+ * @typeParam M - The message list; its `key` types become the resource's
301
+ * key type.
302
+ * @throws {TypeError} When one key is a dot-separated prefix of another
303
+ * (for example `a` and `a.b`).
268
304
  */
269
305
  static create(data, project) {
270
306
  const { title, attributes, notes, messages } = data;
@@ -272,7 +308,7 @@ var MsgResource = class _MsgResource extends Map {
272
308
  if (messages) {
273
309
  messages.forEach((messageData) => {
274
310
  const { key, value, attributes: attributes2, notes: notes2 } = messageData;
275
- res.add(key, value, attributes2, notes2);
311
+ res.add(key, value, attributes2, notes2 && [...notes2]);
276
312
  });
277
313
  } else {
278
314
  res.clear();
@@ -355,7 +391,14 @@ var MsgResource = class _MsgResource extends Map {
355
391
  /**
356
392
  * Adds a message to this resource, merging resource attributes with any overrides.
357
393
  *
394
+ * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
395
+ * values on the message win.
396
+ *
397
+ * Accepts any string key and does not change the resource's key type.
398
+ *
358
399
  * @returns This resource, for chaining.
400
+ * @throws {TypeError} When `key` and an existing key are dot-separated
401
+ * prefixes of one another (for example `a` and `a.b`).
359
402
  */
360
403
  add(key, value, attributes, notes) {
361
404
  const merged = { ...this.attributes, ...attributes };
@@ -368,11 +411,89 @@ var MsgResource = class _MsgResource extends Map {
368
411
  this.set(key, msg);
369
412
  return this;
370
413
  }
414
+ /**
415
+ * Stores a message under `key`.
416
+ *
417
+ * @throws {TypeError} When `key` and an existing key are dot-separated
418
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
419
+ * cannot be both a message and a branch.
420
+ */
421
+ set(key, value) {
422
+ if (!this.has(key)) {
423
+ this.assertNoCollision(key);
424
+ this.updateBranches(key, 1);
425
+ }
426
+ return super.set(key, value);
427
+ }
428
+ /** Removes the message stored under `key`. */
429
+ delete(key) {
430
+ const deleted = super.delete(key);
431
+ if (deleted) {
432
+ this.updateBranches(key, -1);
433
+ }
434
+ return deleted;
435
+ }
436
+ /** Removes every message from this resource. */
437
+ clear() {
438
+ super.clear();
439
+ this._branches.clear();
440
+ }
441
+ /**
442
+ * Throws when `key` would be both a message and a branch in the tree.
443
+ */
444
+ assertNoCollision(key) {
445
+ if (this._branches.has(key)) {
446
+ const descendant = [...this.keys()].find((existing) => existing.startsWith(`${key}.`));
447
+ throw new TypeError(`Message key "${key}" collides with "${descendant}": a key cannot also be a prefix of another key.`);
448
+ }
449
+ const leaf = branchPrefixes(key).find((prefix) => this.has(prefix));
450
+ if (leaf !== void 0) {
451
+ throw new TypeError(`Message key "${key}" collides with "${leaf}": a key cannot also be a prefix of another key.`);
452
+ }
453
+ }
454
+ /**
455
+ * Adds `delta` to the count of every branch `key` passes through,
456
+ * dropping branches that no key uses any more.
457
+ */
458
+ updateBranches(key, delta) {
459
+ for (const prefix of branchPrefixes(key)) {
460
+ const count = (this._branches.get(prefix) ?? 0) + delta;
461
+ if (count > 0) {
462
+ this._branches.set(prefix, count);
463
+ } else {
464
+ this._branches.delete(prefix);
465
+ }
466
+ }
467
+ }
468
+ /**
469
+ * Returns a nested, read-only view of this resource's messages, splitting
470
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
471
+ * under `'home.cta.label'`.
472
+ *
473
+ * The key type comes from `this` rather than the class parameter so that a
474
+ * typed resource stays assignable to a plain `MsgResource`.
475
+ */
476
+ toTree() {
477
+ const root = /* @__PURE__ */ Object.create(null);
478
+ for (const [key, msg] of this) {
479
+ const segments = key.split(".");
480
+ const leaf = segments.pop();
481
+ let node = root;
482
+ for (const segment of segments) {
483
+ node = node[segment] ??= /* @__PURE__ */ Object.create(null);
484
+ }
485
+ node[leaf] = msg;
486
+ }
487
+ return root;
488
+ }
371
489
  /**
372
490
  * Builds a translated copy of this resource from translation data.
373
491
  *
374
492
  * Messages present in the translation replace the source; missing keys keep
375
- * the source message. Notes are carried over from the source.
493
+ * the source message. Keys that are not in this resource are ignored, so the
494
+ * translated resource has the same keys (and key type) as the source. Notes
495
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
496
+ * `dnt` inherit from the translated resource.
376
497
  *
377
498
  * @throws {TypeError} When the translation title does not match this resource.
378
499
  */
@@ -381,29 +502,29 @@ var MsgResource = class _MsgResource extends Map {
381
502
  if (title !== this.title) {
382
503
  throw new TypeError("Title of resource and translations do not match.");
383
504
  }
384
- const translated = _MsgResource.create({
505
+ const translated = new _MsgResource(
385
506
  title,
386
507
  // preserve the source resource's format unless the translation overrides it
387
- attributes: this.preserveFormat(attributes, this.attributes.format),
388
- notes: this.notes
508
+ this.preserveFormat(attributes, this.attributes.format),
509
+ this._project,
510
+ this.notes
389
511
  // transfer the notes
390
- }, this._project);
391
- this.forEach((msg) => {
392
- translated.set(msg.key, msg);
512
+ );
513
+ this.forEach((msg, key) => {
514
+ translated.set(key, msg);
393
515
  });
394
516
  messages?.forEach((messageData) => {
395
517
  const { key, value, attributes: attributes2 } = messageData;
396
- const msg = MsgMessage.create({
518
+ const source = this.get(key);
519
+ if (!source) {
520
+ return;
521
+ }
522
+ translated.add(
397
523
  key,
398
524
  value,
399
- // preserve the source message's format unless the translation overrides it
400
- attributes: this.preserveFormat(attributes2, this.get(key)?.attributes.format)
401
- });
402
- const notes = this.get(key)?.notes || [];
403
- notes.forEach((note) => {
404
- msg.addNote(note.type, note.content);
405
- });
406
- translated.set(key, msg);
525
+ this.preserveFormat(attributes2, source.attributes.format),
526
+ source.notes
527
+ );
407
528
  });
408
529
  return translated;
409
530
  }
@@ -432,8 +553,8 @@ var MsgResource = class _MsgResource extends Map {
432
553
  const project = this._project;
433
554
  const pseudoLocale = project.locales.pseudoLocale;
434
555
  if (lang === pseudoLocale) {
435
- const messages = [...this.values()].map((msg) => ({
436
- key: msg.key,
556
+ const messages = [...this.entries()].map(([key, msg]) => ({
557
+ key,
437
558
  value: pseudoLocalize(msg.value, this.resolveFormat(msg.attributes)),
438
559
  attributes: { ...msg.attributes, lang: pseudoLocale }
439
560
  }));
@@ -473,16 +594,16 @@ var MsgResource = class _MsgResource extends Map {
473
594
  const resourceFormat = this.resolveFormat(this.attributes);
474
595
  const projectFormat = this._project.format;
475
596
  const messages = [];
476
- this.forEach((msg) => {
597
+ this.forEach((msg, key) => {
477
598
  if (this.hasMatchingAttributes(msg)) {
478
599
  const data = {
479
- key: msg.key,
600
+ key,
480
601
  value: msg.value,
481
602
  notes: !stripNotes && msg.notes.length > 0 ? msg.notes : void 0
482
603
  };
483
604
  messages.push(data);
484
605
  } else {
485
- const data = msg.getData(stripNotes);
606
+ const data = { ...msg.getData(stripNotes), key };
486
607
  if (data.attributes && this.resolveFormat(data.attributes) === resourceFormat) {
487
608
  const { format, ...rest } = data.attributes;
488
609
  data.attributes = rest;
@@ -5,8 +5,10 @@ import 'messageformat';
5
5
 
6
6
  /**
7
7
  * Plain data used to create or describe a {@link MsgResource}.
8
+ *
9
+ * @typeParam K - Union of message keys. Defaults to `string`.
8
10
  */
9
- type MsgResourceData = {
11
+ type MsgResourceData<K extends string = string> = {
10
12
  /** Title that identifies this resource within a project. */
11
13
  title: string;
12
14
  /** Locale and formatting metadata for the resource. */
@@ -14,26 +16,103 @@ type MsgResourceData = {
14
16
  /** Optional notes for translators and tooling. */
15
17
  notes?: MsgNote[];
16
18
  /** Optional list of messages in this resource. */
17
- messages?: MsgMessageData[];
19
+ messages?: MsgMessageData<K>[];
20
+ };
21
+ /**
22
+ * The tree shape of an untyped resource (`MsgResource<string>`): every node is
23
+ * either a message or another branch.
24
+ */
25
+ type MsgTreeNode = {
26
+ readonly [segment: string]: MsgMessage | MsgTreeNode;
27
+ };
28
+ /** First dot-separated segment of a key: `'home.cta.label'` → `'home'`. */
29
+ type MsgKeyHead<K extends string> = K extends `${infer H}.${string}` ? H : K;
30
+ /** Remainder of a key after the segment `H`: `('home.cta.label', 'home')` → `'cta.label'`. */
31
+ type MsgKeyRest<K extends string, H extends string> = K extends `${H}.${infer R}` ? R : never;
32
+ /**
33
+ * Nested view of a resource's dot-separated message keys.
34
+ *
35
+ * For keys `'home.title' | 'home.cta.label' | 'footer'` this is
36
+ * `{ home: { title: MsgMessage; cta: { label: MsgMessage } }; footer: MsgMessage }`.
37
+ * When `K` is `string`, it is {@link MsgTreeNode}, so typed trees stay
38
+ * assignable to untyped ones.
39
+ *
40
+ * @typeParam K - Union of message keys.
41
+ */
42
+ type MsgTree<K extends string> = string extends K ? MsgTreeNode : {
43
+ readonly [H in MsgKeyHead<K>]: H extends K ? MsgMessage : MsgTree<MsgKeyRest<K, H>>;
18
44
  };
45
+ /**
46
+ * A message as {@link MsgResource.create} accepts it: {@link MsgMessageData}
47
+ * with readonly properties, so `as const` data is accepted.
48
+ */
49
+ type MsgMessageInput = {
50
+ readonly key: string;
51
+ readonly value: string;
52
+ readonly attributes?: Readonly<MsgAttributes>;
53
+ readonly notes?: readonly Readonly<MsgNote>[];
54
+ };
55
+ /**
56
+ * Key union of the messages passed to {@link MsgResource.create}. Keys are
57
+ * literal types only for `as const` data; an empty list yields `string` so
58
+ * the resource stays usable.
59
+ */
60
+ type MsgMessageKeys<M extends readonly MsgMessageInput[]> = M extends readonly [] ? string : M[number]['key'];
19
61
  /**
20
62
  * A named collection of messages belonging to a {@link MsgProject}.
21
63
  *
22
64
  * Resources inherit format defaults from their project, support translation
23
65
  * loading (including pseudo-localization), and can serialize to plain data.
66
+ *
67
+ * @typeParam K - Union of message keys. Inferred by {@link MsgResource.create}
68
+ * when its messages are `as const`; otherwise `string`.
24
69
  */
25
- declare class MsgResource extends Map<string, MsgMessage> implements MsgInterface {
70
+ declare class MsgResource<K extends string = string> extends Map<K, MsgMessage> implements MsgInterface {
26
71
  private _attributes;
27
72
  private _notes;
28
73
  private _title;
29
74
  private _project;
75
+ /**
76
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
77
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
78
+ * proportional to key depth instead of resource size.
79
+ */
80
+ private _branches;
30
81
  /**
31
82
  * Builds a resource from {@link MsgResourceData} and an owning project.
32
83
  *
33
84
  * When `messages` is provided, each entry is added to the resource.
34
85
  * When omitted, the resource starts empty.
86
+ *
87
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
88
+ * definition) is `as const`, the resource's key type is the union of its
89
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
90
+ * Without `as const` the key type is `string`, exactly as before, so a
91
+ * resource can keep growing through `add()`.
92
+ *
93
+ * ```ts
94
+ * const typed = MsgResource.create({
95
+ * title: 'Home',
96
+ * attributes: { lang: 'en' },
97
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
98
+ * }, project);
99
+ * typed.get('home.titel'); // compile error
100
+ * ```
101
+ *
102
+ * `as const` data is a tuple, so inference also scales to large resources:
103
+ * up to TypeScript's ~10,000-element tuple limit.
104
+ *
105
+ * @typeParam M - The message list; its `key` types become the resource's
106
+ * key type.
107
+ * @throws {TypeError} When one key is a dot-separated prefix of another
108
+ * (for example `a` and `a.b`).
35
109
  */
36
- static create(data: MsgResourceData, project: MsgProject): MsgResource;
110
+ static create<M extends readonly MsgMessageInput[] = MsgMessageData[]>(data: {
111
+ readonly title: string;
112
+ readonly attributes: Readonly<MsgAttributes>;
113
+ readonly notes?: readonly Readonly<MsgNote>[];
114
+ readonly messages?: M;
115
+ }, project: MsgProject): MsgResource<MsgMessageKeys<M>>;
37
116
  /**
38
117
  * Creates a resource bound to a project. Prefer {@link MsgResource.create}.
39
118
  */
@@ -77,18 +156,58 @@ declare class MsgResource extends Map<string, MsgMessage> implements MsgInterfac
77
156
  /**
78
157
  * Adds a message to this resource, merging resource attributes with any overrides.
79
158
  *
159
+ * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
160
+ * values on the message win.
161
+ *
162
+ * Accepts any string key and does not change the resource's key type.
163
+ *
80
164
  * @returns This resource, for chaining.
165
+ * @throws {TypeError} When `key` and an existing key are dot-separated
166
+ * prefixes of one another (for example `a` and `a.b`).
81
167
  */
82
168
  add(key: string, value: string, attributes?: MsgAttributes, notes?: MsgNote[]): this;
169
+ /**
170
+ * Stores a message under `key`.
171
+ *
172
+ * @throws {TypeError} When `key` and an existing key are dot-separated
173
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
174
+ * cannot be both a message and a branch.
175
+ */
176
+ set(key: K, value: MsgMessage): this;
177
+ /** Removes the message stored under `key`. */
178
+ delete(key: K): boolean;
179
+ /** Removes every message from this resource. */
180
+ clear(): void;
181
+ /**
182
+ * Throws when `key` would be both a message and a branch in the tree.
183
+ */
184
+ private assertNoCollision;
185
+ /**
186
+ * Adds `delta` to the count of every branch `key` passes through,
187
+ * dropping branches that no key uses any more.
188
+ */
189
+ private updateBranches;
190
+ /**
191
+ * Returns a nested, read-only view of this resource's messages, splitting
192
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
193
+ * under `'home.cta.label'`.
194
+ *
195
+ * The key type comes from `this` rather than the class parameter so that a
196
+ * typed resource stays assignable to a plain `MsgResource`.
197
+ */
198
+ toTree<T extends string>(this: MsgResource<T>): MsgTree<T>;
83
199
  /**
84
200
  * Builds a translated copy of this resource from translation data.
85
201
  *
86
202
  * Messages present in the translation replace the source; missing keys keep
87
- * the source message. Notes are carried over from the source.
203
+ * the source message. Keys that are not in this resource are ignored, so the
204
+ * translated resource has the same keys (and key type) as the source. Notes
205
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
206
+ * `dnt` inherit from the translated resource.
88
207
  *
89
208
  * @throws {TypeError} When the translation title does not match this resource.
90
209
  */
91
- translate(data: MsgResourceData): MsgResource;
210
+ translate(data: MsgResourceData): MsgResource<K>;
92
211
  /**
93
212
  * Merge a `format` into an attribute set unless one is already present,
94
213
  * so translations inherit the source's format without overriding an
@@ -108,7 +227,7 @@ declare class MsgResource extends Map<string, MsgMessage> implements MsgInterfac
108
227
  *
109
228
  * @throws {Error} When the locale is unsupported or its language chain is empty.
110
229
  */
111
- getTranslation(lang?: string): Promise<MsgResource>;
230
+ getTranslation(lang?: string): Promise<MsgResource<K>>;
112
231
  /**
113
232
  * Returns a plain data object for this resource and its messages.
114
233
  *
@@ -117,7 +236,7 @@ declare class MsgResource extends Map<string, MsgMessage> implements MsgInterfac
117
236
  *
118
237
  * @param stripNotes - When true, notes are omitted from the result.
119
238
  */
120
- getData(stripNotes?: boolean): MsgResourceData;
239
+ getData(stripNotes?: boolean): MsgResourceData<K>;
121
240
  /**
122
241
  * Serializes this resource to a formatted JSON string.
123
242
  *
@@ -207,4 +326,4 @@ declare class MsgProject {
207
326
  getTargetLocale(locale: string): string[] | undefined;
208
327
  }
209
328
 
210
- export { MsgAttributes, MsgFormat, MsgInterface, type MsgLocalesSettings, MsgMessage, MsgMessageData, MsgNote, MsgProject, type MsgProjectData, type MsgProjectSettings, MsgResource, type MsgResourceData, type MsgTargetLocalesSettings, type MsgTranslationLoader, NoteTypes };
329
+ export { MsgAttributes, MsgFormat, MsgInterface, type MsgLocalesSettings, MsgMessage, MsgMessageData, MsgNote, MsgProject, type MsgProjectData, type MsgProjectSettings, MsgResource, type MsgResourceData, type MsgTargetLocalesSettings, type MsgTranslationLoader, type MsgTree, type MsgTreeNode, NoteTypes };
@@ -5,8 +5,10 @@ import 'messageformat';
5
5
 
6
6
  /**
7
7
  * Plain data used to create or describe a {@link MsgResource}.
8
+ *
9
+ * @typeParam K - Union of message keys. Defaults to `string`.
8
10
  */
9
- type MsgResourceData = {
11
+ type MsgResourceData<K extends string = string> = {
10
12
  /** Title that identifies this resource within a project. */
11
13
  title: string;
12
14
  /** Locale and formatting metadata for the resource. */
@@ -14,26 +16,103 @@ type MsgResourceData = {
14
16
  /** Optional notes for translators and tooling. */
15
17
  notes?: MsgNote[];
16
18
  /** Optional list of messages in this resource. */
17
- messages?: MsgMessageData[];
19
+ messages?: MsgMessageData<K>[];
20
+ };
21
+ /**
22
+ * The tree shape of an untyped resource (`MsgResource<string>`): every node is
23
+ * either a message or another branch.
24
+ */
25
+ type MsgTreeNode = {
26
+ readonly [segment: string]: MsgMessage | MsgTreeNode;
27
+ };
28
+ /** First dot-separated segment of a key: `'home.cta.label'` → `'home'`. */
29
+ type MsgKeyHead<K extends string> = K extends `${infer H}.${string}` ? H : K;
30
+ /** Remainder of a key after the segment `H`: `('home.cta.label', 'home')` → `'cta.label'`. */
31
+ type MsgKeyRest<K extends string, H extends string> = K extends `${H}.${infer R}` ? R : never;
32
+ /**
33
+ * Nested view of a resource's dot-separated message keys.
34
+ *
35
+ * For keys `'home.title' | 'home.cta.label' | 'footer'` this is
36
+ * `{ home: { title: MsgMessage; cta: { label: MsgMessage } }; footer: MsgMessage }`.
37
+ * When `K` is `string`, it is {@link MsgTreeNode}, so typed trees stay
38
+ * assignable to untyped ones.
39
+ *
40
+ * @typeParam K - Union of message keys.
41
+ */
42
+ type MsgTree<K extends string> = string extends K ? MsgTreeNode : {
43
+ readonly [H in MsgKeyHead<K>]: H extends K ? MsgMessage : MsgTree<MsgKeyRest<K, H>>;
18
44
  };
45
+ /**
46
+ * A message as {@link MsgResource.create} accepts it: {@link MsgMessageData}
47
+ * with readonly properties, so `as const` data is accepted.
48
+ */
49
+ type MsgMessageInput = {
50
+ readonly key: string;
51
+ readonly value: string;
52
+ readonly attributes?: Readonly<MsgAttributes>;
53
+ readonly notes?: readonly Readonly<MsgNote>[];
54
+ };
55
+ /**
56
+ * Key union of the messages passed to {@link MsgResource.create}. Keys are
57
+ * literal types only for `as const` data; an empty list yields `string` so
58
+ * the resource stays usable.
59
+ */
60
+ type MsgMessageKeys<M extends readonly MsgMessageInput[]> = M extends readonly [] ? string : M[number]['key'];
19
61
  /**
20
62
  * A named collection of messages belonging to a {@link MsgProject}.
21
63
  *
22
64
  * Resources inherit format defaults from their project, support translation
23
65
  * loading (including pseudo-localization), and can serialize to plain data.
66
+ *
67
+ * @typeParam K - Union of message keys. Inferred by {@link MsgResource.create}
68
+ * when its messages are `as const`; otherwise `string`.
24
69
  */
25
- declare class MsgResource extends Map<string, MsgMessage> implements MsgInterface {
70
+ declare class MsgResource<K extends string = string> extends Map<K, MsgMessage> implements MsgInterface {
26
71
  private _attributes;
27
72
  private _notes;
28
73
  private _title;
29
74
  private _project;
75
+ /**
76
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
77
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
78
+ * proportional to key depth instead of resource size.
79
+ */
80
+ private _branches;
30
81
  /**
31
82
  * Builds a resource from {@link MsgResourceData} and an owning project.
32
83
  *
33
84
  * When `messages` is provided, each entry is added to the resource.
34
85
  * When omitted, the resource starts empty.
86
+ *
87
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
88
+ * definition) is `as const`, the resource's key type is the union of its
89
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
90
+ * Without `as const` the key type is `string`, exactly as before, so a
91
+ * resource can keep growing through `add()`.
92
+ *
93
+ * ```ts
94
+ * const typed = MsgResource.create({
95
+ * title: 'Home',
96
+ * attributes: { lang: 'en' },
97
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
98
+ * }, project);
99
+ * typed.get('home.titel'); // compile error
100
+ * ```
101
+ *
102
+ * `as const` data is a tuple, so inference also scales to large resources:
103
+ * up to TypeScript's ~10,000-element tuple limit.
104
+ *
105
+ * @typeParam M - The message list; its `key` types become the resource's
106
+ * key type.
107
+ * @throws {TypeError} When one key is a dot-separated prefix of another
108
+ * (for example `a` and `a.b`).
35
109
  */
36
- static create(data: MsgResourceData, project: MsgProject): MsgResource;
110
+ static create<M extends readonly MsgMessageInput[] = MsgMessageData[]>(data: {
111
+ readonly title: string;
112
+ readonly attributes: Readonly<MsgAttributes>;
113
+ readonly notes?: readonly Readonly<MsgNote>[];
114
+ readonly messages?: M;
115
+ }, project: MsgProject): MsgResource<MsgMessageKeys<M>>;
37
116
  /**
38
117
  * Creates a resource bound to a project. Prefer {@link MsgResource.create}.
39
118
  */
@@ -77,18 +156,58 @@ declare class MsgResource extends Map<string, MsgMessage> implements MsgInterfac
77
156
  /**
78
157
  * Adds a message to this resource, merging resource attributes with any overrides.
79
158
  *
159
+ * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
160
+ * values on the message win.
161
+ *
162
+ * Accepts any string key and does not change the resource's key type.
163
+ *
80
164
  * @returns This resource, for chaining.
165
+ * @throws {TypeError} When `key` and an existing key are dot-separated
166
+ * prefixes of one another (for example `a` and `a.b`).
81
167
  */
82
168
  add(key: string, value: string, attributes?: MsgAttributes, notes?: MsgNote[]): this;
169
+ /**
170
+ * Stores a message under `key`.
171
+ *
172
+ * @throws {TypeError} When `key` and an existing key are dot-separated
173
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
174
+ * cannot be both a message and a branch.
175
+ */
176
+ set(key: K, value: MsgMessage): this;
177
+ /** Removes the message stored under `key`. */
178
+ delete(key: K): boolean;
179
+ /** Removes every message from this resource. */
180
+ clear(): void;
181
+ /**
182
+ * Throws when `key` would be both a message and a branch in the tree.
183
+ */
184
+ private assertNoCollision;
185
+ /**
186
+ * Adds `delta` to the count of every branch `key` passes through,
187
+ * dropping branches that no key uses any more.
188
+ */
189
+ private updateBranches;
190
+ /**
191
+ * Returns a nested, read-only view of this resource's messages, splitting
192
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
193
+ * under `'home.cta.label'`.
194
+ *
195
+ * The key type comes from `this` rather than the class parameter so that a
196
+ * typed resource stays assignable to a plain `MsgResource`.
197
+ */
198
+ toTree<T extends string>(this: MsgResource<T>): MsgTree<T>;
83
199
  /**
84
200
  * Builds a translated copy of this resource from translation data.
85
201
  *
86
202
  * Messages present in the translation replace the source; missing keys keep
87
- * the source message. Notes are carried over from the source.
203
+ * the source message. Keys that are not in this resource are ignored, so the
204
+ * translated resource has the same keys (and key type) as the source. Notes
205
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
206
+ * `dnt` inherit from the translated resource.
88
207
  *
89
208
  * @throws {TypeError} When the translation title does not match this resource.
90
209
  */
91
- translate(data: MsgResourceData): MsgResource;
210
+ translate(data: MsgResourceData): MsgResource<K>;
92
211
  /**
93
212
  * Merge a `format` into an attribute set unless one is already present,
94
213
  * so translations inherit the source's format without overriding an
@@ -108,7 +227,7 @@ declare class MsgResource extends Map<string, MsgMessage> implements MsgInterfac
108
227
  *
109
228
  * @throws {Error} When the locale is unsupported or its language chain is empty.
110
229
  */
111
- getTranslation(lang?: string): Promise<MsgResource>;
230
+ getTranslation(lang?: string): Promise<MsgResource<K>>;
112
231
  /**
113
232
  * Returns a plain data object for this resource and its messages.
114
233
  *
@@ -117,7 +236,7 @@ declare class MsgResource extends Map<string, MsgMessage> implements MsgInterfac
117
236
  *
118
237
  * @param stripNotes - When true, notes are omitted from the result.
119
238
  */
120
- getData(stripNotes?: boolean): MsgResourceData;
239
+ getData(stripNotes?: boolean): MsgResourceData<K>;
121
240
  /**
122
241
  * Serializes this resource to a formatted JSON string.
123
242
  *
@@ -207,4 +326,4 @@ declare class MsgProject {
207
326
  getTargetLocale(locale: string): string[] | undefined;
208
327
  }
209
328
 
210
- export { MsgAttributes, MsgFormat, MsgInterface, type MsgLocalesSettings, MsgMessage, MsgMessageData, MsgNote, MsgProject, type MsgProjectData, type MsgProjectSettings, MsgResource, type MsgResourceData, type MsgTargetLocalesSettings, type MsgTranslationLoader, NoteTypes };
329
+ export { MsgAttributes, MsgFormat, MsgInterface, type MsgLocalesSettings, MsgMessage, MsgMessageData, MsgNote, MsgProject, type MsgProjectData, type MsgProjectSettings, MsgResource, type MsgResourceData, type MsgTargetLocalesSettings, type MsgTranslationLoader, type MsgTree, type MsgTreeNode, NoteTypes };
@@ -4,7 +4,7 @@ import {
4
4
  } from "../chunk-DJFPVXQ5.mjs";
5
5
  import {
6
6
  MsgResource
7
- } from "../chunk-VDOVMTPF.mjs";
7
+ } from "../chunk-HQMBNFN5.mjs";
8
8
  import "../chunk-GHDKBE4P.mjs";
9
9
  import {
10
10
  MsgMessage