@hamur/i18n 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/bun-index-1ve1hj66.js +744 -0
  4. package/dist/chunks/bun-index-8bw4xpv8.js +93 -0
  5. package/dist/chunks/bun-index-ej6vjnjs.js +297 -0
  6. package/dist/chunks/bun-index-pdepkyy1.js +474 -0
  7. package/dist/src/adapters/angular.js +67 -0
  8. package/dist/src/adapters/html.js +34 -0
  9. package/dist/src/adapters/preact.js +23 -0
  10. package/dist/src/adapters/react.js +23 -0
  11. package/dist/src/adapters/solid.js +48 -0
  12. package/dist/src/adapters/svelte.js +74 -0
  13. package/dist/src/adapters/vue.js +48 -0
  14. package/dist/src/cli.js +1898 -0
  15. package/dist/src/index.js +2755 -0
  16. package/dist/src/load.js +35 -0
  17. package/dist/src/server/index.js +395 -0
  18. package/dist/types/src/adapters/angular.d.ts +17 -0
  19. package/dist/types/src/adapters/bind.d.ts +44 -0
  20. package/dist/types/src/adapters/html.d.ts +5 -0
  21. package/dist/types/src/adapters/preact.d.ts +6 -0
  22. package/dist/types/src/adapters/react.d.ts +6 -0
  23. package/dist/types/src/adapters/solid.d.ts +9 -0
  24. package/dist/types/src/adapters/svelte.d.ts +12 -0
  25. package/dist/types/src/adapters/vue.d.ts +8 -0
  26. package/dist/types/src/build/catalog.d.ts +5 -0
  27. package/dist/types/src/build/drop.d.ts +12 -0
  28. package/dist/types/src/build/extract.d.ts +11 -0
  29. package/dist/types/src/build/head.d.ts +4 -0
  30. package/dist/types/src/build/messages.d.ts +27 -0
  31. package/dist/types/src/build/prerender.d.ts +10 -0
  32. package/dist/types/src/build/routes.d.ts +14 -0
  33. package/dist/types/src/build/split.d.ts +37 -0
  34. package/dist/types/src/build/types.d.ts +15 -0
  35. package/dist/types/src/cli.d.ts +12 -0
  36. package/dist/types/src/compiler/compile.d.ts +17 -0
  37. package/dist/types/src/compiler/mf2-parse.d.ts +62 -0
  38. package/dist/types/src/compiler/mf2.d.ts +3 -0
  39. package/dist/types/src/compiler/parse.d.ts +58 -0
  40. package/dist/types/src/compiler/skeleton.d.ts +7 -0
  41. package/dist/types/src/index.d.ts +2 -0
  42. package/dist/types/src/load.d.ts +7 -0
  43. package/dist/types/src/module.d.ts +15 -0
  44. package/dist/types/src/options.d.ts +7 -0
  45. package/dist/types/src/runtime/catalog-client.d.ts +3 -0
  46. package/dist/types/src/runtime/catalog-loader.d.ts +15 -0
  47. package/dist/types/src/runtime/catalog-server.d.ts +5 -0
  48. package/dist/types/src/runtime/catalog.d.ts +60 -0
  49. package/dist/types/src/runtime/chain.d.ts +3 -0
  50. package/dist/types/src/runtime/format.d.ts +27 -0
  51. package/dist/types/src/runtime/head.d.ts +9 -0
  52. package/dist/types/src/runtime/interpret.d.ts +20 -0
  53. package/dist/types/src/runtime/link.d.ts +8 -0
  54. package/dist/types/src/runtime/locale.d.ts +73 -0
  55. package/dist/types/src/runtime/match.d.ts +54 -0
  56. package/dist/types/src/runtime/messages.d.ts +42 -0
  57. package/dist/types/src/runtime/middleware.d.ts +2 -0
  58. package/dist/types/src/runtime/negotiate.d.ts +9 -0
  59. package/dist/types/src/runtime/plugin.d.ts +4 -0
  60. package/dist/types/src/runtime/redirect.d.ts +32 -0
  61. package/dist/types/src/runtime/rich.d.ts +5 -0
  62. package/dist/types/src/runtime/translate.d.ts +21 -0
  63. package/dist/types/src/server/catalog.d.ts +2 -0
  64. package/dist/types/src/server/context.d.ts +48 -0
  65. package/dist/types/src/server/door-all-catalog.d.ts +3 -0
  66. package/dist/types/src/server/door-all.d.ts +2 -0
  67. package/dist/types/src/server/door-catalog.d.ts +3 -0
  68. package/dist/types/src/server/door-root-catalog.d.ts +3 -0
  69. package/dist/types/src/server/door-root.d.ts +2 -0
  70. package/dist/types/src/server/door.d.ts +2 -0
  71. package/dist/types/src/server/index.d.ts +7 -0
  72. package/dist/types/src/server/preferred.d.ts +6 -0
  73. package/dist/types/src/server/redirect.d.ts +3 -0
  74. package/dist/types/src/server/setup.d.ts +2 -0
  75. package/dist/types/src/types.d.ts +163 -0
  76. package/package.json +122 -4
  77. package/src/adapters/angular.ts +65 -0
  78. package/src/adapters/bind.ts +144 -0
  79. package/src/adapters/html.ts +35 -0
  80. package/src/adapters/preact.ts +18 -0
  81. package/src/adapters/react.ts +18 -0
  82. package/src/adapters/solid.ts +44 -0
  83. package/src/adapters/svelte.ts +75 -0
  84. package/src/adapters/test/SveltePage.svelte +18 -0
  85. package/src/adapters/test/SvelteReporting.svelte +20 -0
  86. package/src/adapters/test/SvelteRich.svelte +11 -0
  87. package/src/adapters/test/SvelteRichPlain.svelte +11 -0
  88. package/src/adapters/test/peer.ts +7 -0
  89. package/src/adapters/test/preact-client.ts +43 -0
  90. package/src/adapters/test/preact-page.ts +34 -0
  91. package/src/adapters/test/preact-rich.ts +9 -0
  92. package/src/adapters/test/react-client.ts +49 -0
  93. package/src/adapters/test/react-page.ts +34 -0
  94. package/src/adapters/test/react-rich.ts +15 -0
  95. package/src/adapters/test/runtime.ts +104 -0
  96. package/src/adapters/test/solid-client.ts +33 -0
  97. package/src/adapters/test/solid-page.ts +30 -0
  98. package/src/adapters/test/solid-rich.ts +5 -0
  99. package/src/adapters/test/svelte-client.ts +51 -0
  100. package/src/adapters/test/svelte-log.ts +2 -0
  101. package/src/adapters/test/svelte-plugin.ts +20 -0
  102. package/src/adapters/test/vue-page.ts +26 -0
  103. package/src/adapters/test/vue-rich.ts +16 -0
  104. package/src/adapters/vue.ts +44 -0
  105. package/src/build/catalog.ts +44 -0
  106. package/src/build/drop.ts +36 -0
  107. package/src/build/extract.ts +207 -0
  108. package/src/build/head.ts +10 -0
  109. package/src/build/messages.ts +347 -0
  110. package/src/build/prerender.ts +48 -0
  111. package/src/build/routes.ts +269 -0
  112. package/src/build/split.ts +240 -0
  113. package/src/build/types.ts +156 -0
  114. package/src/cli.ts +25 -0
  115. package/src/compiler/compile.ts +190 -0
  116. package/src/compiler/mf2-parse.ts +469 -0
  117. package/src/compiler/mf2.ts +393 -0
  118. package/src/compiler/parse.ts +265 -0
  119. package/src/compiler/skeleton.ts +85 -0
  120. package/src/env.d.ts +55 -0
  121. package/src/index.ts +24 -0
  122. package/src/load.ts +41 -0
  123. package/src/module.ts +66 -0
  124. package/src/options.ts +198 -0
  125. package/src/runtime/catalog-client.ts +28 -0
  126. package/src/runtime/catalog-loader.ts +28 -0
  127. package/src/runtime/catalog-server.ts +36 -0
  128. package/src/runtime/catalog.ts +190 -0
  129. package/src/runtime/chain.ts +9 -0
  130. package/src/runtime/format.ts +102 -0
  131. package/src/runtime/head.ts +57 -0
  132. package/src/runtime/interpret.ts +504 -0
  133. package/src/runtime/link.ts +36 -0
  134. package/src/runtime/locale.ts +392 -0
  135. package/src/runtime/match.ts +334 -0
  136. package/src/runtime/messages.ts +129 -0
  137. package/src/runtime/middleware.ts +32 -0
  138. package/src/runtime/negotiate.ts +61 -0
  139. package/src/runtime/plugin.ts +69 -0
  140. package/src/runtime/redirect.ts +191 -0
  141. package/src/runtime/rich.ts +21 -0
  142. package/src/runtime/translate.ts +131 -0
  143. package/src/server/catalog.ts +11 -0
  144. package/src/server/context.ts +191 -0
  145. package/src/server/door-all-catalog.ts +7 -0
  146. package/src/server/door-all.ts +5 -0
  147. package/src/server/door-catalog.ts +6 -0
  148. package/src/server/door-root-catalog.ts +7 -0
  149. package/src/server/door-root.ts +5 -0
  150. package/src/server/door.ts +4 -0
  151. package/src/server/index.ts +11 -0
  152. package/src/server/preferred.ts +12 -0
  153. package/src/server/redirect.ts +26 -0
  154. package/src/server/setup.ts +14 -0
  155. package/src/types.ts +182 -0
