@parlajs/compiler 0.0.0-stage → 0.0.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 (171) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -2
  3. package/build/build.d.ts +18 -0
  4. package/build/build.d.ts.map +1 -0
  5. package/build/build.js +10 -0
  6. package/build/cli.d.ts +3 -0
  7. package/build/cli.d.ts.map +1 -0
  8. package/build/cli.js +8 -0
  9. package/build/command.d.ts +13 -0
  10. package/build/command.d.ts.map +1 -0
  11. package/build/command.js +156 -0
  12. package/build/compile/code.d.ts +13 -0
  13. package/build/compile/code.d.ts.map +1 -0
  14. package/build/compile/code.js +42 -0
  15. package/build/compile/compile.d.ts +11 -0
  16. package/build/compile/compile.d.ts.map +1 -0
  17. package/build/compile/compile.js +244 -0
  18. package/build/compile/error.d.ts +4 -0
  19. package/build/compile/error.d.ts.map +1 -0
  20. package/build/compile/error.js +3 -0
  21. package/build/compile/info.d.ts +49 -0
  22. package/build/compile/info.d.ts.map +1 -0
  23. package/build/compile/info.js +22 -0
  24. package/build/compile/scope.d.ts +7 -0
  25. package/build/compile/scope.d.ts.map +1 -0
  26. package/build/compile/scope.js +14 -0
  27. package/build/compile/single.d.ts +11 -0
  28. package/build/compile/single.d.ts.map +1 -0
  29. package/build/compile/single.js +36 -0
  30. package/build/compile/variants.d.ts +16 -0
  31. package/build/compile/variants.d.ts.map +1 -0
  32. package/build/compile/variants.js +48 -0
  33. package/build/compile.d.ts +61 -0
  34. package/build/compile.d.ts.map +1 -0
  35. package/build/compile.js +385 -0
  36. package/build/config/checks.d.ts +21 -0
  37. package/build/config/checks.d.ts.map +1 -0
  38. package/build/config/checks.js +97 -0
  39. package/build/config/config.d.ts +71 -0
  40. package/build/config/config.d.ts.map +1 -0
  41. package/build/config/config.js +7 -0
  42. package/build/config/fallbacks.d.ts +6 -0
  43. package/build/config/fallbacks.d.ts.map +1 -0
  44. package/build/config/fallbacks.js +13 -0
  45. package/build/config/import.d.ts +31 -0
  46. package/build/config/import.d.ts.map +1 -0
  47. package/build/config/import.js +115 -0
  48. package/build/config/load.d.ts +13 -0
  49. package/build/config/load.d.ts.map +1 -0
  50. package/build/config/load.js +59 -0
  51. package/build/config.d.ts +77 -0
  52. package/build/config.d.ts.map +1 -0
  53. package/build/config.js +223 -0
  54. package/build/diagnostics.d.ts +31 -0
  55. package/build/diagnostics.d.ts.map +1 -0
  56. package/build/diagnostics.js +41 -0
  57. package/build/generate/checks.d.ts +9 -0
  58. package/build/generate/checks.d.ts.map +1 -0
  59. package/build/generate/checks.js +93 -0
  60. package/build/generate/chunk.d.ts +11 -0
  61. package/build/generate/chunk.d.ts.map +1 -0
  62. package/build/generate/chunk.js +57 -0
  63. package/build/generate/digits.d.ts +8 -0
  64. package/build/generate/digits.d.ts.map +1 -0
  65. package/build/generate/digits.js +57 -0
  66. package/build/generate/files.d.ts +7 -0
  67. package/build/generate/files.d.ts.map +1 -0
  68. package/build/generate/files.js +59 -0
  69. package/build/generate/locale.d.ts +21 -0
  70. package/build/generate/locale.d.ts.map +1 -0
  71. package/build/generate/locale.js +108 -0
  72. package/build/generate/modules.d.ts +27 -0
  73. package/build/generate/modules.d.ts.map +1 -0
  74. package/build/generate/modules.js +61 -0
  75. package/build/generate/namespace.d.ts +19 -0
  76. package/build/generate/namespace.d.ts.map +1 -0
  77. package/build/generate/namespace.js +65 -0
  78. package/build/generate/namespaces.d.ts +5 -0
  79. package/build/generate/namespaces.d.ts.map +1 -0
  80. package/build/generate/namespaces.js +41 -0
  81. package/build/generate/read.d.ts +21 -0
  82. package/build/generate/read.d.ts.map +1 -0
  83. package/build/generate/read.js +115 -0
  84. package/build/index.d.ts +9 -0
  85. package/build/index.d.ts.map +1 -0
  86. package/build/index.js +7 -0
  87. package/build/init/detect.d.ts +43 -0
  88. package/build/init/detect.d.ts.map +1 -0
  89. package/build/init/detect.js +69 -0
  90. package/build/init/init.d.ts +12 -0
  91. package/build/init/init.d.ts.map +1 -0
  92. package/build/init/init.js +126 -0
  93. package/build/options/date.d.ts +3 -0
  94. package/build/options/date.d.ts.map +1 -0
  95. package/build/options/date.js +77 -0
  96. package/build/options/literal.d.ts +10 -0
  97. package/build/options/literal.d.ts.map +1 -0
  98. package/build/options/literal.js +11 -0
  99. package/build/options/names.d.ts +5 -0
  100. package/build/options/names.d.ts.map +1 -0
  101. package/build/options/names.js +56 -0
  102. package/build/options/number.d.ts +3 -0
  103. package/build/options/number.d.ts.map +1 -0
  104. package/build/options/number.js +17 -0
  105. package/build/options/options.d.ts +7 -0
  106. package/build/options/options.d.ts.map +1 -0
  107. package/build/options/options.js +66 -0
  108. package/build/options.d.ts +9 -0
  109. package/build/options.d.ts.map +1 -0
  110. package/build/options.js +214 -0
  111. package/build/plurals.d.ts +6 -0
  112. package/build/plurals.d.ts.map +1 -0
  113. package/build/plurals.js +50 -0
  114. package/build/types/names.d.ts +9 -0
  115. package/build/types/names.d.ts.map +1 -0
  116. package/build/types/names.js +109 -0
  117. package/build/types/namespace.d.ts +17 -0
  118. package/build/types/namespace.d.ts.map +1 -0
  119. package/build/types/namespace.js +113 -0
  120. package/build/types/signature.d.ts +8 -0
  121. package/build/types/signature.d.ts.map +1 -0
  122. package/build/types/signature.js +87 -0
  123. package/build/types.d.ts +25 -0
  124. package/build/types.d.ts.map +1 -0
  125. package/build/types.js +250 -0
  126. package/build/vite.d.ts +9 -0
  127. package/build/vite.d.ts.map +1 -0
  128. package/build/vite.js +125 -0
  129. package/build/watch.d.ts +12 -0
  130. package/build/watch.d.ts.map +1 -0
  131. package/build/watch.js +93 -0
  132. package/package.json +84 -3
  133. package/src/build.ts +31 -0
  134. package/src/cli.ts +9 -0
  135. package/src/command.ts +195 -0
  136. package/src/compile/code.ts +51 -0
  137. package/src/compile/compile.ts +289 -0
  138. package/src/compile/error.ts +3 -0
  139. package/src/compile/info.ts +63 -0
  140. package/src/compile/scope.ts +14 -0
  141. package/src/compile/single.ts +46 -0
  142. package/src/compile/variants.ts +68 -0
  143. package/src/config/checks.ts +140 -0
  144. package/src/config/config.ts +83 -0
  145. package/src/config/fallbacks.ts +18 -0
  146. package/src/config/import.ts +146 -0
  147. package/src/config/load.ts +75 -0
  148. package/src/diagnostics.ts +98 -0
  149. package/src/generate/checks.ts +103 -0
  150. package/src/generate/chunk.ts +73 -0
  151. package/src/generate/digits.ts +74 -0
  152. package/src/generate/files.ts +83 -0
  153. package/src/generate/locale.ts +145 -0
  154. package/src/generate/modules.ts +94 -0
  155. package/src/generate/namespace.ts +119 -0
  156. package/src/generate/namespaces.ts +59 -0
  157. package/src/generate/read.ts +159 -0
  158. package/src/index.ts +27 -0
  159. package/src/init/detect.ts +103 -0
  160. package/src/init/init.ts +158 -0
  161. package/src/options/date.ts +87 -0
  162. package/src/options/literal.ts +21 -0
  163. package/src/options/names.ts +64 -0
  164. package/src/options/number.ts +20 -0
  165. package/src/options/options.ts +75 -0
  166. package/src/plurals.ts +68 -0
  167. package/src/types/names.ts +115 -0
  168. package/src/types/namespace.ts +148 -0
  169. package/src/types/signature.ts +111 -0
  170. package/src/vite.ts +143 -0
  171. package/src/watch.ts +115 -0
