@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.
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/build/build.d.ts +18 -0
- package/build/build.d.ts.map +1 -0
- package/build/build.js +10 -0
- package/build/cli.d.ts +3 -0
- package/build/cli.d.ts.map +1 -0
- package/build/cli.js +8 -0
- package/build/command.d.ts +13 -0
- package/build/command.d.ts.map +1 -0
- package/build/command.js +156 -0
- package/build/compile/code.d.ts +13 -0
- package/build/compile/code.d.ts.map +1 -0
- package/build/compile/code.js +42 -0
- package/build/compile/compile.d.ts +11 -0
- package/build/compile/compile.d.ts.map +1 -0
- package/build/compile/compile.js +244 -0
- package/build/compile/error.d.ts +4 -0
- package/build/compile/error.d.ts.map +1 -0
- package/build/compile/error.js +3 -0
- package/build/compile/info.d.ts +49 -0
- package/build/compile/info.d.ts.map +1 -0
- package/build/compile/info.js +22 -0
- package/build/compile/scope.d.ts +7 -0
- package/build/compile/scope.d.ts.map +1 -0
- package/build/compile/scope.js +14 -0
- package/build/compile/single.d.ts +11 -0
- package/build/compile/single.d.ts.map +1 -0
- package/build/compile/single.js +36 -0
- package/build/compile/variants.d.ts +16 -0
- package/build/compile/variants.d.ts.map +1 -0
- package/build/compile/variants.js +48 -0
- package/build/compile.d.ts +61 -0
- package/build/compile.d.ts.map +1 -0
- package/build/compile.js +385 -0
- package/build/config/checks.d.ts +21 -0
- package/build/config/checks.d.ts.map +1 -0
- package/build/config/checks.js +97 -0
- package/build/config/config.d.ts +71 -0
- package/build/config/config.d.ts.map +1 -0
- package/build/config/config.js +7 -0
- package/build/config/fallbacks.d.ts +6 -0
- package/build/config/fallbacks.d.ts.map +1 -0
- package/build/config/fallbacks.js +13 -0
- package/build/config/import.d.ts +31 -0
- package/build/config/import.d.ts.map +1 -0
- package/build/config/import.js +115 -0
- package/build/config/load.d.ts +13 -0
- package/build/config/load.d.ts.map +1 -0
- package/build/config/load.js +59 -0
- package/build/config.d.ts +77 -0
- package/build/config.d.ts.map +1 -0
- package/build/config.js +223 -0
- package/build/diagnostics.d.ts +31 -0
- package/build/diagnostics.d.ts.map +1 -0
- package/build/diagnostics.js +41 -0
- package/build/generate/checks.d.ts +9 -0
- package/build/generate/checks.d.ts.map +1 -0
- package/build/generate/checks.js +93 -0
- package/build/generate/chunk.d.ts +11 -0
- package/build/generate/chunk.d.ts.map +1 -0
- package/build/generate/chunk.js +57 -0
- package/build/generate/digits.d.ts +8 -0
- package/build/generate/digits.d.ts.map +1 -0
- package/build/generate/digits.js +57 -0
- package/build/generate/files.d.ts +7 -0
- package/build/generate/files.d.ts.map +1 -0
- package/build/generate/files.js +59 -0
- package/build/generate/locale.d.ts +21 -0
- package/build/generate/locale.d.ts.map +1 -0
- package/build/generate/locale.js +108 -0
- package/build/generate/modules.d.ts +27 -0
- package/build/generate/modules.d.ts.map +1 -0
- package/build/generate/modules.js +61 -0
- package/build/generate/namespace.d.ts +19 -0
- package/build/generate/namespace.d.ts.map +1 -0
- package/build/generate/namespace.js +65 -0
- package/build/generate/namespaces.d.ts +5 -0
- package/build/generate/namespaces.d.ts.map +1 -0
- package/build/generate/namespaces.js +41 -0
- package/build/generate/read.d.ts +21 -0
- package/build/generate/read.d.ts.map +1 -0
- package/build/generate/read.js +115 -0
- package/build/index.d.ts +9 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7 -0
- package/build/init/detect.d.ts +43 -0
- package/build/init/detect.d.ts.map +1 -0
- package/build/init/detect.js +69 -0
- package/build/init/init.d.ts +12 -0
- package/build/init/init.d.ts.map +1 -0
- package/build/init/init.js +126 -0
- package/build/options/date.d.ts +3 -0
- package/build/options/date.d.ts.map +1 -0
- package/build/options/date.js +77 -0
- package/build/options/literal.d.ts +10 -0
- package/build/options/literal.d.ts.map +1 -0
- package/build/options/literal.js +11 -0
- package/build/options/names.d.ts +5 -0
- package/build/options/names.d.ts.map +1 -0
- package/build/options/names.js +56 -0
- package/build/options/number.d.ts +3 -0
- package/build/options/number.d.ts.map +1 -0
- package/build/options/number.js +17 -0
- package/build/options/options.d.ts +7 -0
- package/build/options/options.d.ts.map +1 -0
- package/build/options/options.js +66 -0
- package/build/options.d.ts +9 -0
- package/build/options.d.ts.map +1 -0
- package/build/options.js +214 -0
- package/build/plurals.d.ts +6 -0
- package/build/plurals.d.ts.map +1 -0
- package/build/plurals.js +50 -0
- package/build/types/names.d.ts +9 -0
- package/build/types/names.d.ts.map +1 -0
- package/build/types/names.js +109 -0
- package/build/types/namespace.d.ts +17 -0
- package/build/types/namespace.d.ts.map +1 -0
- package/build/types/namespace.js +113 -0
- package/build/types/signature.d.ts +8 -0
- package/build/types/signature.d.ts.map +1 -0
- package/build/types/signature.js +87 -0
- package/build/types.d.ts +25 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +250 -0
- package/build/vite.d.ts +9 -0
- package/build/vite.d.ts.map +1 -0
- package/build/vite.js +125 -0
- package/build/watch.d.ts +12 -0
- package/build/watch.d.ts.map +1 -0
- package/build/watch.js +93 -0
- package/package.json +84 -3
- package/src/build.ts +31 -0
- package/src/cli.ts +9 -0
- package/src/command.ts +195 -0
- package/src/compile/code.ts +51 -0
- package/src/compile/compile.ts +289 -0
- package/src/compile/error.ts +3 -0
- package/src/compile/info.ts +63 -0
- package/src/compile/scope.ts +14 -0
- package/src/compile/single.ts +46 -0
- package/src/compile/variants.ts +68 -0
- package/src/config/checks.ts +140 -0
- package/src/config/config.ts +83 -0
- package/src/config/fallbacks.ts +18 -0
- package/src/config/import.ts +146 -0
- package/src/config/load.ts +75 -0
- package/src/diagnostics.ts +98 -0
- package/src/generate/checks.ts +103 -0
- package/src/generate/chunk.ts +73 -0
- package/src/generate/digits.ts +74 -0
- package/src/generate/files.ts +83 -0
- package/src/generate/locale.ts +145 -0
- package/src/generate/modules.ts +94 -0
- package/src/generate/namespace.ts +119 -0
- package/src/generate/namespaces.ts +59 -0
- package/src/generate/read.ts +159 -0
- package/src/index.ts +27 -0
- package/src/init/detect.ts +103 -0
- package/src/init/init.ts +158 -0
- package/src/options/date.ts +87 -0
- package/src/options/literal.ts +21 -0
- package/src/options/names.ts +64 -0
- package/src/options/number.ts +20 -0
- package/src/options/options.ts +75 -0
- package/src/plurals.ts +68 -0
- package/src/types/names.ts +115 -0
- package/src/types/namespace.ts +148 -0
- package/src/types/signature.ts +111 -0
- package/src/vite.ts +143 -0
- package/src/watch.ts +115 -0
package/src/command.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import type { ParseArgsConfig } from 'node:util';
|
|
3
|
+
|
|
4
|
+
import { build } from './build.ts';
|
|
5
|
+
import type { BuildResult } from './build.ts';
|
|
6
|
+
import { ConfigError } from './config/config.ts';
|
|
7
|
+
import type { ResolvedConfig } from './config/config.ts';
|
|
8
|
+
import { formatDiagnostics, unreported } from './diagnostics.ts';
|
|
9
|
+
import type { Diagnostic } from './diagnostics.ts';
|
|
10
|
+
import { init } from './init/init.ts';
|
|
11
|
+
import { rebuildOnChange } from './watch.ts';
|
|
12
|
+
|
|
13
|
+
const HELP = `Usage: parla <command> [options]
|
|
14
|
+
|
|
15
|
+
Commands
|
|
16
|
+
build Compile catalogs into per-locale chunks and typed namespace objects
|
|
17
|
+
check Validate catalogs without writing anything
|
|
18
|
+
init Write parla.config.ts, a catalog per locale and the .gitignore line
|
|
19
|
+
|
|
20
|
+
Options
|
|
21
|
+
-c, --config <file> Config file (default: parla.config.ts, then .mts)
|
|
22
|
+
-w, --watch Rebuild on change (build)
|
|
23
|
+
--strict Treat warnings as errors
|
|
24
|
+
--json Print diagnostics as JSON (check)
|
|
25
|
+
--format <name> mf2 or icu (init; default mf2)
|
|
26
|
+
--locales <list> Comma-separated, source first (init; default en)
|
|
27
|
+
--catalogs <dir> Catalog folder (init; default locales)
|
|
28
|
+
-h, --help`;
|
|
29
|
+
|
|
30
|
+
export interface CommandIO {
|
|
31
|
+
readonly cwd: string;
|
|
32
|
+
readonly log: (line: string) => void;
|
|
33
|
+
readonly error: (line: string) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CommandRun {
|
|
37
|
+
readonly code: number;
|
|
38
|
+
/** Stops watching; a no-op unless `--watch`. */
|
|
39
|
+
readonly close: () => void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const done = (code: number): CommandRun => ({
|
|
43
|
+
code,
|
|
44
|
+
close: () => {
|
|
45
|
+
// nothing to stop
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const ARGS = {
|
|
50
|
+
allowPositionals: true,
|
|
51
|
+
options: {
|
|
52
|
+
config: { type: 'string', short: 'c' },
|
|
53
|
+
watch: { type: 'boolean', short: 'w' },
|
|
54
|
+
strict: { type: 'boolean' },
|
|
55
|
+
json: { type: 'boolean' },
|
|
56
|
+
format: { type: 'string' },
|
|
57
|
+
locales: { type: 'string' },
|
|
58
|
+
catalogs: { type: 'string' },
|
|
59
|
+
help: { type: 'boolean', short: 'h' },
|
|
60
|
+
},
|
|
61
|
+
} as const satisfies ParseArgsConfig;
|
|
62
|
+
|
|
63
|
+
type Parsed = ReturnType<typeof parseArgs<typeof ARGS>>;
|
|
64
|
+
|
|
65
|
+
/** The options of `parla`, or why they are wrong. */
|
|
66
|
+
function parse(args: ReadonlyArray<string>): Parsed | string {
|
|
67
|
+
try {
|
|
68
|
+
return parseArgs({ ...ARGS, args: [...args] });
|
|
69
|
+
} catch (error) {
|
|
70
|
+
return (error as Error).message;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const INIT_ONLY = ['format', 'locales', 'catalogs'] as const;
|
|
75
|
+
const NOT_INIT = ['config', 'strict', 'json'] as const;
|
|
76
|
+
|
|
77
|
+
/** Why a known command cannot run as given, or nothing. */
|
|
78
|
+
function misuse(
|
|
79
|
+
command: string,
|
|
80
|
+
{ extra, values }: { extra: string | undefined; values: Parsed['values'] },
|
|
81
|
+
): string {
|
|
82
|
+
if (extra !== undefined) {
|
|
83
|
+
return `unexpected argument "${extra}"`;
|
|
84
|
+
}
|
|
85
|
+
if (values.watch && command !== 'build') {
|
|
86
|
+
return '--watch works only with build';
|
|
87
|
+
}
|
|
88
|
+
if (command === 'init') {
|
|
89
|
+
const option = NOT_INIT.find((name) => values[name] !== undefined);
|
|
90
|
+
return option ? `--${option} does not work with init` : '';
|
|
91
|
+
}
|
|
92
|
+
const option = INIT_ONLY.find((name) => values[name] !== undefined);
|
|
93
|
+
return option ? `--${option} works only with init` : '';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function runInit({ cwd, log, error }: CommandIO, values: Parsed['values']): CommandRun {
|
|
97
|
+
try {
|
|
98
|
+
for (const line of init(cwd, values)) {
|
|
99
|
+
log(line);
|
|
100
|
+
}
|
|
101
|
+
return done(0);
|
|
102
|
+
} catch (error_) {
|
|
103
|
+
error(`parla: ${(error_ as Error).message}`);
|
|
104
|
+
return done(1);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function reportFailure(
|
|
109
|
+
thrown: unknown,
|
|
110
|
+
{ json, io }: { json: boolean | undefined; io: CommandIO },
|
|
111
|
+
): void {
|
|
112
|
+
const { message } = thrown as Error;
|
|
113
|
+
if (json && thrown instanceof ConfigError) {
|
|
114
|
+
// A consumer parsing stdout gets a document either way.
|
|
115
|
+
const diagnostic: Diagnostic = { level: 'error', code: 'invalid-config', message };
|
|
116
|
+
io.log(JSON.stringify([diagnostic], null, 2));
|
|
117
|
+
} else {
|
|
118
|
+
io.error(`parla: ${message}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function filesOf({ written, removed }: BuildResult): string {
|
|
123
|
+
const gone = removed.length > 0 ? ` · ${removed.length} removed` : '';
|
|
124
|
+
return ` · ${written.length} files written${gone}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Runs `parla <args>`: the exit code, and in watch mode the watchers that keep it running. */
|
|
128
|
+
export async function runCommand(
|
|
129
|
+
args: ReadonlyArray<string>,
|
|
130
|
+
{ cwd, log, error }: CommandIO,
|
|
131
|
+
): Promise<CommandRun> {
|
|
132
|
+
const parsed = parse(args);
|
|
133
|
+
if (typeof parsed === 'string') {
|
|
134
|
+
error(`parla: ${parsed}`);
|
|
135
|
+
return done(1);
|
|
136
|
+
}
|
|
137
|
+
const { values, positionals } = parsed;
|
|
138
|
+
const [command, extra] = positionals;
|
|
139
|
+
if (values.help || !command || !['build', 'check', 'init'].includes(command)) {
|
|
140
|
+
log(HELP);
|
|
141
|
+
return done(values.help ? 0 : 1);
|
|
142
|
+
}
|
|
143
|
+
const problem = misuse(command, { extra, values });
|
|
144
|
+
if (problem) {
|
|
145
|
+
error(`parla: ${problem}`);
|
|
146
|
+
return done(1);
|
|
147
|
+
}
|
|
148
|
+
if (command === 'init') {
|
|
149
|
+
return runInit({ cwd, log, error }, values);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const write = command === 'build';
|
|
153
|
+
const fresh = unreported();
|
|
154
|
+
|
|
155
|
+
const run = async (): Promise<{ failed: boolean; config: ResolvedConfig }> => {
|
|
156
|
+
const started = performance.now();
|
|
157
|
+
const result = await build({ cwd, config: values.config, write });
|
|
158
|
+
const { diagnostics, config } = result;
|
|
159
|
+
const reports = formatDiagnostics(diagnostics);
|
|
160
|
+
const errors = reports.filter((r) => r.level === 'error').length;
|
|
161
|
+
const warnings = reports.length - errors;
|
|
162
|
+
if (values.json) {
|
|
163
|
+
log(JSON.stringify(diagnostics, null, 2));
|
|
164
|
+
} else {
|
|
165
|
+
for (const { line } of formatDiagnostics(fresh(diagnostics), config.root)) {
|
|
166
|
+
log(line);
|
|
167
|
+
}
|
|
168
|
+
const ms = Math.round(performance.now() - started);
|
|
169
|
+
const files = write ? filesOf(result) : '';
|
|
170
|
+
log(
|
|
171
|
+
`parla ${command}: ${config.namespaces.length} namespaces × ${config.locales.length} locales · ${errors} errors · ${warnings} warnings · ${ms}ms${files}`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
failed: errors > 0 || (Boolean(values.strict) && warnings > 0),
|
|
176
|
+
config,
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
let first;
|
|
181
|
+
try {
|
|
182
|
+
first = await run();
|
|
183
|
+
} catch (error_) {
|
|
184
|
+
reportFailure(error_, { json: values.json, io: { cwd, log, error } });
|
|
185
|
+
return done(1);
|
|
186
|
+
}
|
|
187
|
+
const code = first.failed ? 1 : 0;
|
|
188
|
+
if (!values.watch) {
|
|
189
|
+
return done(code);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const watcher = rebuildOnChange(first.config, { run, error });
|
|
193
|
+
log(`parla: watching ${watcher.folders} folders`);
|
|
194
|
+
return { code, close: watcher.close };
|
|
195
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Model } from 'messageformat';
|
|
2
|
+
|
|
3
|
+
import { CompileError } from './error.ts';
|
|
4
|
+
|
|
5
|
+
export function literalValue(value: string): string {
|
|
6
|
+
if (/^-?\d+(?:\.\d+)?$/.test(value)) {
|
|
7
|
+
// `02` would be a legacy octal literal: a syntax error in the chunk, which is a module
|
|
8
|
+
return String(Number(value));
|
|
9
|
+
}
|
|
10
|
+
if (value === 'true' || value === 'false') {
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
return JSON.stringify(value);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Where markup finds its callback, without what objects inherit: a check at run time costs 30%. */
|
|
17
|
+
export const params = (markup: string): string =>
|
|
18
|
+
markup in Object.prototype ? '{ __proto__: null, ...p }' : 'p';
|
|
19
|
+
|
|
20
|
+
/** A call's `{ __proto__: value }` sets the object's prototype, so the message would never get it. */
|
|
21
|
+
export function checkName(name: string): void {
|
|
22
|
+
if (name === '__proto__') {
|
|
23
|
+
throw new CompileError('a param or markup cannot be named "__proto__": rename it');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A parser that assigns a `__proto__` option sets the prototype instead, dropping the option. */
|
|
28
|
+
export function checkOptions(options: object | undefined): void {
|
|
29
|
+
if (options && Object.getPrototypeOf(options) !== Object.prototype) {
|
|
30
|
+
throw new CompileError('an option cannot be named "__proto__": rename it');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `:offset`'s `add` or `subtract`, as an operation. */
|
|
35
|
+
export function offsetBy({ options = {} }: Model.FunctionRef): string {
|
|
36
|
+
const [[name, value] = [], ...rest] = Object.entries(options);
|
|
37
|
+
const isDigits = value?.type === 'literal' && /^\d+$/.test(value.value);
|
|
38
|
+
if (!isDigits || rest.length > 0 || (name !== 'add' && name !== 'subtract')) {
|
|
39
|
+
throw new CompileError(':offset needs one literal integer, add or subtract');
|
|
40
|
+
}
|
|
41
|
+
return `${name === 'add' ? '+' : '-'} ${Number(value.value)}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The number a selector picks by: the one its function writes. */
|
|
45
|
+
export function selected(name: string, raw: string): string {
|
|
46
|
+
if (name === 'integer') {
|
|
47
|
+
return `Math.round(Number(${raw}))`;
|
|
48
|
+
}
|
|
49
|
+
// Rounded, as 0.29 * 100 is 28.999999999999996.
|
|
50
|
+
return name === 'percent' ? `Math.round(Number(${raw}) * 1e4) / 100` : raw;
|
|
51
|
+
}
|
|
@@ -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,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
|
+
}
|