@parlajs/compiler 0.0.0-stage → 0.1.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 (159) 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/config/checks.d.ts +21 -0
  34. package/build/config/checks.d.ts.map +1 -0
  35. package/build/config/checks.js +97 -0
  36. package/build/config/config.d.ts +71 -0
  37. package/build/config/config.d.ts.map +1 -0
  38. package/build/config/config.js +7 -0
  39. package/build/config/fallbacks.d.ts +6 -0
  40. package/build/config/fallbacks.d.ts.map +1 -0
  41. package/build/config/fallbacks.js +13 -0
  42. package/build/config/import.d.ts +31 -0
  43. package/build/config/import.d.ts.map +1 -0
  44. package/build/config/import.js +115 -0
  45. package/build/config/load.d.ts +13 -0
  46. package/build/config/load.d.ts.map +1 -0
  47. package/build/config/load.js +59 -0
  48. package/build/diagnostics.d.ts +31 -0
  49. package/build/diagnostics.d.ts.map +1 -0
  50. package/build/diagnostics.js +41 -0
  51. package/build/generate/checks.d.ts +9 -0
  52. package/build/generate/checks.d.ts.map +1 -0
  53. package/build/generate/checks.js +93 -0
  54. package/build/generate/chunk.d.ts +11 -0
  55. package/build/generate/chunk.d.ts.map +1 -0
  56. package/build/generate/chunk.js +57 -0
  57. package/build/generate/digits.d.ts +8 -0
  58. package/build/generate/digits.d.ts.map +1 -0
  59. package/build/generate/digits.js +57 -0
  60. package/build/generate/files.d.ts +7 -0
  61. package/build/generate/files.d.ts.map +1 -0
  62. package/build/generate/files.js +59 -0
  63. package/build/generate/locale.d.ts +21 -0
  64. package/build/generate/locale.d.ts.map +1 -0
  65. package/build/generate/locale.js +108 -0
  66. package/build/generate/modules.d.ts +27 -0
  67. package/build/generate/modules.d.ts.map +1 -0
  68. package/build/generate/modules.js +61 -0
  69. package/build/generate/namespace.d.ts +19 -0
  70. package/build/generate/namespace.d.ts.map +1 -0
  71. package/build/generate/namespace.js +65 -0
  72. package/build/generate/namespaces.d.ts +5 -0
  73. package/build/generate/namespaces.d.ts.map +1 -0
  74. package/build/generate/namespaces.js +41 -0
  75. package/build/generate/read.d.ts +21 -0
  76. package/build/generate/read.d.ts.map +1 -0
  77. package/build/generate/read.js +115 -0
  78. package/build/index.d.ts +9 -0
  79. package/build/index.d.ts.map +1 -0
  80. package/build/index.js +7 -0
  81. package/build/init/detect.d.ts +43 -0
  82. package/build/init/detect.d.ts.map +1 -0
  83. package/build/init/detect.js +69 -0
  84. package/build/init/init.d.ts +12 -0
  85. package/build/init/init.d.ts.map +1 -0
  86. package/build/init/init.js +126 -0
  87. package/build/options/date.d.ts +3 -0
  88. package/build/options/date.d.ts.map +1 -0
  89. package/build/options/date.js +77 -0
  90. package/build/options/literal.d.ts +10 -0
  91. package/build/options/literal.d.ts.map +1 -0
  92. package/build/options/literal.js +11 -0
  93. package/build/options/names.d.ts +5 -0
  94. package/build/options/names.d.ts.map +1 -0
  95. package/build/options/names.js +56 -0
  96. package/build/options/number.d.ts +3 -0
  97. package/build/options/number.d.ts.map +1 -0
  98. package/build/options/number.js +17 -0
  99. package/build/options/options.d.ts +7 -0
  100. package/build/options/options.d.ts.map +1 -0
  101. package/build/options/options.js +66 -0
  102. package/build/plurals.d.ts +6 -0
  103. package/build/plurals.d.ts.map +1 -0
  104. package/build/plurals.js +50 -0
  105. package/build/types/names.d.ts +9 -0
  106. package/build/types/names.d.ts.map +1 -0
  107. package/build/types/names.js +109 -0
  108. package/build/types/namespace.d.ts +17 -0
  109. package/build/types/namespace.d.ts.map +1 -0
  110. package/build/types/namespace.js +113 -0
  111. package/build/types/signature.d.ts +8 -0
  112. package/build/types/signature.d.ts.map +1 -0
  113. package/build/types/signature.js +87 -0
  114. package/build/vite.d.ts +9 -0
  115. package/build/vite.d.ts.map +1 -0
  116. package/build/vite.js +125 -0
  117. package/build/watch.d.ts +12 -0
  118. package/build/watch.d.ts.map +1 -0
  119. package/build/watch.js +93 -0
  120. package/package.json +84 -3
  121. package/src/build.ts +31 -0
  122. package/src/cli.ts +9 -0
  123. package/src/command.ts +195 -0
  124. package/src/compile/code.ts +51 -0
  125. package/src/compile/compile.ts +289 -0
  126. package/src/compile/error.ts +3 -0
  127. package/src/compile/info.ts +63 -0
  128. package/src/compile/scope.ts +14 -0
  129. package/src/compile/single.ts +46 -0
  130. package/src/compile/variants.ts +68 -0
  131. package/src/config/checks.ts +140 -0
  132. package/src/config/config.ts +83 -0
  133. package/src/config/fallbacks.ts +18 -0
  134. package/src/config/import.ts +146 -0
  135. package/src/config/load.ts +75 -0
  136. package/src/diagnostics.ts +98 -0
  137. package/src/generate/checks.ts +103 -0
  138. package/src/generate/chunk.ts +73 -0
  139. package/src/generate/digits.ts +74 -0
  140. package/src/generate/files.ts +83 -0
  141. package/src/generate/locale.ts +145 -0
  142. package/src/generate/modules.ts +94 -0
  143. package/src/generate/namespace.ts +119 -0
  144. package/src/generate/namespaces.ts +59 -0
  145. package/src/generate/read.ts +159 -0
  146. package/src/index.ts +27 -0
  147. package/src/init/detect.ts +103 -0
  148. package/src/init/init.ts +158 -0
  149. package/src/options/date.ts +87 -0
  150. package/src/options/literal.ts +21 -0
  151. package/src/options/names.ts +64 -0
  152. package/src/options/number.ts +20 -0
  153. package/src/options/options.ts +75 -0
  154. package/src/plurals.ts +68 -0
  155. package/src/types/names.ts +115 -0
  156. package/src/types/namespace.ts +148 -0
  157. package/src/types/signature.ts +111 -0
  158. package/src/vite.ts +143 -0
  159. package/src/watch.ts +115 -0
