@parlajs/compiler 0.0.0 → 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.
- package/package.json +4 -4
- package/build/compile.d.ts +0 -61
- package/build/compile.d.ts.map +0 -1
- package/build/compile.js +0 -385
- package/build/config.d.ts +0 -77
- package/build/config.d.ts.map +0 -1
- package/build/config.js +0 -223
- package/build/options.d.ts +0 -9
- package/build/options.d.ts.map +0 -1
- package/build/options.js +0 -214
- package/build/types.d.ts +0 -25
- package/build/types.d.ts.map +0 -1
- package/build/types.js +0 -250
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parlajs/compiler",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "Compiles Parla catalogs into per-locale chunks and typed accessors.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"codegen",
|
|
@@ -59,9 +59,9 @@
|
|
|
59
59
|
"messageformat": "^4.1.0"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
|
-
"@parlajs/core": "^0.
|
|
63
|
-
"@parlajs/format-icu": "^0.
|
|
64
|
-
"@parlajs/format-mf2": "^0.
|
|
62
|
+
"@parlajs/core": "^0.1.0",
|
|
63
|
+
"@parlajs/format-icu": "^0.1.0",
|
|
64
|
+
"@parlajs/format-mf2": "^0.1.0",
|
|
65
65
|
"@types/node": "26.6.6",
|
|
66
66
|
"intl-messageformat": "12.2.0",
|
|
67
67
|
"vite": "8.3.8",
|
package/build/compile.d.ts
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import type { Model } from 'messageformat';
|
|
2
|
-
/** What a custom function's value is: it types the param. */
|
|
3
|
-
export type FunctionKind = 'string' | 'number' | 'date';
|
|
4
|
-
/** Message functions beyond the built-in ones, by what their value is. */
|
|
5
|
-
export type CustomFunctions = Readonly<Record<string, FunctionKind>>;
|
|
6
|
-
/** The built-in message functions; the config's `functions` add to them. */
|
|
7
|
-
export declare const BUILTIN_FUNCTIONS: ReadonlySet<string>;
|
|
8
|
-
/** What a message needs from one parameter. `any` is an unannotated placeholder. */
|
|
9
|
-
export type ParamKind = {
|
|
10
|
-
kind: 'number';
|
|
11
|
-
} | {
|
|
12
|
-
kind: 'date';
|
|
13
|
-
} | {
|
|
14
|
-
kind: 'string';
|
|
15
|
-
} | {
|
|
16
|
-
kind: 'any';
|
|
17
|
-
} | {
|
|
18
|
-
kind: 'select';
|
|
19
|
-
keys: Array<string>;
|
|
20
|
-
open: boolean;
|
|
21
|
-
};
|
|
22
|
-
export interface MessageInfo {
|
|
23
|
-
params: Map<string, Array<ParamKind>>;
|
|
24
|
-
markup: Set<string>;
|
|
25
|
-
rich: boolean;
|
|
26
|
-
/**
|
|
27
|
-
* Set when a `:string` selector's value decides which params a call needs: the params each key
|
|
28
|
-
* needs, `null` for any other string. Unset when every key needs the same.
|
|
29
|
-
*/
|
|
30
|
-
branches?: {
|
|
31
|
-
param: string;
|
|
32
|
-
needs: Map<string | null, Set<string>>;
|
|
33
|
-
};
|
|
34
|
-
/** Each selector that picks by plural category, with the keys its variants name. */
|
|
35
|
-
plurals: Array<{
|
|
36
|
-
type: Intl.PluralRuleType;
|
|
37
|
-
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
|
-
export declare class CompileError extends Error {
|
|
46
|
-
name: string;
|
|
47
|
-
}
|
|
48
|
-
/** Module-level constants shared by every message in one generated chunk. */
|
|
49
|
-
export declare class ModuleScope {
|
|
50
|
-
readonly consts: Array<string>;
|
|
51
|
-
private readonly seen;
|
|
52
|
-
hoist(code: string): string;
|
|
53
|
-
}
|
|
54
|
-
export interface CompileOptions {
|
|
55
|
-
readonly scope?: ModuleScope;
|
|
56
|
-
readonly custom?: CustomFunctions;
|
|
57
|
-
/** The locale whose plural rules apply, when not the chunk's. */
|
|
58
|
-
readonly pluralsOf?: string | undefined;
|
|
59
|
-
}
|
|
60
|
-
export declare function compileMessage(msg: Model.Message, options?: CompileOptions): CompiledMessage;
|
|
61
|
-
//# sourceMappingURL=compile.d.ts.map
|
package/build/compile.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAI3C,6DAA6D;AAC7D,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;AAExD,0EAA0E;AAC1E,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC;AAMrE,4EAA4E;AAC5E,eAAO,MAAM,iBAAiB,EAAE,WAAW,CAAC,MAAM,CAA6C,CAAC;AAEhG,oFAAoF;AACpF,MAAM,MAAM,SAAS,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GACf;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAE3D,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;IACtC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACpB,IAAI,EAAE,OAAO,CAAC;IACd;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;KAAE,CAAC;IACrE,oFAAoF;IACpF,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC;QAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;KAAE,CAAC,CAAC;CAClE;AAED,MAAM,WAAW,eAAe;IAC9B,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,WAAW,CAAC;CACnB;AAED,qBAAa,YAAa,SAAQ,KAAK;IAC5B,IAAI,SAAkB;CAChC;AAED,6EAA6E;AAC7E,qBAAa,WAAW;IACtB,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAM;IACpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQ1B;CACF;AAiHD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,eAAe,CAAC;IAClC,iEAAiE;IACjE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACzC;AAwSD,wBAAgB,cAAc,CAAC,GAAG,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,eAAe,CAOhG"}
|
package/build/compile.js
DELETED
|
@@ -1,385 +0,0 @@
|
|
|
1
|
-
import { inheritedOptions, intlOptions } from './options.js';
|
|
2
|
-
const NUMERIC = new Set(['number', 'integer', 'currency', 'percent', 'unit', 'offset']);
|
|
3
|
-
/** MF2 gives the other number functions no selection. */
|
|
4
|
-
const SELECTS = new Set(['number', 'integer', 'percent']);
|
|
5
|
-
const DATES = new Set(['date', 'time', 'datetime']);
|
|
6
|
-
/** The built-in message functions; the config's `functions` add to them. */
|
|
7
|
-
export const BUILTIN_FUNCTIONS = new Set([...NUMERIC, ...DATES, 'string']);
|
|
8
|
-
export class CompileError extends Error {
|
|
9
|
-
name = 'CompileError';
|
|
10
|
-
}
|
|
11
|
-
/** Module-level constants shared by every message in one generated chunk. */
|
|
12
|
-
export class ModuleScope {
|
|
13
|
-
consts = [];
|
|
14
|
-
seen = new Map();
|
|
15
|
-
hoist(code) {
|
|
16
|
-
let name = this.seen.get(code);
|
|
17
|
-
if (!name) {
|
|
18
|
-
name = `v${this.consts.length}`;
|
|
19
|
-
this.consts.push(`const ${name} = ${code};`);
|
|
20
|
-
this.seen.set(code, name);
|
|
21
|
-
}
|
|
22
|
-
return name;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
function literalValue(value) {
|
|
26
|
-
if (/^-?\d+(?:\.\d+)?$/.test(value)) {
|
|
27
|
-
// `02` would be a legacy octal literal: a syntax error in the chunk, which is a module
|
|
28
|
-
return String(Number(value));
|
|
29
|
-
}
|
|
30
|
-
if (value === 'true' || value === 'false') {
|
|
31
|
-
return value;
|
|
32
|
-
}
|
|
33
|
-
return JSON.stringify(value);
|
|
34
|
-
}
|
|
35
|
-
/** Where markup finds its callback, without what objects inherit: a check at run time costs 30%. */
|
|
36
|
-
const params = (markup) => markup in Object.prototype ? '{ __proto__: null, ...p }' : 'p';
|
|
37
|
-
/** A call's `{ __proto__: value }` sets the object's prototype, so the message would never get it. */
|
|
38
|
-
function checkName(name) {
|
|
39
|
-
if (name === '__proto__') {
|
|
40
|
-
throw new CompileError('a param or markup cannot be named "__proto__": rename it');
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
function kindOf(fn, custom) {
|
|
44
|
-
if (!fn) {
|
|
45
|
-
return { kind: 'any' };
|
|
46
|
-
}
|
|
47
|
-
const declared = custom.get(fn.name);
|
|
48
|
-
if (declared) {
|
|
49
|
-
return { kind: declared };
|
|
50
|
-
}
|
|
51
|
-
if (NUMERIC.has(fn.name)) {
|
|
52
|
-
return { kind: 'number' };
|
|
53
|
-
}
|
|
54
|
-
if (DATES.has(fn.name)) {
|
|
55
|
-
return { kind: 'date' };
|
|
56
|
-
}
|
|
57
|
-
return { kind: 'string' };
|
|
58
|
-
}
|
|
59
|
-
/** `:offset`'s `add` or `subtract`, as an operation. */
|
|
60
|
-
function offsetBy({ options = {} }) {
|
|
61
|
-
const [[name, value] = [], ...rest] = Object.entries(options);
|
|
62
|
-
const isDigits = value?.type === 'literal' && /^\d+$/.test(value.value);
|
|
63
|
-
if (!isDigits || rest.length > 0 || (name !== 'add' && name !== 'subtract')) {
|
|
64
|
-
throw new CompileError(':offset needs one literal integer, add or subtract');
|
|
65
|
-
}
|
|
66
|
-
return `${name === 'add' ? '+' : '-'} ${Number(value.value)}`;
|
|
67
|
-
}
|
|
68
|
-
/** The number a selector picks by: the one its function writes. */
|
|
69
|
-
function selected(name, raw) {
|
|
70
|
-
if (name === 'integer') {
|
|
71
|
-
return `Math.round(Number(${raw}))`;
|
|
72
|
-
}
|
|
73
|
-
// Rounded, as 0.29 * 100 is 28.999999999999996.
|
|
74
|
-
return name === 'percent' ? `Math.round(Number(${raw}) * 1e4) / 100` : raw;
|
|
75
|
-
}
|
|
76
|
-
function switchOn(value, cases) {
|
|
77
|
-
const body = [...cases].map(([key, code]) => `case ${key}: return ${code};`);
|
|
78
|
-
return body.length > 0 ? `switch (${value}) { ${body.join(' ')} } ` : '';
|
|
79
|
-
}
|
|
80
|
-
/** One selector needs no `pick`: exact numbers first, then the category or text, then the catch-all. */
|
|
81
|
-
function single({ numeric, raw, options }, variants) {
|
|
82
|
-
const exact = new Map();
|
|
83
|
-
const named = new Map();
|
|
84
|
-
let rest;
|
|
85
|
-
for (const { key, code } of variants) {
|
|
86
|
-
if (key === null) {
|
|
87
|
-
rest ??= code;
|
|
88
|
-
continue;
|
|
89
|
-
}
|
|
90
|
-
// A letter starts a category, never a number.
|
|
91
|
-
const isExact = numeric && (key.codePointAt(0) ?? 65) < 65;
|
|
92
|
-
const cases = isExact ? exact : named;
|
|
93
|
-
const literal = isExact ? String(Number(key)) : JSON.stringify(key);
|
|
94
|
-
cases.set(literal, cases.get(literal) ?? code);
|
|
95
|
-
}
|
|
96
|
-
// Both formats require a catch-all; without one, `pick` takes the last variant too.
|
|
97
|
-
rest ??= variants.at(-1)?.code ?? '""';
|
|
98
|
-
const number = `Number(${raw})`;
|
|
99
|
-
const value = numeric ? `$.c(${raw}${options})` : `$.s(${raw})`;
|
|
100
|
-
if (exact.size > 1 || named.size > 1) {
|
|
101
|
-
return `{ ${switchOn(number, exact)}${switchOn(value, named)}return ${rest}; }`;
|
|
102
|
-
}
|
|
103
|
-
let code = rest;
|
|
104
|
-
for (const [key, matched] of named) {
|
|
105
|
-
code = `${value} === ${key} ? ${matched} : ${code}`;
|
|
106
|
-
}
|
|
107
|
-
for (const [key, matched] of exact) {
|
|
108
|
-
code = `${number} === ${key} ? ${matched} : ${code}`;
|
|
109
|
-
}
|
|
110
|
-
return code;
|
|
111
|
-
}
|
|
112
|
-
class MessageCompiler {
|
|
113
|
-
vars = new Map();
|
|
114
|
-
scope;
|
|
115
|
-
custom;
|
|
116
|
-
info = { params: new Map(), markup: new Set(), rich: false, plurals: [] };
|
|
117
|
-
/** The params read outside any variant, and those the variant being compiled reads. */
|
|
118
|
-
shared = new Set();
|
|
119
|
-
reads;
|
|
120
|
-
pluralsOf;
|
|
121
|
-
constructor({ scope = new ModuleScope(), custom = {}, pluralsOf }) {
|
|
122
|
-
this.scope = scope;
|
|
123
|
-
this.custom = new Map(Object.entries(custom));
|
|
124
|
-
this.pluralsOf = pluralsOf;
|
|
125
|
-
}
|
|
126
|
-
record(param, kind) {
|
|
127
|
-
checkName(param);
|
|
128
|
-
const list = this.info.params.get(param) ?? [];
|
|
129
|
-
list.push(kind);
|
|
130
|
-
this.info.params.set(param, list);
|
|
131
|
-
(this.reads ?? this.shared).add(param);
|
|
132
|
-
}
|
|
133
|
-
resolve(name) {
|
|
134
|
-
return this.vars.get(name) ?? { raw: `p[${JSON.stringify(name)}]`, param: name };
|
|
135
|
-
}
|
|
136
|
-
options(fn, extra = {}) {
|
|
137
|
-
const entries = Object.entries({ ...this.resolved(fn), ...extra });
|
|
138
|
-
if (entries.length === 0) {
|
|
139
|
-
return '';
|
|
140
|
-
}
|
|
141
|
-
const parts = entries.map(([k, v]) => `${JSON.stringify(k)}: ${v.type === 'literal' ? literalValue(v.value) : this.variable(v)}`);
|
|
142
|
-
const code = `{ ${parts.join(', ')} }`;
|
|
143
|
-
const constant = entries.every(([, v]) => v.type === 'literal');
|
|
144
|
-
return `, ${constant ? this.scope.hoist(code) : code}`;
|
|
145
|
-
}
|
|
146
|
-
/** An option's variable, which the call then needs as it does any placeholder. */
|
|
147
|
-
variable({ name }) {
|
|
148
|
-
const { raw, param } = this.resolve(name);
|
|
149
|
-
if (param) {
|
|
150
|
-
this.record(param, { kind: 'any' });
|
|
151
|
-
}
|
|
152
|
-
return raw;
|
|
153
|
-
}
|
|
154
|
-
resolved(fn) {
|
|
155
|
-
if (this.custom.has(fn.name)) {
|
|
156
|
-
return fn.options ?? {};
|
|
157
|
-
}
|
|
158
|
-
try {
|
|
159
|
-
return intlOptions(fn);
|
|
160
|
-
}
|
|
161
|
-
catch (error) {
|
|
162
|
-
throw new CompileError(error.message, { cause: error });
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
effective(expr) {
|
|
166
|
-
let binding;
|
|
167
|
-
if (expr.arg?.type === 'literal') {
|
|
168
|
-
binding = { raw: JSON.stringify(expr.arg.value) };
|
|
169
|
-
}
|
|
170
|
-
else if (expr.arg?.type === 'variable') {
|
|
171
|
-
binding = { ...this.resolve(expr.arg.name) };
|
|
172
|
-
}
|
|
173
|
-
else {
|
|
174
|
-
binding = { raw: 'undefined' };
|
|
175
|
-
}
|
|
176
|
-
const own = expr.functionRef;
|
|
177
|
-
if (own) {
|
|
178
|
-
if (!BUILTIN_FUNCTIONS.has(own.name) && !this.custom.has(own.name)) {
|
|
179
|
-
throw new CompileError(`unknown function :${own.name}`);
|
|
180
|
-
}
|
|
181
|
-
const { name } = own;
|
|
182
|
-
const isOffset = name === 'offset' && !this.custom.has(name);
|
|
183
|
-
const inherited = binding.fn ? inheritedOptions(binding.fn, isOffset ? 'number' : name) : {};
|
|
184
|
-
if (isOffset) {
|
|
185
|
-
binding.raw = `(Number(${binding.raw}) ${offsetBy(own)})`;
|
|
186
|
-
binding.fn = { type: 'function', name: 'number', options: inherited };
|
|
187
|
-
}
|
|
188
|
-
else {
|
|
189
|
-
binding.fn = { ...own, options: { ...inherited, ...own.options } };
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return binding;
|
|
193
|
-
}
|
|
194
|
-
declare(decl) {
|
|
195
|
-
const binding = this.effective(decl.value);
|
|
196
|
-
if (decl.type === 'input') {
|
|
197
|
-
binding.param = decl.name;
|
|
198
|
-
}
|
|
199
|
-
this.vars.set(decl.name, binding);
|
|
200
|
-
if (binding.param && binding.fn) {
|
|
201
|
-
this.record(binding.param, kindOf(binding.fn, this.custom));
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
expression(expr) {
|
|
205
|
-
const b = this.effective(expr);
|
|
206
|
-
if (b.param) {
|
|
207
|
-
this.record(b.param, kindOf(b.fn, this.custom));
|
|
208
|
-
}
|
|
209
|
-
if (!b.fn) {
|
|
210
|
-
return `$.str(${b.raw})`;
|
|
211
|
-
}
|
|
212
|
-
const options = this.options(b.fn);
|
|
213
|
-
if (b.fn.name === 'number' && !options) {
|
|
214
|
-
return `$.n(${b.raw})`;
|
|
215
|
-
}
|
|
216
|
-
return `$.f(${JSON.stringify(b.fn.name)}, ${b.raw}${options})`;
|
|
217
|
-
}
|
|
218
|
-
pattern(pattern) {
|
|
219
|
-
const root = [];
|
|
220
|
-
const stack = [];
|
|
221
|
-
let rich = false;
|
|
222
|
-
const top = () => stack.at(-1)?.items ?? root;
|
|
223
|
-
for (const part of pattern) {
|
|
224
|
-
if (typeof part === 'string') {
|
|
225
|
-
if (part) {
|
|
226
|
-
top().push(JSON.stringify(part));
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
else if (part.type === 'expression') {
|
|
230
|
-
top().push(this.expression(part));
|
|
231
|
-
}
|
|
232
|
-
else {
|
|
233
|
-
rich = true;
|
|
234
|
-
checkName(part.name);
|
|
235
|
-
this.info.markup.add(part.name);
|
|
236
|
-
if (part.kind === 'open') {
|
|
237
|
-
stack.push({ name: part.name, items: [] });
|
|
238
|
-
}
|
|
239
|
-
else if (part.kind === 'standalone') {
|
|
240
|
-
top().push(`$.tag(${params(part.name)}, ${JSON.stringify(part.name)}, [])`);
|
|
241
|
-
}
|
|
242
|
-
else {
|
|
243
|
-
const open = stack.pop();
|
|
244
|
-
if (open?.name !== part.name) {
|
|
245
|
-
throw new CompileError(`closing markup {/${part.name}} has no matching open`);
|
|
246
|
-
}
|
|
247
|
-
top().push(`$.tag(${params(part.name)}, ${JSON.stringify(part.name)}, [${open.items.join(', ')}])`);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
const unclosed = stack.at(-1);
|
|
252
|
-
if (unclosed) {
|
|
253
|
-
throw new CompileError(`markup {#${unclosed.name}} is never closed`);
|
|
254
|
-
}
|
|
255
|
-
if (rich) {
|
|
256
|
-
this.info.rich = true;
|
|
257
|
-
return { code: `$.rich([${root.join(', ')}])`, rich };
|
|
258
|
-
}
|
|
259
|
-
return { code: root.length > 0 ? root.join(' + ') : '""', rich };
|
|
260
|
-
}
|
|
261
|
-
select(msg) {
|
|
262
|
-
const selectors = msg.selectors.map((sel, i) => {
|
|
263
|
-
const b = this.resolve(sel.name);
|
|
264
|
-
if (!b.fn) {
|
|
265
|
-
throw new CompileError(`selector $${sel.name} needs an annotation such as :number or :string`);
|
|
266
|
-
}
|
|
267
|
-
if (SELECTS.has(b.fn.name)) {
|
|
268
|
-
if (b.param) {
|
|
269
|
-
this.record(b.param, { kind: 'number' });
|
|
270
|
-
}
|
|
271
|
-
const raw = selected(b.fn.name, b.raw);
|
|
272
|
-
return { numeric: true, raw, options: this.plural(b.fn, msg, i) };
|
|
273
|
-
}
|
|
274
|
-
if (b.fn.name === 'string') {
|
|
275
|
-
if (b.param) {
|
|
276
|
-
const keys = new Set();
|
|
277
|
-
let open = false;
|
|
278
|
-
for (const v of msg.variants) {
|
|
279
|
-
const key = v.keys[i];
|
|
280
|
-
if (key?.type === '*') {
|
|
281
|
-
open = true;
|
|
282
|
-
}
|
|
283
|
-
else if (key) {
|
|
284
|
-
keys.add(key.value);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
this.record(b.param, { kind: 'select', keys: [...keys], open });
|
|
288
|
-
}
|
|
289
|
-
return { numeric: false, raw: b.raw, options: '' };
|
|
290
|
-
}
|
|
291
|
-
throw new CompileError(`:${b.fn.name} cannot be used as a selector`);
|
|
292
|
-
});
|
|
293
|
-
const reads = [];
|
|
294
|
-
const codes = msg.variants.map((v) => {
|
|
295
|
-
this.reads = new Set();
|
|
296
|
-
reads.push(this.reads);
|
|
297
|
-
return this.pattern(v.value).code;
|
|
298
|
-
});
|
|
299
|
-
this.reads = undefined;
|
|
300
|
-
this.branch(msg, reads);
|
|
301
|
-
const keys = msg.variants.map((v) => v.keys.map((k) => (k.type === '*' ? null : k.value)));
|
|
302
|
-
const [only] = selectors;
|
|
303
|
-
if (only && selectors.length === 1) {
|
|
304
|
-
return single(only, keys.map(([key = null], i) => ({ key, code: codes[i] ?? '""' })));
|
|
305
|
-
}
|
|
306
|
-
const values = selectors.map((s) => `$.${s.numeric ? 'sn' : 'ss'}(${s.raw}${s.options})`);
|
|
307
|
-
const pick = `$.pick([${values.join(', ')}], ${this.scope.hoist(JSON.stringify(keys))})`;
|
|
308
|
-
// `one`/`other` is the commonest select, and a ternary a fraction of a switch's size.
|
|
309
|
-
if (codes.length === 2) {
|
|
310
|
-
const [first, second] = codes;
|
|
311
|
-
return `${pick} ? ${second} : ${first}`;
|
|
312
|
-
}
|
|
313
|
-
const cases = codes.map((code, i) => `case ${i}: return ${code};`);
|
|
314
|
-
return `{ switch (${pick}) { ${cases.join(' ')} } }`;
|
|
315
|
-
}
|
|
316
|
-
/** A numeric selector's options, noting the categories it picks by. */
|
|
317
|
-
plural(fn, msg, at) {
|
|
318
|
-
const keys = new Set();
|
|
319
|
-
for (const { keys: own } of msg.variants) {
|
|
320
|
-
const key = own[at];
|
|
321
|
-
if (key && key.type !== '*') {
|
|
322
|
-
keys.add(key.value);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
const select = fn.options?.['select'];
|
|
326
|
-
const kind = select?.type === 'literal' ? select.value : 'cardinal';
|
|
327
|
-
if (kind === 'exact') {
|
|
328
|
-
return this.options(fn);
|
|
329
|
-
}
|
|
330
|
-
const type = kind === 'ordinal' ? 'ordinal' : 'cardinal';
|
|
331
|
-
this.info.plurals.push({ type, keys });
|
|
332
|
-
const { pluralsOf } = this;
|
|
333
|
-
return this.options(fn, pluralsOf ? { locale: { type: 'literal', value: pluralsOf } } : {});
|
|
334
|
-
}
|
|
335
|
-
/** Fills `info.branches` when exactly one selector is a `:string` param's. */
|
|
336
|
-
branch(msg, reads) {
|
|
337
|
-
const strings = msg.selectors.flatMap((sel, i) => {
|
|
338
|
-
const b = this.resolve(sel.name);
|
|
339
|
-
return b.fn?.name === 'string' && b.param ? [{ i, param: b.param }] : [];
|
|
340
|
-
});
|
|
341
|
-
const [only] = strings;
|
|
342
|
-
const kinds = only && this.info.params.get(only.param);
|
|
343
|
-
if (strings.length !== 1 ||
|
|
344
|
-
!only ||
|
|
345
|
-
kinds?.some((k) => k.kind !== 'select' && k.kind !== 'string' && k.kind !== 'any')) {
|
|
346
|
-
return;
|
|
347
|
-
}
|
|
348
|
-
const keyOf = (v) => {
|
|
349
|
-
const key = v.keys[only.i];
|
|
350
|
-
return !key || key.type === '*' ? null : key.value;
|
|
351
|
-
};
|
|
352
|
-
const readBy = (match) => {
|
|
353
|
-
const out = new Set(this.shared);
|
|
354
|
-
for (const [n, v] of msg.variants.entries()) {
|
|
355
|
-
for (const param of match(v) ? (reads[n] ?? []) : []) {
|
|
356
|
-
out.add(param);
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
return out;
|
|
360
|
-
};
|
|
361
|
-
const needs = new Map();
|
|
362
|
-
for (const key of new Set(msg.variants.map(keyOf))) {
|
|
363
|
-
if (key === null) {
|
|
364
|
-
needs.set(null, readBy((v) => keyOf(v) === null));
|
|
365
|
-
continue;
|
|
366
|
-
}
|
|
367
|
-
// First, the selector decides alone where a variant has `*` for every other selector.
|
|
368
|
-
const covered = only.i === 0 &&
|
|
369
|
-
msg.variants.some((v) => keyOf(v) === key && v.keys.every((k, j) => j === 0 || k.type === '*'));
|
|
370
|
-
needs.set(key, readBy((v) => keyOf(v) === key || (!covered && keyOf(v) === null)));
|
|
371
|
-
}
|
|
372
|
-
const sets = [...needs.values()];
|
|
373
|
-
if (sets.some((set) => set.size !== sets[0]?.size || [...set].some((p) => !sets[0]?.has(p)))) {
|
|
374
|
-
this.info.branches = { param: only.param, needs };
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
export function compileMessage(msg, options = {}) {
|
|
379
|
-
const c = new MessageCompiler(options);
|
|
380
|
-
for (const decl of msg.declarations) {
|
|
381
|
-
c.declare(decl);
|
|
382
|
-
}
|
|
383
|
-
const body = msg.type === 'message' ? c.pattern(msg.pattern).code : c.select(msg);
|
|
384
|
-
return { body, info: c.info };
|
|
385
|
-
}
|
package/build/config.d.ts
DELETED
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import type { Model } from 'messageformat';
|
|
2
|
-
import type { FunctionKind } from './compile.ts';
|
|
3
|
-
/** Parses one message into the MF2 data model, which the compiler reads. */
|
|
4
|
-
export interface FormatAdapter {
|
|
5
|
-
readonly name: string;
|
|
6
|
-
readonly parse: (source: string) => Model.Message;
|
|
7
|
-
/** Reads a catalog file into `{ key: message | group }`, for files that are not JSON. */
|
|
8
|
-
readonly parseFile?: ((text: string) => unknown) | undefined;
|
|
9
|
-
}
|
|
10
|
-
export declare const defaultFormats: Readonly<Record<string, FormatAdapter>>;
|
|
11
|
-
export interface NamespaceConfig {
|
|
12
|
-
/** Message syntax: `icu`, `mf2` or a key of `formats`. */
|
|
13
|
-
format: string;
|
|
14
|
-
/** Catalog path relative to the config, with a `{locale}` token. */
|
|
15
|
-
path: string;
|
|
16
|
-
}
|
|
17
|
-
export interface ParlaConfig {
|
|
18
|
-
locales?: Array<string>;
|
|
19
|
-
sourceLocale?: string;
|
|
20
|
-
/** Extra fallback chain per locale; the source locale is always last. */
|
|
21
|
-
fallbacks?: Record<string, Array<string>>;
|
|
22
|
-
/** Where generated files go, relative to the config. Default `src/parla`. */
|
|
23
|
-
outDir?: string;
|
|
24
|
-
/** Namespaces this package owns: other packages import their built objects. */
|
|
25
|
-
namespaces?: Record<string, NamespaceConfig>;
|
|
26
|
-
/**
|
|
27
|
-
* Message functions beyond the built-in ones, by what their value is. Each needs an
|
|
28
|
-
* implementation in `createParla({ functions })`.
|
|
29
|
-
*/
|
|
30
|
-
functions?: Record<string, FunctionKind>;
|
|
31
|
-
/** Markup that calls may leave out: `createParla({ markup })` renders it. */
|
|
32
|
-
markup?: Array<string>;
|
|
33
|
-
/** Message syntaxes beyond `icu` and `mf2`, by the name a namespace's `format` gives. */
|
|
34
|
-
formats?: Record<string, FormatAdapter>;
|
|
35
|
-
/**
|
|
36
|
-
* Module the generated types import and augment: the adapter this package depends on.
|
|
37
|
-
* Default: the first of `@parlajs/react`, `solid`, `svelte`, `vue` and `core` in `package.json`.
|
|
38
|
-
*/
|
|
39
|
-
runtime?: string;
|
|
40
|
-
}
|
|
41
|
-
export interface ResolvedNamespace {
|
|
42
|
-
name: string;
|
|
43
|
-
format: string;
|
|
44
|
-
readonly file: (locale: string) => string;
|
|
45
|
-
}
|
|
46
|
-
export interface ResolvedConfig {
|
|
47
|
-
root: string;
|
|
48
|
-
configFile: string;
|
|
49
|
-
locales: Array<string>;
|
|
50
|
-
sourceLocale: string;
|
|
51
|
-
fallbacks: Record<string, Array<string>>;
|
|
52
|
-
outDir: string;
|
|
53
|
-
namespaces: Array<ResolvedNamespace>;
|
|
54
|
-
/** Module the generated types import and augment. */
|
|
55
|
-
runtime: string;
|
|
56
|
-
functions: Record<string, FunctionKind>;
|
|
57
|
-
markup: Array<string>;
|
|
58
|
-
/** `icu`, `mf2` and the config's own `formats`. */
|
|
59
|
-
formats: Record<string, FormatAdapter>;
|
|
60
|
-
/** Every file whose change should trigger a rebuild. */
|
|
61
|
-
watchFiles: Array<string>;
|
|
62
|
-
/** Folders that hold catalogs, which a config may list from disk. */
|
|
63
|
-
watchFolders: Array<string>;
|
|
64
|
-
/** Whether a change to `file` should trigger a rebuild. */
|
|
65
|
-
readonly watches: (file: string) => boolean;
|
|
66
|
-
}
|
|
67
|
-
export declare class ConfigError extends Error {
|
|
68
|
-
name: string;
|
|
69
|
-
}
|
|
70
|
-
/** Types a `parla.config.ts`: `export default defineConfig({ … })`. */
|
|
71
|
-
export declare function defineConfig(config: ParlaConfig): ParlaConfig;
|
|
72
|
-
export declare function loadConfig(cwd: string, configFile?: string): Promise<ResolvedConfig>;
|
|
73
|
-
/** The locales listed for `locale`, then its parents: `zh-Hant-TW` → `zh-Hant`, `zh`. */
|
|
74
|
-
export declare function parents(config: ResolvedConfig, locale: string): Array<string>;
|
|
75
|
-
/** Locales to try, in order, when `locale` lacks a key. */
|
|
76
|
-
export declare function fallbackChain(config: ResolvedConfig, locale: string): Array<string>;
|
|
77
|
-
//# sourceMappingURL=config.d.ts.map
|
package/build/config.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAG3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,4EAA4E;AAC5E,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,KAAK,CAAC,OAAO,CAAC;IAClD,yFAAyF;IACzF,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,SAAS,CAAC;CAC9D;AAED,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAgB,CAAC;AAEpF,MAAM,WAAW,eAAe;IAC9B,0DAA0D;IAC1D,MAAM,EAAE,MAAM,CAAC;IACf,oEAAoE;IACpE,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1C,6EAA6E;IAC7E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC7C;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACzC,6EAA6E;IAC7E,MAAM,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,yFAAyF;IACzF,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC;CAC3C;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACrC,qDAAqD;IACrD,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACxC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACtB,mDAAmD;IACnD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACvC,wDAAwD;IACxD,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1B,qEAAqE;IACrE,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5B,2DAA2D;IAC3D,QAAQ,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAC7C;AAED,qBAAa,WAAY,SAAQ,KAAK;IAC3B,IAAI,SAAiB;CAC/B;AAUD,uEAAuE;AACvE,wBAAgB,YAAY,CAAC,MAAM,EAAE,WAAW,GAAG,WAAW,CAE7D;AAwID,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CA6F1F;AAED,yFAAyF;AACzF,wBAAgB,OAAO,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAO7E;AAED,2DAA2D;AAC3D,wBAAgB,aAAa,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAInF"}
|
package/build/config.js
DELETED
|
@@ -1,223 +0,0 @@
|
|
|
1
|
-
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
-
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
-
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
-
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
-
});
|
|
6
|
-
}
|
|
7
|
-
return path;
|
|
8
|
-
};
|
|
9
|
-
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
10
|
-
import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
11
|
-
import { pathToFileURL } from 'node:url';
|
|
12
|
-
import { icu } from '@parlajs/format-icu';
|
|
13
|
-
import { mf2 } from '@parlajs/format-mf2';
|
|
14
|
-
import { BUILTIN_FUNCTIONS } from './compile.js';
|
|
15
|
-
export const defaultFormats = { icu, mf2 };
|
|
16
|
-
export class ConfigError extends Error {
|
|
17
|
-
name = 'ConfigError';
|
|
18
|
-
}
|
|
19
|
-
const CONFIG_FILE = 'parla.config.ts';
|
|
20
|
-
/** Types a `parla.config.ts`: `export default defineConfig({ … })`. */
|
|
21
|
-
export function defineConfig(config) {
|
|
22
|
-
return config;
|
|
23
|
-
}
|
|
24
|
-
/** The last load of each config file, for watchers. */
|
|
25
|
-
const loads = new Map();
|
|
26
|
-
/** The load to come, before the import: a file added meanwhile counts at the next one. */
|
|
27
|
-
function nextLoad(file) {
|
|
28
|
-
const last = loads.get(file);
|
|
29
|
-
if (!last) {
|
|
30
|
-
return undefined;
|
|
31
|
-
}
|
|
32
|
-
const names = new Map([...last.names.keys()].map((dir) => [dir, last.list(dir)]));
|
|
33
|
-
const same = [...names].every(([dir, list]) => list === last.names.get(dir));
|
|
34
|
-
const next = { ...last, names, version: last.version + (same ? 0 : 1) };
|
|
35
|
-
loads.set(file, next);
|
|
36
|
-
return next;
|
|
37
|
-
}
|
|
38
|
-
async function importConfig(file, version) {
|
|
39
|
-
// Both bust Node's module cache, so a watcher sees an edited config, or one that lists new catalogs.
|
|
40
|
-
const { mtimeNs } = statSync(file, { bigint: true });
|
|
41
|
-
const url = `${pathToFileURL(file).href}?t=${mtimeNs}&v=${version}`;
|
|
42
|
-
let mod;
|
|
43
|
-
try {
|
|
44
|
-
mod = await import(__rewriteRelativeImportExtension(url));
|
|
45
|
-
}
|
|
46
|
-
catch (error) {
|
|
47
|
-
const { message, stack = '' } = error;
|
|
48
|
-
// Only the stack tells where, a syntax error's included.
|
|
49
|
-
const [position = ''] = /^(?::\d+)+/.exec(stack.split(url)[1] ?? '') ?? [];
|
|
50
|
-
throw new ConfigError(`Cannot load ${file}${position}: ${message}`);
|
|
51
|
-
}
|
|
52
|
-
const config = mod.default;
|
|
53
|
-
if (typeof config !== 'object' || config === null) {
|
|
54
|
-
throw new ConfigError(`${file} must \`export default defineConfig({ … })\``);
|
|
55
|
-
}
|
|
56
|
-
return config;
|
|
57
|
-
}
|
|
58
|
-
function readPackageJson(dir) {
|
|
59
|
-
const file = join(dir, 'package.json');
|
|
60
|
-
return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : undefined;
|
|
61
|
-
}
|
|
62
|
-
// The adapters first: an app on one may list core too.
|
|
63
|
-
const RUNTIMES = [
|
|
64
|
-
'@parlajs/react',
|
|
65
|
-
'@parlajs/solid',
|
|
66
|
-
'@parlajs/svelte',
|
|
67
|
-
'@parlajs/vue',
|
|
68
|
-
'@parlajs/core',
|
|
69
|
-
];
|
|
70
|
-
function detectRuntime(dir) {
|
|
71
|
-
const pkg = readPackageJson(dir);
|
|
72
|
-
const deps = { ...pkg?.peerDependencies, ...pkg?.devDependencies, ...pkg?.dependencies };
|
|
73
|
-
return RUNTIMES.find((name) => name in deps) ?? '@parlajs/core';
|
|
74
|
-
}
|
|
75
|
-
function checkFunctions(functions) {
|
|
76
|
-
const shadowing = Object.keys(functions).filter((name) => BUILTIN_FUNCTIONS.has(name));
|
|
77
|
-
if (shadowing.length > 0) {
|
|
78
|
-
throw new ConfigError(`"functions" cannot redefine the built-in ${shadowing.map((n) => `:${n}`).join(', ')}`);
|
|
79
|
-
}
|
|
80
|
-
return functions;
|
|
81
|
-
}
|
|
82
|
-
/** Names that become path segments under `outDir`: no separators, no `..`. */
|
|
83
|
-
const NAMESPACE_NAME = /^[\w-]+(?:\.[\w-]+)*$/;
|
|
84
|
-
/** A tag `Intl` takes, such as `zh-Hant-TW`: any other would throw at the first plural or number. */
|
|
85
|
-
function checkLocale(locale) {
|
|
86
|
-
try {
|
|
87
|
-
Intl.getCanonicalLocales(locale);
|
|
88
|
-
}
|
|
89
|
-
catch {
|
|
90
|
-
const tag = locale.replaceAll('_', '-');
|
|
91
|
-
const hint = tag === locale ? ' such as "en" or "pt-BR"' : `: write "${tag}"`;
|
|
92
|
-
throw new ConfigError(`Locale "${locale}" is not a locale tag${hint}`);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
function isInside(dir, file) {
|
|
96
|
-
const path = relative(dir, file);
|
|
97
|
-
return path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path);
|
|
98
|
-
}
|
|
99
|
-
/** Names of files: on macOS and Windows one would overwrite the other. */
|
|
100
|
-
function checkCase(what, names) {
|
|
101
|
-
const seen = new Map();
|
|
102
|
-
for (const name of names) {
|
|
103
|
-
const other = seen.get(name.toLowerCase()) ?? name;
|
|
104
|
-
if (other !== name) {
|
|
105
|
-
throw new ConfigError(`${what} "${other}" and "${name}" differ only in case: rename one`);
|
|
106
|
-
}
|
|
107
|
-
seen.set(name.toLowerCase(), name);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
/** A fallback outside `locales` lends no text, only its `Intl` formats. */
|
|
111
|
-
function checkFallbacks(fallbacks, { locales, hasCatalog, }) {
|
|
112
|
-
for (const [locale, chain] of Object.entries(fallbacks)) {
|
|
113
|
-
if (!locales.includes(locale)) {
|
|
114
|
-
throw new ConfigError(`"fallbacks" lists "${locale}", which is not in locales`);
|
|
115
|
-
}
|
|
116
|
-
for (const fallback of chain.filter((l) => !locales.includes(l))) {
|
|
117
|
-
if (hasCatalog(fallback)) {
|
|
118
|
-
throw new ConfigError(`"${locale}" falls back to "${fallback}", whose catalogs are not read: add it to locales`);
|
|
119
|
-
}
|
|
120
|
-
if (Intl.NumberFormat.supportedLocalesOf(fallback).length === 0) {
|
|
121
|
-
throw new ConfigError(`"${locale}" falls back to "${fallback}", neither in locales nor known to Intl`);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
export async function loadConfig(cwd, configFile) {
|
|
127
|
-
const file = resolve(cwd, configFile ?? CONFIG_FILE);
|
|
128
|
-
if (!configFile && !existsSync(file)) {
|
|
129
|
-
throw new ConfigError(`No ${CONFIG_FILE} in ${cwd}`);
|
|
130
|
-
}
|
|
131
|
-
const load = nextLoad(file);
|
|
132
|
-
const config = await importConfig(file, load?.version ?? 0);
|
|
133
|
-
const root = dirname(file);
|
|
134
|
-
const sourceLocale = config.sourceLocale ?? 'en';
|
|
135
|
-
const locales = config.locales ?? [sourceLocale];
|
|
136
|
-
const fallbacks = config.fallbacks ?? {};
|
|
137
|
-
for (const locale of [
|
|
138
|
-
...locales,
|
|
139
|
-
...Object.keys(fallbacks),
|
|
140
|
-
...Object.values(fallbacks).flat(),
|
|
141
|
-
]) {
|
|
142
|
-
checkLocale(locale);
|
|
143
|
-
}
|
|
144
|
-
checkCase('Locales', locales);
|
|
145
|
-
const repeated = locales.find((l, i) => locales.indexOf(l) !== i);
|
|
146
|
-
if (repeated !== undefined) {
|
|
147
|
-
throw new ConfigError(`Locale "${repeated}" is listed twice`);
|
|
148
|
-
}
|
|
149
|
-
if (!locales.includes(sourceLocale)) {
|
|
150
|
-
throw new ConfigError(`sourceLocale "${sourceLocale}" is not in locales`);
|
|
151
|
-
}
|
|
152
|
-
checkCase('Namespaces', Object.keys(config.namespaces ?? {}));
|
|
153
|
-
const outDir = resolve(root, config.outDir ?? 'src/parla');
|
|
154
|
-
const namespaces = [];
|
|
155
|
-
const catalogs = [];
|
|
156
|
-
for (const [name, ns] of Object.entries(config.namespaces ?? {})) {
|
|
157
|
-
if (!NAMESPACE_NAME.test(name)) {
|
|
158
|
-
throw new ConfigError(`Namespace "${name}" must be letters, digits, "_", "-" or inner dots: it names files`);
|
|
159
|
-
}
|
|
160
|
-
if (!ns.path.includes('{locale}')) {
|
|
161
|
-
throw new ConfigError(`Namespace "${name}" path must contain {locale}`);
|
|
162
|
-
}
|
|
163
|
-
const resolved = {
|
|
164
|
-
name,
|
|
165
|
-
format: ns.format,
|
|
166
|
-
file: (locale) => resolve(root, ns.path.replaceAll('{locale}', locale)),
|
|
167
|
-
};
|
|
168
|
-
const files = locales.map((l) => resolved.file(l));
|
|
169
|
-
if (files.some((f) => isInside(outDir, f))) {
|
|
170
|
-
throw new ConfigError(`Namespace "${name}" has its catalogs in outDir, which holds generated files only: move one of them`);
|
|
171
|
-
}
|
|
172
|
-
namespaces.push(resolved);
|
|
173
|
-
catalogs.push(...files);
|
|
174
|
-
}
|
|
175
|
-
checkFallbacks(fallbacks, {
|
|
176
|
-
locales,
|
|
177
|
-
hasCatalog: (locale) => namespaces.some((ns) => existsSync(ns.file(locale))),
|
|
178
|
-
});
|
|
179
|
-
const watchFiles = [file, ...catalogs];
|
|
180
|
-
const extensions = new Set(catalogs.map((f) => extname(f)));
|
|
181
|
-
const folders = new Set(catalogs.map((f) => dirname(f)));
|
|
182
|
-
const isCatalog = (f) => extensions.has(extname(f));
|
|
183
|
-
const list = (dir) => existsSync(dir)
|
|
184
|
-
? readdirSync(dir)
|
|
185
|
-
.filter((f) => isCatalog(f))
|
|
186
|
-
.toSorted()
|
|
187
|
-
.join('/')
|
|
188
|
-
: '';
|
|
189
|
-
loads.set(file, {
|
|
190
|
-
version: load?.version ?? 0,
|
|
191
|
-
names: new Map([...folders].map((dir) => [dir, load?.names.get(dir) ?? list(dir)])),
|
|
192
|
-
list,
|
|
193
|
-
});
|
|
194
|
-
return {
|
|
195
|
-
root,
|
|
196
|
-
configFile: file,
|
|
197
|
-
locales,
|
|
198
|
-
sourceLocale,
|
|
199
|
-
fallbacks,
|
|
200
|
-
outDir,
|
|
201
|
-
runtime: config.runtime ?? detectRuntime(root),
|
|
202
|
-
functions: checkFunctions(config.functions ?? {}),
|
|
203
|
-
markup: config.markup ?? [],
|
|
204
|
-
formats: { ...defaultFormats, ...config.formats },
|
|
205
|
-
namespaces,
|
|
206
|
-
watchFiles,
|
|
207
|
-
watchFolders: [...folders],
|
|
208
|
-
watches: (f) => watchFiles.includes(f) || (folders.has(dirname(f)) && isCatalog(f)),
|
|
209
|
-
};
|
|
210
|
-
}
|
|
211
|
-
/** The locales listed for `locale`, then its parents: `zh-Hant-TW` → `zh-Hant`, `zh`. */
|
|
212
|
-
export function parents(config, locale) {
|
|
213
|
-
const subtags = locale.split('-');
|
|
214
|
-
const bases = subtags.map((_, i) => subtags.slice(0, -1 - i).join('-'));
|
|
215
|
-
return [
|
|
216
|
-
...(config.fallbacks[locale] ?? []),
|
|
217
|
-
...bases.filter((base) => config.locales.includes(base)),
|
|
218
|
-
];
|
|
219
|
-
}
|
|
220
|
-
/** Locales to try, in order, when `locale` lacks a key. */
|
|
221
|
-
export function fallbackChain(config, locale) {
|
|
222
|
-
return [...new Set([...parents(config, locale), config.sourceLocale])].filter((l) => l !== locale);
|
|
223
|
-
}
|
package/build/options.d.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import type { Model } from 'messageformat';
|
|
2
|
-
type Value = Model.Literal | Model.VariableRef;
|
|
3
|
-
type Options = Record<string, Value>;
|
|
4
|
-
/** Which of a variable's options a function applied to it takes over. */
|
|
5
|
-
export declare function inheritedOptions(from: Model.FunctionRef, to: string): Options;
|
|
6
|
-
/** A built-in function's options as `Intl` takes them; throws for one it cannot honour. */
|
|
7
|
-
export declare function intlOptions({ name, options }: Model.FunctionRef): Options;
|
|
8
|
-
export {};
|
|
9
|
-
//# sourceMappingURL=options.d.ts.map
|
package/build/options.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAE3C,KAAK,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,WAAW,CAAC;AAC/C,KAAK,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AA+LrC,yEAAyE;AACzE,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,KAAK,CAAC,WAAW,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAiB7E;AAED,2FAA2F;AAC3F,wBAAgB,WAAW,CAAC,EAAE,IAAI,EAAE,OAAY,EAAE,EAAE,KAAK,CAAC,WAAW,GAAG,OAAO,CAmB9E"}
|
package/build/options.js
DELETED
|
@@ -1,214 +0,0 @@
|
|
|
1
|
-
const DIGITS = [
|
|
2
|
-
'minimumIntegerDigits',
|
|
3
|
-
'minimumSignificantDigits',
|
|
4
|
-
'maximumSignificantDigits',
|
|
5
|
-
'roundingIncrement',
|
|
6
|
-
'roundingMode',
|
|
7
|
-
'roundingPriority',
|
|
8
|
-
'trailingZeroDisplay',
|
|
9
|
-
];
|
|
10
|
-
const COMMON = ['signDisplay', 'useGrouping', 'numberingSystem', 'select', 'offset', 'scale'];
|
|
11
|
-
const FRACTION = ['minimumFractionDigits', 'maximumFractionDigits'];
|
|
12
|
-
const COMPACT = ['notation', 'compactDisplay'];
|
|
13
|
-
const FORMAT = [...COMMON, ...DIGITS, ...FRACTION, ...COMPACT];
|
|
14
|
-
const SETTINGS = ['calendar', 'numberingSystem', 'timeZone', 'hour12', 'hourCycle'];
|
|
15
|
-
const FIELDS = [
|
|
16
|
-
'weekday',
|
|
17
|
-
'era',
|
|
18
|
-
'year',
|
|
19
|
-
'month',
|
|
20
|
-
'day',
|
|
21
|
-
'dayPeriod',
|
|
22
|
-
'hour',
|
|
23
|
-
'minute',
|
|
24
|
-
'second',
|
|
25
|
-
'fractionalSecondDigits',
|
|
26
|
-
'timeZoneName',
|
|
27
|
-
];
|
|
28
|
-
const NUMBERS = {
|
|
29
|
-
number: new Set([...FORMAT, 'style']),
|
|
30
|
-
integer: new Set([...COMMON, 'minimumIntegerDigits', 'maximumSignificantDigits', ...COMPACT]),
|
|
31
|
-
currency: new Set([
|
|
32
|
-
...FORMAT,
|
|
33
|
-
'fractionDigits',
|
|
34
|
-
'currency',
|
|
35
|
-
'currencyDisplay',
|
|
36
|
-
'currencySign',
|
|
37
|
-
'unitDisplay',
|
|
38
|
-
]),
|
|
39
|
-
percent: new Set([...FORMAT, 'currencySign']),
|
|
40
|
-
unit: new Set([...FORMAT, 'unit', 'unitDisplay', 'currencyDisplay']),
|
|
41
|
-
};
|
|
42
|
-
const DATES = {
|
|
43
|
-
date: new Set([...SETTINGS, ...FIELDS, 'style', 'length', 'fields']),
|
|
44
|
-
time: new Set([...SETTINGS, ...FIELDS, 'style', 'length', 'precision', 'timeZoneStyle']),
|
|
45
|
-
datetime: new Set([
|
|
46
|
-
...SETTINGS,
|
|
47
|
-
...FIELDS,
|
|
48
|
-
'style',
|
|
49
|
-
'dateStyle',
|
|
50
|
-
'timeStyle',
|
|
51
|
-
'dateFields',
|
|
52
|
-
'dateLength',
|
|
53
|
-
'timePrecision',
|
|
54
|
-
'timeZoneStyle',
|
|
55
|
-
]),
|
|
56
|
-
};
|
|
57
|
-
const DATE_FIELDS = new Set([
|
|
58
|
-
'weekday',
|
|
59
|
-
'day-weekday',
|
|
60
|
-
'month-day',
|
|
61
|
-
'month-day-weekday',
|
|
62
|
-
'year-month-day',
|
|
63
|
-
'year-month-day-weekday',
|
|
64
|
-
]);
|
|
65
|
-
const LENGTHS = new Set(['long', 'medium', 'short']);
|
|
66
|
-
const PRECISIONS = ['hour', 'minute', 'second'];
|
|
67
|
-
const SELECTS = new Set(['plural', 'cardinal', 'ordinal', 'exact']);
|
|
68
|
-
const literal = (value) => ({ type: 'literal', value });
|
|
69
|
-
/** A literal's value, which must be one of `allowed`; a variable cannot name fields at build time. */
|
|
70
|
-
function chosen(name, value, allowed) {
|
|
71
|
-
if (value.type !== 'literal') {
|
|
72
|
-
throw new Error(`${name} must be a literal`);
|
|
73
|
-
}
|
|
74
|
-
if (!allowed.has(value.value)) {
|
|
75
|
-
throw new Error(`${name} must be one of ${[...allowed].join(', ')}, not "${value.value}"`);
|
|
76
|
-
}
|
|
77
|
-
return value.value;
|
|
78
|
-
}
|
|
79
|
-
function numberOptions(options) {
|
|
80
|
-
const { fractionDigits, ...out } = options;
|
|
81
|
-
if (fractionDigits && !(fractionDigits.type === 'literal' && fractionDigits.value === 'auto')) {
|
|
82
|
-
out['minimumFractionDigits'] = fractionDigits;
|
|
83
|
-
out['maximumFractionDigits'] = fractionDigits;
|
|
84
|
-
}
|
|
85
|
-
const { select, useGrouping } = out;
|
|
86
|
-
if (select?.type === 'literal') {
|
|
87
|
-
chosen('select', select, SELECTS);
|
|
88
|
-
}
|
|
89
|
-
if (useGrouping?.type === 'literal' && useGrouping.value === 'never') {
|
|
90
|
-
out['useGrouping'] = literal('false');
|
|
91
|
-
}
|
|
92
|
-
return out;
|
|
93
|
-
}
|
|
94
|
-
/** MF2's fields, length and precision, as `Intl`'s fields. */
|
|
95
|
-
function semanticFields(name, options) {
|
|
96
|
-
const { fields, dateFields, length, dateLength, precision, timePrecision, timeZoneStyle } = options;
|
|
97
|
-
const out = {};
|
|
98
|
-
if (name !== 'time') {
|
|
99
|
-
const size = length ?? dateLength;
|
|
100
|
-
const isLong = size ? chosen('length', size, LENGTHS) : 'medium';
|
|
101
|
-
const asked = fields ?? dateFields;
|
|
102
|
-
const set = asked ? chosen('fields', asked, DATE_FIELDS) : 'year-month-day';
|
|
103
|
-
const months = { long: 'long', medium: 'short', short: 'numeric' };
|
|
104
|
-
for (const field of set.split('-')) {
|
|
105
|
-
let value = 'numeric';
|
|
106
|
-
if (field === 'month') {
|
|
107
|
-
value = months[isLong] ?? value;
|
|
108
|
-
}
|
|
109
|
-
else if (field === 'weekday') {
|
|
110
|
-
value = isLong === 'long' ? 'long' : 'short';
|
|
111
|
-
}
|
|
112
|
-
out[field] = literal(value);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
if (name !== 'date') {
|
|
116
|
-
const asked = precision ?? timePrecision;
|
|
117
|
-
const until = asked ? chosen('precision', asked, new Set(PRECISIONS)) : 'minute';
|
|
118
|
-
for (const field of PRECISIONS.slice(0, PRECISIONS.indexOf(until) + 1)) {
|
|
119
|
-
out[field] = literal('numeric');
|
|
120
|
-
}
|
|
121
|
-
if (timeZoneStyle) {
|
|
122
|
-
out['timeZoneName'] = timeZoneStyle;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
return out;
|
|
126
|
-
}
|
|
127
|
-
const SEMANTIC = ['fields', 'dateFields', 'precision', 'timePrecision', 'timeZoneStyle'];
|
|
128
|
-
function dateOptions(name, options) {
|
|
129
|
-
const out = Object.fromEntries(Object.entries(options).filter(([k]) => SETTINGS.includes(k) || FIELDS.includes(k)));
|
|
130
|
-
if (SEMANTIC.some((k) => options[k])) {
|
|
131
|
-
return { ...out, ...semanticFields(name, options) };
|
|
132
|
-
}
|
|
133
|
-
const { style, length, dateLength, dateStyle, timeStyle } = options;
|
|
134
|
-
if (style || length || dateLength || dateStyle || timeStyle) {
|
|
135
|
-
const size = style ?? length;
|
|
136
|
-
if (name === 'time') {
|
|
137
|
-
return { ...out, timeStyle: size ?? literal('short') };
|
|
138
|
-
}
|
|
139
|
-
out['dateStyle'] = dateStyle ?? dateLength ?? size ?? literal('medium');
|
|
140
|
-
return name === 'date' ? out : { ...out, timeStyle: timeStyle ?? literal('short') };
|
|
141
|
-
}
|
|
142
|
-
if (FIELDS.some((k) => options[k])) {
|
|
143
|
-
return out;
|
|
144
|
-
}
|
|
145
|
-
// Settings alone: the runtime adds the default style only to a call without options.
|
|
146
|
-
return {
|
|
147
|
-
...out,
|
|
148
|
-
...(name === 'time' ? {} : { dateStyle: literal('medium') }),
|
|
149
|
-
...(name === 'date' ? {} : { timeStyle: literal('short') }),
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
// An `Intl` object per message made a build 7 times slower.
|
|
153
|
-
const checked = new Set();
|
|
154
|
-
/** Throws what `Intl` would at run time, where every option is a literal. */
|
|
155
|
-
function check(name, options) {
|
|
156
|
-
const key = name + JSON.stringify(options);
|
|
157
|
-
if (checked.has(key)) {
|
|
158
|
-
return;
|
|
159
|
-
}
|
|
160
|
-
const given = {};
|
|
161
|
-
for (const [k, v] of Object.entries(options)) {
|
|
162
|
-
if (v.type !== 'literal') {
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
given[k] = v.value === 'false' || v.value === 'true' ? v.value === 'true' : v.value;
|
|
166
|
-
}
|
|
167
|
-
if (Object.hasOwn(NUMBERS, name)) {
|
|
168
|
-
const style = name === 'number' || name === 'integer' ? {} : { style: name };
|
|
169
|
-
// oxlint-disable-next-line no-new -- only its errors matter
|
|
170
|
-
new Intl.NumberFormat('en', { ...given, ...style });
|
|
171
|
-
}
|
|
172
|
-
else {
|
|
173
|
-
// oxlint-disable-next-line no-new -- only its errors matter
|
|
174
|
-
new Intl.DateTimeFormat('en', given);
|
|
175
|
-
}
|
|
176
|
-
checked.add(key);
|
|
177
|
-
}
|
|
178
|
-
/** Which of a variable's options a function applied to it takes over. */
|
|
179
|
-
export function inheritedOptions(from, to) {
|
|
180
|
-
const own = NUMBERS[to];
|
|
181
|
-
const entries = Object.entries(from.options ?? {});
|
|
182
|
-
if (own && Object.hasOwn(NUMBERS, from.name)) {
|
|
183
|
-
// `offset` is a plural's: only its own `#` subtracts it.
|
|
184
|
-
return Object.fromEntries(entries.filter(([k]) => own.has(k) && k !== 'style' && k !== 'offset'));
|
|
185
|
-
}
|
|
186
|
-
if (from.name === to) {
|
|
187
|
-
return Object.fromEntries(entries);
|
|
188
|
-
}
|
|
189
|
-
return Object.hasOwn(DATES, to) && Object.hasOwn(DATES, from.name)
|
|
190
|
-
? Object.fromEntries(entries.filter(([k]) => k === 'calendar' || k === 'timeZone' || k === 'hour12'))
|
|
191
|
-
: {};
|
|
192
|
-
}
|
|
193
|
-
/** A built-in function's options as `Intl` takes them; throws for one it cannot honour. */
|
|
194
|
-
export function intlOptions({ name, options = {} }) {
|
|
195
|
-
const known = NUMBERS[name] ?? DATES[name] ?? new Set();
|
|
196
|
-
const entries = Object.entries(options).filter(([k]) => k !== 'u:id');
|
|
197
|
-
for (const [key] of entries) {
|
|
198
|
-
if (!known.has(key)) {
|
|
199
|
-
throw new Error(`:${name} has no option "${key}"`);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
if (entries.length === 0 && name !== 'currency' && name !== 'unit') {
|
|
203
|
-
return {};
|
|
204
|
-
}
|
|
205
|
-
const given = Object.fromEntries(entries);
|
|
206
|
-
try {
|
|
207
|
-
const out = Object.hasOwn(NUMBERS, name) ? numberOptions(given) : dateOptions(name, given);
|
|
208
|
-
check(name, out);
|
|
209
|
-
return out;
|
|
210
|
-
}
|
|
211
|
-
catch (error) {
|
|
212
|
-
throw new Error(`:${name}: ${error.message}`, { cause: error });
|
|
213
|
-
}
|
|
214
|
-
}
|
package/build/types.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type { MessageInfo, ParamKind } from './compile.ts';
|
|
2
|
-
/**
|
|
3
|
-
* Each namespace's export: the name itself where it is an identifier, to match `t`'s key; else one
|
|
4
|
-
* derived from its interface (`foo-bar` → `fooBar`), numbered around the names already taken.
|
|
5
|
-
*/
|
|
6
|
-
export declare function exportNames(ifaces: ReadonlyMap<string, string>): Map<string, string>;
|
|
7
|
-
/** {@link interfaceName} per namespace, numbered where two collide (`foo-bar`, `foo_bar`). */
|
|
8
|
-
export declare function interfaceNames(namespaces: ReadonlyArray<string>): Map<string, string>;
|
|
9
|
-
/** Collapses every use of one parameter into a single TS type. */
|
|
10
|
-
export declare function paramType(kinds: ReadonlyArray<ParamKind>): string;
|
|
11
|
-
/** `defaults`: markup the runtime renders when a call leaves it out (the config's `markup`). */
|
|
12
|
-
export declare function signature(info: MessageInfo, defaults?: ReadonlySet<string>): string;
|
|
13
|
-
export interface NamespaceTypes {
|
|
14
|
-
/** The interfaces, without imports. */
|
|
15
|
-
readonly code: string;
|
|
16
|
-
/** Whether the namespace's interface takes `Node`: only markup needs it. */
|
|
17
|
-
readonly generic: boolean;
|
|
18
|
-
/** Whether `code` names `Text`. */
|
|
19
|
-
readonly usesText: boolean;
|
|
20
|
-
}
|
|
21
|
-
export declare function namespaceTypes(messages: Map<string, {
|
|
22
|
-
info: MessageInfo;
|
|
23
|
-
source: string;
|
|
24
|
-
}>, name: string, defaults: ReadonlySet<string>): NamespaceTypes;
|
|
25
|
-
//# sourceMappingURL=types.d.ts.map
|
package/build/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAyB3D;;;GAGG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAkBpF;AAED,8FAA8F;AAC9F,wBAAgB,cAAc,CAAC,UAAU,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAcrF;AAED,kEAAkE;AAClE,wBAAgB,SAAS,CAAC,KAAK,EAAE,aAAa,CAAC,SAAS,CAAC,GAAG,MAAM,CAsBjE;AAmDD,gGAAgG;AAChG,wBAAgB,SAAS,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,GAAE,WAAW,CAAC,MAAM,CAAa,GAAG,MAAM,CAwB9F;AAuCD,MAAM,WAAW,cAAc;IAC7B,uCAAuC;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4EAA4E;IAC5E,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,mCAAmC;IACnC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B;AAwED,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,EAC5D,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,GAC5B,cAAc,CAyBhB"}
|
package/build/types.js
DELETED
|
@@ -1,250 +0,0 @@
|
|
|
1
|
-
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
2
|
-
const prop = (name) => (IDENT.test(name) ? name : JSON.stringify(name));
|
|
3
|
-
function interfaceName(namespace) {
|
|
4
|
-
const pascal = namespace
|
|
5
|
-
.split(/[^A-Za-z0-9]+/)
|
|
6
|
-
.filter(Boolean)
|
|
7
|
-
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
8
|
-
.join('');
|
|
9
|
-
// `_` keeps a name like `-` from becoming `Messages`, whose plain part would shadow `Text`
|
|
10
|
-
return `${/^(?:\d|$)/.test(pascal) ? '_' : ''}${pascal}Messages`;
|
|
11
|
-
}
|
|
12
|
-
// Not valid as a `const` name in a module, or a built-in TypeScript rejects as one.
|
|
13
|
-
const RESERVED = new Set('arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function globalThis if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof undefined var void while with yield'.split(' '));
|
|
14
|
-
const isOwnName = (ns) => IDENT.test(ns) && !RESERVED.has(ns);
|
|
15
|
-
/**
|
|
16
|
-
* Each namespace's export: the name itself where it is an identifier, to match `t`'s key; else one
|
|
17
|
-
* derived from its interface (`foo-bar` → `fooBar`), numbered around the names already taken.
|
|
18
|
-
*/
|
|
19
|
-
export function exportNames(ifaces) {
|
|
20
|
-
const names = new Map();
|
|
21
|
-
for (const ns of [...ifaces.keys()].filter((n) => isOwnName(n))) {
|
|
22
|
-
names.set(ns, ns);
|
|
23
|
-
}
|
|
24
|
-
const used = new Set(names.values());
|
|
25
|
-
for (const [ns, iface] of [...ifaces].filter(([n]) => !isOwnName(n))) {
|
|
26
|
-
const base = iface.replace(/Messages$/, '');
|
|
27
|
-
const camel = base.charAt(0).toLowerCase() + base.slice(1);
|
|
28
|
-
const derived = RESERVED.has(camel) ? `_${camel}` : camel;
|
|
29
|
-
let name = derived;
|
|
30
|
-
for (let n = 2; used.has(name); n += 1) {
|
|
31
|
-
name = `${derived}${n}`;
|
|
32
|
-
}
|
|
33
|
-
used.add(name);
|
|
34
|
-
names.set(ns, name);
|
|
35
|
-
}
|
|
36
|
-
return names;
|
|
37
|
-
}
|
|
38
|
-
/** {@link interfaceName} per namespace, numbered where two collide (`foo-bar`, `foo_bar`). */
|
|
39
|
-
export function interfaceNames(namespaces) {
|
|
40
|
-
const names = new Map();
|
|
41
|
-
// its kind would shadow the imported `NamespaceKind`
|
|
42
|
-
const used = new Set(['NamespaceMessages']);
|
|
43
|
-
for (const namespace of namespaces) {
|
|
44
|
-
const base = interfaceName(namespace);
|
|
45
|
-
let name = base;
|
|
46
|
-
for (let n = 2; used.has(name); n += 1) {
|
|
47
|
-
name = base.replace(/Messages$/, `${n}Messages`);
|
|
48
|
-
}
|
|
49
|
-
used.add(name);
|
|
50
|
-
names.set(namespace, name);
|
|
51
|
-
}
|
|
52
|
-
return names;
|
|
53
|
-
}
|
|
54
|
-
/** Collapses every use of one parameter into a single TS type. */
|
|
55
|
-
export function paramType(kinds) {
|
|
56
|
-
if (kinds.some((k) => k.kind === 'number')) {
|
|
57
|
-
return 'number';
|
|
58
|
-
}
|
|
59
|
-
if (kinds.some((k) => k.kind === 'date')) {
|
|
60
|
-
return 'Date | number';
|
|
61
|
-
}
|
|
62
|
-
const selects = kinds.filter((k) => k.kind === 'select');
|
|
63
|
-
if (selects.length > 0) {
|
|
64
|
-
// sorted: a translation may list the variants in another order
|
|
65
|
-
const keys = [...new Set(selects.flatMap((s) => s.keys))]
|
|
66
|
-
.toSorted()
|
|
67
|
-
.map((k) => JSON.stringify(k));
|
|
68
|
-
if (selects.some((s) => s.open)) {
|
|
69
|
-
keys.push('(string & {})');
|
|
70
|
-
}
|
|
71
|
-
return keys.join(' | ') || 'string';
|
|
72
|
-
}
|
|
73
|
-
if (kinds.some((k) => k.kind === 'string')) {
|
|
74
|
-
return 'string';
|
|
75
|
-
}
|
|
76
|
-
return 'string | number';
|
|
77
|
-
}
|
|
78
|
-
/** A select param's listed keys as a type, `undefined` unless it also takes any other string. */
|
|
79
|
-
function listedKeys(kinds) {
|
|
80
|
-
const selects = kinds.filter((k) => k.kind === 'select');
|
|
81
|
-
if (selects.every((s) => !s.open) ||
|
|
82
|
-
kinds.some((k) => k.kind === 'number' || k.kind === 'date')) {
|
|
83
|
-
return undefined;
|
|
84
|
-
}
|
|
85
|
-
const keys = new Set(selects.flatMap((s) => s.keys));
|
|
86
|
-
return keys.size > 0
|
|
87
|
-
? [...keys.add('other')]
|
|
88
|
-
.toSorted()
|
|
89
|
-
.map((k) => JSON.stringify(k))
|
|
90
|
-
.join(' | ')
|
|
91
|
-
: undefined;
|
|
92
|
-
}
|
|
93
|
-
/** One params object: `names` typed by their uses, `selected` overriding a selector's type. */
|
|
94
|
-
function fields(info, names, defaults, selected) {
|
|
95
|
-
const out = [...names]
|
|
96
|
-
.toSorted((a, b) => a.localeCompare(b))
|
|
97
|
-
.map((name) => {
|
|
98
|
-
const kinds = info.params.get(name) ?? [];
|
|
99
|
-
const keys = listedKeys(kinds);
|
|
100
|
-
const open = keys === undefined ? paramType(kinds) : `${keys} | Other<G>`;
|
|
101
|
-
const type = name === selected?.[0] ? selected[1] : open;
|
|
102
|
-
return `${prop(name)}: ${type}`;
|
|
103
|
-
});
|
|
104
|
-
let required = out.length;
|
|
105
|
-
for (const tag of [...info.markup].toSorted()) {
|
|
106
|
-
if (!info.params.has(tag)) {
|
|
107
|
-
const optional = defaults.has(tag);
|
|
108
|
-
out.push(`${prop(tag)}${optional ? '?' : ''}: Markup<Node>`);
|
|
109
|
-
required += optional ? 0 : 1;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return { fields: out, required };
|
|
113
|
-
}
|
|
114
|
-
/** Any `string` but a literal, which only a generic tells apart: a literal makes `Record` a required key. */
|
|
115
|
-
const OTHER = 'type Other<G extends string> = G extends string ? {} extends Record<G, 1> ? G : never : never;';
|
|
116
|
-
/** `defaults`: markup the runtime renders when a call leaves it out (the config's `markup`). */
|
|
117
|
-
export function signature(info, defaults = new Set()) {
|
|
118
|
-
const ret = info.rich ? 'Node' : 'string';
|
|
119
|
-
const { branches } = info;
|
|
120
|
-
if (branches) {
|
|
121
|
-
// One member per key, so a key's own params are required only with it; `string` last.
|
|
122
|
-
const every = new Set([...branches.needs.values()].flatMap((names) => [...names]));
|
|
123
|
-
const members = [...branches.needs]
|
|
124
|
-
.toSorted(([a], [b]) => Number(a === null) - Number(b === null) || String(a).localeCompare(String(b)))
|
|
125
|
-
.map(([key, names]) => {
|
|
126
|
-
// a plain `string` may hold any key, so it needs every branch's params
|
|
127
|
-
const [type, needed] = key === null ? ['string', every] : [JSON.stringify(key), names];
|
|
128
|
-
return `{ ${fields(info, needed, defaults, [branches.param, type]).fields.join('; ')} }`;
|
|
129
|
-
});
|
|
130
|
-
return `(params: ${members.join(' | ')}): ${ret}`;
|
|
131
|
-
}
|
|
132
|
-
const own = fields(info, info.params.keys(), defaults);
|
|
133
|
-
if (own.fields.length === 0) {
|
|
134
|
-
return info.rich ? '(): Node' : ': Text';
|
|
135
|
-
}
|
|
136
|
-
// One `G` for every select, as a union of methods with different type params is not callable.
|
|
137
|
-
const generic = own.fields.some((f) => f.includes('Other<G>')) ? '<G extends string>' : '';
|
|
138
|
-
return `${generic}(params${own.required === 0 ? '?' : ''}: { ${own.fields.join('; ')} }): ${ret}`;
|
|
139
|
-
}
|
|
140
|
-
const isLeaf = (n) => !(n instanceof Map);
|
|
141
|
-
/** Whether `node` holds a message with markup (`rich`) or one without. */
|
|
142
|
-
const holds = (node, rich) => isLeaf(node) ? Boolean(node.rich) === rich : [...node.values()].some((n) => holds(n, rich));
|
|
143
|
-
function render(tree, indent) {
|
|
144
|
-
const lines = [];
|
|
145
|
-
for (const [key, node] of tree) {
|
|
146
|
-
if (isLeaf(node)) {
|
|
147
|
-
if (node.doc !== undefined) {
|
|
148
|
-
// Not `/\s*\n\s*/g`, quadratic in a run of spaces.
|
|
149
|
-
const doc = node.doc.split('\n').map((line) => line.trim());
|
|
150
|
-
const text = doc
|
|
151
|
-
.filter(Boolean)
|
|
152
|
-
.join(' ')
|
|
153
|
-
.replaceAll('*/', String.raw `*\/`);
|
|
154
|
-
lines.push(`${indent}/** ${text} */`);
|
|
155
|
-
}
|
|
156
|
-
lines.push(`${indent}${prop(key)}${node.leaf};`);
|
|
157
|
-
}
|
|
158
|
-
else {
|
|
159
|
-
lines.push(`${indent}${prop(key)}: {`, render(node, `${indent} `), `${indent}};`);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
return lines.join('\n');
|
|
163
|
-
}
|
|
164
|
-
function treeOf(entries) {
|
|
165
|
-
const tree = new Map();
|
|
166
|
-
for (const [path, leaf] of entries) {
|
|
167
|
-
const last = path.at(-1) ?? '';
|
|
168
|
-
let node = tree;
|
|
169
|
-
for (const segment of path.slice(0, -1)) {
|
|
170
|
-
let child = node.get(segment);
|
|
171
|
-
if (!child || isLeaf(child)) {
|
|
172
|
-
child = new Map();
|
|
173
|
-
node.set(segment, child);
|
|
174
|
-
}
|
|
175
|
-
node = child;
|
|
176
|
-
}
|
|
177
|
-
node.set(last, leaf);
|
|
178
|
-
}
|
|
179
|
-
return tree;
|
|
180
|
-
}
|
|
181
|
-
const pascal = (key) => key
|
|
182
|
-
.split(/[^A-Za-z0-9]+/)
|
|
183
|
-
.filter(Boolean)
|
|
184
|
-
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
185
|
-
.join('');
|
|
186
|
-
/**
|
|
187
|
-
* Plain messages in a non-generic `XText`, and those with markup in `XMessages<Node> extends XText`,
|
|
188
|
-
* so instantiating `Node` skips every plain message. A group holding both splits the same way.
|
|
189
|
-
*/
|
|
190
|
-
function declare(tree, name, unique, out) {
|
|
191
|
-
const plain = new Map();
|
|
192
|
-
const rich = new Map();
|
|
193
|
-
for (const [key, node] of tree) {
|
|
194
|
-
if (!holds(node, true)) {
|
|
195
|
-
plain.set(key, node);
|
|
196
|
-
}
|
|
197
|
-
else if (isLeaf(node) || !holds(node, false)) {
|
|
198
|
-
rich.set(key, node);
|
|
199
|
-
}
|
|
200
|
-
else {
|
|
201
|
-
const group = unique(name.replace(/Messages$/, `${pascal(key)}Messages`));
|
|
202
|
-
declare(node, group, unique, out);
|
|
203
|
-
rich.set(key, { leaf: `: ${group}<Node>` });
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
const text = name.replace(/Messages$/, 'Text');
|
|
207
|
-
const body = (members) => render(members, ' ');
|
|
208
|
-
if (rich.size === 0) {
|
|
209
|
-
out.push(`export interface ${name} {\n${body(plain)}\n}`);
|
|
210
|
-
}
|
|
211
|
-
else if (plain.size === 0) {
|
|
212
|
-
out.push(`export interface ${name}<Node> {\n${body(rich)}\n}`);
|
|
213
|
-
}
|
|
214
|
-
else {
|
|
215
|
-
out.push(`export interface ${text} {\n${body(plain)}\n}`, `export interface ${name}<Node> extends ${text} {\n${body(rich)}\n}`);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
function withAliases(code) {
|
|
219
|
-
const aliases = [
|
|
220
|
-
...(code.includes('Markup<Node>') ? ['type Markup<Node> = (children: Node) => Node;'] : []),
|
|
221
|
-
...(code.includes('Other<G>') ? [OTHER] : []),
|
|
222
|
-
];
|
|
223
|
-
return aliases.length > 0 ? `${aliases.join('\n')}\n\n${code}\n\nexport {};` : code;
|
|
224
|
-
}
|
|
225
|
-
export function namespaceTypes(messages, name, defaults) {
|
|
226
|
-
const leaves = [...messages].map(([key, { info, source }]) => [
|
|
227
|
-
key.split('.'),
|
|
228
|
-
{ leaf: signature(info, defaults), doc: source, rich: info.rich },
|
|
229
|
-
]);
|
|
230
|
-
const tree = treeOf(leaves);
|
|
231
|
-
const used = new Set([name]);
|
|
232
|
-
const unique = (base) => {
|
|
233
|
-
let group = base;
|
|
234
|
-
for (let n = 2; used.has(group); n += 1) {
|
|
235
|
-
group = base.replace(/Messages$/, `${n}Messages`);
|
|
236
|
-
}
|
|
237
|
-
used.add(group);
|
|
238
|
-
return group;
|
|
239
|
-
};
|
|
240
|
-
const out = [];
|
|
241
|
-
declare(tree, name, unique, out);
|
|
242
|
-
const code = out.join('\n\n');
|
|
243
|
-
return {
|
|
244
|
-
// One alias: TypeScript instantiates it once per node type, not once per tag. `export {}` keeps
|
|
245
|
-
// it private, as a .d.ts otherwise exports every top-level name.
|
|
246
|
-
code: withAliases(code),
|
|
247
|
-
generic: holds(tree, true),
|
|
248
|
-
usesText: leaves.some(([, leaf]) => leaf.leaf === ': Text'),
|
|
249
|
-
};
|
|
250
|
-
}
|