@hamur/i18n 0.0.0-stage → 0.0.2
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 +22 -0
- package/README.md +38 -2
- package/dist/chunks/bun-index-1ve1hj66.js +744 -0
- package/dist/chunks/bun-index-8bw4xpv8.js +93 -0
- package/dist/chunks/bun-index-ej6vjnjs.js +297 -0
- package/dist/chunks/bun-index-pdepkyy1.js +474 -0
- package/dist/src/adapters/angular.js +67 -0
- package/dist/src/adapters/html.js +34 -0
- package/dist/src/adapters/preact.js +23 -0
- package/dist/src/adapters/react.js +23 -0
- package/dist/src/adapters/solid.js +48 -0
- package/dist/src/adapters/svelte.js +74 -0
- package/dist/src/adapters/vue.js +48 -0
- package/dist/src/cli.js +1898 -0
- package/dist/src/index.js +2755 -0
- package/dist/src/load.js +35 -0
- package/dist/src/server/index.js +395 -0
- package/dist/types/src/adapters/angular.d.ts +20 -0
- package/dist/types/src/adapters/bind.d.ts +44 -0
- package/dist/types/src/adapters/html.d.ts +5 -0
- package/dist/types/src/adapters/preact.d.ts +6 -0
- package/dist/types/src/adapters/react.d.ts +6 -0
- package/dist/types/src/adapters/solid.d.ts +9 -0
- package/dist/types/src/adapters/svelte.d.ts +12 -0
- package/dist/types/src/adapters/vue.d.ts +8 -0
- package/dist/types/src/build/catalog.d.ts +5 -0
- package/dist/types/src/build/drop.d.ts +12 -0
- package/dist/types/src/build/extract.d.ts +11 -0
- package/dist/types/src/build/head.d.ts +4 -0
- package/dist/types/src/build/messages.d.ts +27 -0
- package/dist/types/src/build/prerender.d.ts +10 -0
- package/dist/types/src/build/routes.d.ts +14 -0
- package/dist/types/src/build/split.d.ts +37 -0
- package/dist/types/src/build/types.d.ts +15 -0
- package/dist/types/src/cli.d.ts +12 -0
- package/dist/types/src/compiler/compile.d.ts +17 -0
- package/dist/types/src/compiler/mf2-parse.d.ts +62 -0
- package/dist/types/src/compiler/mf2.d.ts +3 -0
- package/dist/types/src/compiler/parse.d.ts +58 -0
- package/dist/types/src/compiler/skeleton.d.ts +7 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/load.d.ts +7 -0
- package/dist/types/src/module.d.ts +15 -0
- package/dist/types/src/options.d.ts +7 -0
- package/dist/types/src/runtime/catalog-client.d.ts +3 -0
- package/dist/types/src/runtime/catalog-loader.d.ts +15 -0
- package/dist/types/src/runtime/catalog-server.d.ts +5 -0
- package/dist/types/src/runtime/catalog.d.ts +60 -0
- package/dist/types/src/runtime/chain.d.ts +3 -0
- package/dist/types/src/runtime/format.d.ts +27 -0
- package/dist/types/src/runtime/head.d.ts +9 -0
- package/dist/types/src/runtime/interpret.d.ts +20 -0
- package/dist/types/src/runtime/link.d.ts +8 -0
- package/dist/types/src/runtime/locale.d.ts +73 -0
- package/dist/types/src/runtime/match.d.ts +54 -0
- package/dist/types/src/runtime/messages.d.ts +42 -0
- package/dist/types/src/runtime/middleware.d.ts +2 -0
- package/dist/types/src/runtime/negotiate.d.ts +9 -0
- package/dist/types/src/runtime/plugin.d.ts +4 -0
- package/dist/types/src/runtime/redirect.d.ts +32 -0
- package/dist/types/src/runtime/rich.d.ts +5 -0
- package/dist/types/src/runtime/translate.d.ts +21 -0
- package/dist/types/src/server/catalog.d.ts +2 -0
- package/dist/types/src/server/context.d.ts +48 -0
- package/dist/types/src/server/door-all-catalog.d.ts +3 -0
- package/dist/types/src/server/door-all.d.ts +2 -0
- package/dist/types/src/server/door-catalog.d.ts +3 -0
- package/dist/types/src/server/door-root-catalog.d.ts +3 -0
- package/dist/types/src/server/door-root.d.ts +2 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/index.d.ts +7 -0
- package/dist/types/src/server/preferred.d.ts +6 -0
- package/dist/types/src/server/redirect.d.ts +3 -0
- package/dist/types/src/server/setup.d.ts +2 -0
- package/dist/types/src/types.d.ts +163 -0
- package/package.json +155 -4
- package/src/adapters/angular.ts +58 -0
- package/src/adapters/bind.ts +144 -0
- package/src/adapters/html.ts +35 -0
- package/src/adapters/preact.ts +18 -0
- package/src/adapters/react.ts +18 -0
- package/src/adapters/solid.ts +44 -0
- package/src/adapters/svelte.ts +75 -0
- package/src/adapters/test/SveltePage.svelte +18 -0
- package/src/adapters/test/SvelteReporting.svelte +20 -0
- package/src/adapters/test/SvelteRich.svelte +11 -0
- package/src/adapters/test/SvelteRichPlain.svelte +11 -0
- package/src/adapters/test/peer.ts +7 -0
- package/src/adapters/test/preact-client.ts +43 -0
- package/src/adapters/test/preact-page.ts +34 -0
- package/src/adapters/test/preact-rich.ts +9 -0
- package/src/adapters/test/react-client.ts +49 -0
- package/src/adapters/test/react-page.ts +34 -0
- package/src/adapters/test/react-rich.ts +15 -0
- package/src/adapters/test/runtime.ts +104 -0
- package/src/adapters/test/solid-client.ts +33 -0
- package/src/adapters/test/solid-page.ts +30 -0
- package/src/adapters/test/solid-rich.ts +5 -0
- package/src/adapters/test/svelte-client.ts +51 -0
- package/src/adapters/test/svelte-log.ts +2 -0
- package/src/adapters/test/svelte-plugin.ts +20 -0
- package/src/adapters/test/vue-page.ts +26 -0
- package/src/adapters/test/vue-rich.ts +16 -0
- package/src/adapters/vue.ts +44 -0
- package/src/build/catalog.ts +44 -0
- package/src/build/drop.ts +36 -0
- package/src/build/extract.ts +207 -0
- package/src/build/head.ts +10 -0
- package/src/build/messages.ts +347 -0
- package/src/build/prerender.ts +48 -0
- package/src/build/routes.ts +269 -0
- package/src/build/split.ts +240 -0
- package/src/build/types.ts +156 -0
- package/src/cli.ts +25 -0
- package/src/compiler/compile.ts +190 -0
- package/src/compiler/mf2-parse.ts +469 -0
- package/src/compiler/mf2.ts +393 -0
- package/src/compiler/parse.ts +265 -0
- package/src/compiler/skeleton.ts +85 -0
- package/src/env.d.ts +55 -0
- package/src/index.ts +24 -0
- package/src/load.ts +41 -0
- package/src/module.ts +66 -0
- package/src/options.ts +198 -0
- package/src/runtime/catalog-client.ts +28 -0
- package/src/runtime/catalog-loader.ts +28 -0
- package/src/runtime/catalog-server.ts +36 -0
- package/src/runtime/catalog.ts +190 -0
- package/src/runtime/chain.ts +9 -0
- package/src/runtime/format.ts +102 -0
- package/src/runtime/head.ts +57 -0
- package/src/runtime/interpret.ts +504 -0
- package/src/runtime/link.ts +36 -0
- package/src/runtime/locale.ts +392 -0
- package/src/runtime/match.ts +334 -0
- package/src/runtime/messages.ts +129 -0
- package/src/runtime/middleware.ts +32 -0
- package/src/runtime/negotiate.ts +61 -0
- package/src/runtime/plugin.ts +69 -0
- package/src/runtime/redirect.ts +191 -0
- package/src/runtime/rich.ts +21 -0
- package/src/runtime/translate.ts +131 -0
- package/src/server/catalog.ts +11 -0
- package/src/server/context.ts +191 -0
- package/src/server/door-all-catalog.ts +7 -0
- package/src/server/door-all.ts +5 -0
- package/src/server/door-catalog.ts +6 -0
- package/src/server/door-root-catalog.ts +7 -0
- package/src/server/door-root.ts +5 -0
- package/src/server/door.ts +4 -0
- package/src/server/index.ts +11 -0
- package/src/server/preferred.ts +12 -0
- package/src/server/redirect.ts +26 -0
- package/src/server/setup.ts +14 -0
- package/src/types.ts +182 -0
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,1898 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
MessageSyntaxError,
|
|
4
|
+
parseMessage,
|
|
5
|
+
FUNCTIONS,
|
|
6
|
+
parseMf2
|
|
7
|
+
} from "../chunks/bun-index-1ve1hj66.js";
|
|
8
|
+
import {
|
|
9
|
+
fallbackChain,
|
|
10
|
+
parsePattern,
|
|
11
|
+
createMatcher
|
|
12
|
+
} from "../chunks/bun-index-ej6vjnjs.js";
|
|
13
|
+
|
|
14
|
+
// packages/i18n/src/build/extract.ts
|
|
15
|
+
import { mkdir, readdir as readdir2, readFile as readFile4, writeFile } from "fs/promises";
|
|
16
|
+
import { dirname as dirname2, join as join3, relative as relative3, sep as sep3 } from "path";
|
|
17
|
+
|
|
18
|
+
// packages/i18n/src/build/drop.ts
|
|
19
|
+
import { existsSync as existsSync2 } from "fs";
|
|
20
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
21
|
+
import { resolve, sep as sep2 } from "path";
|
|
22
|
+
|
|
23
|
+
// packages/i18n/src/build/split.ts
|
|
24
|
+
import { existsSync } from "fs";
|
|
25
|
+
import { readFile } from "fs/promises";
|
|
26
|
+
import { dirname, join, sep } from "path";
|
|
27
|
+
var SCRIPT_LOADERS = {
|
|
28
|
+
".ts": "ts",
|
|
29
|
+
".mts": "ts",
|
|
30
|
+
".cts": "ts",
|
|
31
|
+
".tsx": "tsx",
|
|
32
|
+
".js": "js",
|
|
33
|
+
".mjs": "js",
|
|
34
|
+
".cjs": "js",
|
|
35
|
+
".jsx": "jsx"
|
|
36
|
+
};
|
|
37
|
+
var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|md|mdx|html)$/;
|
|
38
|
+
var IMPORT_TEXT = /\b(?:import|export)\s+(?:[^'"`;]*?\bfrom\s*)?(["'])([^"'\n]+)\1/g;
|
|
39
|
+
var INLINE_OBJECT = "useTranslation\\s*\\([^()]*\\)\\s*\\)?\\s*\\.\\s*t\\s*";
|
|
40
|
+
var BINDING = /\b(?:const|let|var)\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.]*?(?:useI18n|useTranslation|translator)\s*\(/g;
|
|
41
|
+
var baseOf = (name) => name.split("___")[0];
|
|
42
|
+
var escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
43
|
+
var transpilers = new Map;
|
|
44
|
+
function boundNames(source) {
|
|
45
|
+
const functions = new Set;
|
|
46
|
+
const objects = new Set;
|
|
47
|
+
for (const found of source.matchAll(BINDING)) {
|
|
48
|
+
const target = found[1];
|
|
49
|
+
if (!target.startsWith("{")) {
|
|
50
|
+
objects.add(target);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
for (const member of target.slice(1, -1).split(",")) {
|
|
54
|
+
const named = /^\s*t\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:=.*)?$/s.exec(member);
|
|
55
|
+
if (named)
|
|
56
|
+
functions.add(named[1] ?? "t");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return { functions, objects };
|
|
60
|
+
}
|
|
61
|
+
function firstArgument(source, at) {
|
|
62
|
+
let i = at;
|
|
63
|
+
while (/\s/.test(source[i] ?? ""))
|
|
64
|
+
i++;
|
|
65
|
+
const quote = source[i];
|
|
66
|
+
if (quote === ")")
|
|
67
|
+
return;
|
|
68
|
+
if (quote !== '"' && quote !== "'" && quote !== "`")
|
|
69
|
+
return null;
|
|
70
|
+
let end = i + 1;
|
|
71
|
+
while (end < source.length && source[end] !== quote) {
|
|
72
|
+
if (source[end] === "\\" || quote === "`" && source[end] === "$" && source[end + 1] === "{")
|
|
73
|
+
return null;
|
|
74
|
+
end++;
|
|
75
|
+
}
|
|
76
|
+
if (end >= source.length)
|
|
77
|
+
return null;
|
|
78
|
+
let after = end + 1;
|
|
79
|
+
while (/\s/.test(source[after] ?? ""))
|
|
80
|
+
after++;
|
|
81
|
+
return source[after] === "," || source[after] === ")" ? source.slice(i + 1, end) : null;
|
|
82
|
+
}
|
|
83
|
+
function readKeys(source, withDynamic = true) {
|
|
84
|
+
const keys = new Set;
|
|
85
|
+
const positions = new Map;
|
|
86
|
+
let dynamic = false;
|
|
87
|
+
let at;
|
|
88
|
+
const { functions, objects } = boundNames(source);
|
|
89
|
+
const member = withDynamic ? "(?:\\.\\s*(?:rich|dynamic)\\s*)?\\(" : "(?:\\.\\s*rich\\s*)?\\(";
|
|
90
|
+
const patterns = [
|
|
91
|
+
new RegExp(INLINE_OBJECT + member, "g"),
|
|
92
|
+
...[...functions].map((name) => new RegExp("(?<![\\w$.])" + escape(name) + "\\s*" + member, "g")),
|
|
93
|
+
...[...objects].map((name) => new RegExp("(?<![\\w$.])" + escape(name) + "\\s*\\.\\s*t\\s*" + member, "g"))
|
|
94
|
+
];
|
|
95
|
+
for (const pattern of patterns) {
|
|
96
|
+
for (const found of source.matchAll(pattern)) {
|
|
97
|
+
const argument = firstArgument(source, found.index + found[0].length);
|
|
98
|
+
if (argument === undefined)
|
|
99
|
+
continue;
|
|
100
|
+
if (argument === null) {
|
|
101
|
+
dynamic = true;
|
|
102
|
+
at = at === undefined ? found.index : Math.min(at, found.index);
|
|
103
|
+
} else {
|
|
104
|
+
keys.add(argument);
|
|
105
|
+
positions.set(argument, Math.min(positions.get(argument) ?? found.index, found.index));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { keys, dynamic, positions, ...at === undefined ? {} : { at } };
|
|
110
|
+
}
|
|
111
|
+
function importsOf(source, file) {
|
|
112
|
+
const loader = SCRIPT_LOADERS[file.slice(file.lastIndexOf("."))];
|
|
113
|
+
if (loader) {
|
|
114
|
+
let transpiler = transpilers.get(loader);
|
|
115
|
+
if (!transpiler)
|
|
116
|
+
transpilers.set(loader, transpiler = new Bun.Transpiler({ loader }));
|
|
117
|
+
try {
|
|
118
|
+
return transpiler.scan(source).imports.filter((entry) => entry.kind === "import-statement").map((entry) => entry.path);
|
|
119
|
+
} catch {}
|
|
120
|
+
}
|
|
121
|
+
return [...source.matchAll(IMPORT_TEXT)].map((found) => found[2]);
|
|
122
|
+
}
|
|
123
|
+
function createSplitReader(roots) {
|
|
124
|
+
const files = new Map;
|
|
125
|
+
const inside = (file) => !file.includes(sep + "node_modules" + sep) && roots.some((root) => file.startsWith(root + sep)) && SOURCE.test(file);
|
|
126
|
+
const resolve = (specifier, from) => {
|
|
127
|
+
if (!/^[./#]/.test(specifier))
|
|
128
|
+
return;
|
|
129
|
+
try {
|
|
130
|
+
return Bun.resolveSync(specifier, dirname(from));
|
|
131
|
+
} catch {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const load = (file) => {
|
|
136
|
+
let held = files.get(file);
|
|
137
|
+
if (!held) {
|
|
138
|
+
held = readFile(file, "utf8").then((source) => ({
|
|
139
|
+
read: readKeys(source),
|
|
140
|
+
imports: importsOf(source, file).flatMap((specifier) => resolve(specifier, file) ?? [])
|
|
141
|
+
}), () => {
|
|
142
|
+
return;
|
|
143
|
+
});
|
|
144
|
+
files.set(file, held);
|
|
145
|
+
}
|
|
146
|
+
return held;
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
async read(entries) {
|
|
150
|
+
const keys = new Set;
|
|
151
|
+
const dynamic = [];
|
|
152
|
+
const seen = new Set;
|
|
153
|
+
const queue = [...entries];
|
|
154
|
+
for (let file = queue.shift();file !== undefined; file = queue.shift()) {
|
|
155
|
+
if (seen.has(file))
|
|
156
|
+
continue;
|
|
157
|
+
seen.add(file);
|
|
158
|
+
const loaded = await load(file);
|
|
159
|
+
if (!loaded)
|
|
160
|
+
continue;
|
|
161
|
+
for (const key of loaded.read.keys)
|
|
162
|
+
keys.add(key);
|
|
163
|
+
if (loaded.read.dynamic)
|
|
164
|
+
dynamic.push(file);
|
|
165
|
+
queue.push(...loaded.imports.filter((next) => !seen.has(next) && inside(next)));
|
|
166
|
+
}
|
|
167
|
+
return { keys, dynamic };
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function flatten(records, ancestors = []) {
|
|
172
|
+
return records.flatMap((record) => [
|
|
173
|
+
{ record, chain: [...ancestors, record] },
|
|
174
|
+
...flatten(record.children, [...ancestors, record])
|
|
175
|
+
]);
|
|
176
|
+
}
|
|
177
|
+
var slotFiles = (record) => Object.values(record.slots ?? {}).flatMap((slot) => [
|
|
178
|
+
...slot.default ? [slot.default] : [],
|
|
179
|
+
...flatten(slot.routes).map((entry) => entry.record.file)
|
|
180
|
+
]);
|
|
181
|
+
var filesOf = (chain) => chain.flatMap((record) => [
|
|
182
|
+
record.file,
|
|
183
|
+
...[record.error, record.template, record.notFound, record.outletNotFound, record.pending].filter((file) => file !== undefined),
|
|
184
|
+
...slotFiles(record)
|
|
185
|
+
]);
|
|
186
|
+
function errorFile(hamur) {
|
|
187
|
+
for (const { srcDir } of [hamur.options, ...hamur.options.layers]) {
|
|
188
|
+
for (const extension of hamur.adapter.extensions)
|
|
189
|
+
if (existsSync(join(srcDir, "error" + extension)))
|
|
190
|
+
return join(srcDir, "error" + extension);
|
|
191
|
+
}
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
async function planSplit(hamur) {
|
|
195
|
+
const { options } = hamur;
|
|
196
|
+
const roots = [options.rootDir, ...options.layers.map((layer) => layer.rootDir)];
|
|
197
|
+
const reader = createSplitReader(roots);
|
|
198
|
+
const error = errorFile(hamur);
|
|
199
|
+
const sharedFiles = [
|
|
200
|
+
...hamur.layouts.map((layout) => layout.file),
|
|
201
|
+
...hamur.appRoot ? [hamur.appRoot] : [],
|
|
202
|
+
...hamur.notFound ? [hamur.notFound] : [],
|
|
203
|
+
...error ? [error] : []
|
|
204
|
+
];
|
|
205
|
+
const shared = await reader.read(sharedFiles);
|
|
206
|
+
const routes = new Map;
|
|
207
|
+
for (const { record, chain } of flatten(hamur.routes)) {
|
|
208
|
+
const base = baseOf(record.name);
|
|
209
|
+
if (routes.has(base))
|
|
210
|
+
continue;
|
|
211
|
+
const own = await reader.read(filesOf(chain));
|
|
212
|
+
routes.set(base, { keys: new Set([...own.keys].filter((key) => !shared.keys.has(key))), dynamic: own.dynamic });
|
|
213
|
+
}
|
|
214
|
+
return { shared, routes };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// packages/i18n/src/build/drop.ts
|
|
218
|
+
function keepMatcher(glob) {
|
|
219
|
+
const source = glob.split(/(\*\*|\*)/).map((part) => part === "**" ? ".*" : part === "*" ? "[^.]*" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
|
|
220
|
+
return new RegExp("^" + source + "$");
|
|
221
|
+
}
|
|
222
|
+
async function readClientInputs(inputs, rootDir) {
|
|
223
|
+
const keys = new Set;
|
|
224
|
+
let dynamic;
|
|
225
|
+
for (const input of inputs) {
|
|
226
|
+
const file = [resolve(input), resolve(rootDir, input)].find((path) => existsSync2(path));
|
|
227
|
+
if (!file || file.includes(sep2 + "node_modules" + sep2) || !SOURCE.test(file))
|
|
228
|
+
continue;
|
|
229
|
+
const source = await readFile2(file, "utf8").catch(() => {
|
|
230
|
+
return;
|
|
231
|
+
});
|
|
232
|
+
if (source === undefined)
|
|
233
|
+
continue;
|
|
234
|
+
const read = readKeys(source);
|
|
235
|
+
for (const key of read.keys)
|
|
236
|
+
keys.add(key);
|
|
237
|
+
if (read.at !== undefined && !dynamic)
|
|
238
|
+
dynamic = { file, line: source.slice(0, read.at).split(`
|
|
239
|
+
`).length };
|
|
240
|
+
}
|
|
241
|
+
return { keys, ...dynamic ? { dynamic } : {} };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// packages/i18n/src/build/messages.ts
|
|
245
|
+
import { createHash } from "crypto";
|
|
246
|
+
import { readdir, readFile as readFile3, realpath } from "fs/promises";
|
|
247
|
+
import { basename, join as join2, relative as relative2 } from "path";
|
|
248
|
+
import { DiagnosticError as DiagnosticError5, addBunPlugin, addTemplate as addTemplate2, diagnostic as diagnostic2, useLogger as useLogger2 } from "hamur/kit";
|
|
249
|
+
|
|
250
|
+
// packages/i18n/src/compiler/mf2.ts
|
|
251
|
+
import { DiagnosticError } from "hamur/kit";
|
|
252
|
+
var PRELUDE_CORE = String.raw`const R = (a, k) => {
|
|
253
|
+
let v = Object.hasOwn(a, k) ? a[k] : undefined;
|
|
254
|
+
if (v === undefined) for (const n of Object.keys(a)) if (n.normalize("NFC") === k) v = a[n];
|
|
255
|
+
return v === undefined ? { x: 1, t: "{$" + k + "}" } : { v, t: "{$" + k + "}" };
|
|
256
|
+
};
|
|
257
|
+
const D = (x, n) => ({ ...x, t: "{$" + n + "}" });
|
|
258
|
+
const O = (x) => (x.x ? undefined : x.v);
|
|
259
|
+
const T = (x, f) => {
|
|
260
|
+
if (x.x) return x.t;
|
|
261
|
+
try {
|
|
262
|
+
const v = x.v;
|
|
263
|
+
if (x.k === "number" || x.k === "integer") return f.n(v, x.i);
|
|
264
|
+
if (x.k === "datetime" || x.k === "date" || x.k === "time") return f.d(x.d, x.i);
|
|
265
|
+
if (x.k === "string") return v;
|
|
266
|
+
return typeof v === "number" || typeof v === "bigint" ? f.n(v) : v instanceof Date ? f.d(v) : String(v);
|
|
267
|
+
} catch {
|
|
268
|
+
return x.t;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
`;
|
|
272
|
+
var PRELUDE_OPTIONS = String.raw`const en = (l) => (v) => (l.includes(String(v)) ? String(v) : undefined);
|
|
273
|
+
const ds = (v, lo, hi) => {
|
|
274
|
+
v = String(v);
|
|
275
|
+
if (!/^(0|[1-9][0-9]?)$/.test(v)) return undefined;
|
|
276
|
+
v = Number(v);
|
|
277
|
+
return v >= lo && v <= hi ? v : undefined;
|
|
278
|
+
};
|
|
279
|
+
`;
|
|
280
|
+
var PRELUDE_STRING = String.raw`const S = (x, t) => (x === undefined || x.x ? { x: 1, t } : { k: "string", v: String(x.v), t });
|
|
281
|
+
`;
|
|
282
|
+
var PRELUDE_NUMBER = String.raw`const NUM = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/;
|
|
283
|
+
const NO = {
|
|
284
|
+
select: en(["plural", "ordinal", "exact"]),
|
|
285
|
+
signDisplay: en(["auto", "always", "exceptZero", "negative", "never"]),
|
|
286
|
+
useGrouping: en(["auto", "always", "never", "min2"]),
|
|
287
|
+
minimumIntegerDigits: (v) => ds(v, 1, 21),
|
|
288
|
+
minimumFractionDigits: (v) => ds(v, 0, 99),
|
|
289
|
+
maximumFractionDigits: (v) => ds(v, 0, 99),
|
|
290
|
+
minimumSignificantDigits: (v) => ds(v, 1, 21),
|
|
291
|
+
maximumSignificantDigits: (v) => ds(v, 1, 21),
|
|
292
|
+
trailingZeroDisplay: en(["auto", "stripIfInteger"]),
|
|
293
|
+
roundingPriority: en(["auto", "morePrecision", "lessPrecision"]),
|
|
294
|
+
roundingIncrement: (v) => ([1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000].includes(Number(v)) ? Number(v) : undefined),
|
|
295
|
+
roundingMode: en(["ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven"]),
|
|
296
|
+
};
|
|
297
|
+
const NK = ["select", "signDisplay", "useGrouping", "minimumIntegerDigits", "maximumSignificantDigits"];
|
|
298
|
+
const NI = (fn, x, o, t) => {
|
|
299
|
+
const bad = { x: 1, t };
|
|
300
|
+
if (x === undefined || x.x || x.k === "datetime" || x.k === "date" || x.k === "time") return bad;
|
|
301
|
+
let v = x.v;
|
|
302
|
+
if (typeof v === "string" && NUM.test(v)) v = Number(v);
|
|
303
|
+
if (typeof v !== "number" && typeof v !== "bigint") return bad;
|
|
304
|
+
const keys = fn === "integer" ? NK : Object.keys(NO);
|
|
305
|
+
const r = {};
|
|
306
|
+
let ns = x.n || 0;
|
|
307
|
+
if (x.r) {
|
|
308
|
+
for (const k of keys) if (k !== "select" && x.r[k] !== undefined) r[k] = x.r[k];
|
|
309
|
+
if (x.r.select !== undefined) ns = 1;
|
|
310
|
+
}
|
|
311
|
+
for (const k of keys) {
|
|
312
|
+
if (!Object.hasOwn(o, k)) continue;
|
|
313
|
+
const raw = o[k];
|
|
314
|
+
if (k === "select") {
|
|
315
|
+
if (Array.isArray(raw)) ns = 1;
|
|
316
|
+
else if (NO.select(raw) !== undefined) {
|
|
317
|
+
r.select = NO.select(raw);
|
|
318
|
+
ns = 0;
|
|
319
|
+
}
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
const val = NO[k](Array.isArray(raw) ? raw[0] : raw);
|
|
323
|
+
if (val !== undefined) r[k] = val;
|
|
324
|
+
}
|
|
325
|
+
if (fn === "integer") v = typeof v === "bigint" ? v : Math.trunc(v) || 0;
|
|
326
|
+
const i = {};
|
|
327
|
+
for (const k in r) if (k !== "select") i[k] = k === "useGrouping" && r[k] === "never" ? false : r[k];
|
|
328
|
+
if (fn === "integer") i.maximumFractionDigits = 0;
|
|
329
|
+
return { k: fn, v, r, i, n: ns, t };
|
|
330
|
+
};
|
|
331
|
+
`;
|
|
332
|
+
var PRELUDE_DATE = String.raw`const DTL = /^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]{1,3})?(Z|[+-]((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)?$/;
|
|
333
|
+
const dv = (v) => {
|
|
334
|
+
if (v instanceof Date) return isNaN(v.getTime()) ? undefined : { ms: v.getTime() };
|
|
335
|
+
if (typeof v === "number") return isFinite(v) ? { ms: v } : undefined;
|
|
336
|
+
if (typeof v !== "string" || !DTL.test(v)) return undefined;
|
|
337
|
+
const at = v.indexOf("T");
|
|
338
|
+
const date = at < 0 ? v : v.slice(0, at);
|
|
339
|
+
let time = at < 0 ? "00:00:00" : v.slice(at + 1);
|
|
340
|
+
let om;
|
|
341
|
+
const z = /(Z|[+-][0-9]{2}:[0-9]{2})$/.exec(time);
|
|
342
|
+
if (z) {
|
|
343
|
+
time = time.slice(0, -z[1].length);
|
|
344
|
+
om = z[1] === "Z" ? 0 : (z[1][0] === "-" ? -1 : 1) * (Number(z[1].slice(1, 3)) * 60 + Number(z[1].slice(4)));
|
|
345
|
+
}
|
|
346
|
+
const ms = Date.parse(date + "T" + time + "Z");
|
|
347
|
+
if (isNaN(ms)) return undefined;
|
|
348
|
+
return om === undefined ? { ms, fl: 1 } : { ms: ms - om * 60000, om };
|
|
349
|
+
};
|
|
350
|
+
const DO = {
|
|
351
|
+
fields: en(["weekday", "day-weekday", "month-day", "month-day-weekday", "year-month-day", "year-month-day-weekday"]),
|
|
352
|
+
length: en(["long", "medium", "short"]),
|
|
353
|
+
precision: en(["hour", "minute", "second"]),
|
|
354
|
+
timeZoneStyle: en(["long", "short"]),
|
|
355
|
+
timeZone: (v) => {
|
|
356
|
+
v = String(v);
|
|
357
|
+
if (v === "input" || v === "UTC") return v;
|
|
358
|
+
try {
|
|
359
|
+
new Intl.DateTimeFormat("en", { timeZone: v });
|
|
360
|
+
return v;
|
|
361
|
+
} catch {
|
|
362
|
+
return undefined;
|
|
363
|
+
}
|
|
364
|
+
},
|
|
365
|
+
hour12: en(["true", "false"]),
|
|
366
|
+
calendar: (v) => {
|
|
367
|
+
v = String(v);
|
|
368
|
+
try {
|
|
369
|
+
new Intl.DateTimeFormat("en", { calendar: v });
|
|
370
|
+
return v;
|
|
371
|
+
} catch {
|
|
372
|
+
return undefined;
|
|
373
|
+
}
|
|
374
|
+
},
|
|
375
|
+
};
|
|
376
|
+
const DA = { dateFields: "fields", dateLength: "length", timePrecision: "precision" };
|
|
377
|
+
const DT = (fn, x, o, t) => {
|
|
378
|
+
const bad = { x: 1, t };
|
|
379
|
+
if (x === undefined || x.x || x.k === "number" || x.k === "integer") return bad;
|
|
380
|
+
const d = x.k === "datetime" || x.k === "date" || x.k === "time" ? { ms: x.v, om: x.om, fl: x.fl } : dv(x.v);
|
|
381
|
+
if (!d) return bad;
|
|
382
|
+
const r = {};
|
|
383
|
+
if (x.r) for (const k of ["timeZone", "hour12", "calendar"]) if (x.r[k] !== undefined) r[k] = x.r[k];
|
|
384
|
+
for (const n of Object.keys(o)) {
|
|
385
|
+
const key = DA[n] || n;
|
|
386
|
+
const raw = o[n];
|
|
387
|
+
const over = key === "timeZone" || key === "hour12" || key === "calendar";
|
|
388
|
+
if (Array.isArray(raw) && !over) continue;
|
|
389
|
+
const val = DO[key](Array.isArray(raw) ? raw[0] : raw);
|
|
390
|
+
if (val !== undefined) r[key] = val;
|
|
391
|
+
}
|
|
392
|
+
const i = {};
|
|
393
|
+
if (fn !== "time") {
|
|
394
|
+
const p = (r.fields || "year-month-day").split("-");
|
|
395
|
+
const l = r.length || "medium";
|
|
396
|
+
if (p.includes("year")) i.year = l === "short" ? "2-digit" : "numeric";
|
|
397
|
+
if (p.includes("month")) i.month = l === "long" ? "long" : l === "medium" ? "short" : "numeric";
|
|
398
|
+
if (p.includes("day")) i.day = "numeric";
|
|
399
|
+
if (p.includes("weekday")) i.weekday = l === "long" ? "long" : "short";
|
|
400
|
+
}
|
|
401
|
+
if (fn !== "date") {
|
|
402
|
+
const p = r.precision || "minute";
|
|
403
|
+
i.hour = "numeric";
|
|
404
|
+
if (p !== "hour") i.minute = "2-digit";
|
|
405
|
+
if (p === "second") i.second = "2-digit";
|
|
406
|
+
}
|
|
407
|
+
if (r.timeZoneStyle) i.timeZoneName = r.timeZoneStyle;
|
|
408
|
+
if (r.hour12 !== undefined) i.hour12 = r.hour12 === "true";
|
|
409
|
+
if (r.calendar) i.calendar = r.calendar;
|
|
410
|
+
let shown = d.ms;
|
|
411
|
+
if (r.timeZone === "UTC") i.timeZone = "UTC";
|
|
412
|
+
else if (r.timeZone === "input") {
|
|
413
|
+
if (d.om !== undefined) {
|
|
414
|
+
i.timeZone = "UTC";
|
|
415
|
+
shown += d.om * 60000;
|
|
416
|
+
} else if (d.fl) i.timeZone = "UTC";
|
|
417
|
+
} else if (r.timeZone) i.timeZone = r.timeZone;
|
|
418
|
+
else if (d.fl) i.timeZone = "UTC";
|
|
419
|
+
return { k: fn, v: d.ms, om: d.om, fl: d.fl, r, i, d: shown, t };
|
|
420
|
+
};
|
|
421
|
+
`;
|
|
422
|
+
var PRELUDE_SELECT = String.raw`const CAT = { zero: "zero", one: "one", two: "two", few: "few", many: "many", other: "other" };
|
|
423
|
+
const K = (x, f) => {
|
|
424
|
+
if (x.x) return [];
|
|
425
|
+
if (x.k === "string") return [x.v.normalize("NFC")];
|
|
426
|
+
if ((x.k !== "number" && x.k !== "integer") || x.n) return [];
|
|
427
|
+
const n = typeof x.v === "bigint" ? Number(x.v) : x.v;
|
|
428
|
+
const s = x.r.select || "plural";
|
|
429
|
+
const keys = [String(n)];
|
|
430
|
+
if (s !== "exact") keys.push(f.p(n, 0, CAT, s === "ordinal"));
|
|
431
|
+
return keys;
|
|
432
|
+
};
|
|
433
|
+
const W = (s, vs) => {
|
|
434
|
+
let best;
|
|
435
|
+
let rank;
|
|
436
|
+
for (const [k, b] of vs) {
|
|
437
|
+
const r = [];
|
|
438
|
+
for (let i = 0; i < s.length; i++) {
|
|
439
|
+
const j = k[i] === null ? s[i].length : s[i].indexOf(k[i]);
|
|
440
|
+
if (j < 0) break;
|
|
441
|
+
r.push(j);
|
|
442
|
+
}
|
|
443
|
+
if (r.length < s.length) continue;
|
|
444
|
+
let better = rank === undefined;
|
|
445
|
+
for (let i = 0; !better && i < r.length && r[i] <= rank[i]; i++) better = r[i] < rank[i];
|
|
446
|
+
if (better) {
|
|
447
|
+
rank = r;
|
|
448
|
+
best = b;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return best();
|
|
452
|
+
};
|
|
453
|
+
`;
|
|
454
|
+
var q = JSON.stringify;
|
|
455
|
+
var literalFallback = (value) => "{|" + value.replace(/[\\|]/g, "\\$&") + "|}";
|
|
456
|
+
function argKind(call) {
|
|
457
|
+
if (call?.name === "number" || call?.name === "integer")
|
|
458
|
+
return "number";
|
|
459
|
+
if (call?.name === "datetime" || call?.name === "date" || call?.name === "time")
|
|
460
|
+
return "date";
|
|
461
|
+
return "text";
|
|
462
|
+
}
|
|
463
|
+
function compileMf2Catalog(messages, language, options = {}) {
|
|
464
|
+
const entries = [];
|
|
465
|
+
const args = {};
|
|
466
|
+
const tags = {};
|
|
467
|
+
const needs = { rich: false, core: false, opt: false, str: false, num: false, date: false, sel: false };
|
|
468
|
+
const where = (key) => {
|
|
469
|
+
const file = typeof options.file === "function" ? options.file(key) : options.file ?? "locales/" + language + ".json";
|
|
470
|
+
return file + " " + q(key);
|
|
471
|
+
};
|
|
472
|
+
for (const [key, source] of Object.entries(messages)) {
|
|
473
|
+
let message;
|
|
474
|
+
try {
|
|
475
|
+
message = parseMf2(source);
|
|
476
|
+
} catch (error) {
|
|
477
|
+
if (error instanceof MessageSyntaxError)
|
|
478
|
+
throw new DiagnosticError("HAMUR_E5807", error.message, { at: where(key) });
|
|
479
|
+
throw error;
|
|
480
|
+
}
|
|
481
|
+
const kinds = {};
|
|
482
|
+
const scope = new Map;
|
|
483
|
+
let next = 0;
|
|
484
|
+
let dynamic = message.declarations.length > 0 || message.matcher !== undefined;
|
|
485
|
+
const use = (name, kind) => {
|
|
486
|
+
const known = kinds[name];
|
|
487
|
+
if (known === undefined || known === "text")
|
|
488
|
+
kinds[name] = kind;
|
|
489
|
+
else if (kind !== "text" && known !== kind)
|
|
490
|
+
throw new DiagnosticError("HAMUR_E5808", "argument " + q(name) + " is used as both " + known + " and " + kind, {
|
|
491
|
+
at: where(key)
|
|
492
|
+
});
|
|
493
|
+
};
|
|
494
|
+
const ref = (name, kind) => {
|
|
495
|
+
const id = scope.get(name);
|
|
496
|
+
if (id !== undefined)
|
|
497
|
+
return id;
|
|
498
|
+
use(name, kind);
|
|
499
|
+
needs.core = true;
|
|
500
|
+
return "R(a, " + q(name) + ")";
|
|
501
|
+
};
|
|
502
|
+
const expression = ({ operand, call }) => {
|
|
503
|
+
let x = "undefined";
|
|
504
|
+
let t = "{:" + (call?.name ?? "") + "}";
|
|
505
|
+
if (operand?.kind === "literal") {
|
|
506
|
+
t = literalFallback(operand.value);
|
|
507
|
+
x = "{ v: " + q(operand.value) + ", t: " + q(t) + " }";
|
|
508
|
+
} else if (operand) {
|
|
509
|
+
t = "{$" + operand.name + "}";
|
|
510
|
+
x = ref(operand.name, argKind(call));
|
|
511
|
+
}
|
|
512
|
+
if (!call)
|
|
513
|
+
return x;
|
|
514
|
+
const known = FUNCTIONS[call.name];
|
|
515
|
+
const given = call.options.filter((option) => known.includes(option.name)).map((option) => q(option.name) + ": " + (option.value.kind === "literal" ? q(option.value.value) : "[O(" + ref(option.value.name, "text") + ")]"));
|
|
516
|
+
const opts = "{ " + given.join(", ") + " }";
|
|
517
|
+
needs.core = true;
|
|
518
|
+
if (call.name === "string") {
|
|
519
|
+
needs.str = true;
|
|
520
|
+
return "S(" + x + ", " + q(t) + ")";
|
|
521
|
+
}
|
|
522
|
+
if (call.name === "number" || call.name === "integer") {
|
|
523
|
+
needs.opt = needs.num = true;
|
|
524
|
+
return "NI(" + q(call.name) + ", " + x + ", " + opts + ", " + q(t) + ")";
|
|
525
|
+
}
|
|
526
|
+
needs.opt = needs.date = true;
|
|
527
|
+
return "DT(" + q(call.name) + ", " + x + ", " + opts + ", " + q(t) + ")";
|
|
528
|
+
};
|
|
529
|
+
const names = new Set;
|
|
530
|
+
const pattern = (parts) => {
|
|
531
|
+
let pieces = [];
|
|
532
|
+
let text;
|
|
533
|
+
const open = [];
|
|
534
|
+
const flush = () => {
|
|
535
|
+
if (text !== undefined)
|
|
536
|
+
pieces.push(q(text));
|
|
537
|
+
text = undefined;
|
|
538
|
+
};
|
|
539
|
+
const closeTop = () => {
|
|
540
|
+
const frame = open.pop();
|
|
541
|
+
const children = "J(" + pieces.join(", ") + ")";
|
|
542
|
+
pieces = frame.pieces;
|
|
543
|
+
pieces.push("{ tag: " + q(frame.name) + ", children: " + children + " }");
|
|
544
|
+
};
|
|
545
|
+
const rich = parts.some((part) => part.type === "markup");
|
|
546
|
+
if (rich)
|
|
547
|
+
needs.rich = dynamic = true;
|
|
548
|
+
for (const part of parts) {
|
|
549
|
+
if (part.type === "markup") {
|
|
550
|
+
names.add(part.name);
|
|
551
|
+
flush();
|
|
552
|
+
if (part.kind === "open") {
|
|
553
|
+
open.push({ name: part.name, pieces });
|
|
554
|
+
pieces = [];
|
|
555
|
+
} else if (part.kind === "standalone")
|
|
556
|
+
pieces.push("{ tag: " + q(part.name) + ", children: [] }");
|
|
557
|
+
else if (open.some((frame) => frame.name === part.name)) {
|
|
558
|
+
while (open[open.length - 1].name !== part.name)
|
|
559
|
+
closeTop();
|
|
560
|
+
closeTop();
|
|
561
|
+
}
|
|
562
|
+
} else if (part.type === "text")
|
|
563
|
+
text = (text ?? "") + part.value;
|
|
564
|
+
else if (part.type === "expression") {
|
|
565
|
+
const { operand, call } = part.expression;
|
|
566
|
+
if (!call && operand?.kind === "literal")
|
|
567
|
+
text = (text ?? "") + operand.value;
|
|
568
|
+
else {
|
|
569
|
+
flush();
|
|
570
|
+
dynamic = true;
|
|
571
|
+
needs.core = true;
|
|
572
|
+
pieces.push("T(" + expression(part.expression) + ", f)");
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
flush();
|
|
577
|
+
while (open.length)
|
|
578
|
+
closeTop();
|
|
579
|
+
if (rich)
|
|
580
|
+
return "J(" + pieces.join(", ") + ")";
|
|
581
|
+
return pieces.length ? pieces.join(" + ") : '""';
|
|
582
|
+
};
|
|
583
|
+
const lines = [];
|
|
584
|
+
for (const declaration of message.declarations) {
|
|
585
|
+
const id = "d" + next++;
|
|
586
|
+
lines.push("const " + id + " = D(" + expression(declaration.expression) + ", " + q(declaration.name) + ");");
|
|
587
|
+
scope.set(declaration.name, id);
|
|
588
|
+
needs.core = true;
|
|
589
|
+
}
|
|
590
|
+
let body;
|
|
591
|
+
const { matcher } = message;
|
|
592
|
+
if (matcher) {
|
|
593
|
+
needs.sel = true;
|
|
594
|
+
const selectors = matcher.selectors.map((selector) => "K(" + scope.get(selector.name) + ", f)");
|
|
595
|
+
const variants = matcher.variants.map((variant) => "[[" + variant.keys.map((k) => k === null ? "null" : q(k.normalize("NFC"))).join(", ") + "], () => " + pattern(variant.parts) + "]");
|
|
596
|
+
body = "W([" + selectors.join(", ") + "], [" + variants.join(", ") + "])";
|
|
597
|
+
} else
|
|
598
|
+
body = pattern(message.parts);
|
|
599
|
+
args[key] = kinds;
|
|
600
|
+
if (names.size)
|
|
601
|
+
tags[key] = [...names];
|
|
602
|
+
let value;
|
|
603
|
+
if (!dynamic)
|
|
604
|
+
value = body;
|
|
605
|
+
else if (lines.length === 0)
|
|
606
|
+
value = "(a, f) => " + body;
|
|
607
|
+
else
|
|
608
|
+
value = "(a, f) => { " + lines.join(" ") + " return " + body + "; }";
|
|
609
|
+
entries.push(" " + q(key) + ": " + value + ",");
|
|
610
|
+
}
|
|
611
|
+
const prelude = [
|
|
612
|
+
needs.rich ? `const J = (...p) => p.flat();
|
|
613
|
+
` : "",
|
|
614
|
+
needs.core ? PRELUDE_CORE : "",
|
|
615
|
+
needs.opt ? PRELUDE_OPTIONS : "",
|
|
616
|
+
needs.str ? PRELUDE_STRING : "",
|
|
617
|
+
needs.num ? PRELUDE_NUMBER : "",
|
|
618
|
+
needs.date ? PRELUDE_DATE : "",
|
|
619
|
+
needs.sel ? PRELUDE_SELECT : ""
|
|
620
|
+
].join("");
|
|
621
|
+
const body = entries.length ? `export default {
|
|
622
|
+
` + entries.join(`
|
|
623
|
+
`) + `
|
|
624
|
+
};` : "export default {};";
|
|
625
|
+
return { code: prelude + body + `
|
|
626
|
+
`, args, tags };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// packages/i18n/src/compiler/compile.ts
|
|
630
|
+
import { DiagnosticError as DiagnosticError2 } from "hamur/kit";
|
|
631
|
+
var q2 = JSON.stringify;
|
|
632
|
+
function hasTag(nodes) {
|
|
633
|
+
return nodes.some((node) => node.type === "tag" || (node.type === "plural" || node.type === "select") && node.cases.some(({ body }) => hasTag(body)));
|
|
634
|
+
}
|
|
635
|
+
function collectTags(nodes, into) {
|
|
636
|
+
for (const node of nodes) {
|
|
637
|
+
if (node.type === "tag") {
|
|
638
|
+
into.add(node.name);
|
|
639
|
+
collectTags(node.children, into);
|
|
640
|
+
} else if (node.type === "plural" || node.type === "select")
|
|
641
|
+
for (const { body } of node.cases)
|
|
642
|
+
collectTags(body, into);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function categoriesOf(language, type) {
|
|
646
|
+
return new Set(new Intl.PluralRules(language, { type }).resolvedOptions().pluralCategories);
|
|
647
|
+
}
|
|
648
|
+
function compileCatalog(messages, language, options = {}) {
|
|
649
|
+
if (options.syntax === "mf2")
|
|
650
|
+
return compileMf2Catalog(messages, language, options);
|
|
651
|
+
const entries = [];
|
|
652
|
+
const args = {};
|
|
653
|
+
const tags = {};
|
|
654
|
+
const helpers = { g: false, v: false, j: false, m: false };
|
|
655
|
+
const where = (key) => {
|
|
656
|
+
const file = typeof options.file === "function" ? options.file(key) : options.file ?? `locales/${language}.json`;
|
|
657
|
+
return `${file} ${q2(key)}`;
|
|
658
|
+
};
|
|
659
|
+
const cardinal = categoriesOf(language, "cardinal");
|
|
660
|
+
const ordinal = categoriesOf(language, "ordinal");
|
|
661
|
+
for (const [key, source] of Object.entries(messages)) {
|
|
662
|
+
let nodes;
|
|
663
|
+
try {
|
|
664
|
+
nodes = parseMessage(source);
|
|
665
|
+
} catch (error) {
|
|
666
|
+
if (error instanceof MessageSyntaxError)
|
|
667
|
+
throw new DiagnosticError2("HAMUR_E5807", error.message, { at: where(key) });
|
|
668
|
+
throw error;
|
|
669
|
+
}
|
|
670
|
+
const kinds = {};
|
|
671
|
+
const use = (name, kind) => {
|
|
672
|
+
const known = kinds[name];
|
|
673
|
+
if (known === undefined || known === "text")
|
|
674
|
+
kinds[name] = kind;
|
|
675
|
+
else if (kind !== "text" && known !== kind)
|
|
676
|
+
throw new DiagnosticError2("HAMUR_E5808", `argument ${q2(name)} is used as both ${known} and ${kind}`, {
|
|
677
|
+
at: where(key)
|
|
678
|
+
});
|
|
679
|
+
};
|
|
680
|
+
const ref = (name) => {
|
|
681
|
+
helpers.g = true;
|
|
682
|
+
return `g(a, ${q2(name)})`;
|
|
683
|
+
};
|
|
684
|
+
const emit = (list, scope) => list.map((node) => {
|
|
685
|
+
switch (node.type) {
|
|
686
|
+
case "text":
|
|
687
|
+
return q2(node.value);
|
|
688
|
+
case "pound":
|
|
689
|
+
scope.state.used = true;
|
|
690
|
+
return scope.pound;
|
|
691
|
+
case "arg":
|
|
692
|
+
use(node.name, "text");
|
|
693
|
+
helpers.v = true;
|
|
694
|
+
return `v(${ref(node.name)}, f)`;
|
|
695
|
+
case "number": {
|
|
696
|
+
use(node.name, "number");
|
|
697
|
+
const opts = {
|
|
698
|
+
decimal: "{}",
|
|
699
|
+
integer: "{ maximumFractionDigits: 0 }",
|
|
700
|
+
percent: '{ style: "percent" }',
|
|
701
|
+
currency: `{ style: "currency", currency: ${q2(node.currency)} }`,
|
|
702
|
+
skeleton: q2(node.options)
|
|
703
|
+
}[node.style];
|
|
704
|
+
if (node.scale === undefined)
|
|
705
|
+
return `f.n(${ref(node.name)}, ${opts})`;
|
|
706
|
+
helpers.m = true;
|
|
707
|
+
return `f.n(m(${ref(node.name)}, ${node.scale}), ${opts})`;
|
|
708
|
+
}
|
|
709
|
+
case "tag":
|
|
710
|
+
return `{ tag: ${q2(node.name)}, children: ${join(node.children, scope)} }`;
|
|
711
|
+
case "date":
|
|
712
|
+
use(node.name, "date");
|
|
713
|
+
return `f.d(${ref(node.name)}, { ${node.kind === "date" ? "dateStyle" : "timeStyle"}: ${q2(node.style)} })`;
|
|
714
|
+
case "select": {
|
|
715
|
+
use(node.name, "select");
|
|
716
|
+
const cases = node.cases.map(({ key: label, body }) => `${q2(label)}: ${caseBody(body, { pound: scope.pound, state: scope.state, depth: scope.depth }, false)}`);
|
|
717
|
+
return `f.s(${ref(node.name)}, { ${cases.join(", ")} })`;
|
|
718
|
+
}
|
|
719
|
+
case "plural": {
|
|
720
|
+
use(node.name, "number");
|
|
721
|
+
const known = node.ordinal ? ordinal : cardinal;
|
|
722
|
+
for (const { key: label } of node.cases) {
|
|
723
|
+
if (label.startsWith("=") || label === "other" || known.has(label))
|
|
724
|
+
continue;
|
|
725
|
+
options.warn?.(`${where(key)}: plural case ${q2(label)} never applies to ${language}`);
|
|
726
|
+
}
|
|
727
|
+
const cases = node.cases.map(({ key: label, body }) => {
|
|
728
|
+
const own = { pound: `c${scope.depth}`, state: { used: false }, depth: scope.depth + 1 };
|
|
729
|
+
return `${q2(label)}: ${caseBody(body, own, true)}`;
|
|
730
|
+
});
|
|
731
|
+
return `f.p(${ref(node.name)}, ${node.offset}, { ${cases.join(", ")} }, ${node.ordinal})`;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
const join = (list, scope) => {
|
|
736
|
+
helpers.j = true;
|
|
737
|
+
return `J(${emit(list, scope).join(", ")})`;
|
|
738
|
+
};
|
|
739
|
+
const caseBody = (body, scope, takesCount) => {
|
|
740
|
+
const parts = emit(body, scope);
|
|
741
|
+
let text = parts.length === 0 ? '""' : parts.join(" + ");
|
|
742
|
+
if (hasTag(body)) {
|
|
743
|
+
helpers.j = true;
|
|
744
|
+
text = `J(${parts.join(", ")})`;
|
|
745
|
+
}
|
|
746
|
+
if (body.every((node) => node.type === "text"))
|
|
747
|
+
return text;
|
|
748
|
+
return takesCount && scope.state.used ? `(${scope.pound}) => ${text}` : `() => ${text}`;
|
|
749
|
+
};
|
|
750
|
+
const top = { pound: undefined, state: { used: false }, depth: 0 };
|
|
751
|
+
const rich = hasTag(nodes);
|
|
752
|
+
const parts = emit(nodes, top);
|
|
753
|
+
args[key] = kinds;
|
|
754
|
+
if (rich) {
|
|
755
|
+
const names = new Set;
|
|
756
|
+
collectTags(nodes, names);
|
|
757
|
+
tags[key] = [...names];
|
|
758
|
+
helpers.j = true;
|
|
759
|
+
}
|
|
760
|
+
const dynamic = nodes.some((node) => node.type !== "text");
|
|
761
|
+
const body = rich ? `J(${parts.join(", ")})` : parts.length ? parts.join(" + ") : '""';
|
|
762
|
+
entries.push(` ${q2(key)}: ${dynamic ? `(a, f) => ${body}` : body},`);
|
|
763
|
+
}
|
|
764
|
+
const lines = [];
|
|
765
|
+
if (helpers.g)
|
|
766
|
+
lines.push('const g = (a, k) => (k in a && Object.hasOwn(a, k) && a[k] !== undefined ? a[k] : "{" + k + "}");');
|
|
767
|
+
if (helpers.v)
|
|
768
|
+
lines.push('const v = (x, f) => (typeof x === "number" || typeof x === "bigint" ? f.n(x) : x instanceof Date ? f.d(x) : String(x));');
|
|
769
|
+
if (helpers.j)
|
|
770
|
+
lines.push("const J = (...p) => p.flat();");
|
|
771
|
+
if (helpers.m)
|
|
772
|
+
lines.push('const m = (x, s) => (typeof x === "number" || typeof x === "bigint" ? Number(x) * s : x);');
|
|
773
|
+
lines.push(entries.length ? `export default {
|
|
774
|
+
${entries.join(`
|
|
775
|
+
`)}
|
|
776
|
+
};` : "export default {};");
|
|
777
|
+
return { code: `${lines.join(`
|
|
778
|
+
`)}
|
|
779
|
+
`, args, tags };
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// packages/i18n/src/options.ts
|
|
783
|
+
import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
|
|
784
|
+
var CODE = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/;
|
|
785
|
+
var COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
786
|
+
var STRATEGIES = new Set(["prefix_except_default", "prefix", "prefix_and_default", "no_prefix"]);
|
|
787
|
+
var catalogMissing = (catalog) => "i18n.catalog " + JSON.stringify(catalog) + " does not exist";
|
|
788
|
+
var BASE_URL_REMOVED = "i18n.baseUrl was removed: set site.url (HAMUR_SITE_URL at run time)";
|
|
789
|
+
function fail(message) {
|
|
790
|
+
throw new DiagnosticError3("HAMUR_E5806", message);
|
|
791
|
+
}
|
|
792
|
+
function resolveLocale(entry, index) {
|
|
793
|
+
const input = typeof entry === "string" ? { code: entry } : entry;
|
|
794
|
+
const { code } = input;
|
|
795
|
+
if (typeof code !== "string" || !CODE.test(code)) {
|
|
796
|
+
fail(`i18n.locales[${index}].code ${JSON.stringify(code)} must be lower-case letters, digits and "-" (like "fr" or "pt-br")`);
|
|
797
|
+
}
|
|
798
|
+
const language = input.language ?? code;
|
|
799
|
+
try {
|
|
800
|
+
Intl.getCanonicalLocales(language);
|
|
801
|
+
} catch {
|
|
802
|
+
fail(`i18n.locales[${index}].language ${JSON.stringify(language)} is not a BCP 47 language tag`);
|
|
803
|
+
}
|
|
804
|
+
const dir = input.dir ?? (new Intl.Locale(language).getTextInfo().direction === "rtl" ? "rtl" : "ltr");
|
|
805
|
+
const name = input.name ?? new Intl.DisplayNames([language], { type: "language" }).of(language) ?? language;
|
|
806
|
+
return { code, language, dir, name };
|
|
807
|
+
}
|
|
808
|
+
function originOf(value) {
|
|
809
|
+
if (typeof value !== "string")
|
|
810
|
+
return;
|
|
811
|
+
let url;
|
|
812
|
+
try {
|
|
813
|
+
url = new URL(value);
|
|
814
|
+
} catch {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
818
|
+
return;
|
|
819
|
+
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash || /[?#]/.test(value))
|
|
820
|
+
return;
|
|
821
|
+
return url.origin;
|
|
822
|
+
}
|
|
823
|
+
function originExample(value) {
|
|
824
|
+
const host = typeof value === "string" ? value.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/*/, "").replace(/^[^@/?#]*@/, "").split(/[/?#]/)[0] : "";
|
|
825
|
+
try {
|
|
826
|
+
if (host)
|
|
827
|
+
return new URL("https://" + host).origin;
|
|
828
|
+
} catch {
|
|
829
|
+
return "https://example.com";
|
|
830
|
+
}
|
|
831
|
+
return "https://example.com";
|
|
832
|
+
}
|
|
833
|
+
function resolveDomains(entries, locales, strategySet) {
|
|
834
|
+
const given = entries.map((entry) => typeof entry === "string" ? undefined : entry.domain);
|
|
835
|
+
if (given.every((domain) => domain === undefined))
|
|
836
|
+
return;
|
|
837
|
+
const domains = {};
|
|
838
|
+
const byHost = new Map;
|
|
839
|
+
given.forEach((domain, index) => {
|
|
840
|
+
if (domain === undefined)
|
|
841
|
+
return;
|
|
842
|
+
const origin = originOf(domain);
|
|
843
|
+
if (!origin)
|
|
844
|
+
fail(`i18n.locales[${index}].domain ${JSON.stringify(domain)} must be an origin such as ${JSON.stringify(originExample(domain))}`);
|
|
845
|
+
const { code } = locales[index];
|
|
846
|
+
const host = new URL(origin).host;
|
|
847
|
+
const other = byHost.get(host);
|
|
848
|
+
if (other !== undefined)
|
|
849
|
+
fail(`i18n.locales: ${JSON.stringify(other)} and ${JSON.stringify(code)} share the domain ${JSON.stringify(domains[other])}`);
|
|
850
|
+
byHost.set(host, code);
|
|
851
|
+
domains[code] = origin;
|
|
852
|
+
});
|
|
853
|
+
const missing = given.indexOf(undefined);
|
|
854
|
+
if (missing !== -1)
|
|
855
|
+
fail(`i18n.locales[${missing}] has no domain; set domain on every locale or none`);
|
|
856
|
+
if (strategySet)
|
|
857
|
+
fail("i18n.strategy cannot be set with locales[].domain; each domain serves one locale without a prefix");
|
|
858
|
+
return domains;
|
|
859
|
+
}
|
|
860
|
+
function resolveOptions(input) {
|
|
861
|
+
const options = input ?? {};
|
|
862
|
+
if (!Array.isArray(options.locales) || options.locales.length === 0)
|
|
863
|
+
fail("i18n.locales must list at least one locale");
|
|
864
|
+
const locales = options.locales.map(resolveLocale);
|
|
865
|
+
const codes = new Set;
|
|
866
|
+
for (const { code } of locales) {
|
|
867
|
+
if (codes.has(code))
|
|
868
|
+
fail(`i18n.locales: ${JSON.stringify(code)} is listed twice`);
|
|
869
|
+
codes.add(code);
|
|
870
|
+
}
|
|
871
|
+
const defaultLocale = options.defaultLocale;
|
|
872
|
+
if (!codes.has(defaultLocale))
|
|
873
|
+
fail(`i18n.defaultLocale ${JSON.stringify(defaultLocale)} is not in i18n.locales (${[...codes].join(", ")})`);
|
|
874
|
+
const strategy = options.strategy ?? "prefix_except_default";
|
|
875
|
+
if (!STRATEGIES.has(strategy))
|
|
876
|
+
fail(`i18n.strategy ${JSON.stringify(strategy)} is not supported; use "prefix_except_default", "prefix", "prefix_and_default" or "no_prefix"`);
|
|
877
|
+
const redirectToDefaultLocale = options.redirectToDefaultLocale ?? false;
|
|
878
|
+
if (redirectToDefaultLocale && strategy !== "prefix")
|
|
879
|
+
fail('i18n.redirectToDefaultLocale needs strategy "prefix"');
|
|
880
|
+
if (strategy === "no_prefix" && Object.keys(options.pages ?? {}).length > 0)
|
|
881
|
+
fail("i18n.pages needs a prefix strategy; no_prefix keeps one path per page");
|
|
882
|
+
if (Object.hasOwn(options, "baseUrl"))
|
|
883
|
+
fail(BASE_URL_REMOVED);
|
|
884
|
+
const timeZone = options.timeZone ?? "UTC";
|
|
885
|
+
try {
|
|
886
|
+
new Intl.DateTimeFormat("en", { timeZone });
|
|
887
|
+
} catch {
|
|
888
|
+
fail(`i18n.timeZone ${JSON.stringify(timeZone)} is not a time zone this runtime knows`);
|
|
889
|
+
}
|
|
890
|
+
const cookie = options.detect?.cookie ?? "hamur_locale";
|
|
891
|
+
if (cookie !== false && (typeof cookie !== "string" || !COOKIE_NAME.test(cookie)))
|
|
892
|
+
fail(`i18n.detect.cookie ${JSON.stringify(cookie)} is not a valid cookie name`);
|
|
893
|
+
const { redirect } = options.detect ?? {};
|
|
894
|
+
if (redirect !== undefined && redirect !== "root" && redirect !== "all" && redirect !== false)
|
|
895
|
+
fail(`i18n.detect.redirect ${JSON.stringify(redirect)} is not supported; use "root", "all" or false`);
|
|
896
|
+
const fallback = options.fallback ?? "default";
|
|
897
|
+
if (fallback !== "default" && fallback !== false) {
|
|
898
|
+
if (typeof fallback !== "object" || fallback === null || Array.isArray(fallback))
|
|
899
|
+
fail(`i18n.fallback must be "default", false or an object of locale chains (got ${JSON.stringify(fallback)})`);
|
|
900
|
+
for (const [key, chain] of Object.entries(fallback)) {
|
|
901
|
+
if (!codes.has(key))
|
|
902
|
+
fail(`i18n.fallback: ${JSON.stringify(key)} is not in i18n.locales`);
|
|
903
|
+
if (!Array.isArray(chain))
|
|
904
|
+
fail(`i18n.fallback[${JSON.stringify(key)}] must be an array of locale codes`);
|
|
905
|
+
for (const entry of chain) {
|
|
906
|
+
if (!codes.has(entry))
|
|
907
|
+
fail(`i18n.fallback[${JSON.stringify(key)}]: ${JSON.stringify(entry)} is not in i18n.locales`);
|
|
908
|
+
if (entry === key)
|
|
909
|
+
fail(`i18n.fallback[${JSON.stringify(key)}] lists ${JSON.stringify(key)} itself`);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
for (const [name, paths] of Object.entries(options.pages ?? {})) {
|
|
914
|
+
if (paths?.[defaultLocale] === false)
|
|
915
|
+
fail(`i18n.pages.${name}.${defaultLocale}: the default locale always has its page`);
|
|
916
|
+
}
|
|
917
|
+
const missingPage = options.missingPage ?? "404";
|
|
918
|
+
if (missingPage !== "404" && missingPage !== "redirect" && missingPage !== "rewrite")
|
|
919
|
+
fail(`i18n.missingPage must be "404", "redirect" or "rewrite" (got ${JSON.stringify(missingPage)})`);
|
|
920
|
+
const domains = resolveDomains(options.locales, locales, options.strategy !== undefined);
|
|
921
|
+
const localizeLinks = options.localizeLinks ?? true;
|
|
922
|
+
if (typeof localizeLinks !== "boolean")
|
|
923
|
+
fail(`i18n.localizeLinks must be a boolean (got ${JSON.stringify(localizeLinks)})`);
|
|
924
|
+
const split = options.split ?? false;
|
|
925
|
+
if (split !== false && split !== "route")
|
|
926
|
+
fail(`i18n.split ${JSON.stringify(split)} is not supported; use false or "route"`);
|
|
927
|
+
const dropUnusedKeys = options.dropUnusedKeys ?? false;
|
|
928
|
+
if (typeof dropUnusedKeys !== "boolean")
|
|
929
|
+
fail(`i18n.dropUnusedKeys must be a boolean (got ${JSON.stringify(dropUnusedKeys)})`);
|
|
930
|
+
const keepKeys = options.keepKeys ?? [];
|
|
931
|
+
if (!Array.isArray(keepKeys) || keepKeys.some((glob) => typeof glob !== "string" || glob === ""))
|
|
932
|
+
fail('i18n.keepKeys must be an array of key globs such as "status.*"');
|
|
933
|
+
const syntax = options.syntax ?? "mf1";
|
|
934
|
+
if (syntax !== "mf1" && syntax !== "mf2")
|
|
935
|
+
fail(`i18n.syntax must be "mf1" or "mf2" (got ${JSON.stringify(syntax)})`);
|
|
936
|
+
const { catalog } = options;
|
|
937
|
+
if (catalog !== undefined && (typeof catalog !== "string" || catalog === ""))
|
|
938
|
+
fail(catalogMissing(catalog));
|
|
939
|
+
return {
|
|
940
|
+
locales,
|
|
941
|
+
defaultLocale,
|
|
942
|
+
strategy,
|
|
943
|
+
redirectToDefaultLocale,
|
|
944
|
+
detect: { cookie, redirect: options.detect?.redirect ?? (domains ? false : "root") },
|
|
945
|
+
pages: options.pages ?? {},
|
|
946
|
+
timeZone,
|
|
947
|
+
missingPage,
|
|
948
|
+
fallback,
|
|
949
|
+
localizeLinks,
|
|
950
|
+
split,
|
|
951
|
+
dropUnusedKeys,
|
|
952
|
+
keepKeys,
|
|
953
|
+
syntax,
|
|
954
|
+
...catalog === undefined ? {} : { catalog },
|
|
955
|
+
...domains ? { domains } : {}
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// packages/i18n/src/build/routes.ts
|
|
960
|
+
import { relative } from "path";
|
|
961
|
+
import {
|
|
962
|
+
DiagnosticError as DiagnosticError4,
|
|
963
|
+
addAppPlugin,
|
|
964
|
+
addRouteMiddleware,
|
|
965
|
+
addTemplate,
|
|
966
|
+
createResolver,
|
|
967
|
+
diagnostic,
|
|
968
|
+
extendPages,
|
|
969
|
+
useLogger
|
|
970
|
+
} from "hamur/kit";
|
|
971
|
+
var SEPARATOR = "___";
|
|
972
|
+
function paramsOf(segments) {
|
|
973
|
+
return segments.flatMap((segment) => {
|
|
974
|
+
if (segment.kind === "static")
|
|
975
|
+
return [];
|
|
976
|
+
if (segment.kind === "mixed")
|
|
977
|
+
return segment.parts.flatMap((part) => typeof part === "string" ? [] : [{ name: part.param, kind: part.optional ? "optional" : "param" }]);
|
|
978
|
+
return [{ name: segment.name, kind: segment.kind }];
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
var signature = (segments) => paramsOf(segments).map(({ name, kind }) => `${name}:${kind}`).sort().join(",");
|
|
982
|
+
function shapeOf(path) {
|
|
983
|
+
const parts = parsePattern(path).map((segment) => {
|
|
984
|
+
if (segment.kind === "static")
|
|
985
|
+
return segment.text;
|
|
986
|
+
if (segment.kind === "mixed")
|
|
987
|
+
return segment.parts.map((part) => typeof part === "string" ? part : part.optional ? "\x00?\x00" : "\x00").join("");
|
|
988
|
+
return { param: ":", optional: ":?", catchAll: "**", optionalCatchAll: "**?" }[segment.kind];
|
|
989
|
+
});
|
|
990
|
+
return `/${parts.join("/")}`;
|
|
991
|
+
}
|
|
992
|
+
function flatten2(records, ancestors = []) {
|
|
993
|
+
return records.flatMap((record) => [...flatten2(record.children, [...ancestors, record.name]), { record, ancestors }]);
|
|
994
|
+
}
|
|
995
|
+
function tableOf(records, options, copies) {
|
|
996
|
+
const table = { copies, routes: {}, aliases: {} };
|
|
997
|
+
for (const { record } of flatten2(records)) {
|
|
998
|
+
const index = record.name.indexOf(SEPARATOR);
|
|
999
|
+
const base = index === -1 ? record.name : record.name.slice(0, index);
|
|
1000
|
+
const code = index === -1 ? options.defaultLocale : record.name.slice(index + SEPARATOR.length);
|
|
1001
|
+
const own = index !== -1 && code === options.defaultLocale && options.strategy === "prefix_and_default" ? table.aliases[base] ??= {} : table.routes[base] ??= {};
|
|
1002
|
+
own[code] = record.path;
|
|
1003
|
+
}
|
|
1004
|
+
return table;
|
|
1005
|
+
}
|
|
1006
|
+
function localizeRoutes(routes, options, rootDir = "") {
|
|
1007
|
+
if (options.strategy === "no_prefix")
|
|
1008
|
+
return { routes, table: tableOf(routes, options, []) };
|
|
1009
|
+
const shown = (file) => rootDir ? relative(rootDir, file) : file;
|
|
1010
|
+
const originals = flatten2(routes);
|
|
1011
|
+
for (const { record } of originals) {
|
|
1012
|
+
if (record.name.includes(SEPARATOR))
|
|
1013
|
+
throw new DiagnosticError4("HAMUR_E5816", `i18n: route name "${record.name}" (${shown(record.file)}) contains "___", which route copies use`);
|
|
1014
|
+
}
|
|
1015
|
+
const byName = new Map(originals.map(({ record }) => [record.name, record]));
|
|
1016
|
+
const codes = new Set(options.locales.map((locale) => locale.code));
|
|
1017
|
+
for (const [name, paths] of Object.entries(options.pages)) {
|
|
1018
|
+
const record = byName.get(name);
|
|
1019
|
+
if (!record)
|
|
1020
|
+
throw new DiagnosticError4("HAMUR_E5817", `i18n.pages: no route named "${name}"`);
|
|
1021
|
+
const own = parsePattern(record.path);
|
|
1022
|
+
for (const [code, path] of Object.entries(paths ?? {})) {
|
|
1023
|
+
if (!codes.has(code))
|
|
1024
|
+
throw new DiagnosticError4("HAMUR_E5818", `i18n.pages.${name}: "${code}" is not in i18n.locales`);
|
|
1025
|
+
if (path === false)
|
|
1026
|
+
continue;
|
|
1027
|
+
let segments;
|
|
1028
|
+
try {
|
|
1029
|
+
if (typeof path !== "string")
|
|
1030
|
+
throw new Error("not a string");
|
|
1031
|
+
segments = parsePattern(path);
|
|
1032
|
+
} catch {
|
|
1033
|
+
throw new DiagnosticError4("HAMUR_E5819", `i18n.pages.${name}.${code} ${JSON.stringify(path)} must be a route path starting with "/"`);
|
|
1034
|
+
}
|
|
1035
|
+
if (signature(segments) !== signature(own)) {
|
|
1036
|
+
const names = paramsOf(own).map((param) => param.name);
|
|
1037
|
+
throw new DiagnosticError4("HAMUR_E5820", `i18n.pages.${name}.${code} ${JSON.stringify(path)} must keep the params of "${record.path}" (${names.length ? names.join(", ") : "none"})`);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
const localized = (record, code) => {
|
|
1042
|
+
const own = options.pages[record.name]?.[code];
|
|
1043
|
+
return typeof own === "string" ? own : record.path;
|
|
1044
|
+
};
|
|
1045
|
+
const domains = options.domains;
|
|
1046
|
+
const absent = (record, code) => options.pages[record.name]?.[code] === false;
|
|
1047
|
+
const prefixed = (code, path) => domains ? path : `/${code}${path === "/" ? "" : path}`;
|
|
1048
|
+
const copy = (record, code) => ({
|
|
1049
|
+
...record,
|
|
1050
|
+
name: `${record.name}${SEPARATOR}${code}`,
|
|
1051
|
+
path: prefixed(code, localized(record, code)),
|
|
1052
|
+
children: record.children.filter((child) => !absent(child, code)).map((child) => copy(child, code))
|
|
1053
|
+
});
|
|
1054
|
+
const moved = (record) => {
|
|
1055
|
+
const children = record.children.map(moved);
|
|
1056
|
+
const path = localized(record, options.defaultLocale);
|
|
1057
|
+
return path === record.path && children.every((child, index) => child === record.children[index]) ? record : { ...record, path, children };
|
|
1058
|
+
};
|
|
1059
|
+
const keep = domains !== undefined || options.strategy === "prefix_except_default" || options.strategy === "prefix_and_default";
|
|
1060
|
+
const copies = options.locales.map((locale) => locale.code).filter((code) => options.strategy !== "prefix_except_default" && !domains || code !== options.defaultLocale);
|
|
1061
|
+
const kept = keep ? routes.map(moved) : [];
|
|
1062
|
+
const differs = (record, code) => localized(record, code) !== localized(record, options.defaultLocale) || record.children.some((child) => differs(child, code));
|
|
1063
|
+
const made = new Map;
|
|
1064
|
+
const wanted = (record, code) => {
|
|
1065
|
+
if (absent(record, code))
|
|
1066
|
+
return false;
|
|
1067
|
+
if (!domains)
|
|
1068
|
+
return true;
|
|
1069
|
+
if (!differs(record, code))
|
|
1070
|
+
return false;
|
|
1071
|
+
const paths = flatten2([copy(record, code)]).map((entry) => entry.record.path).join(`
|
|
1072
|
+
`);
|
|
1073
|
+
let seen = made.get(record);
|
|
1074
|
+
if (!seen)
|
|
1075
|
+
made.set(record, seen = new Set);
|
|
1076
|
+
if (seen.has(paths))
|
|
1077
|
+
return false;
|
|
1078
|
+
seen.add(paths);
|
|
1079
|
+
return true;
|
|
1080
|
+
};
|
|
1081
|
+
const copied = copies.flatMap((code) => routes.filter((record) => wanted(record, code)).map((record) => copy(record, code)));
|
|
1082
|
+
const result = [...kept, ...copied];
|
|
1083
|
+
const table = tableOf(result, options, domains ? [] : copies);
|
|
1084
|
+
if (domains) {
|
|
1085
|
+
table.domains = domains;
|
|
1086
|
+
for (const { record } of originals) {
|
|
1087
|
+
const own = table.routes[record.name] ??= {};
|
|
1088
|
+
for (const { code } of options.locales)
|
|
1089
|
+
own[code] ??= localized(record, code);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
if (!domains) {
|
|
1093
|
+
for (const { record } of originals) {
|
|
1094
|
+
for (const code of copies) {
|
|
1095
|
+
if (!absent(record, code))
|
|
1096
|
+
continue;
|
|
1097
|
+
(table.routes[record.name] ??= {})[code] = prefixed(code, record.path);
|
|
1098
|
+
(table.missing ??= {})[record.name] = [...table.missing[record.name] ?? [], code];
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
const all = flatten2(result);
|
|
1103
|
+
const seen = new Map;
|
|
1104
|
+
for (const entry of [
|
|
1105
|
+
...all.filter((item) => !item.record.name.includes(SEPARATOR)),
|
|
1106
|
+
...all.filter((item) => item.record.name.includes(SEPARATOR))
|
|
1107
|
+
]) {
|
|
1108
|
+
const shape = shapeOf(entry.record.path);
|
|
1109
|
+
const other = seen.get(shape);
|
|
1110
|
+
const related = other && (other.ancestors.includes(entry.record.name) || entry.ancestors.includes(other.record.name));
|
|
1111
|
+
if (other && !related && entry.record.name.includes(SEPARATOR)) {
|
|
1112
|
+
throw new DiagnosticError4("HAMUR_E5821", `i18n: route copy "${entry.record.path}" (${entry.record.name}) clashes with "${other.record.path}" (${other.record.name}, ${shown(other.record.file)})`);
|
|
1113
|
+
}
|
|
1114
|
+
if (!other)
|
|
1115
|
+
seen.set(shape, entry);
|
|
1116
|
+
}
|
|
1117
|
+
return { routes: result, table };
|
|
1118
|
+
}
|
|
1119
|
+
var tables = new WeakMap;
|
|
1120
|
+
var routeTableOf = (hamur) => tables.get(hamur) ?? { copies: [], routes: {} };
|
|
1121
|
+
var rememberRouteTable = (hamur, table) => void tables.set(hamur, table);
|
|
1122
|
+
var PRERENDER_WARNING = 'i18n: "/" is prerendered, so detect.redirect "root" never runs for it';
|
|
1123
|
+
function setupRoutes(options, hamur) {
|
|
1124
|
+
const r = createResolver(new URL("../../src/build/routes.ts", import.meta.url).href);
|
|
1125
|
+
let table = { copies: [], routes: {} };
|
|
1126
|
+
extendPages((routes) => {
|
|
1127
|
+
const localized = localizeRoutes(routes, options, hamur.options.rootDir);
|
|
1128
|
+
routes.splice(0, routes.length, ...localized.routes);
|
|
1129
|
+
table = localized.table;
|
|
1130
|
+
rememberRouteTable(hamur, table);
|
|
1131
|
+
});
|
|
1132
|
+
const exports = (values) => Object.entries(values).map(([name, value]) => `export const ${name} = ${JSON.stringify(value) ?? "undefined"};
|
|
1133
|
+
`).join("");
|
|
1134
|
+
addTemplate({
|
|
1135
|
+
filename: "i18n/routes",
|
|
1136
|
+
getContents: () => exports({
|
|
1137
|
+
copies: table.copies,
|
|
1138
|
+
routes: table.routes,
|
|
1139
|
+
aliases: table.aliases ?? {},
|
|
1140
|
+
missing: table.missing ?? {},
|
|
1141
|
+
domains: table.domains,
|
|
1142
|
+
server: [...new Set(hamur.serverRoutes.map((route) => route.path))]
|
|
1143
|
+
})
|
|
1144
|
+
});
|
|
1145
|
+
addTemplate({
|
|
1146
|
+
filename: "i18n/options",
|
|
1147
|
+
getContents: () => exports({
|
|
1148
|
+
locales: options.locales,
|
|
1149
|
+
defaultLocale: options.defaultLocale,
|
|
1150
|
+
strategy: options.strategy,
|
|
1151
|
+
redirectToDefaultLocale: options.redirectToDefaultLocale,
|
|
1152
|
+
cookie: options.detect.cookie,
|
|
1153
|
+
timeZone: options.timeZone,
|
|
1154
|
+
fallback: options.fallback,
|
|
1155
|
+
missingPage: options.missingPage,
|
|
1156
|
+
localizeLinks: options.localizeLinks,
|
|
1157
|
+
syntax: options.syntax,
|
|
1158
|
+
baseURL: hamur.options.app.baseURL.endsWith("/") ? hamur.options.app.baseURL : `${hamur.options.app.baseURL}/`
|
|
1159
|
+
})
|
|
1160
|
+
});
|
|
1161
|
+
addAppPlugin({ src: r.resolve("../runtime/plugin.ts"), mode: "all" });
|
|
1162
|
+
addRouteMiddleware({ path: r.resolve("../runtime/middleware.ts"), global: true });
|
|
1163
|
+
if (options.detect.redirect !== "root" || options.strategy === "no_prefix")
|
|
1164
|
+
return;
|
|
1165
|
+
const { preset, routeRules, prerender } = hamur.options;
|
|
1166
|
+
const root = routeRules["/"];
|
|
1167
|
+
const prerendered = preset === "static" || !Array.isArray(root) && root?.prerender === true || typeof prerender.routes === "function" || (prerender.routes ?? []).includes("/");
|
|
1168
|
+
if ((options.strategy === "prefix_except_default" || options.strategy === "prefix_and_default") && prerendered)
|
|
1169
|
+
useLogger("hamur").warn(diagnostic("HAMUR_W5832", PRERENDER_WARNING));
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// packages/i18n/src/build/messages.ts
|
|
1173
|
+
async function scanLocaleFiles(roots, codes) {
|
|
1174
|
+
const byCode = new Map;
|
|
1175
|
+
const ignored = [];
|
|
1176
|
+
for (const root of roots) {
|
|
1177
|
+
const dir = join2(root, "locales");
|
|
1178
|
+
const names = await readdir(dir).catch(() => []);
|
|
1179
|
+
for (const name of names.filter((entry) => entry.endsWith(".json")).sort()) {
|
|
1180
|
+
const code = name.slice(0, -".json".length);
|
|
1181
|
+
if (!CODE.test(code))
|
|
1182
|
+
ignored.push(join2(dir, name));
|
|
1183
|
+
else if (codes.includes(code))
|
|
1184
|
+
byCode.set(code, [...byCode.get(code) ?? [], join2(dir, name)]);
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return { byCode, ignored };
|
|
1188
|
+
}
|
|
1189
|
+
function duplicateKey(text) {
|
|
1190
|
+
const stack = [];
|
|
1191
|
+
let pending = "";
|
|
1192
|
+
for (let i = 0;i < text.length; i++) {
|
|
1193
|
+
const c = text[i];
|
|
1194
|
+
const top = stack.at(-1);
|
|
1195
|
+
if (c === '"') {
|
|
1196
|
+
let end = i + 1;
|
|
1197
|
+
while (text[end] !== '"')
|
|
1198
|
+
end += text[end] === "\\" ? 2 : 1;
|
|
1199
|
+
const value = JSON.parse(text.slice(i, end + 1));
|
|
1200
|
+
i = end;
|
|
1201
|
+
if (top?.keys && top.expectKey) {
|
|
1202
|
+
const path = top.path ? `${top.path}.${value}` : value;
|
|
1203
|
+
if (top.keys.has(value))
|
|
1204
|
+
return path;
|
|
1205
|
+
top.keys.add(value);
|
|
1206
|
+
top.expectKey = false;
|
|
1207
|
+
pending = path;
|
|
1208
|
+
}
|
|
1209
|
+
} else if (c === "{") {
|
|
1210
|
+
stack.push({ keys: new Set, path: top?.keys ? pending : top?.path ?? "", expectKey: true });
|
|
1211
|
+
} else if (c === "[") {
|
|
1212
|
+
stack.push({ path: top?.keys ? pending : top?.path ?? "", expectKey: false });
|
|
1213
|
+
} else if (c === "}" || c === "]") {
|
|
1214
|
+
stack.pop();
|
|
1215
|
+
} else if (c === "," && top?.keys) {
|
|
1216
|
+
top.expectKey = true;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
function flattenMessages(value, file) {
|
|
1222
|
+
const out = {};
|
|
1223
|
+
const walk = (node, prefix) => {
|
|
1224
|
+
for (const [name, child] of Object.entries(node)) {
|
|
1225
|
+
const key = prefix + name;
|
|
1226
|
+
if (name === "")
|
|
1227
|
+
throw new DiagnosticError5("HAMUR_E5809", `key ${JSON.stringify(key)} must not be empty or contain "."`, {
|
|
1228
|
+
at: file
|
|
1229
|
+
});
|
|
1230
|
+
if (name.includes("."))
|
|
1231
|
+
throw new DiagnosticError5("HAMUR_E5809", `key ${JSON.stringify(key)} contains "."; "." nests keys ({ "a": { "b": \u2026 } } is "a.b"), so use a key without it and put the text in the value: "Type to search": "Type to search..."`, { at: file });
|
|
1232
|
+
if (typeof child === "string")
|
|
1233
|
+
out[key] = child;
|
|
1234
|
+
else if (child !== null && typeof child === "object" && !Array.isArray(child))
|
|
1235
|
+
walk(child, `${key}.`);
|
|
1236
|
+
else
|
|
1237
|
+
throw new DiagnosticError5("HAMUR_E5810", `${JSON.stringify(key)} must be a string or an object`, { at: file });
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
1241
|
+
throw new DiagnosticError5("HAMUR_E5811", "must be a JSON object", { at: file });
|
|
1242
|
+
walk(value, "");
|
|
1243
|
+
return out;
|
|
1244
|
+
}
|
|
1245
|
+
async function mergeLocaleFiles(files, rootDir) {
|
|
1246
|
+
const messages = {};
|
|
1247
|
+
const origin = {};
|
|
1248
|
+
for (const path of files) {
|
|
1249
|
+
const file = relative2(rootDir, path);
|
|
1250
|
+
const text = await readFile3(path, "utf8");
|
|
1251
|
+
let json;
|
|
1252
|
+
try {
|
|
1253
|
+
json = JSON.parse(text);
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
throw new DiagnosticError5("HAMUR_E5812", `invalid JSON (${error.message})`, { at: file });
|
|
1256
|
+
}
|
|
1257
|
+
const twice = duplicateKey(text);
|
|
1258
|
+
if (twice)
|
|
1259
|
+
throw new DiagnosticError5("HAMUR_E5813", `${JSON.stringify(twice)} is defined twice`, { at: file });
|
|
1260
|
+
for (const [key, message] of Object.entries(flattenMessages(json, file))) {
|
|
1261
|
+
if (Object.hasOwn(messages, key))
|
|
1262
|
+
continue;
|
|
1263
|
+
messages[key] = message;
|
|
1264
|
+
origin[key] = file;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
return { messages, origin };
|
|
1268
|
+
}
|
|
1269
|
+
function fillFromChain(own, chain) {
|
|
1270
|
+
const merged = { messages: { ...own.messages }, origin: { ...own.origin } };
|
|
1271
|
+
const filled = [];
|
|
1272
|
+
for (const base of chain) {
|
|
1273
|
+
for (const [key, message] of Object.entries(base.messages)) {
|
|
1274
|
+
if (Object.hasOwn(merged.messages, key))
|
|
1275
|
+
continue;
|
|
1276
|
+
merged.messages[key] = message;
|
|
1277
|
+
merged.origin[key] = base.origin[key];
|
|
1278
|
+
filled.push(key);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
return { merged, filled };
|
|
1282
|
+
}
|
|
1283
|
+
var chunkSpecifier = (appId, id) => `#${appId}-chunk/${createHash("sha256").update(id).digest("hex").slice(0, 8)}`;
|
|
1284
|
+
var setupMessages = async (options, hamur) => {
|
|
1285
|
+
const { rootDir, layers, dev } = hamur.options;
|
|
1286
|
+
const log = useLogger2("hamur");
|
|
1287
|
+
const warned = new Set;
|
|
1288
|
+
const warn = (text) => {
|
|
1289
|
+
if (warned.has(text))
|
|
1290
|
+
return;
|
|
1291
|
+
warned.add(text);
|
|
1292
|
+
log.warn(diagnostic2("HAMUR_W5831", `i18n: ${text}`));
|
|
1293
|
+
};
|
|
1294
|
+
const { byCode, ignored } = await scanLocaleFiles([rootDir, ...layers.map((layer) => layer.rootDir)], options.locales.map((locale) => locale.code));
|
|
1295
|
+
for (const path of ignored)
|
|
1296
|
+
warn(`${relative2(rootDir, path)} is ignored: "${basename(path, ".json")}" is not a locale code`);
|
|
1297
|
+
for (const { code } of options.locales) {
|
|
1298
|
+
if (!byCode.has(code))
|
|
1299
|
+
warn(`no locales/${code}.json in the app or a layer; every key of ${code} falls back`);
|
|
1300
|
+
}
|
|
1301
|
+
const drop = options.dropUnusedKeys && !dev;
|
|
1302
|
+
let keep;
|
|
1303
|
+
const compile = async (code, only, client = false) => {
|
|
1304
|
+
const language = options.locales.find((locale) => locale.code === code).language;
|
|
1305
|
+
let merged = await mergeLocaleFiles(byCode.get(code) ?? [], rootDir);
|
|
1306
|
+
let filled = [];
|
|
1307
|
+
const chain = fallbackChain(options.fallback, options.defaultLocale, code);
|
|
1308
|
+
if (chain.length > 0) {
|
|
1309
|
+
({ merged, filled } = fillFromChain(merged, await Promise.all(chain.map((member) => mergeLocaleFiles(byCode.get(member) ?? [], rootDir)))));
|
|
1310
|
+
}
|
|
1311
|
+
const { origin } = merged;
|
|
1312
|
+
const wanted = (key) => (!only || only.has(key)) && (!client || !keep || keep(key));
|
|
1313
|
+
const messages = only || client && keep ? Object.fromEntries(Object.entries(merged.messages).filter(([key]) => wanted(key))) : merged.messages;
|
|
1314
|
+
const compiled = compileCatalog(messages, language, {
|
|
1315
|
+
file: (key) => origin[key] ?? `locales/${code}.json`,
|
|
1316
|
+
warn,
|
|
1317
|
+
syntax: options.syntax
|
|
1318
|
+
});
|
|
1319
|
+
return dev ? { ...compiled, code: `${compiled.code}export const fallbacks = ${JSON.stringify(filled)};
|
|
1320
|
+
` } : compiled;
|
|
1321
|
+
};
|
|
1322
|
+
for (const { code } of options.locales)
|
|
1323
|
+
await compile(code);
|
|
1324
|
+
const anchors = new Map;
|
|
1325
|
+
for (const { code } of options.locales) {
|
|
1326
|
+
const anchor = byCode.get(code)?.[0];
|
|
1327
|
+
if (dev && anchor) {
|
|
1328
|
+
anchors.set(anchor, code);
|
|
1329
|
+
anchors.set(await realpath(anchor), code);
|
|
1330
|
+
}
|
|
1331
|
+
addTemplate2({
|
|
1332
|
+
filename: `i18n/${code}`,
|
|
1333
|
+
getContents: async () => anchor && dev ? `export { default, fallbacks } from ${JSON.stringify(anchor)};
|
|
1334
|
+
` : `${(await compile(code)).code}export const locale = ${JSON.stringify(code)};
|
|
1335
|
+
`
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
if (anchors.size) {
|
|
1339
|
+
const filter = new RegExp(`^(${[...anchors.keys()].map((path) => path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`);
|
|
1340
|
+
addBunPlugin({
|
|
1341
|
+
name: "hamur-i18n-messages",
|
|
1342
|
+
setup(build) {
|
|
1343
|
+
build.onLoad({ filter }, async ({ path }) => ({
|
|
1344
|
+
contents: (await compile(anchors.get(path))).code,
|
|
1345
|
+
loader: "js"
|
|
1346
|
+
}));
|
|
1347
|
+
}
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
const split = options.split === "route" && !dev;
|
|
1351
|
+
const chunked = split || drop;
|
|
1352
|
+
const names = () => split ? ["_shared", ...Object.keys(routeTableOf(hamur).routes)] : ["_shared"];
|
|
1353
|
+
const table = (entry) => `{
|
|
1354
|
+
` + options.locales.map(({ code }) => " " + JSON.stringify(code) + ": " + entry(code) + ",").join(`
|
|
1355
|
+
`) + `
|
|
1356
|
+
}`;
|
|
1357
|
+
const loader = (id) => "() => import(" + JSON.stringify(id) + ")";
|
|
1358
|
+
const full = table((code) => loader("#hamur/i18n/" + code));
|
|
1359
|
+
addTemplate2({
|
|
1360
|
+
filename: "i18n/loaders",
|
|
1361
|
+
getContents: () => {
|
|
1362
|
+
if (!chunked)
|
|
1363
|
+
return "export default " + full + `;
|
|
1364
|
+
export const routes = {};
|
|
1365
|
+
`;
|
|
1366
|
+
const routes = table((code) => "{ " + names().map((name) => JSON.stringify(name) + ": " + loader("#hamur/i18n/" + code + "/" + name)).join(", ") + " }");
|
|
1367
|
+
return "export default import.meta.server ? " + full + ` : {};
|
|
1368
|
+
export const routes = import.meta.server ? {} : ` + routes + `;
|
|
1369
|
+
`;
|
|
1370
|
+
}
|
|
1371
|
+
});
|
|
1372
|
+
addTemplate2({
|
|
1373
|
+
filename: "i18n/chunks",
|
|
1374
|
+
getContents: (context) => {
|
|
1375
|
+
const map = context.manifest.importMap ?? {};
|
|
1376
|
+
const urlOf = (id) => map[chunkSpecifier(hamur.options.appId, "hamur-virtual:" + id)];
|
|
1377
|
+
const chunks = Object.fromEntries(options.locales.flatMap(({ code }) => {
|
|
1378
|
+
if (!chunked) {
|
|
1379
|
+
const url = urlOf("#hamur/i18n/" + code);
|
|
1380
|
+
return url ? [[code, url]] : [];
|
|
1381
|
+
}
|
|
1382
|
+
const urls = names().flatMap((name) => {
|
|
1383
|
+
const url = urlOf("#hamur/i18n/" + code + "/" + name);
|
|
1384
|
+
return url ? [[name, url]] : [];
|
|
1385
|
+
});
|
|
1386
|
+
return [[code, Object.fromEntries(urls)]];
|
|
1387
|
+
}));
|
|
1388
|
+
return "export default " + JSON.stringify(chunks) + `;
|
|
1389
|
+
`;
|
|
1390
|
+
}
|
|
1391
|
+
});
|
|
1392
|
+
if (drop) {
|
|
1393
|
+
const matchers = options.keepKeys.map(keepMatcher);
|
|
1394
|
+
hamur.hooks.hook("build:client:config", async (config) => {
|
|
1395
|
+
if (!config.entrypoints.includes("#hamur/client-entry"))
|
|
1396
|
+
return;
|
|
1397
|
+
keep = () => false;
|
|
1398
|
+
let inputs;
|
|
1399
|
+
try {
|
|
1400
|
+
const probe = {
|
|
1401
|
+
...config,
|
|
1402
|
+
splitting: false,
|
|
1403
|
+
minify: false,
|
|
1404
|
+
sourcemap: "none",
|
|
1405
|
+
metafile: true,
|
|
1406
|
+
throw: false
|
|
1407
|
+
};
|
|
1408
|
+
delete probe.outdir;
|
|
1409
|
+
const result = await Bun.build(probe);
|
|
1410
|
+
if (!result.success)
|
|
1411
|
+
return;
|
|
1412
|
+
inputs = Object.keys(result.metafile?.inputs ?? {});
|
|
1413
|
+
} finally {
|
|
1414
|
+
keep = undefined;
|
|
1415
|
+
}
|
|
1416
|
+
const read = await readClientInputs(inputs, rootDir);
|
|
1417
|
+
if (read.dynamic) {
|
|
1418
|
+
warn(relative2(rootDir, read.dynamic.file) + ":" + read.dynamic.line + " uses a dynamic message key, so dropUnusedKeys is off for this build");
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
const kept = (key) => read.keys.has(key) || matchers.some((matcher) => matcher.test(key));
|
|
1422
|
+
const all = new Set;
|
|
1423
|
+
for (const { code } of options.locales)
|
|
1424
|
+
for (const key of Object.keys((await mergeLocaleFiles(byCode.get(code) ?? [], rootDir)).messages))
|
|
1425
|
+
all.add(key);
|
|
1426
|
+
keep = kept;
|
|
1427
|
+
log.info("i18n: dropped " + [...all].filter((key) => !kept(key)).length + " of " + all.size + " keys");
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
if (!chunked)
|
|
1431
|
+
return;
|
|
1432
|
+
let planned;
|
|
1433
|
+
const plan = () => {
|
|
1434
|
+
planned ??= planSplit(hamur).then((made) => {
|
|
1435
|
+
const files = new Set([...made.shared.dynamic, ...[...made.routes.values()].flatMap((entry) => entry.dynamic)]);
|
|
1436
|
+
for (const file of files)
|
|
1437
|
+
for (const { code } of options.locales)
|
|
1438
|
+
warn(relative2(rootDir, file) + " uses a dynamic message key; its route ships the full " + code + " catalog");
|
|
1439
|
+
return made;
|
|
1440
|
+
});
|
|
1441
|
+
return planned;
|
|
1442
|
+
};
|
|
1443
|
+
hamur.hooks.hook("templates:extend", (templates) => {
|
|
1444
|
+
for (const { code } of options.locales) {
|
|
1445
|
+
for (const name of names()) {
|
|
1446
|
+
templates.push({
|
|
1447
|
+
filename: "i18n/" + code + "/" + name,
|
|
1448
|
+
getContents: async () => {
|
|
1449
|
+
if (!split)
|
|
1450
|
+
return (await compile(code, undefined, true)).code;
|
|
1451
|
+
const { shared, routes } = await plan();
|
|
1452
|
+
const own = name === "_shared" ? shared : routes.get(name);
|
|
1453
|
+
return (await compile(code, own && own.dynamic.length === 0 ? own.keys : undefined, true)).code;
|
|
1454
|
+
}
|
|
1455
|
+
});
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
});
|
|
1459
|
+
};
|
|
1460
|
+
|
|
1461
|
+
// packages/i18n/src/build/extract.ts
|
|
1462
|
+
import { DiagnosticError as DiagnosticError6 } from "hamur/kit";
|
|
1463
|
+
var SCANNED = /\.(?:ts|tsx|js|mjs|vue|svelte)$/;
|
|
1464
|
+
var KEY_ORDER = ["missing", "unused", "dynamic"];
|
|
1465
|
+
var here = (place) => place.file + ":" + place.line;
|
|
1466
|
+
var slashes = (path) => path.split(sep3).join("/");
|
|
1467
|
+
var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1468
|
+
async function sourceFiles(dirs) {
|
|
1469
|
+
const files = new Set;
|
|
1470
|
+
for (const dir of dirs) {
|
|
1471
|
+
const names = await readdir2(dir, { recursive: true }).catch(() => []);
|
|
1472
|
+
for (const name of names) {
|
|
1473
|
+
if (SCANNED.test(name) && !name.split(sep3).some((part) => part === "node_modules" || part.startsWith(".")))
|
|
1474
|
+
files.add(join3(dir, name));
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
return [...files].sort();
|
|
1478
|
+
}
|
|
1479
|
+
async function readCatalog(path, rootDir) {
|
|
1480
|
+
const file = slashes(relative3(rootDir, path));
|
|
1481
|
+
const text = await readFile4(path, "utf8");
|
|
1482
|
+
let json;
|
|
1483
|
+
try {
|
|
1484
|
+
json = JSON.parse(text);
|
|
1485
|
+
} catch (error) {
|
|
1486
|
+
throw new DiagnosticError6("HAMUR_E5812", "invalid JSON (" + error.message + ")", { at: file });
|
|
1487
|
+
}
|
|
1488
|
+
const keys = Object.keys(flattenMessages(json, file));
|
|
1489
|
+
return {
|
|
1490
|
+
path,
|
|
1491
|
+
file,
|
|
1492
|
+
json,
|
|
1493
|
+
keys,
|
|
1494
|
+
indent: /^\{[ \t]*\r?\n([ \t]+)\S/.exec(text)?.[1] ?? 2,
|
|
1495
|
+
newline: text.endsWith(`
|
|
1496
|
+
`)
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
function insert(json, key, file) {
|
|
1500
|
+
const parts = key.split(".");
|
|
1501
|
+
if (parts.some((part) => part === ""))
|
|
1502
|
+
throw new DiagnosticError6("HAMUR_E5822", "key " + JSON.stringify(key) + " must not have an empty segment", {
|
|
1503
|
+
at: file
|
|
1504
|
+
});
|
|
1505
|
+
let node = json;
|
|
1506
|
+
for (let i = 0;i < parts.length - 1; i++) {
|
|
1507
|
+
const next = node[parts[i]];
|
|
1508
|
+
if (next === undefined)
|
|
1509
|
+
node = node[parts[i]] = {};
|
|
1510
|
+
else if (isObject(next))
|
|
1511
|
+
node = next;
|
|
1512
|
+
else
|
|
1513
|
+
throw new DiagnosticError6("HAMUR_E5823", JSON.stringify(parts.slice(0, i + 1).join(".")) + " is a message, so " + JSON.stringify(key) + " cannot be added", { at: file });
|
|
1514
|
+
}
|
|
1515
|
+
const last = parts.at(-1);
|
|
1516
|
+
if (Object.hasOwn(node, last))
|
|
1517
|
+
throw new DiagnosticError6("HAMUR_E5824", JSON.stringify(key) + " is a group of messages, not a message", {
|
|
1518
|
+
at: file
|
|
1519
|
+
});
|
|
1520
|
+
node[last] = key;
|
|
1521
|
+
}
|
|
1522
|
+
function remove(json, key) {
|
|
1523
|
+
const parts = key.split(".");
|
|
1524
|
+
const chain = [json];
|
|
1525
|
+
for (const part of parts.slice(0, -1))
|
|
1526
|
+
chain.push(chain.at(-1)[part]);
|
|
1527
|
+
delete chain.at(-1)[parts.at(-1)];
|
|
1528
|
+
for (let i = chain.length - 1;i > 0 && Object.keys(chain[i]).length === 0; i--)
|
|
1529
|
+
delete chain[i - 1][parts[i - 1]];
|
|
1530
|
+
}
|
|
1531
|
+
async function write(catalog) {
|
|
1532
|
+
await mkdir(dirname2(catalog.path), { recursive: true });
|
|
1533
|
+
await writeFile(catalog.path, JSON.stringify(catalog.json, null, catalog.indent) + (catalog.newline ? `
|
|
1534
|
+
` : ""));
|
|
1535
|
+
}
|
|
1536
|
+
async function extract(hamur, options, flags, out) {
|
|
1537
|
+
if (flags.check && flags.prune)
|
|
1538
|
+
throw new DiagnosticError6("HAMUR_E5825", "--check and --prune cannot be used together");
|
|
1539
|
+
const { rootDir, srcDir, serverDir, layers } = hamur.options;
|
|
1540
|
+
const local = layers.filter((layer) => !layer.rootDir.includes(sep3 + "node_modules" + sep3));
|
|
1541
|
+
const codes = options.locales.map((locale) => locale.code);
|
|
1542
|
+
const used = new Map;
|
|
1543
|
+
const dynamic = [];
|
|
1544
|
+
for (const path of await sourceFiles([
|
|
1545
|
+
srcDir,
|
|
1546
|
+
serverDir,
|
|
1547
|
+
...local.flatMap((layer) => [layer.srcDir, layer.serverDir])
|
|
1548
|
+
])) {
|
|
1549
|
+
const text = await readFile4(path, "utf8");
|
|
1550
|
+
const read = readKeys(text, false);
|
|
1551
|
+
const file = slashes(relative3(rootDir, path));
|
|
1552
|
+
const lineAt = (offset) => text.slice(0, offset).split(`
|
|
1553
|
+
`).length;
|
|
1554
|
+
for (const [key, at] of read.positions)
|
|
1555
|
+
if (!used.has(key))
|
|
1556
|
+
used.set(key, { file, line: lineAt(at) });
|
|
1557
|
+
if (read.at !== undefined)
|
|
1558
|
+
dynamic.push({ file, line: lineAt(read.at) });
|
|
1559
|
+
}
|
|
1560
|
+
const everywhere = await scanLocaleFiles([rootDir, ...layers.map((layer) => layer.rootDir)], codes);
|
|
1561
|
+
const own = await scanLocaleFiles([rootDir], codes);
|
|
1562
|
+
const defaultPath = join3(rootDir, "locales", options.defaultLocale + ".json");
|
|
1563
|
+
const known = (await mergeLocaleFiles(everywhere.byCode.get(options.defaultLocale) ?? [], rootDir)).messages;
|
|
1564
|
+
const missing = [...used].filter(([key]) => !Object.hasOwn(known, key)).map(([key, place]) => ({ key, ...place }));
|
|
1565
|
+
missing.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line);
|
|
1566
|
+
dynamic.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line);
|
|
1567
|
+
const catalogs = [];
|
|
1568
|
+
for (const code of codes)
|
|
1569
|
+
for (const path of own.byCode.get(code) ?? [])
|
|
1570
|
+
catalogs.push(await readCatalog(path, rootDir));
|
|
1571
|
+
const keep = options.keepKeys.map(keepMatcher);
|
|
1572
|
+
const unused = dynamic.length > 0 ? [] : catalogs.flatMap((catalog) => catalog.keys.filter((key) => !used.has(key) && !keep.some((match) => match.test(key))).map((key) => ({ catalog, key })));
|
|
1573
|
+
for (const kind of KEY_ORDER) {
|
|
1574
|
+
if (kind === "missing")
|
|
1575
|
+
for (const entry of missing)
|
|
1576
|
+
out("missing " + entry.key + " " + here(entry));
|
|
1577
|
+
else if (kind === "unused")
|
|
1578
|
+
for (const { catalog, key } of unused)
|
|
1579
|
+
out("unused " + key + " " + catalog.file);
|
|
1580
|
+
else
|
|
1581
|
+
for (const place of dynamic)
|
|
1582
|
+
out("dynamic " + here(place));
|
|
1583
|
+
}
|
|
1584
|
+
const skipped = dynamic.length > 0 ? "; unused not reported: " + dynamic.length + " dynamic key" + (dynamic.length === 1 ? "" : "s") : "";
|
|
1585
|
+
out(missing.length + " missing, " + (dynamic.length > 0 ? "" : unused.length + " unused, ") + dynamic.length + " dynamic" + skipped);
|
|
1586
|
+
if (flags.prune && dynamic.length > 0)
|
|
1587
|
+
throw new DiagnosticError6("HAMUR_E5826", "--prune needs every key to be static; fix the dynamic keys above");
|
|
1588
|
+
if (flags.check)
|
|
1589
|
+
return missing.length > 0 || unused.length > 0 ? 1 : 0;
|
|
1590
|
+
if (missing.length > 0) {
|
|
1591
|
+
let target = catalogs.find((catalog) => catalog.path === defaultPath);
|
|
1592
|
+
if (!target) {
|
|
1593
|
+
target = {
|
|
1594
|
+
path: defaultPath,
|
|
1595
|
+
file: slashes(relative3(rootDir, defaultPath)),
|
|
1596
|
+
json: {},
|
|
1597
|
+
keys: [],
|
|
1598
|
+
indent: 2,
|
|
1599
|
+
newline: true
|
|
1600
|
+
};
|
|
1601
|
+
catalogs.push(target);
|
|
1602
|
+
}
|
|
1603
|
+
for (const { key } of missing)
|
|
1604
|
+
insert(target.json, key, target.file);
|
|
1605
|
+
}
|
|
1606
|
+
if (flags.prune)
|
|
1607
|
+
for (const { catalog, key } of unused)
|
|
1608
|
+
remove(catalog.json, key);
|
|
1609
|
+
const changed = new Set([
|
|
1610
|
+
...missing.length > 0 ? [defaultPath] : [],
|
|
1611
|
+
...flags.prune ? unused.map(({ catalog }) => catalog.path) : []
|
|
1612
|
+
]);
|
|
1613
|
+
for (const catalog of catalogs)
|
|
1614
|
+
if (changed.has(catalog.path))
|
|
1615
|
+
await write(catalog);
|
|
1616
|
+
return 0;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
// packages/i18n/src/module.ts
|
|
1620
|
+
import { DiagnosticError as DiagnosticError9, defineModule } from "hamur/kit";
|
|
1621
|
+
|
|
1622
|
+
// packages/i18n/src/build/catalog.ts
|
|
1623
|
+
import { readFile as readFile5, stat } from "fs/promises";
|
|
1624
|
+
import { relative as relative4, resolve as resolve2 } from "path";
|
|
1625
|
+
import { DiagnosticError as DiagnosticError7, addTemplate as addTemplate3, createResolver as createResolver2 } from "hamur/kit";
|
|
1626
|
+
var DEFAULT_EXPORT = /\bexport\s+default\s+defineCatalog\s*\(/;
|
|
1627
|
+
async function readCatalogFile(rootDir, catalog) {
|
|
1628
|
+
const path = resolve2(rootDir, catalog);
|
|
1629
|
+
const found = await stat(path).catch(() => {
|
|
1630
|
+
return;
|
|
1631
|
+
});
|
|
1632
|
+
if (!found?.isFile())
|
|
1633
|
+
throw new DiagnosticError7("HAMUR_E5814", catalogMissing(catalog));
|
|
1634
|
+
const text = await readFile5(path, "utf8");
|
|
1635
|
+
if (!DEFAULT_EXPORT.test(text))
|
|
1636
|
+
throw new DiagnosticError7("HAMUR_E5815", relative4(rootDir, path) + " must export default defineCatalog({ \u2026 })");
|
|
1637
|
+
return path;
|
|
1638
|
+
}
|
|
1639
|
+
var setupCatalog = async (options, hamur) => {
|
|
1640
|
+
const path = options.catalog === undefined ? undefined : await readCatalogFile(hamur.options.rootDir, options.catalog);
|
|
1641
|
+
const r = createResolver2(new URL("../../src/build/catalog.ts", import.meta.url).href);
|
|
1642
|
+
addTemplate3({
|
|
1643
|
+
filename: "i18n/catalog",
|
|
1644
|
+
getContents: () => path ? "export { loadCatalog as default } from " + JSON.stringify(r.resolve("../runtime/catalog-client.ts")) + `;
|
|
1645
|
+
` : `export default undefined;
|
|
1646
|
+
`
|
|
1647
|
+
});
|
|
1648
|
+
addTemplate3({
|
|
1649
|
+
filename: "i18n/catalog-server",
|
|
1650
|
+
server: true,
|
|
1651
|
+
getContents: () => path ? "export { loadCatalog as default } from " + JSON.stringify(r.resolve("../runtime/catalog-server.ts")) + `;
|
|
1652
|
+
` : `export default undefined;
|
|
1653
|
+
`
|
|
1654
|
+
});
|
|
1655
|
+
addTemplate3({
|
|
1656
|
+
filename: "i18n/catalog-source",
|
|
1657
|
+
server: true,
|
|
1658
|
+
getContents: () => "export default " + (path ? "() => import(" + JSON.stringify(path) + ")" : "undefined") + `;
|
|
1659
|
+
`
|
|
1660
|
+
});
|
|
1661
|
+
};
|
|
1662
|
+
|
|
1663
|
+
// packages/i18n/src/build/head.ts
|
|
1664
|
+
import { diagnostic as diagnostic3, useLogger as useLogger3 } from "hamur/kit";
|
|
1665
|
+
var SITE_URL_WARNING = "[hamur] site.url is not set; hreflang and canonical links are not written";
|
|
1666
|
+
var setupHead = (options, hamur) => {
|
|
1667
|
+
if (!options.domains && hamur.options.site.url === undefined && !process.env.HAMUR_SITE_URL)
|
|
1668
|
+
useLogger3("hamur").warn(diagnostic3("HAMUR_W5833", SITE_URL_WARNING.replace(/^\[hamur\] /, "")));
|
|
1669
|
+
};
|
|
1670
|
+
|
|
1671
|
+
// packages/i18n/src/build/prerender.ts
|
|
1672
|
+
import { diagnostic as diagnostic4, useLogger as useLogger4 } from "hamur/kit";
|
|
1673
|
+
var noPrefixPrerenderWarning = (defaultLocale) => "[hamur] i18n: no_prefix prerenders only the default locale (" + defaultLocale + "); other locales render at request time";
|
|
1674
|
+
var isStaticPreset = (preset) => preset === "static" || preset.endsWith("-static") || preset === "github-pages" || preset === "gitlab-pages";
|
|
1675
|
+
var setupPrerender = (options, hamur) => {
|
|
1676
|
+
if (options.strategy === "no_prefix" || options.domains) {
|
|
1677
|
+
if (options.domains || !isStaticPreset(hamur.options.preset)) {
|
|
1678
|
+
hamur.options.prerender.ignore.push((path) => createMatcher(routeTableOf(hamur)).matchPath(path) !== undefined);
|
|
1679
|
+
return;
|
|
1680
|
+
}
|
|
1681
|
+
let warned = false;
|
|
1682
|
+
hamur.hooks.hook("prerender:routes", (seeds) => {
|
|
1683
|
+
if (seeds.size === 0 || warned)
|
|
1684
|
+
return;
|
|
1685
|
+
warned = true;
|
|
1686
|
+
useLogger4("hamur").warn(diagnostic4("HAMUR_W5834", noPrefixPrerenderWarning(options.defaultLocale).replace(/^\[hamur\] /, "")));
|
|
1687
|
+
});
|
|
1688
|
+
return;
|
|
1689
|
+
}
|
|
1690
|
+
hamur.hooks.hook("prerender:routes", (seeds) => {
|
|
1691
|
+
const table = routeTableOf(hamur);
|
|
1692
|
+
const { matchPath, buildPath } = createMatcher(table);
|
|
1693
|
+
const hidden = (name, code) => options.missingPage === "404" && table.missing?.[name]?.includes(code);
|
|
1694
|
+
for (const seed of [...seeds]) {
|
|
1695
|
+
const match = matchPath(seed);
|
|
1696
|
+
if (!match || table.missing?.[match.name]?.includes(match.code))
|
|
1697
|
+
continue;
|
|
1698
|
+
for (const { code } of options.locales)
|
|
1699
|
+
if (code !== match.code && !hidden(match.name, code))
|
|
1700
|
+
seeds.add(buildPath(match.name, code, match.params));
|
|
1701
|
+
}
|
|
1702
|
+
});
|
|
1703
|
+
};
|
|
1704
|
+
|
|
1705
|
+
// packages/i18n/src/build/types.ts
|
|
1706
|
+
import { DiagnosticError as DiagnosticError8, addTypeTemplate, diagnostic as diagnostic5, useLogger as useLogger5 } from "hamur/kit";
|
|
1707
|
+
function selectCases(nodes, into) {
|
|
1708
|
+
for (const node of nodes) {
|
|
1709
|
+
if (node.type === "select") {
|
|
1710
|
+
const set = into.get(node.name) ?? new Set;
|
|
1711
|
+
for (const { key } of node.cases)
|
|
1712
|
+
if (key !== "other")
|
|
1713
|
+
set.add(key);
|
|
1714
|
+
into.set(node.name, set);
|
|
1715
|
+
}
|
|
1716
|
+
if (node.type === "select" || node.type === "plural")
|
|
1717
|
+
for (const { body } of node.cases)
|
|
1718
|
+
selectCases(body, into);
|
|
1719
|
+
if (node.type === "tag")
|
|
1720
|
+
selectCases(node.children, into);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
function typeOf(kind, cases) {
|
|
1724
|
+
switch (kind) {
|
|
1725
|
+
case "text":
|
|
1726
|
+
return "string | number";
|
|
1727
|
+
case "number":
|
|
1728
|
+
return "number";
|
|
1729
|
+
case "date":
|
|
1730
|
+
return "Date | number";
|
|
1731
|
+
case "select":
|
|
1732
|
+
return [...[...cases ?? []].map((name) => JSON.stringify(name)), "(string & {})"].join(" | ");
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
async function analyzeLocales(options, roots, rootDir) {
|
|
1736
|
+
const { byCode } = await scanLocaleFiles(roots, options.locales.map((locale) => locale.code));
|
|
1737
|
+
const load = async (code) => {
|
|
1738
|
+
const merged = await mergeLocaleFiles(byCode.get(code) ?? [], rootDir);
|
|
1739
|
+
const language = options.locales.find((locale) => locale.code === code).language;
|
|
1740
|
+
const { args, tags } = compileCatalog(merged.messages, language, {
|
|
1741
|
+
file: (key) => merged.origin[key] ?? `locales/${code}.json`,
|
|
1742
|
+
syntax: options.syntax
|
|
1743
|
+
});
|
|
1744
|
+
return { ...merged, args, tags };
|
|
1745
|
+
};
|
|
1746
|
+
const base = await load(options.defaultLocale);
|
|
1747
|
+
const baseKeys = Object.keys(base.messages);
|
|
1748
|
+
const messages = {};
|
|
1749
|
+
for (const key of baseKeys) {
|
|
1750
|
+
const cases = new Map;
|
|
1751
|
+
if (options.syntax === "mf1")
|
|
1752
|
+
selectCases(parseMessage(base.messages[key]), cases);
|
|
1753
|
+
messages[key] = Object.fromEntries(Object.entries(base.args[key]).map(([name, kind]) => [name, typeOf(kind, cases.get(name))]));
|
|
1754
|
+
}
|
|
1755
|
+
const warnings = [];
|
|
1756
|
+
const tags = base.tags;
|
|
1757
|
+
if (baseKeys.length === 0)
|
|
1758
|
+
return { messages, tags, warnings };
|
|
1759
|
+
for (const { code } of options.locales) {
|
|
1760
|
+
if (code === options.defaultLocale || !byCode.has(code))
|
|
1761
|
+
continue;
|
|
1762
|
+
const own = await load(code);
|
|
1763
|
+
const file = `locales/${code}.json`;
|
|
1764
|
+
const missing = baseKeys.filter((key) => !Object.hasOwn(own.messages, key));
|
|
1765
|
+
if (missing.length)
|
|
1766
|
+
warnings.push(`${file} lacks ${missing.length} key${missing.length === 1 ? "" : "s"} of the default locale: ${missing.join(", ")}`);
|
|
1767
|
+
const extra = Object.keys(own.messages).filter((key) => !Object.hasOwn(base.messages, key));
|
|
1768
|
+
if (extra.length)
|
|
1769
|
+
warnings.push(`${file} has ${extra.length} key${extra.length === 1 ? "" : "s"} the default locale lacks: ${extra.join(", ")}`);
|
|
1770
|
+
for (const [key, args] of Object.entries(own.args)) {
|
|
1771
|
+
const expected = base.args[key];
|
|
1772
|
+
if (!expected)
|
|
1773
|
+
continue;
|
|
1774
|
+
const where = own.origin[key] ?? file;
|
|
1775
|
+
for (const tag of own.tags[key] ?? []) {
|
|
1776
|
+
if (!base.tags[key]?.includes(tag))
|
|
1777
|
+
throw new DiagnosticError8("HAMUR_E5827", `${where} ${JSON.stringify(key)}: tag <${tag}> is not in the default locale's message`);
|
|
1778
|
+
}
|
|
1779
|
+
for (const [name, kind] of Object.entries(args)) {
|
|
1780
|
+
if (!Object.hasOwn(expected, name))
|
|
1781
|
+
throw new DiagnosticError8("HAMUR_E5828", `${where} ${JSON.stringify(key)}: argument ${JSON.stringify(name)} is not in the default locale's message`);
|
|
1782
|
+
if (expected[name] !== kind)
|
|
1783
|
+
throw new DiagnosticError8("HAMUR_E5829", `${where} ${JSON.stringify(key)}: argument ${JSON.stringify(name)} is ${kind}, the default locale's message has ${expected[name]}`);
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
return { messages, tags, warnings };
|
|
1788
|
+
}
|
|
1789
|
+
function typesTemplate(options, analysis) {
|
|
1790
|
+
const messages = Object.entries(analysis.messages).map(([key, args]) => {
|
|
1791
|
+
const fields = Object.entries(args).map(([name, type]) => `${JSON.stringify(name)}: ${type}`);
|
|
1792
|
+
return ` ${JSON.stringify(key)}: ${fields.length ? `{ ${fields.join("; ")} }` : "{}"};`;
|
|
1793
|
+
});
|
|
1794
|
+
const locales = options.locales.map(({ code }) => ` ${JSON.stringify(code)}: true;`);
|
|
1795
|
+
const tagged = Object.entries(analysis.tags).map(([key, names]) => ` ${JSON.stringify(key)}: ${names.map((name) => JSON.stringify(name)).join(" | ")};`);
|
|
1796
|
+
const tags = tagged.length ? ` interface HamurI18nTags {
|
|
1797
|
+
${tagged.join(`
|
|
1798
|
+
`)}
|
|
1799
|
+
}
|
|
1800
|
+
` : "";
|
|
1801
|
+
return `declare module "@hamur/i18n" {
|
|
1802
|
+
interface HamurI18nMessages {
|
|
1803
|
+
${messages.join(`
|
|
1804
|
+
`)}
|
|
1805
|
+
}
|
|
1806
|
+
${tags} interface HamurI18nLocales {
|
|
1807
|
+
${locales.join(`
|
|
1808
|
+
`)}
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
export {};
|
|
1812
|
+
`;
|
|
1813
|
+
}
|
|
1814
|
+
function rootPathTypes(options, hamur) {
|
|
1815
|
+
if (!hamur.options.typescript.typedPaths || options.strategy !== "prefix" || options.detect.redirect === false)
|
|
1816
|
+
return "";
|
|
1817
|
+
return `declare module "hamur/app" {
|
|
1818
|
+
interface HamurRoutePaths {
|
|
1819
|
+
"i18n /": "/";
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
`;
|
|
1823
|
+
}
|
|
1824
|
+
var setupTypes = async (options, hamur) => {
|
|
1825
|
+
const { rootDir, layers } = hamur.options;
|
|
1826
|
+
const roots = [rootDir, ...layers.map((layer) => layer.rootDir)];
|
|
1827
|
+
const log = useLogger5("hamur");
|
|
1828
|
+
const analysis = await analyzeLocales(options, roots, rootDir);
|
|
1829
|
+
for (const text of analysis.warnings)
|
|
1830
|
+
log.warn(diagnostic5("HAMUR_W5830", `i18n: ${text}`));
|
|
1831
|
+
addTypeTemplate({
|
|
1832
|
+
filename: "i18n.d.ts",
|
|
1833
|
+
getContents: async () => typesTemplate(options, await analyzeLocales(options, roots, rootDir)) + rootPathTypes(options, hamur)
|
|
1834
|
+
});
|
|
1835
|
+
};
|
|
1836
|
+
|
|
1837
|
+
// packages/i18n/src/server/setup.ts
|
|
1838
|
+
import { addServer, createResolver as createResolver3 } from "hamur/kit";
|
|
1839
|
+
var setupServer = (options) => {
|
|
1840
|
+
const mode = options.domains ? "" : options.detect.redirect === "root" ? "-root" : options.detect.redirect === "all" && options.strategy !== "no_prefix" ? "-all" : "";
|
|
1841
|
+
const door = "./door" + mode + (options.catalog === undefined ? "" : "-catalog") + ".ts";
|
|
1842
|
+
addServer(createResolver3(new URL("../../src/server/setup.ts", import.meta.url).href).resolve(door));
|
|
1843
|
+
};
|
|
1844
|
+
|
|
1845
|
+
// packages/i18n/src/module.ts
|
|
1846
|
+
var resolvedOptions = new WeakMap;
|
|
1847
|
+
var DOMAIN_STATIC = "i18n: locales[].domain needs a server preset (static serves one host)";
|
|
1848
|
+
var CATALOG_STATIC = "i18n.catalog needs a server preset (static has no server to load the catalog)";
|
|
1849
|
+
var DOMAIN_ORIGIN = "i18n: locales[].domain cannot be used with app.origin, which gives every request one host";
|
|
1850
|
+
var PATH_KEYED_ISR = new Set(["vercel", "netlify"]);
|
|
1851
|
+
var domainIsrError = (preset, pattern) => "i18n: locales[].domain cannot be used with an isr route rule on the " + preset + " preset (" + JSON.stringify(pattern) + "); its ISR cache keys on the path, not the host";
|
|
1852
|
+
var isIsr = (rule) => {
|
|
1853
|
+
const isr = rule?.isr;
|
|
1854
|
+
return isr === true || typeof isr === "number" && isr > 0;
|
|
1855
|
+
};
|
|
1856
|
+
function checkDomainHosting(hamur) {
|
|
1857
|
+
const { preset, app, routeRules } = hamur.options;
|
|
1858
|
+
if (isStaticPreset(preset))
|
|
1859
|
+
throw new DiagnosticError9("HAMUR_E5802", DOMAIN_STATIC);
|
|
1860
|
+
if (app.origin !== undefined)
|
|
1861
|
+
throw new DiagnosticError9("HAMUR_E5803", DOMAIN_ORIGIN);
|
|
1862
|
+
if (!PATH_KEYED_ISR.has(preset))
|
|
1863
|
+
return;
|
|
1864
|
+
for (const [pattern, rule] of Object.entries(routeRules)) {
|
|
1865
|
+
if ((Array.isArray(rule) ? rule : [rule]).some(isIsr))
|
|
1866
|
+
throw new DiagnosticError9("HAMUR_E5804", domainIsrError(preset, pattern));
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
var module_default = defineModule({
|
|
1870
|
+
meta: { name: "i18n", configKey: "i18n" },
|
|
1871
|
+
async setup(input, hamur) {
|
|
1872
|
+
const options = resolveOptions(input);
|
|
1873
|
+
if (options.domains)
|
|
1874
|
+
checkDomainHosting(hamur);
|
|
1875
|
+
if (options.catalog !== undefined && isStaticPreset(hamur.options.preset))
|
|
1876
|
+
throw new DiagnosticError9("HAMUR_E5805", CATALOG_STATIC);
|
|
1877
|
+
await setupRoutes(options, hamur);
|
|
1878
|
+
await setupMessages(options, hamur);
|
|
1879
|
+
await setupCatalog(options, hamur);
|
|
1880
|
+
await setupServer(options, hamur);
|
|
1881
|
+
await setupHead(options, hamur);
|
|
1882
|
+
await setupPrerender(options, hamur);
|
|
1883
|
+
await setupTypes(options, hamur);
|
|
1884
|
+
resolvedOptions.set(hamur, options);
|
|
1885
|
+
}
|
|
1886
|
+
});
|
|
1887
|
+
|
|
1888
|
+
// packages/i18n/src/cli.ts
|
|
1889
|
+
import { DiagnosticError as DiagnosticError10 } from "hamur/kit";
|
|
1890
|
+
async function runI18nCommand(args, hamur) {
|
|
1891
|
+
const options = resolvedOptions.get(hamur);
|
|
1892
|
+
if (!options)
|
|
1893
|
+
throw new DiagnosticError10("HAMUR_E5801", "hamur i18n needs @hamur/i18n (bun add @hamur/i18n, then add it to modules)");
|
|
1894
|
+
return extract(hamur, options, { check: args.check === true, prune: args.prune === true }, args.out);
|
|
1895
|
+
}
|
|
1896
|
+
export {
|
|
1897
|
+
runI18nCommand
|
|
1898
|
+
};
|