@prunellejs/i18n 0.0.0-stage → 0.7.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 +21 -0
- package/llms.txt +66 -0
- package/package.json +24 -4
- package/src/index.ts +391 -0
- package/src/routes.ts +172 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# @prunellejs/i18n Reference
|
|
2
|
+
|
|
3
|
+
> Locale URL rewriting, dictionary translation, `<html lang>`, automatic internal link prefixing, `hreflang` alternates, localized prerendering, `Intl` formatters, and missing-key checks.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/i18n`: `i18n`, `stripLocalePrefix`, `localizePath`, `alternateLinks`, `formatDate`, `formatNumber`; type `I18nOptions`.
|
|
8
|
+
|
|
9
|
+
## Plugin Setup (`i18n(options)`)
|
|
10
|
+
|
|
11
|
+
- `locales`: `string[]` (e.g. `['en', 'fr']`).
|
|
12
|
+
- `defaultLocale`: `string` (e.g. `'en'`).
|
|
13
|
+
- `messages`: `Record<locale, Record<key, string>>` (optional; falls back to `defaultLocale`, then returns `key`).
|
|
14
|
+
- `prefixDefault`: `boolean` (default `false`; when `true`, default locale is also prefixed as `/en/...`).
|
|
15
|
+
- Options are checked when `i18n()` runs: an empty `locales`, a duplicate, a malformed tag (`en US`, `fr/ca`) or a `defaultLocale` outside `locales` throws `@prunellejs/i18n: ...` with the fix.
|
|
16
|
+
- `site`: optional public origin (inherits `PrunelleConfig.site`); when set, injects `<link rel="alternate" hreflang="...">` tags into `<head>`, plus `hreflang="x-default"` pointing at the default locale URL.
|
|
17
|
+
|
|
18
|
+
## Mounted Routes, Rewriting & `ctx.locals`
|
|
19
|
+
|
|
20
|
+
- Request rewrite: strips `/<locale>` prefix (e.g. `/fr/about` → `/about`) before routing and populates `ctx.locals`:
|
|
21
|
+
- `ctx.locals.locale`: active locale string
|
|
22
|
+
- `ctx.locals.t(key)`: translate string for active locale
|
|
23
|
+
- `ctx.locals.localize(path, targetLocale?)`: build localized path
|
|
24
|
+
- `ctx.locals.alternates()`: `Array<{ locale, href }>` for the current page
|
|
25
|
+
- One URL per page: with `prefixDefault: false`, `/en/about` (the default locale prefixed) answers 301 to `/about`; with `true`, an unprefixed page answers 302 to `/en/about`. Both keep the query, apply to GET and HEAD, and only to pages: plugin and API routes and 404s answer as they are.
|
|
26
|
+
- Mounted route: `GET /_i18n/locales` → `{ locales, defaultLocale, current }`.
|
|
27
|
+
- HTML & build integration:
|
|
28
|
+
- The link rewrite reads attributes: only `href` (single or double quotes) on an `<a>` is changed, never `data-href`, and a `>` inside another attribute value does not hide it.
|
|
29
|
+
- Sets `<html lang={locale}>` and `hreflang` links in `head()`.
|
|
30
|
+
- Prefixes internal `<a href="/...">` for non-default locales (`data-no-localize` opts a link out, e.g. language switchers; skips `/_pru/`, `/_i18n/`, already-prefixed paths).
|
|
31
|
+
- Expands `prerenderPaths` across all configured locales and shares `I18N_CONFIG_SERVICE` with `@prunellejs/seo` for multilingual `sitemap.xml`.
|
|
32
|
+
- Checks & CLI: `prunelle check` fails on translation keys missing vs `defaultLocale`; `prunelle i18n-check` prints missing keys.
|
|
33
|
+
|
|
34
|
+
## Helpers
|
|
35
|
+
|
|
36
|
+
- `localizePath(pathname, targetLocale, defaultLocale, locales, prefixDefault?)`
|
|
37
|
+
- `stripLocalePrefix(pathname, locales)` → `{ locale, path }`
|
|
38
|
+
- `alternateLinks(pathname, { site?, locales, defaultLocale, prefixDefault? })`
|
|
39
|
+
- `formatDate(value, locale, options?)`, `formatNumber(value, locale, options?)`
|
|
40
|
+
|
|
41
|
+
## Snippets
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// prunelle.config.ts
|
|
45
|
+
import { i18n } from '@prunellejs/i18n'
|
|
46
|
+
import { defineConfig } from 'prunelle/config'
|
|
47
|
+
|
|
48
|
+
export default defineConfig({
|
|
49
|
+
site: 'https://example.com',
|
|
50
|
+
plugins: [i18n({ locales: ['en', 'fr'], defaultLocale: 'en', messages: { en: { hello: 'Hello' }, fr: { hello: 'Bonjour' } } })],
|
|
51
|
+
})
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
// src/routes/index.tsx
|
|
56
|
+
import type { PageProps } from 'prunelle'
|
|
57
|
+
|
|
58
|
+
export default function Home({ locals }: PageProps) {
|
|
59
|
+
return (
|
|
60
|
+
<main>
|
|
61
|
+
<h1>{locals.t?.('hello')}</h1>
|
|
62
|
+
<a href={locals.localize?.('/', 'fr')} data-no-localize>Français</a>
|
|
63
|
+
</main>
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/i18n",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.2",
|
|
4
|
+
"description": "Locale URL rewriting and dictionary internationalization plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"bun": ">=1.4.0"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
21
|
+
"directory": "packages/plugin-i18n"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"prunelle": "^0.7.2"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
// @prunellejs/i18n — opt-in locale routing, <html lang> & link rewriting, localized prerendering,
|
|
2
|
+
// hreflang alternates, Intl formatters, and CLI missing-key check.
|
|
3
|
+
// Implemented 100% through PrunellePlugin public hooks — zero i18n logic in @prunellejs/core.
|
|
4
|
+
|
|
5
|
+
import type { ActiveI18nConfig, PrunellePlugin } from 'prunelle/config'
|
|
6
|
+
import type { Middleware } from 'prunelle/server'
|
|
7
|
+
import type { CanonicalRouteIndex, I18nBuildData } from './routes'
|
|
8
|
+
import { definePlugin, I18N_CONFIG_SERVICE } from 'prunelle/config'
|
|
9
|
+
import { escAttr, isTrustedOrigin } from 'prunelle/server'
|
|
10
|
+
import { buildCanonicalRouteIndex, collectI18nBuildData, isCanonicalHtmlTarget, normalizePathname } from './routes'
|
|
11
|
+
|
|
12
|
+
declare module 'prunelle/server' {
|
|
13
|
+
interface PrunelleLocals {
|
|
14
|
+
locale?: string | undefined
|
|
15
|
+
t?: ((key: string) => string) | undefined
|
|
16
|
+
localize?: ((path: string, targetLocale?: string) => string) | undefined
|
|
17
|
+
alternates?: (() => Array<{ locale: string, href: string }>) | undefined
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface I18nOptions {
|
|
22
|
+
locales: string[]
|
|
23
|
+
defaultLocale: string
|
|
24
|
+
messages?: Record<string, Record<string, string>> | undefined
|
|
25
|
+
/** Prefix URLs for default locale too (default: false). */
|
|
26
|
+
prefixDefault?: boolean | undefined
|
|
27
|
+
/** Optional site origin (e.g. 'https://example.com') to auto-inject <link rel="alternate" hreflang="..."> tags. */
|
|
28
|
+
site?: string | undefined
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^>]*>|<a(?=[\s>/])((?:[^>"']|"[^"]*"|'[^']*')*)>/gi
|
|
32
|
+
// One attribute of a start tag: its leading space, its name, and the value when it is quoted.
|
|
33
|
+
const ATTR_RE = /(\s)([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g
|
|
34
|
+
const NO_LOCALIZE_RE = /\sdata-no-localize(?=[\s=/]|$)/i
|
|
35
|
+
const NON_HTML_EXT_RE = /\.(?:xml|json|txt|pdf|ico|png|jpe?g|gif|svg|webp|avif|webmanifest|zip|tar|gz|bz2|xz|7z|css|m?js|cjs|wasm|map|woff2?|ttf|otf|eot|mp3|mp4|webm|ogg|wav|csv|tsv|rss|atom|ics|vcf|epub|docx?|xlsx?|pptx?)$/i
|
|
36
|
+
|
|
37
|
+
function isSkippedI18nPath(pathname: string, assetPrefix: string, assetPrefixSlash: string): boolean {
|
|
38
|
+
return pathname === assetPrefix
|
|
39
|
+
|| pathname.startsWith(assetPrefixSlash)
|
|
40
|
+
|| pathname === '/_i18n'
|
|
41
|
+
|| pathname.startsWith('/_i18n/')
|
|
42
|
+
|| pathname === '/api'
|
|
43
|
+
|| pathname.startsWith('/api/')
|
|
44
|
+
|| pathname === '/auth'
|
|
45
|
+
|| pathname.startsWith('/auth/')
|
|
46
|
+
|| NON_HTML_EXT_RE.test(pathname)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function localizeHtmlLinks(
|
|
50
|
+
html: string,
|
|
51
|
+
locale: string,
|
|
52
|
+
localeSet: ReadonlySet<string>,
|
|
53
|
+
assetPrefix: string,
|
|
54
|
+
): string {
|
|
55
|
+
const assetPrefixSlash = `${assetPrefix}/`
|
|
56
|
+
const escapedLocale = escAttr(locale)
|
|
57
|
+
let inTextarea = false
|
|
58
|
+
let codePreDepth = 0
|
|
59
|
+
HTML_TOKEN_RE.lastIndex = 0
|
|
60
|
+
const localizeHref = (href: string): string | undefined => {
|
|
61
|
+
if (!href.startsWith('/') || href.startsWith('//'))
|
|
62
|
+
return undefined
|
|
63
|
+
const cut = href.search(/[?#]/)
|
|
64
|
+
const pathOnly = cut === -1 ? href : href.slice(0, cut)
|
|
65
|
+
if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
|
|
66
|
+
return undefined
|
|
67
|
+
const seg = pathOnly.slice(1).split('/', 1)[0]
|
|
68
|
+
if (seg !== undefined && localeSet.has(seg))
|
|
69
|
+
return undefined
|
|
70
|
+
// `href` is already extracted from a quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&`.
|
|
71
|
+
return href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
|
|
72
|
+
}
|
|
73
|
+
return html.replace(
|
|
74
|
+
HTML_TOKEN_RE,
|
|
75
|
+
(match, slash: string | undefined, skipTag: string | undefined, attrs: string | undefined) => {
|
|
76
|
+
if (skipTag !== undefined) {
|
|
77
|
+
const tag = skipTag.toLowerCase()
|
|
78
|
+
const isClosing = slash === '/'
|
|
79
|
+
const isSelfClosing = !isClosing && match.endsWith('/>')
|
|
80
|
+
if (inTextarea) {
|
|
81
|
+
if (isClosing && tag === 'textarea')
|
|
82
|
+
inTextarea = false
|
|
83
|
+
}
|
|
84
|
+
else if (tag === 'textarea') {
|
|
85
|
+
if (!isClosing && !isSelfClosing)
|
|
86
|
+
inTextarea = true
|
|
87
|
+
}
|
|
88
|
+
else if (isClosing) {
|
|
89
|
+
if (codePreDepth > 0)
|
|
90
|
+
codePreDepth--
|
|
91
|
+
}
|
|
92
|
+
else if (!isSelfClosing) {
|
|
93
|
+
codePreDepth++
|
|
94
|
+
}
|
|
95
|
+
return match
|
|
96
|
+
}
|
|
97
|
+
if (inTextarea || codePreDepth > 0 || attrs === undefined || NO_LOCALIZE_RE.test(attrs))
|
|
98
|
+
return match
|
|
99
|
+
const rewritten = attrs.replace(ATTR_RE, (attr, space: string, name: string, double: string | undefined, single: string | undefined) => {
|
|
100
|
+
const value = double ?? single
|
|
101
|
+
const next = name.toLowerCase() === 'href' && value !== undefined ? localizeHref(value) : undefined
|
|
102
|
+
if (next === undefined)
|
|
103
|
+
return attr
|
|
104
|
+
const quote = double !== undefined ? '"' : "'"
|
|
105
|
+
return `${space}${name}=${quote}${next}${quote}`
|
|
106
|
+
})
|
|
107
|
+
return `<a${rewritten}>`
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function collapseLeadingSlashes(p: string): string {
|
|
113
|
+
if (!p)
|
|
114
|
+
return '/'
|
|
115
|
+
const collapsed = p.replace(/^\/+/, '/')
|
|
116
|
+
return collapsed.startsWith('/') ? collapsed : `/${collapsed}`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function stripLocalePrefix(pathname: string, locales: readonly string[]): { locale: string | undefined, path: string } {
|
|
120
|
+
const normalized = collapseLeadingSlashes(pathname)
|
|
121
|
+
const parts = normalized.split('/')
|
|
122
|
+
const first = parts[1]
|
|
123
|
+
if (first !== undefined && locales.includes(first)) {
|
|
124
|
+
const rest = collapseLeadingSlashes(`/${parts.slice(2).join('/')}`)
|
|
125
|
+
return { locale: first, path: rest === '/' ? '/' : rest.replace(/\/+$/, '') || '/' }
|
|
126
|
+
}
|
|
127
|
+
return { locale: undefined, path: normalized }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function localizePath(
|
|
131
|
+
pathname: string,
|
|
132
|
+
targetLocale: string,
|
|
133
|
+
defaultLocale: string,
|
|
134
|
+
locales: readonly string[],
|
|
135
|
+
prefixDefault = false,
|
|
136
|
+
): string {
|
|
137
|
+
const { path } = stripLocalePrefix(pathname, locales)
|
|
138
|
+
const safePath = collapseLeadingSlashes(path)
|
|
139
|
+
if (targetLocale === defaultLocale && !prefixDefault)
|
|
140
|
+
return safePath
|
|
141
|
+
return safePath === '/' ? `/${targetLocale}` : `/${targetLocale}${safePath}`
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function alternateLinks(
|
|
145
|
+
pathname: string,
|
|
146
|
+
options: { site?: string | undefined, locales: readonly string[], defaultLocale: string, prefixDefault?: boolean | undefined },
|
|
147
|
+
): Array<{ locale: string, href: string }> {
|
|
148
|
+
const origin = options.site ? options.site.replace(/\/$/, '') : ''
|
|
149
|
+
return options.locales.map(loc => ({
|
|
150
|
+
locale: loc,
|
|
151
|
+
href: `${origin}${localizePath(pathname, loc, options.defaultLocale, options.locales, options.prefixDefault)}`,
|
|
152
|
+
}))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function formatDate(
|
|
156
|
+
value: Date | string | number,
|
|
157
|
+
locale: string,
|
|
158
|
+
options: Intl.DateTimeFormatOptions = { dateStyle: 'long' },
|
|
159
|
+
): string {
|
|
160
|
+
const d = value instanceof Date ? value : new Date(value)
|
|
161
|
+
return new Intl.DateTimeFormat(locale, options).format(d)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function formatNumber(
|
|
165
|
+
value: number,
|
|
166
|
+
locale: string,
|
|
167
|
+
options?: Intl.NumberFormatOptions,
|
|
168
|
+
): string {
|
|
169
|
+
return new Intl.NumberFormat(locale, options).format(value)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const LOCALE_TAG_RE = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i
|
|
173
|
+
|
|
174
|
+
function validateOptions({ locales, defaultLocale }: I18nOptions): void {
|
|
175
|
+
const fail = (what: string, fix: string): never => {
|
|
176
|
+
throw new Error(`@prunellejs/i18n: ${what}: ${fix}.`)
|
|
177
|
+
}
|
|
178
|
+
if (locales.length === 0)
|
|
179
|
+
fail('locales is empty', "list at least one locale tag, for example locales: ['en']")
|
|
180
|
+
const seen = new Set<string>()
|
|
181
|
+
for (const loc of locales) {
|
|
182
|
+
if (!LOCALE_TAG_RE.test(loc))
|
|
183
|
+
fail(`"${loc}" is not a valid locale tag`, "use a BCP 47 tag such as 'en' or 'fr-CA'")
|
|
184
|
+
if (seen.has(loc))
|
|
185
|
+
fail(`locale "${loc}" is listed twice`, 'remove the duplicate from locales')
|
|
186
|
+
seen.add(loc)
|
|
187
|
+
}
|
|
188
|
+
if (!seen.has(defaultLocale))
|
|
189
|
+
fail(`defaultLocale "${defaultLocale}" is not in locales`, 'add it to locales or pick one of them')
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** A successful HTML page, as opposed to a plugin or API route answering JSON, XML or a stream, or a 404. */
|
|
193
|
+
function isHtmlPage(res: Response): boolean {
|
|
194
|
+
return res.status >= 200 && res.status < 300 && (res.headers.get('content-type') ?? '').startsWith('text/html')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
interface CanonicalRedirectOptions {
|
|
198
|
+
readonly locales: readonly string[]
|
|
199
|
+
readonly defaultLocale: string
|
|
200
|
+
readonly prefixDefault: boolean
|
|
201
|
+
readonly assetPrefix: string
|
|
202
|
+
readonly assetPrefixSlash: string
|
|
203
|
+
readonly canonicalRoutes: CanonicalRouteIndex | undefined
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// One URL per page: the default locale is prefixed (301 away) only with prefixDefault, and unprefixed (302 to the prefix) only without it.
|
|
207
|
+
// Matching against the build's prerendered HTML URLs and SSR HTML page routes lets us redirect before load() / downstream middleware
|
|
208
|
+
// and avoids 404s on dynamic prerendered routes, while leaving plugin routes, API routes and missing pages alone.
|
|
209
|
+
function createCanonicalRedirectMiddleware(opts: CanonicalRedirectOptions): Middleware {
|
|
210
|
+
const { locales, defaultLocale, prefixDefault, assetPrefix, assetPrefixSlash, canonicalRoutes } = opts
|
|
211
|
+
return async (ctx, next) => {
|
|
212
|
+
const method = ctx.request.method
|
|
213
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
214
|
+
return next()
|
|
215
|
+
const rawPath = ctx.url.pathname
|
|
216
|
+
const { locale, path } = stripLocalePrefix(rawPath, locales)
|
|
217
|
+
let target: string
|
|
218
|
+
let status: 301 | 302
|
|
219
|
+
if (locale === undefined && prefixDefault) {
|
|
220
|
+
if (isSkippedI18nPath(rawPath, assetPrefix, assetPrefixSlash))
|
|
221
|
+
return next()
|
|
222
|
+
target = normalizePathname(localizePath(rawPath, defaultLocale, defaultLocale, locales, true))
|
|
223
|
+
status = 302
|
|
224
|
+
}
|
|
225
|
+
else if (locale === defaultLocale && !prefixDefault) {
|
|
226
|
+
target = path
|
|
227
|
+
status = 301
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
return next()
|
|
231
|
+
}
|
|
232
|
+
if (canonicalRoutes !== undefined) {
|
|
233
|
+
if (isCanonicalHtmlTarget(canonicalRoutes, target, path, ctx.params))
|
|
234
|
+
return ctx.redirect(`${target}${ctx.url.search}`, status)
|
|
235
|
+
return next()
|
|
236
|
+
}
|
|
237
|
+
const res = await next()
|
|
238
|
+
if (!isHtmlPage(res))
|
|
239
|
+
return res
|
|
240
|
+
void res.body?.cancel()
|
|
241
|
+
return ctx.redirect(`${target}${ctx.url.search}`, status)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function i18n(options: I18nOptions): PrunellePlugin {
|
|
246
|
+
validateOptions(options)
|
|
247
|
+
const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
|
|
248
|
+
let activeSite = options.site?.replace(/\/$/, '')
|
|
249
|
+
let activeAssetPrefix = '/_pru'
|
|
250
|
+
const localeSet = new Set(locales)
|
|
251
|
+
const sharedConfig: ActiveI18nConfig = { locales, defaultLocale, prefixDefault }
|
|
252
|
+
|
|
253
|
+
function translate(locale: string, key: string): string {
|
|
254
|
+
return messages[locale]?.[key] ?? messages[defaultLocale]?.[key] ?? key
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function* missingKeys(): Generator<{ locale: string, key: string }> {
|
|
258
|
+
const baseKeys = Object.keys(messages[defaultLocale] ?? {})
|
|
259
|
+
for (const locale of locales) {
|
|
260
|
+
if (locale === defaultLocale)
|
|
261
|
+
continue
|
|
262
|
+
const dict = messages[locale] ?? {}
|
|
263
|
+
for (const key of baseKeys) {
|
|
264
|
+
if (!(key in dict))
|
|
265
|
+
yield { locale, key }
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return definePlugin({
|
|
271
|
+
name: '@prunellejs/i18n',
|
|
272
|
+
enforce: 'pre',
|
|
273
|
+
providesLocals: ['locale', 't', 'localize', 'alternates'],
|
|
274
|
+
|
|
275
|
+
build(ctx) {
|
|
276
|
+
if (options.site === undefined && ctx.site !== undefined)
|
|
277
|
+
activeSite = ctx.site.replace(/\/$/, '')
|
|
278
|
+
if (ctx.assetPrefix)
|
|
279
|
+
activeAssetPrefix = ctx.assetPrefix.replace(/\/+$/, '') || '/_pru'
|
|
280
|
+
ctx.provide(I18N_CONFIG_SERVICE, sharedConfig)
|
|
281
|
+
},
|
|
282
|
+
|
|
283
|
+
afterPrerender(ctx) {
|
|
284
|
+
ctx.setData({ ...collectI18nBuildData(ctx.routes) })
|
|
285
|
+
},
|
|
286
|
+
|
|
287
|
+
server(api) {
|
|
288
|
+
if (options.site === undefined && api.site !== undefined)
|
|
289
|
+
activeSite = api.site.replace(/\/$/, '')
|
|
290
|
+
if (api.assetPrefix)
|
|
291
|
+
activeAssetPrefix = api.assetPrefix.replace(/\/+$/, '') || '/_pru'
|
|
292
|
+
const assetPrefixSlash = `${activeAssetPrefix}/`
|
|
293
|
+
const actionPrefix = `${assetPrefixSlash}action/`
|
|
294
|
+
const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
|
|
295
|
+
const canonicalRoutes = buildCanonicalRouteIndex(api.getBuildData<I18nBuildData>())
|
|
296
|
+
api.provide(I18N_CONFIG_SERVICE, sharedConfig)
|
|
297
|
+
|
|
298
|
+
// Rewrite /fr/about -> /about and attach locale + helpers onto ctx.locals
|
|
299
|
+
api.rewrite((pathname, ctx) => {
|
|
300
|
+
const stripped = stripLocalePrefix(pathname, locales)
|
|
301
|
+
let matched = stripped.locale
|
|
302
|
+
let path = stripped.path
|
|
303
|
+
// Server action URLs live under <assetPrefix>/action/<id> without a locale prefix; recover locale from trusted Referer.
|
|
304
|
+
if (matched === undefined && pathname.startsWith(actionPrefix)) {
|
|
305
|
+
const referer = ctx.request.headers.get('referer')
|
|
306
|
+
if (referer !== null && URL.canParse(referer)) {
|
|
307
|
+
const refUrl = new URL(referer)
|
|
308
|
+
if (isTrustedOrigin(refUrl.origin, ctx.request, trustedOrigins, api.trustProxy, ctx.url)) {
|
|
309
|
+
const fromRef = stripLocalePrefix(refUrl.pathname, locales)
|
|
310
|
+
matched = fromRef.locale
|
|
311
|
+
path = fromRef.path
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const active = matched ?? defaultLocale
|
|
316
|
+
ctx.locals.locale = active
|
|
317
|
+
ctx.locals.t = (key: string) => translate(active, key)
|
|
318
|
+
ctx.locals.localize = (p: string, target = active) => localizePath(p, target, defaultLocale, locales, prefixDefault)
|
|
319
|
+
ctx.locals.alternates = () => alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
|
|
320
|
+
return stripped.locale !== undefined ? stripped.path : undefined
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
api.use(createCanonicalRedirectMiddleware({
|
|
324
|
+
locales,
|
|
325
|
+
defaultLocale,
|
|
326
|
+
prefixDefault,
|
|
327
|
+
assetPrefix: activeAssetPrefix,
|
|
328
|
+
assetPrefixSlash,
|
|
329
|
+
canonicalRoutes,
|
|
330
|
+
}), { scope: 'rendered' })
|
|
331
|
+
|
|
332
|
+
api.route('GET', '/_i18n/locales', ctx =>
|
|
333
|
+
ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
|
|
334
|
+
},
|
|
335
|
+
|
|
336
|
+
prerenderPaths(paths) {
|
|
337
|
+
const out = new Set<string>()
|
|
338
|
+
for (const raw of paths) {
|
|
339
|
+
const { locale } = stripLocalePrefix(raw, locales)
|
|
340
|
+
if (locale !== undefined) {
|
|
341
|
+
// The default locale is only ever served unprefixed when prefixDefault is off: `/en/x` is a redirect, never a page.
|
|
342
|
+
out.add(locale === defaultLocale && !prefixDefault ? localizePath(raw, locale, defaultLocale, locales, false) : raw)
|
|
343
|
+
continue
|
|
344
|
+
}
|
|
345
|
+
for (const loc of locales)
|
|
346
|
+
out.add(localizePath(raw, loc, defaultLocale, locales, prefixDefault))
|
|
347
|
+
}
|
|
348
|
+
return [...out]
|
|
349
|
+
},
|
|
350
|
+
|
|
351
|
+
head(head, ctx) {
|
|
352
|
+
const locale = ctx.locals.locale ?? defaultLocale
|
|
353
|
+
head.lang = locale
|
|
354
|
+
|
|
355
|
+
if (activeSite) {
|
|
356
|
+
const { path } = stripLocalePrefix(ctx.url.pathname, locales)
|
|
357
|
+
const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
|
|
358
|
+
for (const l of links)
|
|
359
|
+
head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
|
|
360
|
+
const base = links.find(l => l.locale === defaultLocale)
|
|
361
|
+
if (base !== undefined)
|
|
362
|
+
head.add(`<link rel="alternate" hreflang="x-default" href="${escAttr(base.href)}">`)
|
|
363
|
+
}
|
|
364
|
+
},
|
|
365
|
+
|
|
366
|
+
transformHtml(html, ctx) {
|
|
367
|
+
const locale = ctx.locals.locale ?? defaultLocale
|
|
368
|
+
// Prefix internal <a href="/..."> links for non-default locales only
|
|
369
|
+
if (locale === defaultLocale && !prefixDefault)
|
|
370
|
+
return html
|
|
371
|
+
return localizeHtmlLinks(html, locale, localeSet, activeAssetPrefix)
|
|
372
|
+
},
|
|
373
|
+
|
|
374
|
+
check(ctx) {
|
|
375
|
+
for (const { locale, key } of missingKeys())
|
|
376
|
+
ctx.error(`[i18n] ${locale}: missing translation key "${key}"`)
|
|
377
|
+
},
|
|
378
|
+
|
|
379
|
+
commands: {
|
|
380
|
+
'i18n-check': () => {
|
|
381
|
+
let missing = 0
|
|
382
|
+
for (const { locale, key } of missingKeys()) {
|
|
383
|
+
console.log(`[i18n] ${locale}: missing "${key}"`)
|
|
384
|
+
missing++
|
|
385
|
+
}
|
|
386
|
+
if (missing === 0)
|
|
387
|
+
console.log('[i18n] all locales complete')
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
})
|
|
391
|
+
}
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Build-time route index for @prunellejs/i18n canonical-URL redirects: avoids 404s on dynamic prerendered routes
|
|
2
|
+
// and avoids invoking load() or downstream middleware before redirecting SSR HTML routes.
|
|
3
|
+
|
|
4
|
+
import type { FinalizeBuildContext } from 'prunelle/config'
|
|
5
|
+
|
|
6
|
+
type RouteEntry = FinalizeBuildContext['routes'][number]
|
|
7
|
+
|
|
8
|
+
export interface I18nBuildData {
|
|
9
|
+
/** Canonical prerendered HTML URLs (normalized, no trailing slash except '/'). */
|
|
10
|
+
prerenderedHtml: string[]
|
|
11
|
+
/** Static SSR HTML page paths (e.g. '/', '/about'). */
|
|
12
|
+
staticPages: string[]
|
|
13
|
+
/** Dynamic SSR HTML page route patterns (e.g. '/blog/:slug', '/docs/*path'). */
|
|
14
|
+
dynamicPages: string[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface CompiledSegment {
|
|
18
|
+
readonly kind: 'static' | 'param' | 'optional' | 'catchall'
|
|
19
|
+
readonly value: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CanonicalRouteIndex {
|
|
23
|
+
readonly prerenderedHtml: ReadonlySet<string>
|
|
24
|
+
readonly staticPages: ReadonlySet<string>
|
|
25
|
+
readonly dynamicPages: readonly (readonly CompiledSegment[])[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function normalizePathname(pathname: string): string {
|
|
29
|
+
return pathname.length > 1 ? pathname.replace(/\/+$/, '') || '/' : pathname
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function decodeSegments(pathname: string): string[] | undefined {
|
|
33
|
+
const norm = normalizePathname(pathname)
|
|
34
|
+
if (norm === '/')
|
|
35
|
+
return []
|
|
36
|
+
const raw = norm.slice(1).split('/')
|
|
37
|
+
const out: string[] = []
|
|
38
|
+
for (const seg of raw) {
|
|
39
|
+
let decoded: string
|
|
40
|
+
try {
|
|
41
|
+
decoded = decodeURIComponent(seg)
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined
|
|
45
|
+
}
|
|
46
|
+
if (decoded.includes('/') || decoded.includes('\\') || decoded.includes('\0'))
|
|
47
|
+
return undefined
|
|
48
|
+
out.push(decoded)
|
|
49
|
+
}
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function decodePathname(pathname: string): string | undefined {
|
|
54
|
+
const segs = decodeSegments(pathname)
|
|
55
|
+
if (segs === undefined)
|
|
56
|
+
return undefined
|
|
57
|
+
return segs.length === 0 ? '/' : `/${segs.join('/')}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isHtmlOutput(relOut: string): boolean {
|
|
61
|
+
return relOut.endsWith('.html') || relOut.endsWith('.htm')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parseSegment(seg: string): CompiledSegment {
|
|
65
|
+
if (seg.startsWith('*')) {
|
|
66
|
+
const body = seg.slice(1)
|
|
67
|
+
const eq = body.indexOf('=')
|
|
68
|
+
return { kind: 'catchall', value: (eq === -1 ? body : body.slice(0, eq)) || 'rest' }
|
|
69
|
+
}
|
|
70
|
+
if (seg.startsWith(':')) {
|
|
71
|
+
const body = seg.slice(1)
|
|
72
|
+
const optional = body.endsWith('?')
|
|
73
|
+
const spec = optional ? body.slice(0, -1) : body
|
|
74
|
+
const eq = spec.indexOf('=')
|
|
75
|
+
return { kind: optional ? 'optional' : 'param', value: eq === -1 ? spec : spec.slice(0, eq) }
|
|
76
|
+
}
|
|
77
|
+
return { kind: 'static', value: seg }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Collects prerendered HTML URLs and SSR HTML page routes for persistence in `manifest.pluginData`. */
|
|
81
|
+
export function collectI18nBuildData(routes: readonly RouteEntry[]): I18nBuildData {
|
|
82
|
+
const prerenderedHtml = new Set<string>()
|
|
83
|
+
const staticPages = new Set<string>()
|
|
84
|
+
const dynamicPages = new Set<string>()
|
|
85
|
+
for (const route of routes) {
|
|
86
|
+
if (route.prerendered !== undefined) {
|
|
87
|
+
for (const [url, relOut] of Object.entries(route.prerendered)) {
|
|
88
|
+
if (isHtmlOutput(relOut))
|
|
89
|
+
prerenderedHtml.add(normalizePathname(url))
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (typeof route.isIsland !== 'boolean')
|
|
93
|
+
continue
|
|
94
|
+
const isDynamic = route.path.includes(':') || route.path.includes('*')
|
|
95
|
+
if (isDynamic) {
|
|
96
|
+
if (!(route.prerender === true && route.prerendered !== undefined))
|
|
97
|
+
dynamicPages.add(route.path)
|
|
98
|
+
}
|
|
99
|
+
else if (route.prerendered === undefined || Object.keys(route.prerendered).length === 0) {
|
|
100
|
+
staticPages.add(normalizePathname(route.path))
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
prerenderedHtml: [...prerenderedHtml],
|
|
105
|
+
staticPages: [...staticPages],
|
|
106
|
+
dynamicPages: [...dynamicPages],
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function buildCanonicalRouteIndex(data: I18nBuildData | undefined): CanonicalRouteIndex | undefined {
|
|
111
|
+
if (data === undefined)
|
|
112
|
+
return undefined
|
|
113
|
+
const dynamicPages = data.dynamicPages.map((pattern) => {
|
|
114
|
+
const norm = normalizePathname(pattern)
|
|
115
|
+
return norm === '/' ? [] : norm.slice(1).split('/').map(parseSegment)
|
|
116
|
+
})
|
|
117
|
+
return {
|
|
118
|
+
prerenderedHtml: new Set(data.prerenderedHtml),
|
|
119
|
+
staticPages: new Set(data.staticPages),
|
|
120
|
+
dynamicPages,
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function matchPattern(
|
|
125
|
+
pattern: readonly CompiledSegment[],
|
|
126
|
+
parts: readonly string[],
|
|
127
|
+
params: Readonly<Record<string, string>>,
|
|
128
|
+
pi = 0,
|
|
129
|
+
si = 0,
|
|
130
|
+
): boolean {
|
|
131
|
+
if (pi === pattern.length)
|
|
132
|
+
return si === parts.length
|
|
133
|
+
const seg = pattern[pi]!
|
|
134
|
+
if (seg.kind === 'catchall')
|
|
135
|
+
return params[seg.value] === parts.slice(si).join('/')
|
|
136
|
+
if (seg.kind === 'optional') {
|
|
137
|
+
if (si < parts.length && params[seg.value] === parts[si] && matchPattern(pattern, parts, params, pi + 1, si + 1))
|
|
138
|
+
return true
|
|
139
|
+
return !Object.hasOwn(params, seg.value) && matchPattern(pattern, parts, params, pi + 1, si)
|
|
140
|
+
}
|
|
141
|
+
if (si >= parts.length)
|
|
142
|
+
return false
|
|
143
|
+
if (seg.kind === 'static')
|
|
144
|
+
return seg.value === parts[si] && matchPattern(pattern, parts, params, pi + 1, si + 1)
|
|
145
|
+
return params[seg.value] === parts[si] && matchPattern(pattern, parts, params, pi + 1, si + 1)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** True when `target` is a known prerendered HTML page or `strippedPath` matches an SSR HTML page route. */
|
|
149
|
+
export function isCanonicalHtmlTarget(
|
|
150
|
+
index: CanonicalRouteIndex,
|
|
151
|
+
target: string,
|
|
152
|
+
strippedPath: string,
|
|
153
|
+
params: Readonly<Record<string, string>>,
|
|
154
|
+
): boolean {
|
|
155
|
+
const normTarget = normalizePathname(target)
|
|
156
|
+
if (index.prerenderedHtml.has(normTarget))
|
|
157
|
+
return true
|
|
158
|
+
if (normTarget.includes('%')) {
|
|
159
|
+
const decodedTarget = decodePathname(normTarget)
|
|
160
|
+
if (decodedTarget !== undefined && index.prerenderedHtml.has(decodedTarget))
|
|
161
|
+
return true
|
|
162
|
+
}
|
|
163
|
+
const decodedPath = decodePathname(strippedPath)
|
|
164
|
+
if (decodedPath === undefined)
|
|
165
|
+
return false
|
|
166
|
+
if (index.staticPages.has(decodedPath))
|
|
167
|
+
return true
|
|
168
|
+
if (index.dynamicPages.length === 0)
|
|
169
|
+
return false
|
|
170
|
+
const parts = decodedPath === '/' ? [] : decodedPath.slice(1).split('/')
|
|
171
|
+
return index.dynamicPages.some(pattern => matchPattern(pattern, parts, params))
|
|
172
|
+
}
|
package/README.md
DELETED