@rimelight/i18n 0.0.2 → 0.0.4

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 Rimelight Entertainment
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rimelight/i18n",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "private": false,
5
5
  "description": "Rimelight i18n — unified translation loader with optional KV backing",
6
6
  "files": [
@@ -11,6 +11,7 @@
11
11
  ".": "./src/index.ts",
12
12
  "./integration": "./src/integration.ts",
13
13
  "./middleware": "./src/middleware.ts",
14
+ "./runtime": "./src/runtime.ts",
14
15
  "./types": "./src/types.ts",
15
16
  "./utils": "./src/utils.ts"
16
17
  },
@@ -19,8 +20,7 @@
19
20
  },
20
21
  "dependencies": {
21
22
  "@nanostores/i18n": "1.3.3",
22
- "astro-nanostores-i18n": "0.7.0",
23
- "nanostores": "1.3.0"
23
+ "nanostores": "1.4.0"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "astro": ">=6.0.0"
package/src/env.d.ts ADDED
@@ -0,0 +1 @@
1
+ /// <reference types="astro/client" />
package/src/index.ts CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  clearCache,
9
9
  getI18nInstance,
10
10
  getFormatterInstance
11
- } from "astro-nanostores-i18n:runtime"
11
+ } from "@rimelight/i18n:runtime"
12
12
  import type { Translations } from "@nanostores/i18n"
13
13
 
14
14
  export { currentLocale, useFormat, clearCache, getI18nInstance, getFormatterInstance }
@@ -110,3 +110,11 @@ export function createTranslationLoader(
110
110
  return Object.assign({}, ...results)
111
111
  }
112
112
  }
113
+
114
+ /**
115
+ * Returns the plural category (e.g. 'one', 'few', 'many', 'other') for a given number and locale
116
+ * using the native browser Intl.PluralRules API.
117
+ */
118
+ export function getPluralCategory(count: number, locale: string = "en"): Intl.LDMLPluralRule {
119
+ return new Intl.PluralRules(locale).select(count)
120
+ }
@@ -1,4 +1,3 @@
1
- import nanostoresI18n from "astro-nanostores-i18n"
2
1
  import type { AstroIntegration } from "astro"
3
2
  import fs from "node:fs"
4
3
  import path from "node:path"
@@ -10,42 +9,131 @@ export interface RimelightI18nOptions {
10
9
  translationLoader?: string
11
10
  }
12
11
 
