@prunellejs/i18n 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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 CHANGED
@@ -12,7 +12,8 @@
12
12
  - `defaultLocale`: `string` (e.g. `'en'`).
13
13
  - `messages`: `Record<locale, Record<key, string>>` (optional; falls back to `defaultLocale`, then returns `key`).
14
14
  - `prefixDefault`: `boolean` (default `false`; when `true`, default locale is also prefixed as `/en/...`).
15
- - `site`: optional public origin (inherits `PrunelleConfig.site`); when set, injects `<link rel="alternate" hreflang="...">` tags into `<head>`.
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.
16
17
 
17
18
  ## Mounted Routes, Rewriting & `ctx.locals`
18
19
 
@@ -21,8 +22,10 @@
21
22
  - `ctx.locals.t(key)`: translate string for active locale
22
23
  - `ctx.locals.localize(path, targetLocale?)`: build localized path
23
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.
24
26
  - Mounted route: `GET /_i18n/locales` → `{ locales, defaultLocale, current }`.
25
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.
26
29
  - Sets `<html lang={locale}>` and `hreflang` links in `head()`.
27
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).
28
31
  - Expands `prerenderPaths` across all configured locales and shares `I18N_CONFIG_SERVICE` with `@prunellejs/seo` for multilingual `sitemap.xml`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/i18n",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Locale URL rewriting and dictionary internationalization plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-i18n"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.6.0"
24
+ "prunelle": "^0.7.0"
25
25
  }
26
26
  }
package/src/index.ts CHANGED
@@ -25,7 +25,10 @@ export interface I18nOptions {
25
25
  site?: string | undefined
26
26
  }
27
27
 
