@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.
- 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 +17 -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 +122 -4
- package/src/adapters/angular.ts +65 -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
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { AppContext } from "hamur/app"
|
|
2
|
+
import { localizeRoutes } from "../../build/routes.ts"
|
|
3
|
+
import { resolveOptions } from "../../options.ts"
|
|
4
|
+
import { createI18nRuntime, forApp } from "../../runtime/locale.ts"
|
|
5
|
+
import { messageStore, type Catalog } from "../../runtime/messages.ts"
|
|
6
|
+
|
|
7
|
+
const options = resolveOptions({
|
|
8
|
+
locales: ["en", { code: "fr", language: "fr-FR" }, { code: "ar", language: "ar-EG" }],
|
|
9
|
+
defaultLocale: "en",
|
|
10
|
+
pages: { about: { fr: "/a-propos", ar: "/hawl" } },
|
|
11
|
+
})
|
|
12
|
+
const { table } = localizeRoutes(
|
|
13
|
+
[
|
|
14
|
+
{ name: "index", path: "/", file: "index.tsx", children: [] },
|
|
15
|
+
{ name: "about", path: "/about", file: "about.tsx", children: [] },
|
|
16
|
+
],
|
|
17
|
+
options,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
export const i18n = createI18nRuntime({
|
|
21
|
+
...table,
|
|
22
|
+
locales: options.locales,
|
|
23
|
+
defaultLocale: "en",
|
|
24
|
+
strategy: options.strategy,
|
|
25
|
+
cookie: "hamur_locale",
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
const single = resolveOptions({
|
|
29
|
+
locales: ["en", { code: "fr", language: "fr-FR" }, { code: "ar", language: "ar-EG" }],
|
|
30
|
+
defaultLocale: "en",
|
|
31
|
+
strategy: "no_prefix",
|
|
32
|
+
})
|
|
33
|
+
const singleTable = localizeRoutes(
|
|
34
|
+
[
|
|
35
|
+
{ name: "index", path: "/", file: "index.tsx", children: [] },
|
|
36
|
+
{ name: "about", path: "/about", file: "about.tsx", children: [] },
|
|
37
|
+
],
|
|
38
|
+
single,
|
|
39
|
+
).table
|
|
40
|
+
|
|
41
|
+
/** The `app.i18n` of a `no_prefix` app that starts in English; `refresh` is what the navigator's `refresh()` does. */
|
|
42
|
+
export function noPrefixI18n(refresh: () => Promise<void>) {
|
|
43
|
+
const base = createI18nRuntime({
|
|
44
|
+
...singleTable,
|
|
45
|
+
locales: single.locales,
|
|
46
|
+
defaultLocale: "en",
|
|
47
|
+
strategy: "no_prefix",
|
|
48
|
+
cookie: false,
|
|
49
|
+
})
|
|
50
|
+
const app = { modulePayload: {}, config: {}, hooks: { hook: () => {} } } as unknown as AppContext
|
|
51
|
+
return forApp(base, app, false, { path: "/about", refresh })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const catalog = (hello: string): Catalog => ({
|
|
55
|
+
"home.hello": (args) => `${hello} ${String(args.name)}`,
|
|
56
|
+
"home.bold": (args) => ["Hello ", { tag: "b", children: [String(args.name)] }, "!"],
|
|
57
|
+
})
|
|
58
|
+
messageStore.install({
|
|
59
|
+
en: async () => ({ default: catalog("Hello") }),
|
|
60
|
+
fr: async () => ({ default: catalog("Bonjour") }),
|
|
61
|
+
ar: async () => ({ default: catalog("Marhaba") }),
|
|
62
|
+
})
|
|
63
|
+
await messageStore.loadAll()
|
|
64
|
+
|
|
65
|
+
export interface TestRoute {
|
|
66
|
+
name: string | null
|
|
67
|
+
path: string
|
|
68
|
+
fullPath: string
|
|
69
|
+
params: Record<string, string>
|
|
70
|
+
query: Record<string, string>
|
|
71
|
+
hash: string
|
|
72
|
+
meta: Record<string, unknown>
|
|
73
|
+
matched: never[]
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const routeAt = (path: string, name: string | null): TestRoute => ({
|
|
77
|
+
name,
|
|
78
|
+
path,
|
|
79
|
+
fullPath: path,
|
|
80
|
+
params: {},
|
|
81
|
+
query: {},
|
|
82
|
+
hash: "",
|
|
83
|
+
meta: {},
|
|
84
|
+
matched: [],
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
export const routes = {
|
|
88
|
+
fr: routeAt("/fr", "index___fr"),
|
|
89
|
+
home: routeAt("/", "index___en"),
|
|
90
|
+
about: routeAt("/about", "about"),
|
|
91
|
+
frAbout: routeAt("/fr/a-propos", "about___fr"),
|
|
92
|
+
arAbout: routeAt("/ar/hawl", "about___ar"),
|
|
93
|
+
frNope: routeAt("/fr/nope", null),
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const summary = (parts: {
|
|
97
|
+
hello: string
|
|
98
|
+
code: string
|
|
99
|
+
language: string
|
|
100
|
+
dir: string
|
|
101
|
+
locales: number
|
|
102
|
+
about: string
|
|
103
|
+
arabic: string
|
|
104
|
+
}) => [parts.hello, parts.code, parts.language, parts.dir, parts.locales, parts.about, parts.arabic].join("|")
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Run by solid.test.ts as `bun --conditions=browser`, so `solid-js` resolves to its client build; prints JSON.
|
|
2
|
+
import { createComponent, createRoot, createSignal } from "solid-js"
|
|
3
|
+
import { Root, appState } from "../../../../adapter-solid/src/context.ts"
|
|
4
|
+
import { mounted } from "../../../../adapter-solid/src/test/mount.ts"
|
|
5
|
+
import { i18n, noPrefixI18n, routes } from "./runtime.ts"
|
|
6
|
+
import { ReportingPage, mounts, texts } from "./solid-page.ts"
|
|
7
|
+
|
|
8
|
+
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
|
|
9
|
+
const stateOf = (route: typeof routes.fr, runtime: unknown = i18n) =>
|
|
10
|
+
appState({
|
|
11
|
+
route,
|
|
12
|
+
tree: { components: [{ id: "page", component: ReportingPage }] },
|
|
13
|
+
payload: {},
|
|
14
|
+
app: { i18n: runtime },
|
|
15
|
+
head: {},
|
|
16
|
+
href: (to: string) => to,
|
|
17
|
+
} as never)
|
|
18
|
+
|
|
19
|
+
const setLocale = process.argv[2] === "set-locale"
|
|
20
|
+
const runtime: ReturnType<typeof noPrefixI18n> = noPrefixI18n(async () => {
|
|
21
|
+
setState(stateOf(routes.about, runtime))
|
|
22
|
+
})
|
|
23
|
+
const [state, setState] = createSignal(setLocale ? stateOf(routes.about, runtime) : stateOf(routes.fr))
|
|
24
|
+
const dispose = createRoot((dispose) => {
|
|
25
|
+
mounted(createComponent(Root, { state }))
|
|
26
|
+
return dispose
|
|
27
|
+
})
|
|
28
|
+
await settle()
|
|
29
|
+
if (setLocale) await runtime.setLocale("fr")
|
|
30
|
+
else setState(stateOf(routes.home))
|
|
31
|
+
await settle()
|
|
32
|
+
dispose()
|
|
33
|
+
console.log(JSON.stringify({ mounts: mounts.length, texts }))
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createEffect, onSettled } from "solid-js"
|
|
2
|
+
import { useI18n } from "../solid.ts"
|
|
3
|
+
|
|
4
|
+
export const mounts: number[] = []
|
|
5
|
+
export const texts: string[] = []
|
|
6
|
+
|
|
7
|
+
export function useText() {
|
|
8
|
+
const { t, locale, localePath, switchLocalePath } = useI18n()
|
|
9
|
+
return () => {
|
|
10
|
+
const current = locale()
|
|
11
|
+
return [
|
|
12
|
+
t("home.hello", { name: "Ada" }),
|
|
13
|
+
current.code,
|
|
14
|
+
current.language,
|
|
15
|
+
current.dir,
|
|
16
|
+
current.locales.length,
|
|
17
|
+
localePath("/about"),
|
|
18
|
+
switchLocalePath("ar"),
|
|
19
|
+
].join("|")
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const Page = () => useText()
|
|
24
|
+
|
|
25
|
+
export function ReportingPage() {
|
|
26
|
+
const text = useText()
|
|
27
|
+
onSettled(() => void mounts.push(1))
|
|
28
|
+
createEffect(text, (value) => void texts.push(value))
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Run by svelte.test.ts as `bun --conditions=browser`, so `svelte` resolves to its client runtime; prints JSON.
|
|
2
|
+
import { compileSvelte, compileSvelteModule } from "../../../../adapter-svelte/src/plugin.ts"
|
|
3
|
+
import { target } from "../../../../adapter-svelte/src/test/fake-dom.ts"
|
|
4
|
+
import { registerSvelte } from "./svelte-plugin.ts"
|
|
5
|
+
|
|
6
|
+
Bun.plugin({
|
|
7
|
+
name: "hamur-svelte-adapter-client",
|
|
8
|
+
setup(build) {
|
|
9
|
+
build.onLoad({ filter: /adapter-svelte\/src\/.*\.svelte\.ts$/, namespace: "file" }, async ({ path }) => ({
|
|
10
|
+
contents: compileSvelteModule(path, await Bun.file(path).text(), "client"),
|
|
11
|
+
loader: "js",
|
|
12
|
+
}))
|
|
13
|
+
build.onLoad({ filter: /adapter-svelte\/src\/.*\.svelte$/, namespace: "file" }, async ({ path }) => ({
|
|
14
|
+
contents: compileSvelte(path, await Bun.file(path).text(), "client").code,
|
|
15
|
+
loader: "js",
|
|
16
|
+
}))
|
|
17
|
+
},
|
|
18
|
+
})
|
|
19
|
+
registerSvelte("client")
|
|
20
|
+
|
|
21
|
+
const { mount, update } = await import("../../../../adapter-svelte/src/runtime/client.ts")
|
|
22
|
+
const { i18n, noPrefixI18n, routes } = await import("./runtime.ts")
|
|
23
|
+
const { mounts, texts } = await import("./svelte-log.ts")
|
|
24
|
+
const { default: Page } = await import("./SvelteReporting.svelte")
|
|
25
|
+
|
|
26
|
+
const context = (route: typeof routes.fr, runtime: unknown = i18n) =>
|
|
27
|
+
({
|
|
28
|
+
url: new URL(`http://localhost${route.path}`),
|
|
29
|
+
route,
|
|
30
|
+
tree: { components: [{ id: "page", component: Page }] },
|
|
31
|
+
payload: { data: {} },
|
|
32
|
+
head: {},
|
|
33
|
+
app: { i18n: runtime },
|
|
34
|
+
baseURL: "/",
|
|
35
|
+
href: (to: string) => to,
|
|
36
|
+
root: target,
|
|
37
|
+
}) as never
|
|
38
|
+
|
|
39
|
+
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
|
|
40
|
+
if (process.argv[2] === "set-locale") {
|
|
41
|
+
const runtime: ReturnType<typeof noPrefixI18n> = noPrefixI18n(async () => update(context(routes.about, runtime)))
|
|
42
|
+
await mount(context(routes.about, runtime))
|
|
43
|
+
await settle()
|
|
44
|
+
await runtime.setLocale("fr")
|
|
45
|
+
await settle()
|
|
46
|
+
} else {
|
|
47
|
+
await mount(context(routes.fr))
|
|
48
|
+
update(context(routes.home))
|
|
49
|
+
await settle()
|
|
50
|
+
}
|
|
51
|
+
console.log(JSON.stringify({ mounts: mounts.length, texts }))
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { join } from "node:path"
|
|
2
|
+
import { compileSvelte } from "../../../../adapter-svelte/src/plugin.ts"
|
|
3
|
+
|
|
4
|
+
const adapter = join(import.meta.dir, "../../../../adapter-svelte")
|
|
5
|
+
|
|
6
|
+
/** Compiles the test components, and points their `svelte` imports at the adapter's install, which is where the repo has it. */
|
|
7
|
+
export function registerSvelte(mode: "server" | "client"): void {
|
|
8
|
+
Bun.plugin({
|
|
9
|
+
name: `hamur-i18n-svelte-${mode}`,
|
|
10
|
+
setup(build) {
|
|
11
|
+
build.onLoad({ filter: /packages\/i18n\/src\/adapters\/test\/.*\.svelte$/ }, async ({ path }) => ({
|
|
12
|
+
contents: compileSvelte(path, await Bun.file(path).text(), mode).code.replace(
|
|
13
|
+
/(from|import) ['"](svelte(?:\/[^'"]*)?)['"]/g,
|
|
14
|
+
(_, keyword: string, specifier: string) => `${keyword} "${Bun.resolveSync(specifier, adapter)}"`,
|
|
15
|
+
),
|
|
16
|
+
loader: "js",
|
|
17
|
+
}))
|
|
18
|
+
},
|
|
19
|
+
})
|
|
20
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { h, onMounted } from "vue"
|
|
2
|
+
import { useI18n } from "../vue.ts"
|
|
3
|
+
|
|
4
|
+
export const mounts: number[] = []
|
|
5
|
+
|
|
6
|
+
export const Page = {
|
|
7
|
+
setup() {
|
|
8
|
+
const { t, locale, localePath, switchLocalePath } = useI18n()
|
|
9
|
+
onMounted(() => void mounts.push(1))
|
|
10
|
+
return () => {
|
|
11
|
+
const current = locale.value
|
|
12
|
+
return h(
|
|
13
|
+
"p",
|
|
14
|
+
[
|
|
15
|
+
t("home.hello", { name: "Ada" }),
|
|
16
|
+
current.code,
|
|
17
|
+
current.language,
|
|
18
|
+
current.dir,
|
|
19
|
+
current.locales.length,
|
|
20
|
+
localePath("/about"),
|
|
21
|
+
switchLocalePath("ar"),
|
|
22
|
+
].join("|"),
|
|
23
|
+
)
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { h } from "vue"
|
|
2
|
+
import { useI18n } from "../vue.ts"
|
|
3
|
+
|
|
4
|
+
export const BoldPage = {
|
|
5
|
+
setup() {
|
|
6
|
+
const { t } = useI18n()
|
|
7
|
+
return () => h("p", t.rich("home.bold", { name: "Ada" }, { b: (chunks) => [h("b", chunks)] }))
|
|
8
|
+
},
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const PlainPage = {
|
|
12
|
+
setup() {
|
|
13
|
+
const { t } = useI18n()
|
|
14
|
+
return () => h("p", t.rich("home.bold", { name: "<script>" }, {}))
|
|
15
|
+
},
|
|
16
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { computed, createTextVNode, shallowRef, type ComputedRef, type ShallowRef, type VNode } from "vue"
|
|
2
|
+
import { useApp, useRoute } from "@hamur/adapter-vue"
|
|
3
|
+
import type { CurrentLocale, I18nRuntime, LocaleInfo, RichJoin } from "../types.ts"
|
|
4
|
+
import { bindFunctions, currentLocale, i18nOf, onSetLocale, type I18nFunctions } from "./bind.ts"
|
|
5
|
+
|
|
6
|
+
export type { CurrentLocale }
|
|
7
|
+
|
|
8
|
+
const join: RichJoin<VNode[]> = (parts) =>
|
|
9
|
+
parts.flatMap((part) => (typeof part === "string" ? [createTextVNode(part)] : part.node))
|
|
10
|
+
|
|
11
|
+
const holders = new WeakMap<I18nRuntime, ShallowRef<LocaleInfo>>()
|
|
12
|
+
|
|
13
|
+
function holderOf(i18n: I18nRuntime): ShallowRef<LocaleInfo> {
|
|
14
|
+
let holder = holders.get(i18n)
|
|
15
|
+
if (!holder) {
|
|
16
|
+
const created = shallowRef(i18n.locale)
|
|
17
|
+
holders.set(i18n, (holder = created))
|
|
18
|
+
onSetLocale(i18n, () => void (created.value = i18n.locale))
|
|
19
|
+
}
|
|
20
|
+
return holder
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function useLocale(): ComputedRef<CurrentLocale> {
|
|
24
|
+
const i18n = i18nOf(useApp())
|
|
25
|
+
const route = useRoute()
|
|
26
|
+
const holder = holderOf(i18n)
|
|
27
|
+
return computed(() => {
|
|
28
|
+
void holder.value
|
|
29
|
+
return currentLocale(i18n, route.path)
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function useI18n(): I18nFunctions<VNode[]> & { locale: ComputedRef<CurrentLocale> } {
|
|
34
|
+
const i18n = i18nOf(useApp())
|
|
35
|
+
const route = useRoute()
|
|
36
|
+
const holder = holderOf(i18n)
|
|
37
|
+
return {
|
|
38
|
+
locale: useLocale(),
|
|
39
|
+
...bindFunctions(() => {
|
|
40
|
+
void holder.value
|
|
41
|
+
return { i18n, route }
|
|
42
|
+
}, join),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises"
|
|
2
|
+
import { relative, resolve } from "node:path"
|
|
3
|
+
import { DiagnosticError, addTemplate, createResolver } from "hamur/kit"
|
|
4
|
+
import { catalogMissing } from "../options.ts"
|
|
5
|
+
import type { I18nSetup } from "../types.ts"
|
|
6
|
+
|
|
7
|
+
const DEFAULT_EXPORT = /\bexport\s+default\s+defineCatalog\s*\(/
|
|
8
|
+
|
|
9
|
+
/** `i18n.catalog`, read without running it; the build error when it names no file or its default export is not `defineCatalog({ … })`. */
|
|
10
|
+
export async function readCatalogFile(rootDir: string, catalog: string): Promise<string> {
|
|
11
|
+
const path = resolve(rootDir, catalog)
|
|
12
|
+
const found = await stat(path).catch(() => undefined)
|
|
13
|
+
if (!found?.isFile()) throw new DiagnosticError("HAMUR_E5814", catalogMissing(catalog))
|
|
14
|
+
const text = await readFile(path, "utf8")
|
|
15
|
+
if (!DEFAULT_EXPORT.test(text))
|
|
16
|
+
throw new DiagnosticError("HAMUR_E5815", relative(rootDir, path) + " must export default defineCatalog({ … })")
|
|
17
|
+
return path
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The loaders `#hamur/i18n/catalog` (browser) and `#hamur/i18n/catalog-server`, or `undefined`, and the server's `#hamur/i18n/catalog-source`. */
|
|
21
|
+
export const setupCatalog: I18nSetup = async (options, hamur) => {
|
|
22
|
+
const path = options.catalog === undefined ? undefined : await readCatalogFile(hamur.options.rootDir, options.catalog)
|
|
23
|
+
const r = createResolver(import.meta.url)
|
|
24
|
+
addTemplate({
|
|
25
|
+
filename: "i18n/catalog",
|
|
26
|
+
getContents: () =>
|
|
27
|
+
path
|
|
28
|
+
? "export { loadCatalog as default } from " + JSON.stringify(r.resolve("../runtime/catalog-client.ts")) + ";\n"
|
|
29
|
+
: "export default undefined;\n",
|
|
30
|
+
})
|
|
31
|
+
addTemplate({
|
|
32
|
+
filename: "i18n/catalog-server",
|
|
33
|
+
server: true,
|
|
34
|
+
getContents: () =>
|
|
35
|
+
path
|
|
36
|
+
? "export { loadCatalog as default } from " + JSON.stringify(r.resolve("../runtime/catalog-server.ts")) + ";\n"
|
|
37
|
+
: "export default undefined;\n",
|
|
38
|
+
})
|
|
39
|
+
addTemplate({
|
|
40
|
+
filename: "i18n/catalog-source",
|
|
41
|
+
server: true,
|
|
42
|
+
getContents: () => "export default " + (path ? "() => import(" + JSON.stringify(path) + ")" : "undefined") + ";\n",
|
|
43
|
+
})
|
|
44
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { readFile } from "node:fs/promises"
|
|
3
|
+
import { resolve, sep } from "node:path"
|
|
4
|
+
import { readKeys, SOURCE } from "./split.ts"
|
|
5
|
+
|
|
6
|
+
/** A `keepKeys` glob as a matcher over a whole key; `*` is one segment, `**` any run of characters. */
|
|
7
|
+
export function keepMatcher(glob: string): RegExp {
|
|
8
|
+
const source = glob
|
|
9
|
+
.split(/(\*\*|\*)/)
|
|
10
|
+
.map((part) => (part === "**" ? ".*" : part === "*" ? "[^.]*" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))
|
|
11
|
+
.join("")
|
|
12
|
+
return new RegExp("^" + source + "$")
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ClientRead {
|
|
16
|
+
keys: Set<string>
|
|
17
|
+
/** The first file and line of a call whose key is not a literal. */
|
|
18
|
+
dynamic?: { file: string; line: number }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The literal keys of every source file among the client build's metafile inputs, outside `node_modules`. */
|
|
22
|
+
export async function readClientInputs(inputs: Iterable<string>, rootDir: string): Promise<ClientRead> {
|
|
23
|
+
const keys = new Set<string>()
|
|
24
|
+
let dynamic: ClientRead["dynamic"]
|
|
25
|
+
for (const input of inputs) {
|
|
26
|
+
// Bun writes metafile inputs relative to the process's cwd, not to the build root.
|
|
27
|
+
const file = [resolve(input), resolve(rootDir, input)].find((path) => existsSync(path))
|
|
28
|
+
if (!file || file.includes(sep + "node_modules" + sep) || !SOURCE.test(file)) continue
|
|
29
|
+
const source = await readFile(file, "utf8").catch(() => undefined)
|
|
30
|
+
if (source === undefined) continue
|
|
31
|
+
const read = readKeys(source)
|
|
32
|
+
for (const key of read.keys) keys.add(key)
|
|
33
|
+
if (read.at !== undefined && !dynamic) dynamic = { file, line: source.slice(0, read.at).split("\n").length }
|
|
34
|
+
}
|
|
35
|
+
return { keys, ...(dynamic ? { dynamic } : {}) }
|
|
36
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"
|
|
2
|
+
import { dirname, join, relative, sep } from "node:path"
|
|
3
|
+
import type { HamurContext } from "hamur/kit"
|
|
4
|
+
import type { ResolvedI18nOptions } from "../types.ts"
|
|
5
|
+
import { keepMatcher } from "./drop.ts"
|
|
6
|
+
import { flattenMessages, mergeLocaleFiles, scanLocaleFiles } from "./messages.ts"
|
|
7
|
+
import { readKeys } from "./split.ts"
|
|
8
|
+
import { DiagnosticError } from "hamur/kit"
|
|
9
|
+
|
|
10
|
+
const SCANNED = /\.(?:ts|tsx|js|mjs|vue|svelte)$/
|
|
11
|
+
const KEY_ORDER = ["missing", "unused", "dynamic"] as const
|
|
12
|
+
|
|
13
|
+
export interface ExtractFlags {
|
|
14
|
+
check: boolean
|
|
15
|
+
prune: boolean
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface Place {
|
|
19
|
+
file: string
|
|
20
|
+
line: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const here = (place: Place) => place.file + ":" + place.line
|
|
24
|
+
const slashes = (path: string) => path.split(sep).join("/")
|
|
25
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
26
|
+
value !== null && typeof value === "object" && !Array.isArray(value)
|
|
27
|
+
|
|
28
|
+
async function sourceFiles(dirs: string[]): Promise<string[]> {
|
|
29
|
+
const files = new Set<string>()
|
|
30
|
+
for (const dir of dirs) {
|
|
31
|
+
const names = await readdir(dir, { recursive: true }).catch(() => [] as string[])
|
|
32
|
+
for (const name of names) {
|
|
33
|
+
if (SCANNED.test(name) && !name.split(sep).some((part) => part === "node_modules" || part.startsWith(".")))
|
|
34
|
+
files.add(join(dir, name))
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return [...files].sort()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Catalog {
|
|
41
|
+
path: string
|
|
42
|
+
file: string
|
|
43
|
+
json: Record<string, unknown>
|
|
44
|
+
keys: string[]
|
|
45
|
+
indent: string | number
|
|
46
|
+
newline: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function readCatalog(path: string, rootDir: string): Promise<Catalog> {
|
|
50
|
+
const file = slashes(relative(rootDir, path))
|
|
51
|
+
const text = await readFile(path, "utf8")
|
|
52
|
+
let json: unknown
|
|
53
|
+
try {
|
|
54
|
+
json = JSON.parse(text)
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new DiagnosticError("HAMUR_E5812", "invalid JSON (" + (error as Error).message + ")", { at: file })
|
|
57
|
+
}
|
|
58
|
+
const keys = Object.keys(flattenMessages(json, file))
|
|
59
|
+
return {
|
|
60
|
+
path,
|
|
61
|
+
file,
|
|
62
|
+
json: json as Record<string, unknown>,
|
|
63
|
+
keys,
|
|
64
|
+
indent: /^\{[ \t]*\r?\n([ \t]+)\S/.exec(text)?.[1] ?? 2,
|
|
65
|
+
newline: text.endsWith("\n"),
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function insert(json: Record<string, unknown>, key: string, file: string): void {
|
|
70
|
+
const parts = key.split(".")
|
|
71
|
+
if (parts.some((part) => part === ""))
|
|
72
|
+
throw new DiagnosticError("HAMUR_E5822", "key " + JSON.stringify(key) + " must not have an empty segment", {
|
|
73
|
+
at: file,
|
|
74
|
+
})
|
|
75
|
+
let node = json
|
|
76
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
77
|
+
const next = node[parts[i]!]
|
|
78
|
+
if (next === undefined) node = node[parts[i]!] = {} as Record<string, unknown>
|
|
79
|
+
else if (isObject(next)) node = next
|
|
80
|
+
else
|
|
81
|
+
throw new DiagnosticError(
|
|
82
|
+
"HAMUR_E5823",
|
|
83
|
+
JSON.stringify(parts.slice(0, i + 1).join(".")) +
|
|
84
|
+
" is a message, so " +
|
|
85
|
+
JSON.stringify(key) +
|
|
86
|
+
" cannot be added",
|
|
87
|
+
{ at: file },
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
const last = parts.at(-1)!
|
|
91
|
+
if (Object.hasOwn(node, last))
|
|
92
|
+
throw new DiagnosticError("HAMUR_E5824", JSON.stringify(key) + " is a group of messages, not a message", {
|
|
93
|
+
at: file,
|
|
94
|
+
})
|
|
95
|
+
node[last] = key
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Removes the leaf and every parent object it leaves empty. */
|
|
99
|
+
function remove(json: Record<string, unknown>, key: string): void {
|
|
100
|
+
const parts = key.split(".")
|
|
101
|
+
const chain: Record<string, unknown>[] = [json]
|
|
102
|
+
for (const part of parts.slice(0, -1)) chain.push(chain.at(-1)![part] as Record<string, unknown>)
|
|
103
|
+
delete chain.at(-1)![parts.at(-1)!]
|
|
104
|
+
for (let i = chain.length - 1; i > 0 && Object.keys(chain[i]!).length === 0; i--) delete chain[i - 1]![parts[i - 1]!]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function write(catalog: Catalog): Promise<void> {
|
|
108
|
+
await mkdir(dirname(catalog.path), { recursive: true })
|
|
109
|
+
await writeFile(catalog.path, JSON.stringify(catalog.json, null, catalog.indent) + (catalog.newline ? "\n" : ""))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Prints the findings of `hamur i18n extract` to `out`, writes the catalogs and resolves to the exit code. `--check` with
|
|
114
|
+
* `--prune`, and `--prune` with a dynamic key, reject.
|
|
115
|
+
*/
|
|
116
|
+
export async function extract(
|
|
117
|
+
hamur: HamurContext,
|
|
118
|
+
options: ResolvedI18nOptions,
|
|
119
|
+
flags: ExtractFlags,
|
|
120
|
+
out: (line: string) => void,
|
|
121
|
+
): Promise<number> {
|
|
122
|
+
if (flags.check && flags.prune)
|
|
123
|
+
throw new DiagnosticError("HAMUR_E5825", "--check and --prune cannot be used together")
|
|
124
|
+
const { rootDir, srcDir, serverDir, layers } = hamur.options
|
|
125
|
+
const local = layers.filter((layer) => !layer.rootDir.includes(sep + "node_modules" + sep))
|
|
126
|
+
const codes = options.locales.map((locale) => locale.code)
|
|
127
|
+
const used = new Map<string, Place>()
|
|
128
|
+
const dynamic: Place[] = []
|
|
129
|
+
for (const path of await sourceFiles([
|
|
130
|
+
srcDir,
|
|
131
|
+
serverDir,
|
|
132
|
+
...local.flatMap((layer) => [layer.srcDir, layer.serverDir]),
|
|
133
|
+
])) {
|
|
134
|
+
const text = await readFile(path, "utf8")
|
|
135
|
+
const read = readKeys(text, false)
|
|
136
|
+
const file = slashes(relative(rootDir, path))
|
|
137
|
+
const lineAt = (offset: number) => text.slice(0, offset).split("\n").length
|
|
138
|
+
for (const [key, at] of read.positions) if (!used.has(key)) used.set(key, { file, line: lineAt(at) })
|
|
139
|
+
if (read.at !== undefined) dynamic.push({ file, line: lineAt(read.at) })
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const everywhere = await scanLocaleFiles([rootDir, ...layers.map((layer) => layer.rootDir)], codes)
|
|
143
|
+
const own = await scanLocaleFiles([rootDir], codes)
|
|
144
|
+
const defaultPath = join(rootDir, "locales", options.defaultLocale + ".json")
|
|
145
|
+
const known = (await mergeLocaleFiles(everywhere.byCode.get(options.defaultLocale) ?? [], rootDir)).messages
|
|
146
|
+
const missing = [...used].filter(([key]) => !Object.hasOwn(known, key)).map(([key, place]) => ({ key, ...place }))
|
|
147
|
+
missing.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line))
|
|
148
|
+
dynamic.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line))
|
|
149
|
+
|
|
150
|
+
const catalogs: Catalog[] = []
|
|
151
|
+
for (const code of codes)
|
|
152
|
+
for (const path of own.byCode.get(code) ?? []) catalogs.push(await readCatalog(path, rootDir))
|
|
153
|
+
const keep = options.keepKeys.map(keepMatcher)
|
|
154
|
+
const unused =
|
|
155
|
+
dynamic.length > 0
|
|
156
|
+
? []
|
|
157
|
+
: catalogs.flatMap((catalog) =>
|
|
158
|
+
catalog.keys
|
|
159
|
+
.filter((key) => !used.has(key) && !keep.some((match) => match.test(key)))
|
|
160
|
+
.map((key) => ({ catalog, key })),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
for (const kind of KEY_ORDER) {
|
|
164
|
+
if (kind === "missing") for (const entry of missing) out("missing " + entry.key + " " + here(entry))
|
|
165
|
+
else if (kind === "unused") for (const { catalog, key } of unused) out("unused " + key + " " + catalog.file)
|
|
166
|
+
else for (const place of dynamic) out("dynamic " + here(place))
|
|
167
|
+
}
|
|
168
|
+
const skipped =
|
|
169
|
+
dynamic.length > 0
|
|
170
|
+
? "; unused not reported: " + dynamic.length + " dynamic key" + (dynamic.length === 1 ? "" : "s")
|
|
171
|
+
: ""
|
|
172
|
+
out(
|
|
173
|
+
missing.length +
|
|
174
|
+
" missing, " +
|
|
175
|
+
(dynamic.length > 0 ? "" : unused.length + " unused, ") +
|
|
176
|
+
dynamic.length +
|
|
177
|
+
" dynamic" +
|
|
178
|
+
skipped,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if (flags.prune && dynamic.length > 0)
|
|
182
|
+
throw new DiagnosticError("HAMUR_E5826", "--prune needs every key to be static; fix the dynamic keys above")
|
|
183
|
+
if (flags.check) return missing.length > 0 || unused.length > 0 ? 1 : 0
|
|
184
|
+
|
|
185
|
+
if (missing.length > 0) {
|
|
186
|
+
let target = catalogs.find((catalog) => catalog.path === defaultPath)
|
|
187
|
+
if (!target) {
|
|
188
|
+
target = {
|
|
189
|
+
path: defaultPath,
|
|
190
|
+
file: slashes(relative(rootDir, defaultPath)),
|
|
191
|
+
json: {},
|
|
192
|
+
keys: [],
|
|
193
|
+
indent: 2,
|
|
194
|
+
newline: true,
|
|
195
|
+
}
|
|
196
|
+
catalogs.push(target)
|
|
197
|
+
}
|
|
198
|
+
for (const { key } of missing) insert(target.json, key, target.file)
|
|
199
|
+
}
|
|
200
|
+
if (flags.prune) for (const { catalog, key } of unused) remove(catalog.json, key)
|
|
201
|
+
const changed = new Set([
|
|
202
|
+
...(missing.length > 0 ? [defaultPath] : []),
|
|
203
|
+
...(flags.prune ? unused.map(({ catalog }) => catalog.path) : []),
|
|
204
|
+
])
|
|
205
|
+
for (const catalog of catalogs) if (changed.has(catalog.path)) await write(catalog)
|
|
206
|
+
return 0
|
|
207
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { diagnostic, useLogger } from "hamur/kit"
|
|
2
|
+
import type { I18nSetup } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
/** The build's `site.url` or the variable that sets it at run time; without either the head writes no hreflang or canonical. */
|
|
5
|
+
export const SITE_URL_WARNING = "[hamur] site.url is not set; hreflang and canonical links are not written"
|
|
6
|
+
|
|
7
|
+
export const setupHead: I18nSetup = (options, hamur) => {
|
|
8
|
+
if (!options.domains && hamur.options.site.url === undefined && !process.env.HAMUR_SITE_URL)
|
|
9
|
+
useLogger("hamur").warn(diagnostic("HAMUR_W5833", SITE_URL_WARNING.replace(/^\[hamur\] /, "")))
|
|
10
|
+
}
|