@@ -0,0 +1,347 @@
1
+ import { createHash } from "node:crypto"
2
+ import { readdir, readFile, realpath } from "node:fs/promises"
3
+ import { basename, join, relative } from "node:path"
4
+ import { DiagnosticError, addBunPlugin, addTemplate, diagnostic, useLogger, type HamurContext } from "hamur/kit"
5
+ import { compileCatalog, type CompiledCatalog } from "../compiler/compile.ts"
6
+ import { CODE } from "../options.ts"
7
+ import { fallbackChain } from "../runtime/chain.ts"
8
+ import type { I18nSetup, ResolvedI18nOptions } from "../types.ts"
9
+ import { routeTableOf } from "./routes.ts"
10
+ import { keepMatcher, readClientInputs } from "./drop.ts"
11
+ import { planSplit, type SplitPlan } from "./split.ts"
12
+
13
+ export interface LocaleFiles {
14
+ /** Locale code to its files, the highest priority first. */
15
+ byCode: Map<string, string[]>
16
+ /** Files in a `locales/` whose name is not a locale code. */
17
+ ignored: string[]
18
+ }
19
+
20
+ /** The `locales/<code>.json` of each root (the app, then its layers), for the configured codes. */
21
+ export async function scanLocaleFiles(roots: string[], codes: string[]): Promise<LocaleFiles> {
22
+ const byCode = new Map<string, string[]>()
23
+ const ignored: string[] = []
24
+ for (const root of roots) {
25
+ const dir = join(root, "locales")
26
+ const names = await readdir(dir).catch(() => [] as string[])
27
+ for (const name of names.filter((entry) => entry.endsWith(".json")).sort()) {
28
+ const code = name.slice(0, -".json".length)
29
+ if (!CODE.test(code)) ignored.push(join(dir, name))
30
+ else if (codes.includes(code)) byCode.set(code, [...(byCode.get(code) ?? []), join(dir, name)])
31
+ }
32
+ }
33
+ return { byCode, ignored }
34
+ }
35
+
36
+ /** The first key defined twice in one JSON object, as a dotted path; `JSON.parse` keeps the last one silently. */
37
+ export function duplicateKey(text: string): string | undefined {
38
+ const stack: Array<{ keys?: Set<string>; path: string; expectKey: boolean }> = []
39
+ let pending = ""
40
+ for (let i = 0; i < text.length; i++) {
41
+ const c = text[i]!
42
+ const top = stack.at(-1)
43
+ if (c === '"') {
44
+ let end = i + 1
45
+ while (text[end] !== '"') end += text[end] === "\\" ? 2 : 1
46
+ const value = JSON.parse(text.slice(i, end + 1)) as string
47
+ i = end
48
+ if (top?.keys && top.expectKey) {
49
+ const path = top.path ? `${top.path}.${value}` : value
50
+ if (top.keys.has(value)) return path
51
+ top.keys.add(value)
52
+ top.expectKey = false
53
+ pending = path
54
+ }
55
+ } else if (c === "{") {
56
+ stack.push({ keys: new Set(), path: top?.keys ? pending : (top?.path ?? ""), expectKey: true })
57
+ } else if (c === "[") {
58
+ stack.push({ path: top?.keys ? pending : (top?.path ?? ""), expectKey: false })
59
+ } else if (c === "}" || c === "]") {
60
+ stack.pop()
61
+ } else if (c === "," && top?.keys) {
62
+ top.expectKey = true
63
+ }
64
+ }
65
+ return undefined
66
+ }
67
+
68
+ /** `{ "home": { "title": "x" } }` as `{ "home.title": "x" }`; its JSON errors name `file` and the key. */
69
+ export function flattenMessages(value: unknown, file: string): Record<string, string> {
70
+ const out: Record<string, string> = {}
71
+ const walk = (node: Record<string, unknown>, prefix: string) => {
72
+ for (const [name, child] of Object.entries(node)) {
73
+ const key = prefix + name
74
+ if (name === "")
75
+ throw new DiagnosticError("HAMUR_E5809", `key ${JSON.stringify(key)} must not be empty or contain "."`, {
76
+ at: file,
77
+ })
78
+ if (name.includes("."))
79
+ throw new DiagnosticError(
80
+ "HAMUR_E5809",
81
+ `key ${JSON.stringify(key)} contains "."; "." nests keys ({ "a": { "b": … } } is "a.b"), so use a key without it and put the text in the value: "Type to search": "Type to search..."`,
82
+ { at: file },
83
+ )
84
+ if (typeof child === "string") out[key] = child
85
+ else if (child !== null && typeof child === "object" && !Array.isArray(child))
86
+ walk(child as Record<string, unknown>, `${key}.`)
87
+ else
88
+ throw new DiagnosticError("HAMUR_E5810", `${JSON.stringify(key)} must be a string or an object`, { at: file })
89
+ }
90
+ }
91
+ if (value === null || typeof value !== "object" || Array.isArray(value))
92
+ throw new DiagnosticError("HAMUR_E5811", "must be a JSON object", { at: file })
93
+ walk(value as Record<string, unknown>, "")
94
+ return out
95
+ }
96
+
97
+ export interface MergedMessages {
98
+ messages: Record<string, string>
99
+ /** The file each key came from. */
100
+ origin: Record<string, string>
101
+ }
102
+
103
+ /** The flattened messages of `files` (the highest priority first); a key in an earlier file wins. */
104
+ export async function mergeLocaleFiles(files: string[], rootDir: string): Promise<MergedMessages> {
105
+ const messages: Record<string, string> = {}
106
+ const origin: Record<string, string> = {}
107
+ for (const path of files) {
108
+ const file = relative(rootDir, path)
109
+ const text = await readFile(path, "utf8")
110
+ let json: unknown
111
+ try {
112
+ json = JSON.parse(text)
113
+ } catch (error) {
114
+ throw new DiagnosticError("HAMUR_E5812", `invalid JSON (${(error as Error).message})`, { at: file })
115
+ }
116
+ const twice = duplicateKey(text)
117
+ if (twice) throw new DiagnosticError("HAMUR_E5813", `${JSON.stringify(twice)} is defined twice`, { at: file })
118
+ for (const [key, message] of Object.entries(flattenMessages(json, file))) {
119
+ if (Object.hasOwn(messages, key)) continue
120
+ messages[key] = message
121
+ origin[key] = file
122
+ }
123
+ }
124
+ return { messages, origin }
125
+ }
126
+
127
+ /** `own` plus every key a locale of `chain` has, the first of the chain winning; the added keys are listed in `filled`. */
128
+ export function fillFromChain(
129
+ own: MergedMessages,
130
+ chain: MergedMessages[],
131
+ ): { merged: MergedMessages; filled: string[] } {
132
+ const merged: MergedMessages = { messages: { ...own.messages }, origin: { ...own.origin } }
133
+ const filled: string[] = []
134
+ for (const base of chain) {
135
+ for (const [key, message] of Object.entries(base.messages)) {
136
+ if (Object.hasOwn(merged.messages, key)) continue
137
+ merged.messages[key] = message
138
+ merged.origin[key] = base.origin[key]!
139
+ filled.push(key)
140
+ }
141
+ }
142
+ return { merged, filled }
143
+ }
144
+
145
+ const chunkSpecifier = (appId: string, id: string) =>
146
+ `#${appId}-chunk/${createHash("sha256").update(id).digest("hex").slice(0, 8)}`
147
+
148
+ /** The per-locale modules `#hamur/i18n/<code>`, the loaders and the server's chunk table. */
149
+ export const setupMessages: I18nSetup = async (options: ResolvedI18nOptions, hamur: HamurContext) => {
150
+ const { rootDir, layers, dev } = hamur.options
151
+ const log = useLogger("hamur")
152
+ const warned = new Set<string>()
153
+ const warn = (text: string) => {
154
+ if (warned.has(text)) return
155
+ warned.add(text)
156
+ log.warn(diagnostic("HAMUR_W5831", `i18n: ${text}`))
157
+ }
158
+ const { byCode, ignored } = await scanLocaleFiles(
159
+ [rootDir, ...layers.map((layer) => layer.rootDir)],
160
+ options.locales.map((locale) => locale.code),
161
+ )
162
+ for (const path of ignored)
163
+ warn(`${relative(rootDir, path)} is ignored: "${basename(path, ".json")}" is not a locale code`)
164
+ for (const { code } of options.locales) {
165
+ if (!byCode.has(code)) warn(`no locales/${code}.json in the app or a layer; every key of ${code} falls back`)
166
+ }
167
+
168
+ const drop = options.dropUnusedKeys && !dev
169
+ let keep: ((key: string) => boolean) | undefined
170
+
171
+ const compile = async (code: string, only?: ReadonlySet<string>, client = false): Promise<CompiledCatalog> => {
172
+ const language = options.locales.find((locale) => locale.code === code)!.language
173
+ let merged = await mergeLocaleFiles(byCode.get(code) ?? [], rootDir)
174
+ let filled: string[] = []
175
+ const chain = fallbackChain(options.fallback, options.defaultLocale, code)
176
+ if (chain.length > 0) {
177
+ ;({ merged, filled } = fillFromChain(
178
+ merged,
179
+ await Promise.all(chain.map((member) => mergeLocaleFiles(byCode.get(member) ?? [], rootDir))),
180
+ ))
181
+ }
182
+ const { origin } = merged
183
+ const wanted = (key: string) => (!only || only.has(key)) && (!client || !keep || keep(key))
184
+ const messages =
185
+ only || (client && keep)
186
+ ? Object.fromEntries(Object.entries(merged.messages).filter(([key]) => wanted(key)))
187
+ : merged.messages
188
+ const compiled = compileCatalog(messages, language, {
189
+ file: (key) => origin[key] ?? `locales/${code}.json`,
190
+ warn,
191
+ syntax: options.syntax,
192
+ })
193
+ return dev
194
+ ? { ...compiled, code: `${compiled.code}export const fallbacks = ${JSON.stringify(filled)};\n` }
195
+ : compiled
196
+ }
197
+ for (const { code } of options.locales) await compile(code)
198
+
199
+ const anchors = new Map<string, string>()
200
+ for (const { code } of options.locales) {
201
+ const anchor = byCode.get(code)?.[0]
202
+ if (dev && anchor) {
203
+ anchors.set(anchor, code)
204
+ anchors.set(await realpath(anchor), code)
205
+ }
206
+ addTemplate({
207
+ filename: `i18n/${code}`,
208
+ getContents: async () =>
209
+ anchor && dev
210
+ ? `export { default, fallbacks } from ${JSON.stringify(anchor)};\n`
211
+ : `${(await compile(code)).code}export const locale = ${JSON.stringify(code)};\n`,
212
+ })
213
+ }
214
+ if (anchors.size) {
215
+ const filter = new RegExp(
216
+ `^(${[...anchors.keys()].map((path) => path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`,
217
+ )
218
+ addBunPlugin({
219
+ name: "hamur-i18n-messages",
220
+ setup(build) {
221
+ build.onLoad({ filter }, async ({ path }) => ({
222
+ contents: (await compile(anchors.get(path)!)).code,
223
+ loader: "js",
224
+ }))
225
+ },
226
+ })
227
+ }
228
+
229
+ const split = options.split === "route" && !dev
230
+ const chunked = split || drop
231
+ const names = () => (split ? ["_shared", ...Object.keys(routeTableOf(hamur).routes)] : ["_shared"])
232
+ const table = (entry: (code: string) => string) =>
233
+ "{\n" + options.locales.map(({ code }) => " " + JSON.stringify(code) + ": " + entry(code) + ",").join("\n") + "\n}"
234
+ const loader = (id: string) => "() => import(" + JSON.stringify(id) + ")"
235
+ const full = table((code) => loader("#hamur/i18n/" + code))
236
+ addTemplate({
237
+ filename: "i18n/loaders",
238
+ getContents: () => {
239
+ if (!chunked) return "export default " + full + ";\nexport const routes = {};\n"
240
+ const routes = table(
241
+ (code) =>
242
+ "{ " +
243
+ names()
244
+ .map((name) => JSON.stringify(name) + ": " + loader("#hamur/i18n/" + code + "/" + name))
245
+ .join(", ") +
246
+ " }",
247
+ )
248
+ return (
249
+ "export default import.meta.server ? " +
250
+ full +
251
+ " : {};\nexport const routes = import.meta.server ? {} : " +
252
+ routes +
253
+ ";\n"
254
+ )
255
+ },
256
+ })
257
+ addTemplate({
258
+ filename: "i18n/chunks",
259
+ getContents: (context) => {
260
+ const map = context.manifest.importMap ?? {}
261
+ const urlOf = (id: string) => map[chunkSpecifier(hamur.options.appId, "hamur-virtual:" + id)]
262
+ const chunks = Object.fromEntries(
263
+ options.locales.flatMap(({ code }) => {
264
+ if (!chunked) {
265
+ const url = urlOf("#hamur/i18n/" + code)
266
+ return url ? [[code, url]] : []
267
+ }
268
+ const urls = names().flatMap((name) => {
269
+ const url = urlOf("#hamur/i18n/" + code + "/" + name)
270
+ return url ? [[name, url]] : []
271
+ })
272
+ return [[code, Object.fromEntries(urls)]]
273
+ }),
274
+ )
275
+ return "export default " + JSON.stringify(chunks) + ";\n"
276
+ },
277
+ })
278
+ if (drop) {
279
+ const matchers = options.keepKeys.map(keepMatcher)
280
+ hamur.hooks.hook("build:client:config", async (config) => {
281
+ if (!config.entrypoints.includes("#hamur/client-entry")) return
282
+ // The locale chunks are loaded while the client build runs, so the keys it reads are found by a first build with empty chunks.
283
+ keep = () => false
284
+ let inputs: string[]
285
+ try {
286
+ const probe: Bun.BuildConfig = {
287
+ ...config,
288
+ splitting: false,
289
+ minify: false,
290
+ sourcemap: "none",
291
+ metafile: true,
292
+ throw: false,
293
+ }
294
+ delete probe.outdir
295
+ const result = await Bun.build(probe)
296
+ if (!result.success) return
297
+ inputs = Object.keys(result.metafile?.inputs ?? {})
298
+ } finally {
299
+ keep = undefined
300
+ }
301
+ const read = await readClientInputs(inputs, rootDir)
302
+ if (read.dynamic) {
303
+ warn(
304
+ relative(rootDir, read.dynamic.file) +
305
+ ":" +
306
+ read.dynamic.line +
307
+ " uses a dynamic message key, so dropUnusedKeys is off for this build",
308
+ )
309
+ return
310
+ }
311
+ const kept = (key: string) => read.keys.has(key) || matchers.some((matcher) => matcher.test(key))
312
+ const all = new Set<string>()
313
+ for (const { code } of options.locales)
314
+ for (const key of Object.keys((await mergeLocaleFiles(byCode.get(code) ?? [], rootDir)).messages)) all.add(key)
315
+ keep = kept
316
+ log.info("i18n: dropped " + [...all].filter((key) => !kept(key)).length + " of " + all.size + " keys")
317
+ })
318
+ }
319
+ if (!chunked) return
320
+
321
+ let planned: Promise<SplitPlan> | undefined
322
+ const plan = () => {
323
+ planned ??= planSplit(hamur).then((made) => {
324
+ const files = new Set([...made.shared.dynamic, ...[...made.routes.values()].flatMap((entry) => entry.dynamic)])
325
+ for (const file of files)
326
+ for (const { code } of options.locales)
327
+ warn(relative(rootDir, file) + " uses a dynamic message key; its route ships the full " + code + " catalog")
328
+ return made
329
+ })
330
+ return planned
331
+ }
332
+ hamur.hooks.hook("templates:extend", (templates) => {
333
+ for (const { code } of options.locales) {
334
+ for (const name of names()) {
335
+ templates.push({
336
+ filename: "i18n/" + code + "/" + name,
337
+ getContents: async () => {
338
+ if (!split) return (await compile(code, undefined, true)).code
339
+ const { shared, routes } = await plan()
340
+ const own = name === "_shared" ? shared : routes.get(name)
341
+ return (await compile(code, own && own.dynamic.length === 0 ? own.keys : undefined, true)).code
342
+ },
343
+ })
344
+ }
345
+ }
346
+ })
347
+ }
@@ -0,0 +1,48 @@
1
+ import { diagnostic, useLogger } from "hamur/kit"
2
+ import { createMatcher } from "../runtime/match.ts"
3
+ import type { I18nSetup } from "../types.ts"
4
+ import { routeTableOf } from "./routes.ts"
5
+
6
+ /** On a static preset the one URL of a page under `no_prefix` is written in the default locale only. */
7
+ export const noPrefixPrerenderWarning = (defaultLocale: string): string =>
8
+ "[hamur] i18n: no_prefix prerenders only the default locale (" +
9
+ defaultLocale +
10
+ "); other locales render at request time"
11
+
12
+ export const isStaticPreset = (preset: string): boolean =>
13
+ preset === "static" || preset.endsWith("-static") || preset === "github-pages" || preset === "gitlab-pages"
14
+
15
+ /**
16
+ * Every seeded page is also seeded in every other locale. Under `no_prefix` a page has one URL: a server
17
+ * preset prerenders no page (a `prerender.ignore` entry), so each renders in the request's locale; a static preset writes it in
18
+ * the default locale and the build warns once. With domains the host picks the locale, so no page is prerendered either.
19
+ */
20
+ export const setupPrerender: I18nSetup = (options, hamur) => {
21
+ if (options.strategy === "no_prefix" || options.domains) {
22
+ if (options.domains || !isStaticPreset(hamur.options.preset)) {
23
+ hamur.options.prerender.ignore.push((path) => createMatcher(routeTableOf(hamur)).matchPath(path) !== undefined)
24
+ return
25
+ }
26
+ let warned = false
27
+ hamur.hooks.hook("prerender:routes", (seeds) => {
28
+ if (seeds.size === 0 || warned) return
29
+ warned = true
30
+ useLogger("hamur").warn(
31
+ diagnostic("HAMUR_W5834", noPrefixPrerenderWarning(options.defaultLocale).replace(/^\[hamur\] /, "")),
32
+ )
33
+ })
34
+ return
35
+ }
36
+ hamur.hooks.hook("prerender:routes", (seeds) => {
37
+ const table = routeTableOf(hamur)
38
+ const { matchPath, buildPath } = createMatcher(table)
39
+ const hidden = (name: string, code: string) =>
40
+ options.missingPage === "404" && table.missing?.[name]?.includes(code)
41
+ for (const seed of [...seeds]) {
42
+ const match = matchPath(seed)
43
+ if (!match || table.missing?.[match.name]?.includes(match.code)) continue
44
+ for (const { code } of options.locales)
45
+ if (code !== match.code && !hidden(match.name, code)) seeds.add(buildPath(match.name, code, match.params))
46
+ }
47
+ })
48
+ }
@@ -0,0 +1,269 @@
1
+ import { relative } from "node:path"
2
+ import {
3
+ DiagnosticError,
4
+ addAppPlugin,
5
+ addRouteMiddleware,
6
+ addTemplate,
7
+ createResolver,
8
+ diagnostic,
9
+ extendPages,
10
+ useLogger,
11
+ type RouteRecord,
12
+ type HamurContext,
13
+ } from "hamur/kit"
14
+ import { parsePattern, type RouteTable, type Segment } from "../runtime/match.ts"
15
+ import type { ResolvedI18nOptions } from "../types.ts"
16
+
17
+ const SEPARATOR = "___"
18
+
19
+ type ParamKind = "param" | "optional" | "catchAll" | "optionalCatchAll"
20
+
21
+ function paramsOf(segments: Segment[]): { name: string; kind: ParamKind }[] {
22
+ return segments.flatMap((segment) => {
23
+ if (segment.kind === "static") return []
24
+ if (segment.kind === "mixed")
25
+ return segment.parts.flatMap((part) =>
26
+ typeof part === "string"
27
+ ? []
28
+ : [{ name: part.param, kind: part.optional ? ("optional" as const) : ("param" as const) }],
29
+ )
30
+ return [{ name: segment.name, kind: segment.kind }]
31
+ })
32
+ }
33
+
34
+ const signature = (segments: Segment[]) =>
35
+ paramsOf(segments)
36
+ .map(({ name, kind }) => `${name}:${kind}`)
37
+ .sort()
38
+ .join(",")
39
+
40
+ function shapeOf(path: string): string {
41
+ const parts = parsePattern(path).map((segment) => {
42
+ if (segment.kind === "static") return segment.text
43
+ if (segment.kind === "mixed")
44
+ return segment.parts.map((part) => (typeof part === "string" ? part : part.optional ? "\0?\0" : "\0")).join("")
45
+ return { param: ":", optional: ":?", catchAll: "**", optionalCatchAll: "**?" }[segment.kind]
46
+ })
47
+ return `/${parts.join("/")}`
48
+ }
49
+
50
+ function flatten(records: RouteRecord[], ancestors: string[] = []): { record: RouteRecord; ancestors: string[] }[] {
51
+ return records.flatMap((record) => [...flatten(record.children, [...ancestors, record.name]), { record, ancestors }])
52
+ }
53
+
54
+ function tableOf(records: RouteRecord[], options: ResolvedI18nOptions, copies: string[]): RouteTable {
55
+ const table: RouteTable = { copies, routes: {}, aliases: {} }
56
+ for (const { record } of flatten(records)) {
57
+ const index = record.name.indexOf(SEPARATOR)
58
+ const base = index === -1 ? record.name : record.name.slice(0, index)
59
+ const code = index === -1 ? options.defaultLocale : record.name.slice(index + SEPARATOR.length)
60
+ const own =
61
+ index !== -1 && code === options.defaultLocale && options.strategy === "prefix_and_default"
62
+ ? (table.aliases![base] ??= {})
63
+ : (table.routes[base] ??= {})
64
+ own[code] = record.path
65
+ }
66
+ return table
67
+ }
68
+
69
+ export interface LocalizedRoutes {
70
+ routes: RouteRecord[]
71
+ table: RouteTable
72
+ }
73
+
74
+ /** The page records with their per-locale copies, and the route table of `#hamur/i18n/routes`; `routes` is not changed. */
75
+ export function localizeRoutes(routes: RouteRecord[], options: ResolvedI18nOptions, rootDir = ""): LocalizedRoutes {
76
+ if (options.strategy === "no_prefix") return { routes, table: tableOf(routes, options, []) }
77
+ const shown = (file: string) => (rootDir ? relative(rootDir, file) : file)
78
+ const originals = flatten(routes)
79
+ for (const { record } of originals) {
80
+ if (record.name.includes(SEPARATOR))
81
+ throw new DiagnosticError(
82
+ "HAMUR_E5816",
83
+ `i18n: route name "${record.name}" (${shown(record.file)}) contains "___", which route copies use`,
84
+ )
85
+ }
86
+ const byName = new Map(originals.map(({ record }) => [record.name, record]))
87
+ const codes = new Set<string>(options.locales.map((locale) => locale.code))
88
+ for (const [name, paths] of Object.entries(options.pages)) {
89
+ const record = byName.get(name)
90
+ if (!record) throw new DiagnosticError("HAMUR_E5817", `i18n.pages: no route named "${name}"`)
91
+ const own = parsePattern(record.path)
92
+ for (const [code, path] of Object.entries(paths ?? {})) {
93
+ if (!codes.has(code))
94
+ throw new DiagnosticError("HAMUR_E5818", `i18n.pages.${name}: "${code}" is not in i18n.locales`)
95
+ if (path === false) continue
96
+ let segments: Segment[]
97
+ try {
98
+ if (typeof path !== "string") throw new Error("not a string")
99
+ segments = parsePattern(path)
100
+ } catch {
101
+ throw new DiagnosticError(
102
+ "HAMUR_E5819",
103
+ `i18n.pages.${name}.${code} ${JSON.stringify(path)} must be a route path starting with "/"`,
104
+ )
105
+ }
106
+ if (signature(segments) !== signature(own)) {
107
+ const names = paramsOf(own).map((param) => param.name)
108
+ throw new DiagnosticError(
109
+ "HAMUR_E5820",
110
+ `i18n.pages.${name}.${code} ${JSON.stringify(path)} must keep the params of "${record.path}" (${names.length ? names.join(", ") : "none"})`,
111
+ )
112
+ }
113
+ }
114
+ }
115
+
116
+ const localized = (record: RouteRecord, code: string) => {
117
+ const own = options.pages[record.name]?.[code]
118
+ return typeof own === "string" ? own : record.path
119
+ }
120
+ const domains = options.domains
121
+ const absent = (record: RouteRecord, code: string) => options.pages[record.name]?.[code] === false
122
+ const prefixed = (code: string, path: string) => (domains ? path : `/${code}${path === "/" ? "" : path}`)
123
+ const copy = (record: RouteRecord, code: string): RouteRecord => ({
124
+ ...record,
125
+ name: `${record.name}${SEPARATOR}${code}`,
126
+ path: prefixed(code, localized(record, code)),
127
+ children: record.children.filter((child) => !absent(child, code)).map((child) => copy(child, code)),
128
+ })
129
+ const moved = (record: RouteRecord): RouteRecord => {
130
+ const children = record.children.map(moved)
131
+ const path = localized(record, options.defaultLocale)
132
+ return path === record.path && children.every((child, index) => child === record.children[index])
133
+ ? record
134
+ : { ...record, path, children }
135
+ }
136
+
137
+ const keep =
138
+ domains !== undefined || options.strategy === "prefix_except_default" || options.strategy === "prefix_and_default"
139
+ const copies = options.locales
140
+ .map((locale) => locale.code)
141
+ .filter((code) => (options.strategy !== "prefix_except_default" && !domains) || code !== options.defaultLocale)
142
+ const kept = keep ? routes.map(moved) : []
143
+ const differs = (record: RouteRecord, code: string): boolean =>
144
+ localized(record, code) !== localized(record, options.defaultLocale) ||
145
+ record.children.some((child) => differs(child, code))
146
+ const made = new Map<RouteRecord, Set<string>>()
147
+ const wanted = (record: RouteRecord, code: string): boolean => {
148
+ if (absent(record, code)) return false
149
+ if (!domains) return true
150
+ if (!differs(record, code)) return false
151
+ const paths = flatten([copy(record, code)])
152
+ .map((entry) => entry.record.path)
153
+ .join("\n")
154
+ let seen = made.get(record)
155
+ if (!seen) made.set(record, (seen = new Set()))
156
+ if (seen.has(paths)) return false
157
+ seen.add(paths)
158
+ return true
159
+ }
160
+ const copied = copies.flatMap((code) =>
161
+ routes.filter((record) => wanted(record, code)).map((record) => copy(record, code)),
162
+ )
163
+ const result = [...kept, ...copied]
164
+
165
+ const table = tableOf(result, options, domains ? [] : copies)
166
+ if (domains) {
167
+ table.domains = domains
168
+ for (const { record } of originals) {
169
+ const own = (table.routes[record.name] ??= {})
170
+ for (const { code } of options.locales) own[code] ??= localized(record, code)
171
+ }
172
+ }
173
+
174
+ if (!domains) {
175
+ for (const { record } of originals) {
176
+ for (const code of copies) {
177
+ if (!absent(record, code)) continue
178
+ ;(table.routes[record.name] ??= {})[code] = prefixed(code, record.path)
179
+ ;(table.missing ??= {})[record.name] = [...(table.missing[record.name] ?? []), code]
180
+ }
181
+ }
182
+ }
183
+
184
+ const all = flatten(result)
185
+ const seen = new Map<string, { record: RouteRecord; ancestors: string[] }>()
186
+ for (const entry of [
187
+ ...all.filter((item) => !item.record.name.includes(SEPARATOR)),
188
+ ...all.filter((item) => item.record.name.includes(SEPARATOR)),
189
+ ]) {
190
+ const shape = shapeOf(entry.record.path)
191
+ const other = seen.get(shape)
192
+ const related =
193
+ other && (other.ancestors.includes(entry.record.name) || entry.ancestors.includes(other.record.name))
194
+ if (other && !related && entry.record.name.includes(SEPARATOR)) {
195
+ throw new DiagnosticError(
196
+ "HAMUR_E5821",
197
+ `i18n: route copy "${entry.record.path}" (${entry.record.name}) clashes with "${other.record.path}" (${other.record.name}, ${shown(other.record.file)})`,
198
+ )
199
+ }
200
+ if (!other) seen.set(shape, entry)
201
+ }
202
+ return { routes: result, table }
203
+ }
204
+
205
+ const tables = new WeakMap<HamurContext, RouteTable>()
206
+
207
+ /** The route table `setupRoutes` built for `hamur`; empty before `extendPages` ran. */
208
+ export const routeTableOf = (hamur: HamurContext): RouteTable => tables.get(hamur) ?? { copies: [], routes: {} }
209
+
210
+ export const rememberRouteTable = (hamur: HamurContext, table: RouteTable): void => void tables.set(hamur, table)
211
+
212
+ const PRERENDER_WARNING = 'i18n: "/" is prerendered, so detect.redirect "root" never runs for it'
213
+
214
+ /** Route copies, the route table and options templates, the app plugin, the route middleware and the root redirect. */
215
+ export function setupRoutes(options: ResolvedI18nOptions, hamur: HamurContext): void {
216
+ const r = createResolver(import.meta.url)
217
+ let table: RouteTable = { copies: [], routes: {} }
218
+ extendPages((routes) => {
219
+ const localized = localizeRoutes(routes, options, hamur.options.rootDir)
220
+ routes.splice(0, routes.length, ...localized.routes)
221
+ table = localized.table
222
+ rememberRouteTable(hamur, table)
223
+ })
224
+ const exports = (values: Record<string, unknown>) =>
225
+ Object.entries(values)
226
+ .map(([name, value]) => `export const ${name} = ${JSON.stringify(value) ?? "undefined"};\n`)
227
+ .join("")
228
+ addTemplate({
229
+ filename: "i18n/routes",
230
+ getContents: () =>
231
+ exports({
232
+ copies: table.copies,
233
+ routes: table.routes,
234
+ aliases: table.aliases ?? {},
235
+ missing: table.missing ?? {},
236
+ domains: table.domains,
237
+ server: [...new Set(hamur.serverRoutes.map((route) => route.path))],
238
+ }),
239
+ })
240
+ addTemplate({
241
+ filename: "i18n/options",
242
+ getContents: () =>
243
+ exports({
244
+ locales: options.locales,
245
+ defaultLocale: options.defaultLocale,
246
+ strategy: options.strategy,
247
+ redirectToDefaultLocale: options.redirectToDefaultLocale,
248
+ cookie: options.detect.cookie,
249
+ timeZone: options.timeZone,
250
+ fallback: options.fallback,
251
+ missingPage: options.missingPage,
252
+ localizeLinks: options.localizeLinks,
253
+ syntax: options.syntax,
254
+ baseURL: hamur.options.app.baseURL.endsWith("/") ? hamur.options.app.baseURL : `${hamur.options.app.baseURL}/`,
255
+ }),
256
+ })
257
+ addAppPlugin({ src: r.resolve("../runtime/plugin.ts"), mode: "all" })
258
+ addRouteMiddleware({ path: r.resolve("../runtime/middleware.ts"), global: true })
259
+ if (options.detect.redirect !== "root" || options.strategy === "no_prefix") return
260
+ const { preset, routeRules, prerender } = hamur.options
261
+ const root = routeRules["/"]
262
+ const prerendered =
263
+ preset === "static" ||
264
+ (!Array.isArray(root) && root?.prerender === true) ||
265
+ typeof prerender.routes === "function" ||
266
+ (prerender.routes ?? []).includes("/")
267
+ if ((options.strategy === "prefix_except_default" || options.strategy === "prefix_and_default") && prerendered)
268
+ useLogger("hamur").warn(diagnostic("HAMUR_W5832", PRERENDER_WARNING))
269
+ }