28
- const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^>]*>|<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi
28
+ const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^>]*>|<a(?=[\s>/])((?:[^>"']|"[^"]*"|'[^']*')*)>/gi
29
+ // One attribute of a start tag: its leading space, its name, and the value when it is quoted.
30
+ const ATTR_RE = /(\s)([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g
31
+ const NO_LOCALIZE_RE = /\sdata-no-localize(?=[\s=/]|$)/i
29
32
  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
30
33
 
31
34
  function isSkippedI18nPath(pathname: string, assetPrefix: string, assetPrefixSlash: string): boolean {
@@ -51,9 +54,22 @@ function localizeHtmlLinks(
51
54
  let inTextarea = false
52
55
  let codePreDepth = 0
53
56
  HTML_TOKEN_RE.lastIndex = 0
57
+ const localizeHref = (href: string): string | undefined => {
58
+ if (!href.startsWith('/') || href.startsWith('//'))
59
+ return undefined
60
+ const cut = href.search(/[?#]/)
61
+ const pathOnly = cut === -1 ? href : href.slice(0, cut)
62
+ if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
63
+ return undefined
64
+ const seg = pathOnly.slice(1).split('/', 1)[0]
65
+ if (seg !== undefined && localeSet.has(seg))
66
+ return undefined
67
+ // `href` is already extracted from a quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&amp;`.
68
+ return href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
69
+ }
54
70
  return html.replace(
55
71
  HTML_TOKEN_RE,
56
- (match, slash: string | undefined, skipTag: string | undefined, before: string | undefined, href: string | undefined, after: string | undefined) => {
72
+ (match, slash: string | undefined, skipTag: string | undefined, attrs: string | undefined) => {
57
73
  if (skipTag !== undefined) {
58
74
  const tag = skipTag.toLowerCase()
59
75
  const isClosing = slash === '/'
@@ -75,22 +91,17 @@ function localizeHtmlLinks(
75
91
  }
76
92
  return match
77
93
  }
78
- if (inTextarea || codePreDepth > 0 || href === undefined)
79
- return match
80
- const pre = before ?? ''
81
- const post = after ?? ''
82
- if (pre.includes('data-no-localize') || post.includes('data-no-localize') || href.startsWith('//'))
83
- return match
84
- const cut = href.search(/[?#]/)
85
- const pathOnly = cut === -1 ? href : href.slice(0, cut)
86
- if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
94
+ if (inTextarea || codePreDepth > 0 || attrs === undefined || NO_LOCALIZE_RE.test(attrs))
87
95
  return match
88
- const seg = pathOnly.slice(1).split('/', 1)[0]
89
- if (seg !== undefined && localeSet.has(seg))
90
- return match
91
- // `href` is already extracted from a double-quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&amp;`.
92
- const prefixed = href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
93
- return `<a${pre}href="${prefixed}"${post}>`
96
+ const rewritten = attrs.replace(ATTR_RE, (attr, space: string, name: string, double: string | undefined, single: string | undefined) => {
97
+ const value = double ?? single
98
+ const next = name.toLowerCase() === 'href' && value !== undefined ? localizeHref(value) : undefined
99
+ if (next === undefined)
100
+ return attr
101
+ const quote = double !== undefined ? '"' : "'"
102
+ return `${space}${name}=${quote}${next}${quote}`
103
+ })
104
+ return `<a${rewritten}>`
94
105
  },
95
106
  )
96
107
  }
@@ -155,7 +166,33 @@ export function formatNumber(
155
166
  return new Intl.NumberFormat(locale, options).format(value)
156
167
  }
157
168
 
169
+ const LOCALE_TAG_RE = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i
170
+
171
+ function validateOptions({ locales, defaultLocale }: I18nOptions): void {
172
+ const fail = (what: string, fix: string): never => {
173
+ throw new Error(`@prunellejs/i18n: ${what}: ${fix}.`)
174
+ }
175
+ if (locales.length === 0)
176
+ fail('locales is empty', "list at least one locale tag, for example locales: ['en']")
177
+ const seen = new Set<string>()
178
+ for (const loc of locales) {
179
+ if (!LOCALE_TAG_RE.test(loc))
180
+ fail(`"${loc}" is not a valid locale tag`, "use a BCP 47 tag such as 'en' or 'fr-CA'")
181
+ if (seen.has(loc))
182
+ fail(`locale "${loc}" is listed twice`, 'remove the duplicate from locales')
183
+ seen.add(loc)
184
+ }
185
+ if (!seen.has(defaultLocale))
186
+ fail(`defaultLocale "${defaultLocale}" is not in locales`, 'add it to locales or pick one of them')
187
+ }
188
+
189
+ /** A successful HTML page, as opposed to a plugin or API route answering JSON, XML or a stream, or a 404. */
190
+ function isHtmlPage(res: Response): boolean {
191
+ return res.status >= 200 && res.status < 300 && (res.headers.get('content-type') ?? '').startsWith('text/html')
192
+ }
193
+
158
194
  export function i18n(options: I18nOptions): PrunellePlugin {
195
+ validateOptions(options)
159
196
  const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
160
197
  let activeSite = options.site?.replace(/\/$/, '')
161
198
  let activeAssetPrefix = '/_pru'
@@ -227,21 +264,36 @@ export function i18n(options: I18nOptions): PrunellePlugin {
227
264
  return stripped.locale !== undefined ? stripped.path : undefined
228
265
  })
229
266
 
230
- if (prefixDefault) {
231
- // Every prerendered path carries a locale prefix (`prerenderPaths`), so prerendered pages skip this redirect.
232
- api.use((ctx, next) => {
233
- const method = ctx.request.method
234
- if (method !== 'GET' && method !== 'HEAD')
235
- return next()
236
- const rawPath = ctx.url.pathname
267
+ // One URL per page: the default locale is prefixed (301 away) only with prefixDefault, and unprefixed (302 to the prefix) only without it.
268
+ // The redirect waits for the chain, so plugin and API routes and missing pages answer as they are.
269
+ // Prerendered paths never need it (`prerenderPaths`), so prerendered pages skip it.
270
+ api.use(async (ctx, next) => {
271
+ const method = ctx.request.method
272
+ if (method !== 'GET' && method !== 'HEAD')
273
+ return next()
274
+ const rawPath = ctx.url.pathname
275
+ const { locale, path } = stripLocalePrefix(rawPath, locales)
276
+ let target: string
277
+ let status: 301 | 302
278
+ if (locale === undefined && prefixDefault) {
237
279
  if (isSkippedI18nPath(rawPath, activeAssetPrefix, assetPrefixSlash))
238
280
  return next()
239
- if (stripLocalePrefix(rawPath, locales).locale !== undefined)
240
- return next()
241
- const target = localizePath(rawPath, defaultLocale, defaultLocale, locales, true)
242
- return ctx.redirect(`${target}${ctx.url.search}`, 302)
243
- }, { scope: 'rendered' })
244
- }
281
+ target = localizePath(rawPath, defaultLocale, defaultLocale, locales, true)
282
+ status = 302
283
+ }
284
+ else if (locale === defaultLocale && !prefixDefault) {
285
+ target = path
286
+ status = 301
287
+ }
288
+ else {
289
+ return next()
290
+ }
291
+ const res = await next()
292
+ if (!isHtmlPage(res))
293
+ return res
294
+ void res.body?.cancel()
295
+ return ctx.redirect(`${target}${ctx.url.search}`, status)
296
+ }, { scope: 'rendered' })
245
297
 
246
298
  api.route('GET', '/_i18n/locales', ctx =>
247
299
  ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
@@ -250,8 +302,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
250
302
  prerenderPaths(paths) {
251
303
  const out = new Set<string>()
252
304
  for (const raw of paths) {
253
- if (stripLocalePrefix(raw, locales).locale !== undefined) {
254
- out.add(raw)
305
+ const { locale } = stripLocalePrefix(raw, locales)
306
+ if (locale !== undefined) {
307
+ // The default locale is only ever served unprefixed when prefixDefault is off: `/en/x` is a redirect, never a page.
308
+ out.add(locale === defaultLocale && !prefixDefault ? localizePath(raw, locale, defaultLocale, locales, false) : raw)
255
309
  continue
256
310
  }
257
311
  for (const loc of locales)
@@ -269,6 +323,9 @@ export function i18n(options: I18nOptions): PrunellePlugin {
269
323
  const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
270
324
  for (const l of links)
271
325
  head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
326
+ const base = links.find(l => l.locale === defaultLocale)
327
+ if (base !== undefined)
328
+ head.add(`<link rel="alternate" hreflang="x-default" href="${escAttr(base.href)}">`)
272
329
  }
273
330
  },
274
331