@parlajs/compiler 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/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/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/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/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
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {
|
|
2
|
+
existsSync,
|
|
3
|
+
lstatSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
writeFileSync,
|
|
10
|
+
} from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import type { ResolvedConfig } from '../config/config.ts';
|
|
14
|
+
|
|
15
|
+
import { catalogDeclaration, catalogModule, MARK } from './modules.ts';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Writes through a dotted temp file and a rename: builds run at once (one per app of a monorepo, the
|
|
19
|
+
* dev server beside `tsc --watch`) must never read a half-written chunk.
|
|
20
|
+
*/
|
|
21
|
+
function writeIfChanged(file: string, content: string): boolean {
|
|
22
|
+
if (existsSync(file) && readFileSync(file, 'utf8') === content) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
26
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`);
|
|
27
|
+
writeFileSync(tmp, content);
|
|
28
|
+
renameSync(tmp, file);
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Not a symlink: it leads out of `outDir`. */
|
|
33
|
+
const isFolder = (dir: string): boolean =>
|
|
34
|
+
lstatSync(dir, { throwIfNoEntry: false })?.isDirectory() ?? false;
|
|
35
|
+
|
|
36
|
+
function isGenerated(file: string): boolean {
|
|
37
|
+
try {
|
|
38
|
+
return readFileSync(file, 'utf8').startsWith(MARK);
|
|
39
|
+
} catch {
|
|
40
|
+
// a parallel build removed it first
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Removes the files in `out/rel` that an earlier build generated and this one did not. */
|
|
46
|
+
function removeStale(
|
|
47
|
+
out: string,
|
|
48
|
+
{ rel, kept }: { rel: string; kept: ReadonlyMap<string, string> },
|
|
49
|
+
): Array<string> {
|
|
50
|
+
const removed: Array<string> = [];
|
|
51
|
+
const dir = path.join(out, rel);
|
|
52
|
+
for (const entry of isFolder(dir) ? readdirSync(dir, { withFileTypes: true }) : []) {
|
|
53
|
+
const file = path.join(dir, entry.name);
|
|
54
|
+
// a dotted file is another build's write in progress
|
|
55
|
+
const isStale =
|
|
56
|
+
entry.isFile() && !entry.name.startsWith('.') && !kept.has(path.join(rel, entry.name));
|
|
57
|
+
if (isStale && isGenerated(file)) {
|
|
58
|
+
rmSync(file, { force: true });
|
|
59
|
+
removed.push(file);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return removed;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Writes what changed of `files` and the catalog, then removes what an earlier build left. */
|
|
66
|
+
export function writeOutput(
|
|
67
|
+
config: ResolvedConfig,
|
|
68
|
+
files: ReadonlyMap<string, string>,
|
|
69
|
+
): { written: Array<string>; removed: Array<string> } {
|
|
70
|
+
const out = config.outDir;
|
|
71
|
+
const all = new Map([
|
|
72
|
+
...files,
|
|
73
|
+
['catalog.js', catalogModule(config)],
|
|
74
|
+
['catalog.d.ts', catalogDeclaration(config)],
|
|
75
|
+
]);
|
|
76
|
+
const written = [...all].filter(([rel, code]) => writeIfChanged(path.join(out, rel), code));
|
|
77
|
+
const removed = removeStale(out, { rel: 'namespaces', kept: all });
|
|
78
|
+
const messagesDir = path.join(out, 'messages');
|
|
79
|
+
for (const locale of isFolder(messagesDir) ? readdirSync(messagesDir) : []) {
|
|
80
|
+
removed.push(...removeStale(out, { rel: path.join('messages', locale), kept: all }));
|
|
81
|
+
}
|
|
82
|
+
return { written: written.map(([rel]) => path.join(out, rel)), removed };
|
|
83
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { compileMessage } from '../compile/compile.ts';
|
|
2
|
+
import { CompileError } from '../compile/error.ts';
|
|
3
|
+
import type { CompiledMessage, MessageInfo } from '../compile/info.ts';
|
|
4
|
+
import { ModuleScope } from '../compile/scope.ts';
|
|
5
|
+
import type { ResolvedConfig, ResolvedNamespace } from '../config/config.ts';
|
|
6
|
+
import { fallbackChain } from '../config/fallbacks.ts';
|
|
7
|
+
import type { Diagnostic, Unplaced } from '../diagnostics.ts';
|
|
8
|
+
import { missingPlurals, samePlurals } from '../plurals.ts';
|
|
9
|
+
|
|
10
|
+
import { inherits, mismatches, omissions } from './checks.ts';
|
|
11
|
+
import { emitFactory, treeOf } from './chunk.ts';
|
|
12
|
+
import { HEADER } from './modules.ts';
|
|
13
|
+
import type { Entry } from './read.ts';
|
|
14
|
+
|
|
15
|
+
type Messages = Map<string, { info: MessageInfo; source: string }>;
|
|
16
|
+
|
|
17
|
+
export interface LocaleInput {
|
|
18
|
+
readonly config: ResolvedConfig;
|
|
19
|
+
readonly ns: ResolvedNamespace;
|
|
20
|
+
readonly catalogs: ReadonlyMap<string, ReadonlyMap<string, Entry>>;
|
|
21
|
+
readonly reported: ReadonlySet<string>;
|
|
22
|
+
/** The source locale's messages, filled by its own call, which comes first. */
|
|
23
|
+
readonly sourceInfo: Messages;
|
|
24
|
+
readonly diagnostics: Array<Diagnostic>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface Context extends LocaleInput {
|
|
28
|
+
readonly locale: string;
|
|
29
|
+
readonly own: ReadonlyMap<string, Entry>;
|
|
30
|
+
readonly chain: ReadonlyArray<string>;
|
|
31
|
+
/** A locale with a parent leaves gaps by design. */
|
|
32
|
+
readonly gapsAllowed: boolean;
|
|
33
|
+
readonly at: (d: Unplaced) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The entry a locale compiles for `key`: its own, else the first of its chain that has it. */
|
|
37
|
+
function entryFor(
|
|
38
|
+
key: string,
|
|
39
|
+
{ config, locale, own, catalogs, chain, gapsAllowed, reported, at }: Context,
|
|
40
|
+
): { entry: Entry | undefined; from: string } {
|
|
41
|
+
const entry = own.get(key);
|
|
42
|
+
if (entry) {
|
|
43
|
+
return { entry, from: locale };
|
|
44
|
+
}
|
|
45
|
+
// the chain ends at the source locale, which has every key
|
|
46
|
+
const from = chain.find((l) => catalogs.get(l)?.has(key)) ?? config.sourceLocale;
|
|
47
|
+
if (!gapsAllowed && !reported.has(locale) && !reported.has(`${locale}\0${key}`)) {
|
|
48
|
+
at({
|
|
49
|
+
level: 'warning',
|
|
50
|
+
code: 'missing-translation',
|
|
51
|
+
key,
|
|
52
|
+
message: `untranslated, using "${from}"`,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return { entry: catalogs.get(from)?.get(key), from };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A translation's params, markup and plurals against the source message's. */
|
|
59
|
+
function compare(
|
|
60
|
+
key: string,
|
|
61
|
+
{ compiled, ctx }: { compiled: CompiledMessage; ctx: Context },
|
|
62
|
+
): void {
|
|
63
|
+
const { config, locale, own, sourceInfo, at } = ctx;
|
|
64
|
+
// A source message that fails to compile is reported for the source locale.
|
|
65
|
+
const ref = sourceInfo.get(key)?.info;
|
|
66
|
+
if (locale !== config.sourceLocale && own.has(key) && ref) {
|
|
67
|
+
for (const message of mismatches(compiled.info, ref)) {
|
|
68
|
+
at({ level: 'error', code: 'param-mismatch', key, message });
|
|
69
|
+
}
|
|
70
|
+
for (const message of omissions(compiled.info, ref)) {
|
|
71
|
+
at({ level: 'warning', code: 'missing-param', key, message });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const missing = own.has(key) ? missingPlurals(locale, compiled.info) : [];
|
|
75
|
+
if (missing.length > 0) {
|
|
76
|
+
const message = `has no plural form for ${missing.join(', ')}, which "${locale}" uses`;
|
|
77
|
+
at({ level: 'warning', code: 'missing-plural', key, message });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One locale's chunk of a namespace: every source key, translated or borrowed. */
|
|
82
|
+
export function compileLocale(locale: string, input: LocaleInput): string {
|
|
83
|
+
const { config, ns, catalogs, reported, sourceInfo, diagnostics } = input;
|
|
84
|
+
const source = catalogs.get(config.sourceLocale) ?? new Map<string, Entry>();
|
|
85
|
+
const own = catalogs.get(locale) ?? new Map<string, Entry>();
|
|
86
|
+
const at = (d: Unplaced): void => {
|
|
87
|
+
diagnostics.push({ ...d, namespace: ns.name, locale, file: ns.file(locale) });
|
|
88
|
+
};
|
|
89
|
+
const ctx: Context = {
|
|
90
|
+
...input,
|
|
91
|
+
locale,
|
|
92
|
+
own,
|
|
93
|
+
chain: fallbackChain(config, locale),
|
|
94
|
+
gapsAllowed: inherits(config, locale),
|
|
95
|
+
at,
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
// A source that failed to parse may have the key.
|
|
99
|
+
if (!reported.has(config.sourceLocale)) {
|
|
100
|
+
for (const key of own.keys()) {
|
|
101
|
+
if (source.has(key) || reported.has(`${config.sourceLocale}\0${key}`)) {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
at({
|
|
105
|
+
level: 'warning',
|
|
106
|
+
code: 'unknown-key',
|
|
107
|
+
key,
|
|
108
|
+
message: `not in "${config.sourceLocale}", so dropped: add it there or remove it`,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const scope = new ModuleScope();
|
|
114
|
+
const messages: Array<[key: string, fn: string]> = [];
|
|
115
|
+
for (const [key, srcEntry] of source) {
|
|
116
|
+
const { entry = srcEntry, from } = entryFor(key, ctx);
|
|
117
|
+
let compiled;
|
|
118
|
+
try {
|
|
119
|
+
compiled = compileMessage(entry.model, {
|
|
120
|
+
scope,
|
|
121
|
+
custom: config.functions,
|
|
122
|
+
pluralsOf: from === locale || samePlurals(from, locale) ? undefined : from,
|
|
123
|
+
});
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (!(error instanceof CompileError)) {
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
// borrowed text is reported for the locale that wrote it
|
|
129
|
+
if (from === locale) {
|
|
130
|
+
at({ level: 'error', code: 'invalid-syntax', key, message: error.message });
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (locale === config.sourceLocale) {
|
|
135
|
+
sourceInfo.set(key, { info: compiled.info, source: srcEntry.source });
|
|
136
|
+
}
|
|
137
|
+
compare(key, { compiled, ctx });
|
|
138
|
+
// A message that never reads `p` takes no default, so a call without params allocates nothing.
|
|
139
|
+
const param = /\bp\b/.test(compiled.body) ? 'p = {}' : 'p';
|
|
140
|
+
messages.push([key, `(${param}) => ${compiled.body}`]);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const consts = scope.consts.length > 0 ? `${scope.consts.join('\n')}\n` : '';
|
|
144
|
+
return `${HEADER}${consts}export default ${emitFactory(treeOf(messages))};\n`;
|
|
145
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { MessageInfo } from '../compile/info.ts';
|
|
2
|
+
import type { ResolvedConfig } from '../config/config.ts';
|
|
3
|
+
import { fallbackChain } from '../config/fallbacks.ts';
|
|
4
|
+
import { namespaceTypes } from '../types/namespace.ts';
|
|
5
|
+
|
|
6
|
+
import { groupSeparator, hasPlainDigits } from './digits.ts';
|
|
7
|
+
|
|
8
|
+
export const MARK = '// Generated by parla. Do not edit.\n';
|
|
9
|
+
|
|
10
|
+
// Not all linters skip what `.gitignore` lists, and oxlint may be set to ignore ESLint's directives.
|
|
11
|
+
export const HEADER = `${MARK}/* eslint-disable */\n/* oxlint-disable */\n`;
|
|
12
|
+
|
|
13
|
+
/** One registry augmentation, or nothing when it has no member. */
|
|
14
|
+
function registry(name: string, keys: ReadonlyArray<string>): string {
|
|
15
|
+
const members = keys.map((k) => ` ${JSON.stringify(k)}: true;\n`).join('');
|
|
16
|
+
return members ? ` interface ${name} {\n${members} }\n` : '';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const localeType = (config: ResolvedConfig): string =>
|
|
20
|
+
config.locales.map((l) => JSON.stringify(l)).join(' | ');
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The namespace object's type: its messages, a kind that hands them the instance's node type when
|
|
24
|
+
* they have markup, and the locales it was built for.
|
|
25
|
+
*/
|
|
26
|
+
export function namespaceDeclaration(
|
|
27
|
+
config: ResolvedConfig,
|
|
28
|
+
{
|
|
29
|
+
namespace,
|
|
30
|
+
iface,
|
|
31
|
+
exported,
|
|
32
|
+
messages,
|
|
33
|
+
}: {
|
|
34
|
+
namespace: string;
|
|
35
|
+
iface: string;
|
|
36
|
+
exported: string;
|
|
37
|
+
messages: Map<string, { info: MessageInfo; source: string }>;
|
|
38
|
+
},
|
|
39
|
+
): string {
|
|
40
|
+
const types = namespaceTypes(messages, { name: iface, defaults: new Set(config.markup) });
|
|
41
|
+
const kind = iface.replace(/Messages$/, 'Kind');
|
|
42
|
+
const imported = ['Namespace', 'NamespaceKind', ...(types.usesText ? ['Text'] : [])];
|
|
43
|
+
return `${HEADER}import type { ${imported.join(', ')} } from '${config.runtime}';
|
|
44
|
+
|
|
45
|
+
${types.code}
|
|
46
|
+
|
|
47
|
+
export interface ${kind} extends NamespaceKind {
|
|
48
|
+
readonly messages: ${iface}${types.generic ? "<this['node']>" : ''};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export declare const ${exported}: Namespace<${JSON.stringify(namespace)}, ${kind}, ${localeType(config)}>;
|
|
52
|
+
`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What an app imports to load a namespace: its name and one chunk loader per locale. */
|
|
56
|
+
export function namespaceModule(
|
|
57
|
+
namespace: string,
|
|
58
|
+
{ exported, locales }: { exported: string; locales: ReadonlyArray<string> },
|
|
59
|
+
): string {
|
|
60
|
+
const loaders = locales
|
|
61
|
+
.map(
|
|
62
|
+
(l) =>
|
|
63
|
+
` ${JSON.stringify(l)}: () => import(${JSON.stringify(`../messages/${l}/${namespace}.js`)}),`,
|
|
64
|
+
)
|
|
65
|
+
.join('\n');
|
|
66
|
+
return `${HEADER}export const ${exported} = {\n name: ${JSON.stringify(namespace)},\n load: {\n${loaders}\n },\n};\n`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** `catalog.js`, which an app passes to `createParla`. */
|
|
70
|
+
export function catalogModule(config: ResolvedConfig): string {
|
|
71
|
+
const fallbacks = Object.fromEntries(config.locales.map((l) => [l, fallbackChain(config, l)]));
|
|
72
|
+
const plainDigits = Object.fromEntries(
|
|
73
|
+
config.locales
|
|
74
|
+
.filter((l) => [l, ...(fallbacks[l] ?? [])].every((tag) => hasPlainDigits(tag)))
|
|
75
|
+
.map((l) => [l, groupSeparator(l, fallbacks[l] ?? []) ?? true]),
|
|
76
|
+
);
|
|
77
|
+
const members = Object.entries({
|
|
78
|
+
locales: config.locales,
|
|
79
|
+
sourceLocale: config.sourceLocale,
|
|
80
|
+
fallbacks,
|
|
81
|
+
plainDigits,
|
|
82
|
+
}).map(([key, value]) => ` ${key}: ${JSON.stringify(value)},\n`);
|
|
83
|
+
return `${HEADER}export const catalog = {\n${members.join('')}};\n`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `catalog.d.ts`: the locales, and the registries it adds to the runtime. */
|
|
87
|
+
export function catalogDeclaration(config: ResolvedConfig): string {
|
|
88
|
+
const registries = [
|
|
89
|
+
registry('LocaleRegistry', config.locales),
|
|
90
|
+
registry('FunctionRegistry', Object.keys(config.functions)),
|
|
91
|
+
registry('MarkupRegistry', config.markup),
|
|
92
|
+
].join('');
|
|
93
|
+
return `${HEADER}import type { Catalog } from '${config.runtime}';\n\nexport type Locale = ${localeType(config)};\n\nexport declare const catalog: Catalog & { readonly locales: readonly Locale[]; readonly sourceLocale: ${JSON.stringify(config.sourceLocale)} };\n\ndeclare module '${config.runtime}' {\n${registries}}\n`;
|
|
94
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
import type { MessageInfo } from '../compile/info.ts';
|
|
4
|
+
import type { FormatAdapter, ResolvedConfig, ResolvedNamespace } from '../config/config.ts';
|
|
5
|
+
import type { Diagnostic } from '../diagnostics.ts';
|
|
6
|
+
|
|
7
|
+
import { inherits } from './checks.ts';
|
|
8
|
+
import { compileLocale } from './locale.ts';
|
|
9
|
+
import { namespaceDeclaration, namespaceModule } from './modules.ts';
|
|
10
|
+
import { readCatalog } from './read.ts';
|
|
11
|
+
import type { CatalogText, Entry } from './read.ts';
|
|
12
|
+
|
|
13
|
+
/** What a build collects: its diagnostics, and the files to write by path under `outDir`. */
|
|
14
|
+
export interface Output {
|
|
15
|
+
readonly diagnostics: Array<Diagnostic>;
|
|
16
|
+
readonly files: Map<string, string>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface Read {
|
|
20
|
+
readonly catalogs: Map<string, Map<string, Entry>>;
|
|
21
|
+
/** A locale, or `locale\0key`, already reported: what it lacks is the same problem. */
|
|
22
|
+
readonly reported: Set<string>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readCatalogs(
|
|
26
|
+
ns: ResolvedNamespace,
|
|
27
|
+
{
|
|
28
|
+
config,
|
|
29
|
+
adapter,
|
|
30
|
+
texts,
|
|
31
|
+
diagnostics,
|
|
32
|
+
}: {
|
|
33
|
+
config: ResolvedConfig;
|
|
34
|
+
adapter: FormatAdapter;
|
|
35
|
+
texts: ReadonlyArray<CatalogText>;
|
|
36
|
+
} & Pick<Output, 'diagnostics'>,
|
|
37
|
+
): Read {
|
|
38
|
+
const catalogs = new Map<string, Map<string, Entry>>();
|
|
39
|
+
const reported = new Set<string>();
|
|
40
|
+
for (const [index, locale] of config.locales.entries()) {
|
|
41
|
+
const read = readCatalog(ns, {
|
|
42
|
+
locale,
|
|
43
|
+
adapter,
|
|
44
|
+
text: texts[index],
|
|
45
|
+
report: (d) => {
|
|
46
|
+
reported.add(d.key ? `${locale}\0${d.key}` : locale);
|
|
47
|
+
diagnostics.push({ ...d, namespace: ns.name, locale });
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
if (!read.exists && (locale === config.sourceLocale || !inherits(config, locale))) {
|
|
51
|
+
reported.add(locale);
|
|
52
|
+
diagnostics.push({
|
|
53
|
+
level: locale === config.sourceLocale ? 'error' : 'warning',
|
|
54
|
+
code: 'missing-file',
|
|
55
|
+
namespace: ns.name,
|
|
56
|
+
locale,
|
|
57
|
+
file: read.file,
|
|
58
|
+
message: 'no such file: create it',
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
catalogs.set(locale, read.entries);
|
|
62
|
+
}
|
|
63
|
+
return { catalogs, reported };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A namespace's chunk per locale, its object and its types, from its catalogs' `texts` per locale. */
|
|
67
|
+
export function buildNamespace(
|
|
68
|
+
ns: ResolvedNamespace,
|
|
69
|
+
{
|
|
70
|
+
config,
|
|
71
|
+
names: { iface, exported },
|
|
72
|
+
texts,
|
|
73
|
+
out,
|
|
74
|
+
}: {
|
|
75
|
+
config: ResolvedConfig;
|
|
76
|
+
names: { readonly iface: string; readonly exported: string };
|
|
77
|
+
texts: ReadonlyArray<CatalogText>;
|
|
78
|
+
out: Output;
|
|
79
|
+
},
|
|
80
|
+
): void {
|
|
81
|
+
const { diagnostics, files } = out;
|
|
82
|
+
if (exported !== ns.name) {
|
|
83
|
+
// two names for one namespace is what tools like codemods and x18n trip over
|
|
84
|
+
diagnostics.push({
|
|
85
|
+
level: 'warning',
|
|
86
|
+
code: 'namespace-name',
|
|
87
|
+
namespace: ns.name,
|
|
88
|
+
message: `exports as ${exported} while t keeps "${ns.name}": name it as an identifier and map the file in path`,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
const adapter = config.formats[ns.format];
|
|
92
|
+
if (!adapter) {
|
|
93
|
+
diagnostics.push({
|
|
94
|
+
level: 'error',
|
|
95
|
+
code: 'unknown-format',
|
|
96
|
+
namespace: ns.name,
|
|
97
|
+
message: `format "${ns.format}" is not in formats (${Object.keys(config.formats).join(', ') || 'empty'})`,
|
|
98
|
+
});
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const read = readCatalogs(ns, { config, adapter, texts, diagnostics });
|
|
102
|
+
const sourceInfo = new Map<string, { info: MessageInfo; source: string }>();
|
|
103
|
+
// The source locale first, so every translation has its source message to compare against.
|
|
104
|
+
const locales = [config.sourceLocale, ...config.locales.filter((l) => l !== config.sourceLocale)];
|
|
105
|
+
for (const locale of locales) {
|
|
106
|
+
files.set(
|
|
107
|
+
path.join('messages', locale, `${ns.name}.js`),
|
|
108
|
+
compileLocale(locale, { ...read, config, ns, sourceInfo, diagnostics }),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
files.set(
|
|
112
|
+
path.join('namespaces', `${ns.name}.js`),
|
|
113
|
+
namespaceModule(ns.name, { exported, locales: config.locales }),
|
|
114
|
+
);
|
|
115
|
+
files.set(
|
|
116
|
+
path.join('namespaces', `${ns.name}.d.ts`),
|
|
117
|
+
namespaceDeclaration(config, { namespace: ns.name, iface, exported, messages: sourceInfo }),
|
|
118
|
+
);
|
|
119
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { FormatAdapter, ResolvedConfig } from '../config/config.ts';
|
|
2
|
+
import type { Diagnostic } from '../diagnostics.ts';
|
|
3
|
+
import { exportNames, interfaceNames } from '../types/names.ts';
|
|
4
|
+
|
|
5
|
+
import { buildNamespace } from './namespace.ts';
|
|
6
|
+
import type { Output } from './namespace.ts';
|
|
7
|
+
import { readText } from './read.ts';
|
|
8
|
+
import type { CatalogText } from './read.ts';
|
|
9
|
+
|
|
10
|
+
/** A namespace's output, and all it was built from. */
|
|
11
|
+
interface Kept {
|
|
12
|
+
readonly settings: string;
|
|
13
|
+
readonly adapter: FormatAdapter | undefined;
|
|
14
|
+
readonly texts: ReadonlyArray<CatalogText>;
|
|
15
|
+
readonly diagnostics: ReadonlyArray<Diagnostic>;
|
|
16
|
+
readonly files: ReadonlyMap<string, string>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Per config file, its last build: a watcher's rebuild compiles only the namespaces that changed.
|
|
20
|
+
const builds = new Map<string, Map<string, Kept>>();
|
|
21
|
+
|
|
22
|
+
/** Every namespace's output, the last build's where nothing the namespace reads has changed. */
|
|
23
|
+
export function buildNamespaces(config: ResolvedConfig, out: Output): void {
|
|
24
|
+
const ifaces = interfaceNames(config.namespaces.map((ns) => ns.name));
|
|
25
|
+
const exports = exportNames(ifaces);
|
|
26
|
+
// Whatever else the config holds, so an option added later is not forgotten here.
|
|
27
|
+
const shared = JSON.stringify({
|
|
28
|
+
...config,
|
|
29
|
+
formats: Object.keys(config.formats),
|
|
30
|
+
namespaces: 0,
|
|
31
|
+
watchFiles: 0,
|
|
32
|
+
watchFolders: 0,
|
|
33
|
+
});
|
|
34
|
+
const last = builds.get(config.configFile);
|
|
35
|
+
const kept = new Map<string, Kept>();
|
|
36
|
+
for (const ns of config.namespaces) {
|
|
37
|
+
const names = { iface: ifaces.get(ns.name) ?? '', exported: exports.get(ns.name) ?? '' };
|
|
38
|
+
const files = config.locales.map((locale) => ns.file(locale));
|
|
39
|
+
const settings = JSON.stringify([shared, ns.format, names, files]);
|
|
40
|
+
const adapter = config.formats[ns.format];
|
|
41
|
+
const texts = files.map((file) => readText(file));
|
|
42
|
+
let built = last?.get(ns.name);
|
|
43
|
+
if (
|
|
44
|
+
built?.settings !== settings ||
|
|
45
|
+
built.adapter !== adapter ||
|
|
46
|
+
texts.some((text, i) => text !== built?.texts[i])
|
|
47
|
+
) {
|
|
48
|
+
const fresh: Output = { diagnostics: [], files: new Map() };
|
|
49
|
+
buildNamespace(ns, { config, names, texts, out: fresh });
|
|
50
|
+
built = { settings, adapter, texts, ...fresh };
|
|
51
|
+
}
|
|
52
|
+
kept.set(ns.name, built);
|
|
53
|
+
out.diagnostics.push(...built.diagnostics);
|
|
54
|
+
for (const [file, content] of built.files) {
|
|
55
|
+
out.files.set(file, content);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
builds.set(config.configFile, kept);
|
|
59
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
import type { Model } from 'messageformat';
|
|
4
|
+
|
|
5
|
+
import type { FormatAdapter, ResolvedNamespace } from '../config/config.ts';
|
|
6
|
+
import type { ErrorDiagnostic, Unplaced } from '../diagnostics.ts';
|
|
7
|
+
|
|
8
|
+
/** Groups in groups past this would overflow the stack, here or in what reads the output. */
|
|
9
|
+
const MAX_DEPTH = 100;
|
|
10
|
+
|
|
11
|
+
interface Problem {
|
|
12
|
+
key: string;
|
|
13
|
+
message: string;
|
|
14
|
+
code: ErrorDiagnostic['code'];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** `value`'s messages into `out` by dotted key. */
|
|
18
|
+
function flatten(
|
|
19
|
+
value: unknown,
|
|
20
|
+
{
|
|
21
|
+
prefix,
|
|
22
|
+
out,
|
|
23
|
+
report,
|
|
24
|
+
}: { prefix: string; out: Map<string, string>; report: (problem: Problem) => void },
|
|
25
|
+
): void {
|
|
26
|
+
const invalid = (message: string): void => {
|
|
27
|
+
report({ key: prefix, message, code: 'invalid-resource' });
|
|
28
|
+
};
|
|
29
|
+
if (prefix.split('.').length > MAX_DEPTH) {
|
|
30
|
+
invalid(`more than ${MAX_DEPTH} levels of keys`);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === 'string') {
|
|
34
|
+
if (out.has(prefix)) {
|
|
35
|
+
report({
|
|
36
|
+
key: prefix,
|
|
37
|
+
message: `"${prefix}" is written twice, with dots and in a group`,
|
|
38
|
+
code: 'key-conflict',
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
out.set(prefix, value);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
45
|
+
for (const [k, v] of Object.entries(value)) {
|
|
46
|
+
flatten(v, { prefix: `${prefix}.${k}`, out, report });
|
|
47
|
+
}
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const kind = Array.isArray(value) ? 'array' : typeof value;
|
|
51
|
+
invalid(`expected a string or an object, got ${value === null ? 'null' : kind}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A catalog's messages by dotted key; nothing, reported, unless it is an object. */
|
|
55
|
+
function flattenRoot(
|
|
56
|
+
tree: unknown,
|
|
57
|
+
report: (problem: Problem) => void,
|
|
58
|
+
): Map<string, string> | undefined {
|
|
59
|
+
if (!tree || typeof tree !== 'object' || Array.isArray(tree)) {
|
|
60
|
+
const kind = Array.isArray(tree) ? 'array' : typeof tree;
|
|
61
|
+
const message = `expected an object of messages, got ${tree === null ? 'null' : kind}`;
|
|
62
|
+
report({ key: '', message, code: 'invalid-resource' });
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
const out = new Map<string, string>();
|
|
66
|
+
// From the root, as a group named "" would otherwise pass for it.
|
|
67
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
68
|
+
flatten(value, { prefix: key, out, report });
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface Entry {
|
|
74
|
+
source: string;
|
|
75
|
+
model: Model.Message;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A catalog's text: none where there is no file, an error where it cannot be read. */
|
|
79
|
+
export type CatalogText = string | Error | undefined;
|
|
80
|
+
|
|
81
|
+
export function readText(file: string): CatalogText {
|
|
82
|
+
if (!existsSync(file)) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
return readFileSync(file, 'utf8');
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return error as Error;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function readCatalog(
|
|
93
|
+
ns: ResolvedNamespace,
|
|
94
|
+
{
|
|
95
|
+
locale,
|
|
96
|
+
adapter,
|
|
97
|
+
text,
|
|
98
|
+
report: diag,
|
|
99
|
+
}: {
|
|
100
|
+
locale: string;
|
|
101
|
+
adapter: FormatAdapter;
|
|
102
|
+
text: CatalogText;
|
|
103
|
+
report: (d: Unplaced) => void;
|
|
104
|
+
},
|
|
105
|
+
): { file: string; entries: Map<string, Entry>; exists: boolean } {
|
|
106
|
+
const file = ns.file(locale);
|
|
107
|
+
const entries = new Map<string, Entry>();
|
|
108
|
+
if (text === undefined) {
|
|
109
|
+
return { file, entries, exists: false };
|
|
110
|
+
}
|
|
111
|
+
let tree: unknown;
|
|
112
|
+
try {
|
|
113
|
+
if (text instanceof Error) {
|
|
114
|
+
throw text;
|
|
115
|
+
}
|
|
116
|
+
tree = adapter.parseFile ? adapter.parseFile(text) : JSON.parse(text);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
diag({ level: 'error', code: 'invalid-resource', message: (error as Error).message, file });
|
|
119
|
+
return { file, entries, exists: true };
|
|
120
|
+
}
|
|
121
|
+
const flat = flattenRoot(tree, (problem) => {
|
|
122
|
+
diag({ level: 'error', ...problem, file });
|
|
123
|
+
});
|
|
124
|
+
if (!flat) {
|
|
125
|
+
return { file, entries, exists: true };
|
|
126
|
+
}
|
|
127
|
+
// Every prefix, not a sorted neighbour: `-` and others sort between `a` and `a.b`.
|
|
128
|
+
const groups = new Set<string>();
|
|
129
|
+
for (const key of flat.keys()) {
|
|
130
|
+
for (let dot = key.indexOf('.'); dot !== -1; dot = key.indexOf('.', dot + 1)) {
|
|
131
|
+
groups.add(key.slice(0, dot));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
for (const key of flat.keys()) {
|
|
135
|
+
if (groups.has(key)) {
|
|
136
|
+
diag({
|
|
137
|
+
level: 'error',
|
|
138
|
+
code: 'key-conflict',
|
|
139
|
+
key,
|
|
140
|
+
message: `"${key}" is both a message and a group`,
|
|
141
|
+
file,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
for (const [key, source] of flat) {
|
|
146
|
+
try {
|
|
147
|
+
entries.set(key, { source, model: adapter.parse(source) });
|
|
148
|
+
} catch (error) {
|
|
149
|
+
diag({
|
|
150
|
+
level: 'error',
|
|
151
|
+
code: 'invalid-syntax',
|
|
152
|
+
key,
|
|
153
|
+
message: (error as Error).message,
|
|
154
|
+
file,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { file, entries, exists: true };
|
|
159
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export { build, type BuildOptions, type BuildResult } from './build.ts';
|
|
2
|
+
export { compileMessage } from './compile/compile.ts';
|
|
3
|
+
export { CompileError } from './compile/error.ts';
|
|
4
|
+
export type {
|
|
5
|
+
CompiledMessage,
|
|
6
|
+
CustomFunctions,
|
|
7
|
+
FunctionKind,
|
|
8
|
+
MessageInfo,
|
|
9
|
+
ParamKind,
|
|
10
|
+
} from './compile/info.ts';
|
|
11
|
+
export { ModuleScope } from './compile/scope.ts';
|
|
12
|
+
export {
|
|
13
|
+
ConfigError,
|
|
14
|
+
defineConfig,
|
|
15
|
+
type FormatAdapter,
|
|
16
|
+
type NamespaceConfig,
|
|
17
|
+
type ParlaConfig,
|
|
18
|
+
type ResolvedConfig,
|
|
19
|
+
type ResolvedNamespace,
|
|
20
|
+
} from './config/config.ts';
|
|
21
|
+
export { loadConfig } from './config/load.ts';
|
|
22
|
+
export {
|
|
23
|
+
formatDiagnostic,
|
|
24
|
+
type Diagnostic,
|
|
25
|
+
type ErrorDiagnostic,
|
|
26
|
+
type WarningDiagnostic,
|
|
27
|
+
} from './diagnostics.ts';
|