13
- export function rimelightI18n(options?: RimelightI18nOptions): any {
12
+ export function rimelightI18n(options?: RimelightI18nOptions): AstroIntegration[] {
14
13
  const validateExtraction = options?.validateExtraction ?? true
15
14
  const translations = options?.translations
16
15
  const kvBinding = options?.kvBinding ?? "TRANSLATIONS_KV"
17
- const translationLoader = options?.translationLoader ?? "./src/i18n/loader.ts"
16
+ const translationLoader = options?.translationLoader
18
17
 
19
- const nanostoresTranslations: Record<string, any> = {}
18
+ // Normalise locale keys: "pt" "pt-br" for nanostores compatibility
19
+ const normalisedTranslations: Record<string, any> = {}
20
20
  if (translations) {
21
21
  for (const [locale, val] of Object.entries(translations)) {
22
- if (locale === "pt") {
23
- nanostoresTranslations["pt-br"] = val
24
- } else {
25
- nanostoresTranslations[locale] = val
26
- }
22
+ normalisedTranslations[locale === "pt" ? "pt-br" : locale] = val
27
23
  }
28
24
  }
29
25
 
26
+ // ---------- Vite virtual module: @rimelight/i18n:runtime ----------
27
+ // This replicates what astro-nanostores-i18n integration.js used to do:
28
+ // it creates a virtual module that calls initializeI18n() once at module
29
+ // evaluation time and re-exports all runtime helpers.
30
+ const VIRTUAL_MODULE_ID = "@rimelight/i18n:runtime"
31
+ const RESOLVED_VIRTUAL_MODULE_ID = "\0" + VIRTUAL_MODULE_ID
32
+
33
+ // Use the package export specifier so Vite resolves it through normal
34
+ // module resolution rather than an absolute filesystem path.
35
+ const runtimeSpecifier = "@rimelight/i18n/runtime"
36
+
37
+ const loaderImport = translationLoader
38
+ ? `import translationLoader from ${JSON.stringify(translationLoader)};`
39
+ : ""
40
+ const loaderOption = translationLoader ? ", get: translationLoader" : ""
41
+
42
+ // ----------------------------------------------------------------
43
+
30
44
  const rimelightI18nCore: AstroIntegration = {
31
45
  name: "@rimelight/i18n",
32
46
  hooks: {
33
- "astro:config:setup": ({ addMiddleware, updateConfig, logger }) => {
47
+ "astro:config:setup": ({ config, addMiddleware, updateConfig, logger }) => {
48
+ const locales = config.i18n?.locales ?? ["en"]
49
+ const defaultLocale = config.i18n?.defaultLocale ?? "en"
50
+
51
+ const virtualModuleContent = `\
52
+ import { initializeI18n, useFormat, useI18n, useI18nAsync,
53
+ currentLocale, getI18nInstance, getFormatterInstance, clearCache }
54
+ from ${JSON.stringify(runtimeSpecifier)};
55
+ ${loaderImport}
56
+
57
+ initializeI18n({
58
+ defaultLocale: ${JSON.stringify(defaultLocale)},
59
+ translations: ${JSON.stringify(normalisedTranslations)}${loaderOption}
60
+ });
61
+
62
+ export { useFormat, useI18n, useI18nAsync, currentLocale,
63
+ getI18nInstance, getFormatterInstance, clearCache };
64
+ `
65
+
34
66
  addMiddleware({
35
67
  entrypoint: "@rimelight/i18n/middleware",
36
68
  order: "pre"
37
69
  })
70
+
38
71
  updateConfig({
39
72
  vite: {
40
73
  ssr: {
41
74
  noExternal: ["@rimelight/i18n"]
42
- }
75
+ },
76
+ plugins: [
77
+ // Virtual module: @rimelight/i18n:runtime
78
+ {
79
+ name: "vite-plugin-rimelight-i18n-runtime",
80
+ resolveId(id) {
81
+ if (id === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID
82
+ return null
83
+ },
84
+ load(id) {
85
+ if (id === RESOLVED_VIRTUAL_MODULE_ID) return virtualModuleContent
86
+ return null
87
+ }
88
+ },
89
+ // Virtual module: virtual:rimelight-i18n-config (locale metadata)
90
+ {
91
+ name: "vite-plugin-rimelight-i18n-config",
92
+ resolveId(id) {
93
+ if (id === "virtual:rimelight-i18n-config") return "\0" + id
94
+ return null
95
+ },
96
+ load(id) {
97
+ if (id === "\0virtual:rimelight-i18n-config") {
98
+ return `
99
+ export const locales = ${JSON.stringify(locales)};
100
+ export const defaultLocale = ${JSON.stringify(defaultLocale)};
101
+ `
102
+ }
103
+ return null
104
+ }
105
+ }
106
+ ]
43
107
  }
44
108
  })
109
+
45
110
  if (validateExtraction) {
46
111
  logger.info("i18n extraction validation active")
47
112
  }
48
113
  },
114
+
115
+ "astro:config:done": ({ injectTypes }) => {
116
+ // Inject ambient type declarations for the virtual module so TypeScript
117
+ // and editor tooling know the shape of @rimelight/i18n:runtime.
118
+ injectTypes({
119
+ filename: "rimelight-i18n.d.ts",
120
+ content: `\
121
+ declare module "@rimelight/i18n:runtime" {
122
+ import type { Translations } from '@nanostores/i18n';
123
+ export type { InitializeI18nOptions } from '@rimelight/i18n/runtime';
124
+ export const currentLocale: import('nanostores').PreinitializedWritableAtom<string> & object;
125
+ export declare function initializeI18n(options: import('@rimelight/i18n/runtime').InitializeI18nOptions): void;
126
+ export declare function useFormat(): import('@nanostores/i18n').Formatter;
127
+ export declare function useI18n<Body extends Translations>(componentName: string, baseTranslations: Body): Body;
128
+ export declare function useI18nAsync<Body extends Translations>(componentName: string, baseTranslations: Body): Promise<Body>;
129
+ export declare function getI18nInstance(): ReturnType<typeof import('@nanostores/i18n').createI18n>;
130
+ export declare function getFormatterInstance(): ReturnType<typeof import('@nanostores/i18n').formatter>;
131
+ export declare function clearCache(locale?: string): void;
132
+ }
133
+ `
134
+ })
135
+ },
136
+
49
137
  "astro:build:done": async ({ logger }) => {
50
138
  if (translations) {
51
139
  const seedData: { keys: { key: string; value: string }[] } = { keys: [] }
@@ -84,12 +172,5 @@ export function rimelightI18n(options?: RimelightI18nOptions): any {
84
172
  }
85
173
  }
86
174
 
87
- return [
88
- nanostoresI18n({
89
- translationLoader,
90
- addMiddleware: false,
91
- translations: nanostoresTranslations
92
- }),
93
- rimelightI18nCore
94
- ]
175
+ return [rimelightI18nCore]
95
176
  }
@@ -1,7 +1,7 @@
1
1
  import { setKVBinding } from "../index"
2
2
  import { env } from "cloudflare:workers"
3
3
 
4
- export const onRequest = async (context: any, next: any) => {
4
+ export const onRequest = async (_context: unknown, next: () => Promise<Response>) => {
5
5
  const kv = Reflect.get(env, "TRANSLATIONS_KV")
6
6
  if (kv) {
7
7
  setKVBinding(kv)
@@ -1,5 +1,7 @@
1
- const SUPPORTED_LOCALES = new Set(["en", "pt", "es"])
2
- const DEFAULT_LOCALE = "en"
1
+ import { locales, defaultLocale } from "virtual:rimelight-i18n-config"
2
+
3
+ const SUPPORTED_LOCALES = new Set(locales)
4
+ const DEFAULT_LOCALE = defaultLocale
3
5
 
4
6
  function getPreferredLocale(acceptLanguage: string | null): string {
5
7
  if (!acceptLanguage) return DEFAULT_LOCALE
@@ -8,13 +10,14 @@ function getPreferredLocale(acceptLanguage: string | null): string {
8
10
  .split(",")
9
11
  .map((lang) => {
10
12
  const parts = lang.split(";")
11
- const code = parts[0].trim().toLowerCase()
12
- const base = code.split("-")[0]
13
+ const code = (parts[0] ?? "").trim().toLowerCase()
14
+ const base = code.split("-")[0] ?? ""
13
15
  let q = 1.0
14
- if (parts[1]) {
15
- const qMatch = parts[1].match(/q=([0-9.]+)/)
16
+ const qualityPart = parts[1]
17
+ if (qualityPart) {
18
+ const qMatch = qualityPart.match(/q=([0-9.]+)/)
16
19
  if (qMatch) {
17
- q = parseFloat(qMatch[1])
20
+ q = parseFloat(qMatch[1] ?? "1")
18
21
  }
19
22
  }
20
23
  return { code, base, q }
@@ -25,8 +28,9 @@ function getPreferredLocale(acceptLanguage: string | null): string {
25
28
  if (SUPPORTED_LOCALES.has(item.code)) {
26
29
  return item.code
27
30
  }
28
- if (SUPPORTED_LOCALES.has(item.base)) {
29
- return item.base
31
+ const base: string = item.base
32
+ if (SUPPORTED_LOCALES.has(base)) {
33
+ return base
30
34
  }
31
35
  }
32
36
 
package/src/middleware.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { env } from "cloudflare:workers"
2
2
  import { setKVBinding } from "./index"
3
3
 
4
- export const onRequest = async (context: any, next: any) => {
4
+ export const onRequest = async (_context: unknown, next: () => Promise<Response>) => {
5
5
  const kv = Reflect.get(env, "TRANSLATIONS_KV")
6
6
  if (kv) {
7
7
  setKVBinding(kv)
package/src/runtime.ts ADDED
@@ -0,0 +1,149 @@
1
+ import { createI18n, formatter, translationsLoading } from "@nanostores/i18n"
2
+ import type {
3
+ TranslationLoader,
4
+ Translations,
5
+ I18n,
6
+ Components,
7
+ ComponentsJSON
8
+ } from "@nanostores/i18n"
9
+ import { atom } from "nanostores"
10
+
11
+ /**
12
+ * A reactive store containing the current locale code. Set by middleware on each request, or
13
+ * manually via `currentLocale.set(locale)`.
14
+ */
15
+ export const currentLocale = atom("")
16
+
17
+ type I18nInstance = I18n
18
+ type FormatterInstance = ReturnType<typeof formatter>
19
+
20
+ let i18nInstance: I18nInstance | undefined
21
+ let formatterInstance: FormatterInstance | undefined
22
+
23
+ function throwNotInitialized(): never {
24
+ throw new Error("i18n not initialized. Call initializeI18n first.")
25
+ }
26
+
27
+ /**
28
+ * Wraps a TranslationLoader so that the returned object is guaranteed to contain a key for every
29
+ * requested component.
30
+ *
31
+ * The nanostores i18n library uses the keys of the object returned from `get` to clear its internal
32
+ * "requested" set. If a requested component is missing from the result (e.g. because the backend
33
+ * has no translations for it in the given locale yet), the internal loading atom is never set back
34
+ * to `false`, which causes useI18nAsync / translationsLoading to hang forever.
35
+ *
36
+ * This wrapper normalises the loader output so missing components are filled in with empty
37
+ * translation objects, falling back to the base translations defined at the call site.
38
+ */
39
+ function wrapLoader(loader: TranslationLoader): TranslationLoader {
40
+ return async (code, components): Promise<ComponentsJSON> => {
41
+ const raw = await loader(code, components)
42
+ const normalised: ComponentsJSON = Array.isArray(raw)
43
+ ? Object.assign({} as ComponentsJSON, ...raw)
44
+ : { ...raw }
45
+ for (const component of components) {
46
+ if (!(component in normalised)) normalised[component] = {}
47
+ }
48
+ return normalised
49
+ }
50
+ }
51
+
52
+ export interface InitializeI18nOptions {
53
+ /**
54
+ * The default locale code (e.g. 'en').
55
+ */
56
+ defaultLocale: string
57
+ /**
58
+ * Pre-loaded translations keyed by locale then component.
59
+ */
60
+ translations: Record<string, Components>
61
+ /**
62
+ * Optional dynamic loader called when a locale is not in cache.
63
+ */
64
+ get?: TranslationLoader
65
+ }
66
+
67
+ /**
68
+ * Initializes the i18n system. Must be called once before any other i18n functions are used (the
69
+ * integration virtual module does this automatically).
70
+ */
71
+ export function initializeI18n(options: InitializeI18nOptions): void {
72
+ const { defaultLocale, translations, get } = options
73
+ if (!i18nInstance) {
74
+ currentLocale.set(defaultLocale)
75
+ i18nInstance = createI18n(currentLocale, {
76
+ baseLocale: defaultLocale,
77
+ get: wrapLoader(get ?? (async (): Promise<ComponentsJSON> => ({}))),
78
+ cache: translations,
79
+ isSSR: true
80
+ })
81
+ }
82
+ formatterInstance = formatter(currentLocale)
83
+ }
84
+
85
+ /**
86
+ * Returns the underlying nanostores/i18n instance. Throws if not initialized.
87
+ */
88
+ export function getI18nInstance(): I18nInstance {
89
+ if (!i18nInstance) throwNotInitialized()
90
+ return i18nInstance
91
+ }
92
+
93
+ /**
94
+ * Returns the formatter instance. Throws if not initialized.
95
+ */
96
+ export function getFormatterInstance(): FormatterInstance {
97
+ if (!formatterInstance) throwNotInitialized()
98
+ return formatterInstance
99
+ }
100
+
101
+ /**
102
+ * Returns a Formatter object for the current locale with methods for formatting numbers, dates, and
103
+ * relative times using the native Intl API.
104
+ */
105
+ export function useFormat(): ReturnType<FormatterInstance["get"]> {
106
+ return getFormatterInstance().get()
107
+ }
108
+
109
+ /**
110
+ * Returns the translated strings for a component in the current locale. Falls back to
111
+ * `baseTranslations` for any key not present in the loaded locale.
112
+ */
113
+ export function useI18n<Body extends Translations>(
114
+ componentName: string,
115
+ baseTranslations: Body
116
+ ): Body {
117
+ return getI18nInstance()(componentName, baseTranslations).get()
118
+ }
119
+
120
+ /**
121
+ * Async version of useI18n that waits for translations to finish loading. Required when using a
122
+ * dynamic translationLoader (e.g. KV-backed loading).
123
+ */
124
+ export async function useI18nAsync<Body extends Translations>(
125
+ componentName: string,
126
+ baseTranslations: Body
127
+ ): Promise<Body> {
128
+ const i18n = getI18nInstance()
129
+ const store = i18n(componentName, baseTranslations)
130
+ const unsubscribe = store.listen(() => {})
131
+ await translationsLoading(i18n)
132
+ unsubscribe()
133
+ return store.get()
134
+ }
135
+
136
+ /**
137
+ * Clears the translation cache.
138
+ *
139
+ * @param locale - If provided, clears only that locale's cache. Otherwise clears all.
140
+ */
141
+ export function clearCache(locale?: string): void {
142
+ if (!i18nInstance) throwNotInitialized()
143
+ const cache = i18nInstance.cache
144
+ if (locale) {
145
+ cache[locale] = {}
146
+ } else {
147
+ for (const key in cache) cache[key] = {}
148
+ }
149
+ }
package/src/utils.ts CHANGED
@@ -19,13 +19,14 @@ export function unflatten(flat: FlattenedTranslations): ComponentsJSON {
19
19
  for (const [key, value] of Object.entries(flat)) {
20
20
  const parts = key.split(".")
21
21
  if (parts.length < 2) continue
22
- const component = parts[0]
22
+ const component: string = parts[0] ?? ""
23
+ if (!component) continue
23
24
  const translationKey = parts.slice(1).join(".")
24
25
 
25
26
  if (!(component in result)) {
26
27
  result[component] = {}
27
28
  }
28
- result[component][translationKey] = value
29
+ result[component]![translationKey] = value
29
30
  }
30
31
  return result
31
32
  }
package/src/virtual.d.ts CHANGED
@@ -1,3 +1,16 @@
1
- declare module "astro-nanostores-i18n:runtime" {
2
- export * from "astro-nanostores-i18n/runtime"
1
+ declare module "@rimelight/i18n:runtime" {
2
+ export * from "@rimelight/i18n/runtime"
3
+ }
4
+
5
+ declare module "virtual:rimelight-i18n-config" {
6
+ export const locales: string[]
7
+ export const defaultLocale: string
8
+ }
9
+
10
+ declare module "cloudflare:workers" {
11
+ /**
12
+ * Ambient Cloudflare Workers env — populated at runtime by the CF runtime.
13
+ */
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ export const env: Record<string, any>
3
16
  }