@@ -0,0 +1,289 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ import { inheritedOptions, intlOptions } from '../options/options.ts';
4
+
5
+ import { checkName, checkOptions, literalValue, offsetBy, params, selected } from './code.ts';
6
+ import { CompileError } from './error.ts';
7
+ import { BUILTIN_FUNCTIONS, kindOf, SELECTS } from './info.ts';
8
+ import type {
9
+ CompiledMessage,
10
+ CustomFunctions,
11
+ CustomKinds,
12
+ MessageInfo,
13
+ ParamKind,
14
+ } from './info.ts';
15
+ import { ModuleScope } from './scope.ts';
16
+ import { single } from './single.ts';
17
+ import { branchNeeds, keysAt } from './variants.ts';
18
+
19
+ interface Binding {
20
+ raw: string;
21
+ fn?: Model.FunctionRef;
22
+ param?: string;
23
+ }
24
+
25
+ export interface CompileOptions {
26
+ readonly scope?: ModuleScope;
27
+ readonly custom?: CustomFunctions;
28
+ /** The locale whose plural rules apply, when not the chunk's. */
29
+ readonly pluralsOf?: string | undefined;
30
+ }
31
+
32
+ class MessageCompiler {
33
+ private readonly vars = new Map<string, Binding>();
34
+ private readonly scope: ModuleScope;
35
+ private readonly custom: CustomKinds;
36
+ readonly info: MessageInfo = { params: new Map(), markup: new Set(), rich: false, plurals: [] };
37
+ /** The params read outside any variant, and those the variant being compiled reads. */
38
+ private readonly shared = new Set<string>();
39
+ private reads: Set<string> | undefined;
40
+ private readonly pluralsOf: string | undefined;
41
+
42
+ constructor({ scope = new ModuleScope(), custom = {}, pluralsOf }: CompileOptions) {
43
+ this.scope = scope;
44
+ this.custom = new Map(Object.entries(custom));
45
+ this.pluralsOf = pluralsOf;
46
+ }
47
+
48
+ private record(param: string, kind: ParamKind): void {
49
+ checkName(param);
50
+ const list = this.info.params.get(param) ?? [];
51
+ list.push(kind);
52
+ this.info.params.set(param, list);
53
+ (this.reads ?? this.shared).add(param);
54
+ }
55
+
56
+ private resolve(name: string): Binding {
57
+ return this.vars.get(name) ?? { raw: `p[${JSON.stringify(name)}]`, param: name };
58
+ }
59
+
60
+ private options(fn: Model.FunctionRef, extra: Record<string, Model.Literal> = {}): string {
61
+ const entries = Object.entries({ ...this.resolved(fn), ...extra });
62
+ if (entries.length === 0) {
63
+ return '';
64
+ }
65
+ // A custom function's options are text: `zip=01234` is no number.
66
+ const literal = this.custom.has(fn.name) ? JSON.stringify : literalValue;
67
+ const parts = entries.map(
68
+ ([k, v]) =>
69
+ `${JSON.stringify(k)}: ${v.type === 'literal' ? literal(v.value) : this.variable(v)}`,
70
+ );
71
+ const code = `{ ${parts.join(', ')} }`;
72
+ const constant = entries.every(([, v]) => v.type === 'literal');
73
+ return `, ${constant ? this.scope.hoist(code) : code}`;
74
+ }
75
+
76
+ /** An option's variable, which the call then needs as it does any placeholder. */
77
+ private variable({ name }: Model.VariableRef): string {
78
+ const { raw, param } = this.resolve(name);
79
+ if (param) {
80
+ this.record(param, { kind: 'any' });
81
+ }
82
+ return raw;
83
+ }
84
+
85
+ private resolved(fn: Model.FunctionRef): Model.Options {
86
+ if (this.custom.has(fn.name)) {
87
+ return fn.options ?? {};
88
+ }
89
+ try {
90
+ return intlOptions(fn);
91
+ } catch (error) {
92
+ throw new CompileError((error as Error).message, { cause: error });
93
+ }
94
+ }
95
+
96
+ private effective(expr: Model.Expression): Binding {
97
+ let binding: Binding;
98
+ if (expr.arg?.type === 'literal') {
99
+ binding = { raw: JSON.stringify(expr.arg.value) };
100
+ } else if (expr.arg?.type === 'variable') {
101
+ binding = { ...this.resolve(expr.arg.name) };
102
+ } else {
103
+ binding = { raw: 'undefined' };
104
+ }
105
+ const own = expr.functionRef;
106
+ if (own) {
107
+ if (!BUILTIN_FUNCTIONS.has(own.name) && !this.custom.has(own.name)) {
108
+ throw new CompileError(`unknown function :${own.name}`);
109
+ }
110
+ checkOptions(own.options);
111
+ const { name } = own;
112
+ const isOffset = name === 'offset' && !this.custom.has(name);
113
+ const inherited = binding.fn ? inheritedOptions(binding.fn, isOffset ? 'number' : name) : {};
114
+ if (isOffset) {
115
+ binding.raw = `(Number(${binding.raw}) ${offsetBy(own)})`;
116
+ binding.fn = { type: 'function', name: 'number', options: inherited };
117
+ } else {
118
+ binding.fn = { ...own, options: { ...inherited, ...own.options } };
119
+ }
120
+ }
121
+ return binding;
122
+ }
123
+
124
+ declare(decl: Model.Declaration): void {
125
+ const binding = this.effective(decl.value);
126
+ if (decl.type === 'input') {
127
+ binding.param = decl.name;
128
+ }
129
+ this.vars.set(decl.name, binding);
130
+ if (binding.param && binding.fn) {
131
+ this.record(binding.param, kindOf(binding.fn, this.custom));
132
+ }
133
+ }
134
+
135
+ private expression(expr: Model.Expression): string {
136
+ const b = this.effective(expr);
137
+ if (b.param) {
138
+ this.record(b.param, kindOf(b.fn, this.custom));
139
+ }
140
+ if (!b.fn) {
141
+ return `$.str(${b.raw})`;
142
+ }
143
+ const options = this.options(b.fn);
144
+ if (b.fn.name === 'number' && !options) {
145
+ return `$.n(${b.raw})`;
146
+ }
147
+ return `$.f(${JSON.stringify(b.fn.name)}, ${b.raw}${options})`;
148
+ }
149
+
150
+ pattern(pattern: Model.Pattern): { code: string; rich: boolean } {
151
+ const root: Array<string> = [];
152
+ const stack: Array<{ name: string; items: Array<string> }> = [];
153
+ let rich = false;
154
+ const top = (): Array<string> => stack.at(-1)?.items ?? root;
155
+ for (const part of pattern) {
156
+ if (typeof part === 'string') {
157
+ if (part) {
158
+ top().push(JSON.stringify(part));
159
+ }
160
+ } else if (part.type === 'expression') {
161
+ top().push(this.expression(part));
162
+ } else {
163
+ rich = true;
164
+ checkName(part.name);
165
+ this.info.markup.add(part.name);
166
+ if (part.kind === 'open') {
167
+ stack.push({ name: part.name, items: [] });
168
+ } else if (part.kind === 'standalone') {
169
+ top().push(`$.tag(${params(part.name)}, ${JSON.stringify(part.name)}, [])`);
170
+ } else {
171
+ const open = stack.pop();
172
+ if (open?.name !== part.name) {
173
+ throw new CompileError(`closing markup {/${part.name}} has no matching open`);
174
+ }
175
+ top().push(
176
+ `$.tag(${params(part.name)}, ${JSON.stringify(part.name)}, [${open.items.join(', ')}])`,
177
+ );
178
+ }
179
+ }
180
+ }
181
+ const unclosed = stack.at(-1);
182
+ if (unclosed) {
183
+ throw new CompileError(`markup {#${unclosed.name}} is never closed`);
184
+ }
185
+ if (rich) {
186
+ this.info.rich = true;
187
+ return { code: `$.rich([${root.join(', ')}])`, rich };
188
+ }
189
+ return { code: root.length > 0 ? root.join(' + ') : '""', rich };
190
+ }
191
+
192
+ select(msg: Model.SelectMessage): string {
193
+ const selectors = msg.selectors.map((sel, i) => {
194
+ const b = this.resolve(sel.name);
195
+ if (!b.fn) {
196
+ throw new CompileError(
197
+ `selector $${sel.name} needs an annotation such as :number or :string`,
198
+ );
199
+ }
200
+ if (SELECTS.has(b.fn.name)) {
201
+ if (b.param) {
202
+ this.record(b.param, { kind: 'number' });
203
+ }
204
+ const raw = selected(b.fn.name, b.raw);
205
+ return { numeric: true, raw, options: this.plural(b.fn, { msg, at: i }) };
206
+ }
207
+ if (b.fn.name === 'string') {
208
+ if (b.param) {
209
+ const { keys, open } = keysAt(msg, i);
210
+ this.record(b.param, { kind: 'select', keys: [...keys], open });
211
+ }
212
+ return { numeric: false, raw: b.raw, options: '' };
213
+ }
214
+ throw new CompileError(`:${b.fn.name} cannot be used as a selector`);
215
+ });
216
+ const reads: Array<Set<string>> = [];
217
+ const codes = msg.variants.map((v) => {
218
+ this.reads = new Set();
219
+ reads.push(this.reads);
220
+ return this.pattern(v.value).code;
221
+ });
222
+ this.reads = undefined;
223
+ this.branch(msg, reads);
224
+ const keys = msg.variants.map((v) => v.keys.map((k) => (k.type === '*' ? null : k.value)));
225
+ const [only] = selectors;
226
+ if (only && selectors.length === 1) {
227
+ return single(
228
+ only,
229
+ keys.map(([key = null], i) => ({ key, code: codes[i] ?? '""' })),
230
+ );
231
+ }
232
+ const values = selectors.map((s) => `$.${s.numeric ? 'sn' : 'ss'}(${s.raw}${s.options})`);
233
+ const pick = `$.pick([${values.join(', ')}], ${this.scope.hoist(JSON.stringify(keys))})`;
234
+ // `one`/`other` is the commonest select, and a ternary a fraction of a switch's size.
235
+ if (codes.length === 2) {
236
+ const [first, second] = codes as [string, string];
237
+ return `${pick} ? ${second} : ${first}`;
238
+ }
239
+ const cases = codes.map((code, i) => `case ${i}: return ${code};`);
240
+ return `{ switch (${pick}) { ${cases.join(' ')} } }`;
241
+ }
242
+
243
+ /** A numeric selector's options, noting the categories it picks by. */
244
+ private plural(
245
+ fn: Model.FunctionRef,
246
+ { msg, at }: { msg: Model.SelectMessage; at: number },
247
+ ): string {
248
+ const { keys } = keysAt(msg, at);
249
+ const select = fn.options?.['select'];
250
+ const kind = select?.type === 'literal' ? select.value : 'cardinal';
251
+ if (kind === 'exact') {
252
+ return this.options(fn);
253
+ }
254
+ const type = kind === 'ordinal' ? 'ordinal' : 'cardinal';
255
+ this.info.plurals.push({ type, keys });
256
+ const { pluralsOf } = this;
257
+ return this.options(fn, pluralsOf ? { locale: { type: 'literal', value: pluralsOf } } : {});
258
+ }
259
+
260
+ /** Fills `info.branches` when exactly one selector is a `:string` param's. */
261
+ private branch(msg: Model.SelectMessage, reads: ReadonlyArray<Set<string>>): void {
262
+ const strings = msg.selectors.flatMap((sel, i) => {
263
+ const b = this.resolve(sel.name);
264
+ return b.fn?.name === 'string' && b.param ? [{ i, param: b.param }] : [];
265
+ });
266
+ const [only] = strings;
267
+ const kinds = only && this.info.params.get(only.param);
268
+ if (
269
+ strings.length !== 1 ||
270
+ !only ||
271
+ kinds?.some((k) => k.kind !== 'select' && k.kind !== 'string' && k.kind !== 'any')
272
+ ) {
273
+ return;
274
+ }
275
+ const needs = branchNeeds(msg, { at: only.i, shared: this.shared, reads });
276
+ if (needs) {
277
+ this.info.branches = { param: only.param, needs };
278
+ }
279
+ }
280
+ }
281
+
282
+ export function compileMessage(msg: Model.Message, options: CompileOptions = {}): CompiledMessage {
283
+ const c = new MessageCompiler(options);
284
+ for (const decl of msg.declarations) {
285
+ c.declare(decl);
286
+ }
287
+ const body = msg.type === 'message' ? c.pattern(msg.pattern).code : c.select(msg);
288
+ return { body, info: c.info };
289
+ }
@@ -0,0 +1,3 @@
1
+ export class CompileError extends Error {
2
+ override name = 'CompileError';
3
+ }
@@ -0,0 +1,63 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ /** What a custom function's value is: it types the param. */
4
+ export type FunctionKind = 'string' | 'number' | 'date';
5
+
6
+ /** Message functions beyond the built-in ones, by what their value is. */
7
+ export type CustomFunctions = Readonly<Record<string, FunctionKind>>;
8
+
9
+ const NUMERIC = new Set(['number', 'integer', 'currency', 'percent', 'unit', 'offset']);
10
+
11
+ /** MF2 gives the other number functions no selection. */
12
+ export const SELECTS = new Set(['number', 'integer', 'percent']);
13
+
14
+ const DATES = new Set(['date', 'time', 'datetime']);
15
+
16
+ /** The built-in message functions; the config's `functions` add to them. */
17
+ export const BUILTIN_FUNCTIONS: ReadonlySet<string> = new Set([...NUMERIC, ...DATES, 'string']);
18
+
19
+ /** What a message needs from one parameter. `any` is an unannotated placeholder. */
20
+ export type ParamKind =
21
+ | { kind: 'number' }
22
+ | { kind: 'date' }
23
+ | { kind: 'string' }
24
+ | { kind: 'any' }
25
+ | { kind: 'select'; keys: Array<string>; open: boolean };
26
+
27
+ export interface MessageInfo {
28
+ params: Map<string, Array<ParamKind>>;
29
+ markup: Set<string>;
30
+ rich: boolean;
31
+ /**
32
+ * Set when a `:string` selector's value decides which params a call needs: the params each key
33
+ * needs, `null` for any other string. Unset when every key needs the same.
34
+ */
35
+ branches?: { param: string; needs: Map<string | null, Set<string>> };
36
+ /** Each selector that picks by plural category, with the keys its variants name. */
37
+ plurals: Array<{ type: Intl.PluralRuleType; keys: Set<string> }>;
38
+ }
39
+
40
+ export interface CompiledMessage {
41
+ /** A function body reading params from `p` and the runtime from `$`. */
42
+ body: string;
43
+ info: MessageInfo;
44
+ }
45
+
46
+ export type CustomKinds = ReadonlyMap<string, FunctionKind>;
47
+
48
+ export function kindOf(fn: Model.FunctionRef | undefined, custom: CustomKinds): ParamKind {
49
+ if (!fn) {
50
+ return { kind: 'any' };
51
+ }
52
+ const declared = custom.get(fn.name);
53
+ if (declared) {
54
+ return { kind: declared };
55
+ }
56
+ if (NUMERIC.has(fn.name)) {
57
+ return { kind: 'number' };
58
+ }
59
+ if (DATES.has(fn.name)) {
60
+ return { kind: 'date' };
61
+ }
62
+ return { kind: 'string' };
63
+ }
@@ -0,0 +1,14 @@
1
+ /** Module-level constants shared by every message in one generated chunk. */
2
+ export class ModuleScope {
3
+ readonly consts: Array<string> = [];
4
+ private readonly seen = new Map<string, string>();
5
+ hoist(code: string): string {
6
+ let name = this.seen.get(code);
7
+ if (!name) {
8
+ name = `v${this.consts.length}`;
9
+ this.consts.push(`const ${name} = ${code};`);
10
+ this.seen.set(code, name);
11
+ }
12
+ return name;
13
+ }
14
+ }
@@ -0,0 +1,46 @@
1
+ export interface Selector {
2
+ numeric: boolean;
3
+ raw: string;
4
+ options: string;
5
+ }
6
+
7
+ function switchOn(value: string, cases: ReadonlyMap<string, string>): string {
8
+ const body = [...cases].map(([key, code]) => `case ${key}: return ${code};`);
9
+ return body.length > 0 ? `switch (${value}) { ${body.join(' ')} } ` : '';
10
+ }
11
+
12
+ /** One selector needs no `pick`: exact numbers first, then the category or text, then the catch-all. */
13
+ export function single(
14
+ { numeric, raw, options }: Selector,
15
+ variants: ReadonlyArray<{ key: string | null; code: string }>,
16
+ ): string {
17
+ const exact = new Map<string, string>();
18
+ const named = new Map<string, string>();
19
+ let rest: string | undefined;
20
+ for (const { key, code } of variants) {
21
+ if (key === null) {
22
+ rest ??= code;
23
+ continue;
24
+ }
25
+ // A letter starts a category, never a number.
26
+ const isExact = numeric && (key.codePointAt(0) ?? 65) < 65;
27
+ const cases = isExact ? exact : named;
28
+ const literal = isExact ? String(Number(key)) : JSON.stringify(key);
29
+ cases.set(literal, cases.get(literal) ?? code);
30
+ }
31
+ // Both formats require a catch-all; without one, `pick` takes the last variant too.
32
+ rest ??= variants.at(-1)?.code ?? '""';
33
+ const number = `Number(${raw})`;
34
+ const value = numeric ? `$.c(${raw}${options})` : `$.s(${raw})`;
35
+ if (exact.size > 1 || named.size > 1) {
36
+ return `{ ${switchOn(number, exact)}${switchOn(value, named)}return ${rest}; }`;
37
+ }
38
+ let code = rest;
39
+ for (const [key, matched] of named) {
40
+ code = `${value} === ${key} ? ${matched} : ${code}`;
41
+ }
42
+ for (const [key, matched] of exact) {
43
+ code = `${number} === ${key} ? ${matched} : ${code}`;
44
+ }
45
+ return code;
46
+ }
@@ -0,0 +1,68 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ /** The keys the variants give selector `at`, and whether one is the catch-all `*`. */
4
+ export function keysAt(msg: Model.SelectMessage, at: number): { keys: Set<string>; open: boolean } {
5
+ const keys = new Set<string>();
6
+ let open = false;
7
+ for (const v of msg.variants) {
8
+ const key = v.keys[at];
9
+ if (key?.type === '*') {
10
+ open = true;
11
+ } else if (key) {
12
+ keys.add(key.value);
13
+ }
14
+ }
15
+ return { keys, open };
16
+ }
17
+
18
+ /**
19
+ * The params each key of the `:string` selector `at` needs, `null` for any other string; `undefined`
20
+ * when every key needs the same. `shared` are read outside any variant, `reads` by each variant.
21
+ */
22
+ export function branchNeeds(
23
+ msg: Model.SelectMessage,
24
+ {
25
+ at,
26
+ shared,
27
+ reads,
28
+ }: { at: number; shared: ReadonlySet<string>; reads: ReadonlyArray<Set<string>> },
29
+ ): Map<string | null, Set<string>> | undefined {
30
+ const keyOf = (v: Model.Variant): string | null => {
31
+ const key = v.keys[at];
32
+ return !key || key.type === '*' ? null : key.value;
33
+ };
34
+ const readBy = (match: (v: Model.Variant) => boolean): Set<string> => {
35
+ const out = new Set(shared);
36
+ for (const [n, v] of msg.variants.entries()) {
37
+ for (const param of match(v) ? (reads[n] ?? []) : []) {
38
+ out.add(param);
39
+ }
40
+ }
41
+ return out;
42
+ };
43
+ const needs = new Map<string | null, Set<string>>();
44
+ for (const key of new Set(msg.variants.map(keyOf))) {
45
+ if (key === null) {
46
+ needs.set(
47
+ null,
48
+ readBy((v) => keyOf(v) === null),
49
+ );
50
+ continue;
51
+ }
52
+ // First, the selector decides alone where a variant has `*` for every other selector.
53
+ const covered =
54
+ at === 0 &&
55
+ msg.variants.some(
56
+ (v) => keyOf(v) === key && v.keys.every((k, j) => j === 0 || k.type === '*'),
57
+ );
58
+ needs.set(
59
+ key,
60
+ readBy((v) => keyOf(v) === key || (!covered && keyOf(v) === null)),
61
+ );
62
+ }
63
+ const sets = [...needs.values()];
64
+ const differ = sets.some(
65
+ (set) => set.size !== sets[0]?.size || [...set].some((p) => !sets[0]?.has(p)),
66
+ );
67
+ return differ ? needs : undefined;
68
+ }
@@ -0,0 +1,140 @@
1
+ import path from 'node:path';
2
+
3
+ import { BUILTIN_FUNCTIONS } from '../compile/info.ts';
4
+ import type { FunctionKind } from '../compile/info.ts';
5
+
6
+ import { ConfigError } from './config.ts';
7
+ import type { NamespaceConfig, ResolvedNamespace } from './config.ts';
8
+
9
+ export function checkFunctions(
10
+ functions: Record<string, FunctionKind>,
11
+ ): Record<string, FunctionKind> {
12
+ const shadowing = Object.keys(functions).filter((name) => BUILTIN_FUNCTIONS.has(name));
13
+ if (shadowing.length > 0) {
14
+ throw new ConfigError(
15
+ `"functions" cannot redefine the built-in ${shadowing.map((n) => `:${n}`).join(', ')}`,
16
+ );
17
+ }
18
+ return functions;
19
+ }
20
+
21
+ /** Names that become path segments under `outDir`: no separators, no `..`. */
22
+ const NAMESPACE_NAME = /^[\w-]+(?:\.[\w-]+)*$/;
23
+
24
+ /** A tag `Intl` takes, such as `zh-Hant-TW`: any other would throw at the first plural or number. */
25
+ function checkLocale(locale: string): void {
26
+ let canonical: string | undefined;
27
+ try {
28
+ [canonical] = Intl.getCanonicalLocales(locale);
29
+ } catch {
30
+ const tag = locale.replaceAll('_', '-');
31
+ const hint = tag === locale ? ' such as "en" or "pt-BR"' : `: write "${tag}"`;
32
+ throw new ConfigError(`Locale "${locale}" is not a locale tag${hint}`);
33
+ }
34
+ // Fallbacks match tags by their spelling: `zh-hant-tw` would never inherit from `zh-Hant`.
35
+ if (canonical !== locale) {
36
+ throw new ConfigError(`Locale "${locale}" is not canonical: write "${canonical}"`);
37
+ }
38
+ }
39
+
40
+ function isInside(dir: string, file: string): boolean {
41
+ const rel = path.relative(dir, file);
42
+ return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
43
+ }
44
+
45
+ /** Names of files: on macOS and Windows one would overwrite the other. */
46
+ function checkCase(what: string, names: ReadonlyArray<string>): void {
47
+ const seen = new Map<string, string>();
48
+ for (const name of names) {
49
+ const other = seen.get(name.toLowerCase()) ?? name;
50
+ if (other !== name) {
51
+ throw new ConfigError(`${what} "${other}" and "${name}" differ only in case: rename one`);
52
+ }
53
+ seen.set(name.toLowerCase(), name);
54
+ }
55
+ }
56
+
57
+ /** A fallback outside `locales` lends no text, only its `Intl` formats. */
58
+ export function checkFallbacks(
59
+ fallbacks: Record<string, Array<string>>,
60
+ {
61
+ locales,
62
+ hasCatalog,
63
+ }: {
64
+ readonly locales: ReadonlyArray<string>;
65
+ readonly hasCatalog: (locale: string) => boolean;
66
+ },
67
+ ): void {
68
+ for (const [locale, chain] of Object.entries(fallbacks)) {
69
+ if (!locales.includes(locale)) {
70
+ throw new ConfigError(`"fallbacks" lists "${locale}", which is not in locales`);
71
+ }
72
+ for (const fallback of chain.filter((l) => !locales.includes(l))) {
73
+ if (hasCatalog(fallback)) {
74
+ throw new ConfigError(
75
+ `"${locale}" falls back to "${fallback}", whose catalogs are not read: add it to locales`,
76
+ );
77
+ }
78
+ if (Intl.NumberFormat.supportedLocalesOf(fallback).length === 0) {
79
+ throw new ConfigError(
80
+ `"${locale}" falls back to "${fallback}", neither in locales nor known to Intl`,
81
+ );
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ /** Every tag `Intl` takes, each locale once, and the source locale among them. */
88
+ export function checkLocales({
89
+ locales,
90
+ sourceLocale,
91
+ fallbacks,
92
+ }: {
93
+ locales: ReadonlyArray<string>;
94
+ sourceLocale: string;
95
+ fallbacks: Record<string, Array<string>>;
96
+ }): void {
97
+ for (const locale of [
98
+ ...locales,
99
+ ...Object.keys(fallbacks),
100
+ ...Object.values(fallbacks).flat(),
101
+ ]) {
102
+ checkLocale(locale);
103
+ }
104
+ const repeated = locales.find((l, i) => locales.indexOf(l) !== i);
105
+ if (repeated !== undefined) {
106
+ throw new ConfigError(`Locale "${repeated}" is listed twice`);
107
+ }
108
+ if (!locales.includes(sourceLocale)) {
109
+ throw new ConfigError(`sourceLocale "${sourceLocale}" is not in locales`);
110
+ }
111
+ }
112
+
113
+ /** The config's namespaces, each with its catalogs' paths, none of them in `outDir`. */
114
+ export function resolveNamespaces(
115
+ namespaces: Record<string, NamespaceConfig>,
116
+ { root, outDir, locales }: { root: string; outDir: string; locales: ReadonlyArray<string> },
117
+ ): Array<ResolvedNamespace> {
118
+ checkCase('Namespaces', Object.keys(namespaces));
119
+ return Object.entries(namespaces).map(([name, ns]) => {
120
+ if (!NAMESPACE_NAME.test(name)) {
121
+ throw new ConfigError(
122
+ `Namespace "${name}" must be letters, digits, "_", "-" or inner dots: it names files`,
123
+ );
124
+ }
125
+ if (!ns.path.includes('{locale}')) {
126
+ throw new ConfigError(`Namespace "${name}" path must contain {locale}`);
127
+ }
128
+ const resolved: ResolvedNamespace = {
129
+ name,
130
+ format: ns.format,
131
+ file: (locale) => path.resolve(root, ns.path.replaceAll('{locale}', locale)),
132
+ };
133
+ if (locales.some((l) => isInside(outDir, resolved.file(l)))) {
134
+ throw new ConfigError(
135
+ `Namespace "${name}" has its catalogs in outDir, which holds generated files only: move one of them`,
136
+ );
137
+ }
138
+ return resolved;
139
+ });
140
+ }