@@ -0,0 +1,87 @@
1
+ import { chosen, literal } from './literal.ts';
2
+ import type { Options } from './literal.ts';
3
+ import { FIELDS, SETTINGS } from './names.ts';
4
+
5
+ const DATE_FIELDS: ReadonlySet<string> = new Set([
6
+ 'weekday',
7
+ 'day-weekday',
8
+ 'month-day',
9
+ 'month-day-weekday',
10
+ 'year-month-day',
11
+ 'year-month-day-weekday',
12
+ ]);
13
+
14
+ const LENGTHS: ReadonlySet<string> = new Set(['long', 'medium', 'short']);
15
+
16
+ const PRECISIONS = ['hour', 'minute', 'second'];
17
+
18
+ /** MF2's fields, length and precision, as `Intl`'s fields. */
19
+ function semanticFields(name: string, options: Options): Options {
20
+ const { fields, dateFields, length, dateLength, precision, timePrecision, timeZoneStyle } =
21
+ options;
22
+ const out: Options = {};
23
+ if (name !== 'time') {
24
+ const size = length ?? dateLength;
25
+ const isLong = size ? chosen('length', { value: size, allowed: LENGTHS }) : 'medium';
26
+ const asked = fields ?? dateFields;
27
+ const set = asked ? chosen('fields', { value: asked, allowed: DATE_FIELDS }) : 'year-month-day';
28
+ const months: Record<string, string> = { long: 'long', medium: 'short', short: 'numeric' };
29
+ for (const field of set.split('-')) {
30
+ let value = 'numeric';
31
+ if (field === 'month') {
32
+ value = months[isLong] ?? value;
33
+ } else if (field === 'weekday') {
34
+ value = isLong === 'long' ? 'long' : 'short';
35
+ }
36
+ out[field] = literal(value);
37
+ }
38
+ }
39
+ if (name !== 'date') {
40
+ const asked = precision ?? timePrecision;
41
+ const until = asked
42
+ ? chosen('precision', { value: asked, allowed: new Set(PRECISIONS) })
43
+ : 'minute';
44
+ for (const field of PRECISIONS.slice(0, PRECISIONS.indexOf(until) + 1)) {
45
+ out[field] = literal('numeric');
46
+ }
47
+ if (timeZoneStyle) {
48
+ out['timeZoneName'] = timeZoneStyle;
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ const STYLES = ['style', 'dateStyle', 'timeStyle'];
55
+
56
+ const SEMANTIC = ['fields', 'dateFields', 'precision', 'timePrecision', 'timeZoneStyle'];
57
+
58
+ export function dateOptions(name: string, options: Options): Options {
59
+ const out = Object.fromEntries(
60
+ Object.entries(options).filter(([k]) => SETTINGS.includes(k) || FIELDS.includes(k)),
61
+ );
62
+ if (SEMANTIC.some((k) => options[k])) {
63
+ const style = STYLES.find((k) => options[k]);
64
+ if (style) {
65
+ throw new Error(`${style} cannot be combined with fields or a precision: use length`);
66
+ }
67
+ return { ...out, ...semanticFields(name, options) };
68
+ }
69
+ const { style, length, dateLength, dateStyle, timeStyle } = options;
70
+ if (style || length || dateLength || dateStyle || timeStyle) {
71
+ const size = style ?? length;
72
+ if (name === 'time') {
73
+ return { ...out, timeStyle: size ?? literal('short') };
74
+ }
75
+ out['dateStyle'] = dateStyle ?? dateLength ?? size ?? literal('medium');
76
+ return name === 'date' ? out : { ...out, timeStyle: timeStyle ?? literal('short') };
77
+ }
78
+ if (FIELDS.some((k) => options[k])) {
79
+ return out;
80
+ }
81
+ // Settings alone: the runtime adds the default style only to a call without options.
82
+ return {
83
+ ...out,
84
+ ...(name === 'time' ? {} : { dateStyle: literal('medium') }),
85
+ ...(name === 'date' ? {} : { timeStyle: literal('short') }),
86
+ };
87
+ }
@@ -0,0 +1,21 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ export type Value = Model.Literal | Model.VariableRef;
4
+
5
+ export type Options = Record<string, Value>;
6
+
7
+ export const literal = (value: string): Model.Literal => ({ type: 'literal', value });
8
+
9
+ /** A literal's value, which must be one of `allowed`; a variable cannot name fields at build time. */
10
+ export function chosen(
11
+ name: string,
12
+ { value, allowed }: { value: Value; allowed: ReadonlySet<string> },
13
+ ): string {
14
+ if (value.type !== 'literal') {
15
+ throw new Error(`${name} must be a literal`);
16
+ }
17
+ if (!allowed.has(value.value)) {
18
+ throw new Error(`${name} must be one of ${[...allowed].join(', ')}, not "${value.value}"`);
19
+ }
20
+ return value.value;
21
+ }
@@ -0,0 +1,64 @@
1
+ const DIGITS = [
2
+ 'minimumIntegerDigits',
3
+ 'minimumSignificantDigits',
4
+ 'maximumSignificantDigits',
5
+ 'roundingIncrement',
6
+ 'roundingMode',
7
+ 'roundingPriority',
8
+ 'trailingZeroDisplay',
9
+ ];
10
+
11
+ const COMMON = ['signDisplay', 'useGrouping', 'numberingSystem', 'select', 'offset', 'scale'];
12
+
13
+ const FRACTION = ['minimumFractionDigits', 'maximumFractionDigits'];
14
+
15
+ const COMPACT = ['notation', 'compactDisplay'];
16
+
17
+ const FORMAT = [...COMMON, ...DIGITS, ...FRACTION, ...COMPACT];
18
+
19
+ export const SETTINGS = ['calendar', 'numberingSystem', 'timeZone', 'hour12', 'hourCycle'];
20
+
21
+ export const FIELDS = [
22
+ 'weekday',
23
+ 'era',
24
+ 'year',
25
+ 'month',
26
+ 'day',
27
+ 'dayPeriod',
28
+ 'hour',
29
+ 'minute',
30
+ 'second',
31
+ 'fractionalSecondDigits',
32
+ 'timeZoneName',
33
+ ];
34
+
35
+ export const NUMBERS: Readonly<Record<string, ReadonlySet<string>>> = {
36
+ number: new Set([...FORMAT, 'style']),
37
+ integer: new Set([...COMMON, 'minimumIntegerDigits', 'maximumSignificantDigits', ...COMPACT]),
38
+ currency: new Set([
39
+ ...FORMAT,
40
+ 'fractionDigits',
41
+ 'currency',
42
+ 'currencyDisplay',
43
+ 'currencySign',
44
+ 'unitDisplay',
45
+ ]),
46
+ percent: new Set([...FORMAT, 'currencySign']),
47
+ unit: new Set([...FORMAT, 'unit', 'unitDisplay', 'currencyDisplay']),
48
+ };
49
+
50
+ export const DATES: Readonly<Record<string, ReadonlySet<string>>> = {
51
+ date: new Set([...SETTINGS, ...FIELDS, 'style', 'length', 'fields']),
52
+ time: new Set([...SETTINGS, ...FIELDS, 'style', 'length', 'precision', 'timeZoneStyle']),
53
+ datetime: new Set([
54
+ ...SETTINGS,
55
+ ...FIELDS,
56
+ 'style',
57
+ 'dateStyle',
58
+ 'timeStyle',
59
+ 'dateFields',
60
+ 'dateLength',
61
+ 'timePrecision',
62
+ 'timeZoneStyle',
63
+ ]),
64
+ };
@@ -0,0 +1,20 @@
1
+ import { chosen, literal } from './literal.ts';
2
+ import type { Options } from './literal.ts';
3
+
4
+ const SELECTS: ReadonlySet<string> = new Set(['plural', 'cardinal', 'ordinal', 'exact']);
5
+
6
+ export function numberOptions(options: Options): Options {
7
+ const { fractionDigits, ...out } = options;
8
+ if (fractionDigits && !(fractionDigits.type === 'literal' && fractionDigits.value === 'auto')) {
9
+ out['minimumFractionDigits'] = fractionDigits;
10
+ out['maximumFractionDigits'] = fractionDigits;
11
+ }
12
+ const { select, useGrouping } = out;
13
+ if (select?.type === 'literal') {
14
+ chosen('select', { value: select, allowed: SELECTS });
15
+ }
16
+ if (useGrouping?.type === 'literal' && useGrouping.value === 'never') {
17
+ out['useGrouping'] = literal('false');
18
+ }
19
+ return out;
20
+ }
@@ -0,0 +1,75 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ import { dateOptions } from './date.ts';
4
+ import type { Options } from './literal.ts';
5
+ import { DATES, NUMBERS } from './names.ts';
6
+ import { numberOptions } from './number.ts';
7
+
8
+ // An `Intl` object per message made a build 7 times slower.
9
+ const checked = new Set<string>();
10
+
11
+ /** Throws what `Intl` would at run time, where every option is a literal. */
12
+ function check(name: string, options: Options): void {
13
+ const key = name + JSON.stringify(options);
14
+ if (checked.has(key)) {
15
+ return;
16
+ }
17
+ const given: Record<string, unknown> = {};
18
+ for (const [k, v] of Object.entries(options)) {
19
+ if (v.type !== 'literal') {
20
+ return;
21
+ }
22
+ given[k] = v.value === 'false' || v.value === 'true' ? v.value === 'true' : v.value;
23
+ }
24
+ if (Object.hasOwn(NUMBERS, name)) {
25
+ const style = name === 'number' || name === 'integer' ? {} : { style: name };
26
+ // oxlint-disable-next-line no-new -- only its errors matter
27
+ new Intl.NumberFormat('en', { ...given, ...style } as Intl.NumberFormatOptions);
28
+ } else {
29
+ // oxlint-disable-next-line no-new -- only its errors matter
30
+ new Intl.DateTimeFormat('en', given);
31
+ }
32
+ checked.add(key);
33
+ }
34
+
35
+ /** Which of a variable's options a function applied to it takes over. */
36
+ export function inheritedOptions(from: Model.FunctionRef, to: string): Options {
37
+ const own = NUMBERS[to];
38
+ const entries = Object.entries(from.options ?? {});
39
+ if (own && Object.hasOwn(NUMBERS, from.name)) {
40
+ // `offset` is a plural's: only its own `#` subtracts it.
41
+ return Object.fromEntries(
42
+ entries.filter(([k]) => own.has(k) && k !== 'style' && k !== 'offset'),
43
+ );
44
+ }
45
+ if (from.name === to) {
46
+ return Object.fromEntries(entries);
47
+ }
48
+ return Object.hasOwn(DATES, to) && Object.hasOwn(DATES, from.name)
49
+ ? Object.fromEntries(
50
+ entries.filter(([k]) => k === 'calendar' || k === 'timeZone' || k === 'hour12'),
51
+ )
52
+ : {};
53
+ }
54
+
55
+ /** A built-in function's options as `Intl` takes them; throws for one it cannot honour. */
56
+ export function intlOptions({ name, options = {} }: Model.FunctionRef): Options {
57
+ const known = NUMBERS[name] ?? DATES[name] ?? new Set<string>();
58
+ const entries = Object.entries(options).filter(([k]) => k !== 'u:id');
59
+ for (const [key] of entries) {
60
+ if (!known.has(key)) {
61
+ throw new Error(`:${name} has no option "${key}"`);
62
+ }
63
+ }
64
+ if (entries.length === 0 && name !== 'currency' && name !== 'unit') {
65
+ return {};
66
+ }
67
+ const given = Object.fromEntries(entries);
68
+ try {
69
+ const out = Object.hasOwn(NUMBERS, name) ? numberOptions(given) : dateOptions(name, given);
70
+ check(name, out);
71
+ return out;
72
+ } catch (error) {
73
+ throw new Error(`:${name}: ${(error as Error).message}`, { cause: error });
74
+ }
75
+ }
package/src/plurals.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { MessageInfo } from './compile/info.ts';
2
+
3
+ // Italian's `many` is for millions: asking every catalog for it would be noise.
4
+ const COMMON = Array.from({ length: 1000 }, (_, n) => n);
5
+ const CATEGORIES: ReadonlySet<string> = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
6
+
7
+ interface Rules {
8
+ readonly rules: Intl.PluralRules;
9
+ /** The numbers below 1000 of each category. */
10
+ readonly numbers: ReadonlyMap<string, ReadonlyArray<string>>;
11
+ }
12
+
13
+ const known = new Map<string, Rules | undefined>();
14
+
15
+ function makeRules(locale: string, type: Intl.PluralRuleType): Rules | undefined {
16
+ if (Intl.PluralRules.supportedLocalesOf(locale).length === 0) {
17
+ // It would answer for the machine's own locale.
18
+ return undefined;
19
+ }
20
+ const rules = new Intl.PluralRules(locale, { type });
21
+ return { rules, numbers: Map.groupBy(COMMON.map(String), (n) => rules.select(Number(n))) };
22
+ }
23
+
24
+ /** `undefined` for a locale whose plurals `Intl` does not know. */
25
+ function rulesOf(locale: string, type: Intl.PluralRuleType): Rules | undefined {
26
+ const key = `${locale} ${type}`;
27
+ if (!known.has(key)) {
28
+ known.set(key, makeRules(locale, type));
29
+ }
30
+ return known.get(key);
31
+ }
32
+
33
+ const same = new Map<string, boolean>();
34
+
35
+ /** Whether a message's plurals read the same under both locales' rules. */
36
+ export function samePlurals(a: string, b: string): boolean {
37
+ const key = `${a} ${b}`;
38
+ let answer = same.get(key);
39
+ if (answer === undefined) {
40
+ answer = (['cardinal', 'ordinal'] as const).every((type) => {
41
+ const [one, two] = [rulesOf(a, type)?.rules, rulesOf(b, type)?.rules];
42
+ return (
43
+ one !== undefined &&
44
+ two !== undefined &&
45
+ [...COMMON, 0.1, 0.5, 1.5, 2.5, 1e6].every((n) => one.select(n) === two.select(n))
46
+ );
47
+ });
48
+ same.set(key, answer);
49
+ }
50
+ return answer;
51
+ }
52
+
53
+ const hasCategory = (keys: ReadonlySet<string>): boolean =>
54
+ [...keys].some((key) => CATEGORIES.has(key));
55
+
56
+ /** The categories `locale` uses for everyday numbers that a plural leaves to its catch-all. */
57
+ export function missingPlurals(locale: string, { plurals }: MessageInfo): Array<string> {
58
+ const missing = new Set<string>();
59
+ // A catch-all alone is a choice: Italian's "file" is its own plural.
60
+ for (const { type, keys } of plurals.filter((p) => hasCategory(p.keys))) {
61
+ for (const [category, numbers] of rulesOf(locale, type)?.numbers ?? []) {
62
+ if (category !== 'other' && !keys.has(category) && !numbers.every((n) => keys.has(n))) {
63
+ missing.add(category);
64
+ }
65
+ }
66
+ }
67
+ return [...missing];
68
+ }
@@ -0,0 +1,115 @@
1
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
2
+
3
+ export const prop = (name: string): string => (IDENT.test(name) ? name : JSON.stringify(name));
4
+
5
+ function interfaceName(namespace: string): string {
6
+ const pascal = namespace
7
+ .split(/[^A-Za-z0-9]+/)
8
+ .filter(Boolean)
9
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
10
+ .join('');
11
+ // `_` keeps a name like `-` from becoming `Messages`, whose plain part would shadow `Text`
12
+ return `${/^(?:\d|$)/.test(pascal) ? '_' : ''}${pascal}Messages`;
13
+ }
14
+
15
+ // Not valid as a `const` name in a module, or a built-in TypeScript rejects as one.
16
+ const RESERVED = new Set([
17
+ 'arguments',
18
+ 'await',
19
+ 'break',
20
+ 'case',
21
+ 'catch',
22
+ 'class',
23
+ 'const',
24
+ 'continue',
25
+ 'debugger',
26
+ 'default',
27
+ 'delete',
28
+ 'do',
29
+ 'else',
30
+ 'enum',
31
+ 'eval',
32
+ 'export',
33
+ 'extends',
34
+ 'false',
35
+ 'finally',
36
+ 'for',
37
+ 'function',
38
+ 'globalThis',
39
+ 'if',
40
+ 'implements',
41
+ 'import',
42
+ 'in',
43
+ 'instanceof',
44
+ 'interface',
45
+ 'let',
46
+ 'new',
47
+ 'null',
48
+ 'package',
49
+ 'private',
50
+ 'protected',
51
+ 'public',
52
+ 'return',
53
+ 'static',
54
+ 'super',
55
+ 'switch',
56
+ 'this',
57
+ 'throw',
58
+ 'true',
59
+ 'try',
60
+ 'typeof',
61
+ 'undefined',
62
+ 'var',
63
+ 'void',
64
+ 'while',
65
+ 'with',
66
+ 'yield',
67
+ ]);
68
+
69
+ const isOwnName = (ns: string): boolean => IDENT.test(ns) && !RESERVED.has(ns);
70
+
71
+ /**
72
+ * Each namespace's export: the name itself where it is an identifier, to match `t`'s key; else one
73
+ * derived from its interface (`foo-bar` → `fooBar`), numbered around the names already taken.
74
+ */
75
+ export function exportNames(ifaces: ReadonlyMap<string, string>): Map<string, string> {
76
+ const names = new Map<string, string>();
77
+ for (const ns of ifaces.keys()) {
78
+ if (isOwnName(ns)) {
79
+ names.set(ns, ns);
80
+ }
81
+ }
82
+ const used = new Set(names.values());
83
+ for (const [ns, iface] of ifaces) {
84
+ if (isOwnName(ns)) {
85
+ continue;
86
+ }
87
+ const base = iface.replace(/Messages$/, '');
88
+ const camel = base.charAt(0).toLowerCase() + base.slice(1);
89
+ const derived = RESERVED.has(camel) ? `_${camel}` : camel;
90
+ let name = derived;
91
+ for (let n = 2; used.has(name); n += 1) {
92
+ name = `${derived}${n}`;
93
+ }
94
+ used.add(name);
95
+ names.set(ns, name);
96
+ }
97
+ return names;
98
+ }
99
+
100
+ /** {@link interfaceName} per namespace, numbered where two collide (`foo-bar`, `foo_bar`). */
101
+ export function interfaceNames(namespaces: ReadonlyArray<string>): Map<string, string> {
102
+ const names = new Map<string, string>();
103
+ // its kind would shadow the imported `NamespaceKind`
104
+ const used = new Set<string>(['NamespaceMessages']);
105
+ for (const namespace of namespaces) {
106
+ const base = interfaceName(namespace);
107
+ let name = base;
108
+ for (let n = 2; used.has(name); n += 1) {
109
+ name = base.replace(/Messages$/, `${n}Messages`);
110
+ }
111
+ used.add(name);
112
+ names.set(namespace, name);
113
+ }
114
+ return names;
115
+ }
@@ -0,0 +1,148 @@
1
+ import type { MessageInfo } from '../compile/info.ts';
2
+
3
+ import { prop } from './names.ts';
4
+ import { OTHER, signature } from './signature.ts';
5
+
6
+ interface Leaf {
7
+ readonly leaf: string;
8
+ readonly doc?: string;
9
+ readonly rich?: boolean;
10
+ }
11
+
12
+ // A map, as a key may be `constructor` or `__proto__`.
13
+ // oxlint-disable-next-line typescript/no-empty-object-type -- a type alias cannot refer to itself here
14
+ interface Tree extends Map<string, Tree | Leaf> {}
15
+
16
+ const isLeaf = (n: Tree | Leaf): n is Leaf => !(n instanceof Map);
17
+
18
+ /** Whether `node` holds a message with markup (`rich`) or one without. */
19
+ const holds = (node: Tree | Leaf, rich: boolean): boolean =>
20
+ isLeaf(node) ? Boolean(node.rich) === rich : [...node.values()].some((n) => holds(n, rich));
21
+
22
+ function render(tree: Tree, indent: string): string {
23
+ const lines: Array<string> = [];
24
+ for (const [key, node] of tree) {
25
+ if (isLeaf(node)) {
26
+ if (node.doc !== undefined) {
27
+ // Not `/\s*\n\s*/g`, quadratic in a run of spaces.
28
+ const doc = node.doc.split('\n').map((line) => line.trim());
29
+ const text = doc
30
+ .filter(Boolean)
31
+ .join(' ')
32
+ .replaceAll('*/', String.raw`*\/`);
33
+ lines.push(`${indent}/** ${text} */`);
34
+ }
35
+ lines.push(`${indent}${prop(key)}${node.leaf};`);
36
+ } else {
37
+ lines.push(`${indent}${prop(key)}: {`, render(node, `${indent} `), `${indent}};`);
38
+ }
39
+ }
40
+ return lines.join('\n');
41
+ }
42
+
43
+ export interface NamespaceTypes {
44
+ /** The interfaces, without imports. */
45
+ readonly code: string;
46
+ /** Whether the namespace's interface takes `Node`: only markup needs it. */
47
+ readonly generic: boolean;
48
+ /** Whether `code` names `Text`. */
49
+ readonly usesText: boolean;
50
+ }
51
+
52
+ function treeOf(entries: ReadonlyArray<[path: Array<string>, leaf: Leaf]>): Tree {
53
+ const tree: Tree = new Map();
54
+ for (const [path, leaf] of entries) {
55
+ const last = path.at(-1) ?? '';
56
+ let node = tree;
57
+ for (const segment of path.slice(0, -1)) {
58
+ let child = node.get(segment);
59
+ if (!child || isLeaf(child)) {
60
+ child = new Map();
61
+ node.set(segment, child);
62
+ }
63
+ node = child;
64
+ }
65
+ node.set(last, leaf);
66
+ }
67
+ return tree;
68
+ }
69
+
70
+ const pascal = (key: string): string =>
71
+ key
72
+ .split(/[^A-Za-z0-9]+/)
73
+ .filter(Boolean)
74
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
75
+ .join('');
76
+
77
+ /**
78
+ * Plain messages in a non-generic `XText`, and those with markup in `XMessages<Node> extends XText`,
79
+ * so instantiating `Node` skips every plain message. A group holding both splits the same way.
80
+ */
81
+ function declare(
82
+ tree: Tree,
83
+ { name, unique, out }: { name: string; unique: (name: string) => string; out: Array<string> },
84
+ ): void {
85
+ const plain: Tree = new Map();
86
+ const rich: Tree = new Map();
87
+ for (const [key, node] of tree) {
88
+ if (!holds(node, true)) {
89
+ plain.set(key, node);
90
+ } else if (isLeaf(node) || !holds(node, false)) {
91
+ rich.set(key, node);
92
+ } else {
93
+ const group = unique(name.replace(/Messages$/, `${pascal(key)}Messages`));
94
+ declare(node, { name: group, unique, out });
95
+ rich.set(key, { leaf: `: ${group}<Node>` });
96
+ }
97
+ }
98
+ const text = name.replace(/Messages$/, 'Text');
99
+ const body = (members: Tree): string => render(members, ' ');
100
+ if (rich.size === 0) {
101
+ out.push(`export interface ${name} {\n${body(plain)}\n}`);
102
+ } else if (plain.size === 0) {
103
+ out.push(`export interface ${name}<Node> {\n${body(rich)}\n}`);
104
+ } else {
105
+ out.push(
106
+ `export interface ${text} {\n${body(plain)}\n}`,
107
+ `export interface ${name}<Node> extends ${text} {\n${body(rich)}\n}`,
108
+ );
109
+ }
110
+ }
111
+
112
+ function withAliases(code: string): string {
113
+ const aliases = [
114
+ ...(code.includes('Markup<Node>') ? ['type Markup<Node> = (children: Node) => Node;'] : []),
115
+ ...(code.includes('Other<G>') ? [OTHER] : []),
116
+ ];
117
+ return aliases.length > 0 ? `${aliases.join('\n')}\n\n${code}\n\nexport {};` : code;
118
+ }
119
+
120
+ export function namespaceTypes(
121
+ messages: Map<string, { info: MessageInfo; source: string }>,
122
+ { name, defaults }: { name: string; defaults: ReadonlySet<string> },
123
+ ): NamespaceTypes {
124
+ const leaves: Array<[Array<string>, Leaf]> = [...messages].map(([key, { info, source }]) => [
125
+ key.split('.'),
126
+ { leaf: signature(info, defaults), doc: source, rich: info.rich },
127
+ ]);
128
+ const tree = treeOf(leaves);
129
+ const used = new Set([name]);
130
+ const unique = (base: string): string => {
131
+ let group = base;
132
+ for (let n = 2; used.has(group); n += 1) {
133
+ group = base.replace(/Messages$/, `${n}Messages`);
134
+ }
135
+ used.add(group);
136
+ return group;
137
+ };
138
+ const out: Array<string> = [];
139
+ declare(tree, { name, unique, out });
140
+ const code = out.join('\n\n');
141
+ return {
142
+ // One alias: TypeScript instantiates it once per node type, not once per tag. `export {}` keeps
143
+ // it private, as a .d.ts otherwise exports every top-level name.
144
+ code: withAliases(code),
145
+ generic: holds(tree, true),
146
+ usesText: leaves.some(([, leaf]) => leaf.leaf === ': Text'),
147
+ };
148
+ }