@sonenta/astro 0.1.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/CONTRACT.md ADDED
@@ -0,0 +1,85 @@
1
+ # @sonenta/astro — API contract & forward-compatibility
2
+
3
+ This document is the binding contract for the package's public surface. v0.1
4
+ ships as a **standalone** integration (no dependency on the future shared i18n
5
+ engine); the contract here is frozen so the move onto `@sonenta/i18n-core`
6
+ (`0.2.0`) is a **non-breaking, additive** internal refactor.
7
+
8
+ ## Trajectory
9
+
10
+ | Version | What it is |
11
+ | --- | --- |
12
+ | **0.1.0** | Standalone. Build-time CDN fetch + string resolution + `{var}` interpolation + source-language fallback. Pure SSG, zero client JS. |
13
+ | **0.2.0** | Internals swapped to `@sonenta/i18n-core`. Adds CLDR plurals, accessibility surfaces (`t.aria`/`t.alt`), responsive variants, BCP-47 variant→base inheritance, and optional SSR/hybrid — all **additive**. The 0.1 API keeps working unchanged. |
14
+ | **1.0.0** | Promoted to stable once the demos / website have validated parity. |
15
+
16
+ ## Frozen public surface (will not break across 0.x → 1.0)
17
+
18
+ ### Default export — the integration
19
+
20
+ ```ts
21
+ import sonenta from "@sonenta/astro";
22
+ sonenta(options: SonentaI18nOptions): AstroIntegration
23
+ ```
24
+
25
+ ### Configuration keys (`SonentaI18nOptions`)
26
+
27
+ `project`, `version`, `locales`, `defaultLocale`, `fallbackLng`, `namespaces`,
28
+ `cdnBase`, `apiBase`, `fetchImpl`.
29
+
30
+ These names are **identical to what `@sonenta/i18n-core` consumes**, so the
31
+ 0.2.0 refactor reads the same config. New optional keys may be **added** (e.g.
32
+ `surface`, `mode: "ssg" | "hybrid"`); existing keys never change meaning or
33
+ type.
34
+
35
+ ### Virtual module `sonenta:i18n`
36
+
37
+ ```ts
38
+ export const getT: (locale: Locale) => TFn; // t(key, vars?) => string
39
+ export const locales: Locale[];
40
+ export const defaultLocale: Locale;
41
+ export const getCatalog: (locale, namespace?) => Record<string, unknown> | null;
42
+ export default i18n: SonentaI18n;
43
+ ```
44
+
45
+ `getT(locale)` returns a `t()` whose **call signature is frozen**:
46
+ `t(key: string, vars?: Record<string, string | number>): string`. The 0.2.0
47
+ release **adds methods** to the returned function (e.g. `t.aria(key)`,
48
+ `t.alt(key)`, plural-aware `t(key, { count })`) — additive, never breaking the
49
+ bare `t(key)` call.
50
+
51
+ ### Runtime entry `@sonenta/astro/runtime`
52
+
53
+ `createSonentaI18n(options)`, `createT(...)`, `fetchAll`/`fetchBundle`/
54
+ `fetchNamespace`, `buildBundleUrl`, `resolveCdnBase`, and all types. Stable.
55
+
56
+ ### CDN wire layout (owned by backend, consumed here)
57
+
58
+ `{cdnBase}/p/{project}/{version}/latest/{locale}/{namespace}.json`
59
+
60
+ - `200` → bundle JSON.
61
+ - `404` → treated as **absent** (`null`); the locale falls back to the source.
62
+ - any other non-OK / transport error → **throws** (a misconfigured build fails
63
+ loudly rather than silently shipping empty pages).
64
+
65
+ ## v0.1 explicit non-goals (deliberately deferred to the core-backed release)
66
+
67
+ To guarantee the additive path above, v0.1 ships **no naive implementation** of
68
+ the following — there is therefore no v0.1 behaviour to break when core takes
69
+ over their semantics:
70
+
71
+ - **CLDR plurals** (`t(key, { count })` pluralization).
72
+ - **Accessibility surfaces** (`t.aria`, `t.alt`, screen-reader / plain-language
73
+ variants).
74
+ - **Responsive surface variants** (desktop / mobile / tablet overlays).
75
+ - **BCP-47 variant→base inheritance** (`fr-CA → fr`). v0.1 applies the
76
+ configured `fallbackLng` list literally.
77
+ - **SSR / hybrid** request-scoped resolution. v0.1 is build-time SSG only.
78
+
79
+ ## Boundaries
80
+
81
+ - Backend owns the API/CDN wire contract; this package is a **consumer** and
82
+ never changes it. Contract questions route through the SDK owner.
83
+ - Add-on SDKs (`feedback`, `realtime`, `in-context`) are runtime/DOM and run
84
+ only inside Astro **client islands** (via the React bindings), never in
85
+ static `.astro` output.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Verbumia
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/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @sonenta/astro
2
+
3
+ Official [Astro](https://astro.build) integration for [Sonenta](https://sonenta.com) i18n.
4
+
5
+ Your translations live in Sonenta; this integration pulls the released bundles
6
+ from the CDN **at build time** and inlines them into your static HTML. There is
7
+ **zero client-side JavaScript** — it's pure SSG, the way Astro content sites
8
+ want i18n to work.
9
+
10
+ ```sh
11
+ npm install @sonenta/astro
12
+ # or: pnpm add @sonenta/astro / yarn add @sonenta/astro
13
+ ```
14
+
15
+ > **v0.1 — standalone.** This release does string resolution, `{var}`
16
+ > interpolation, and source-language fallback. CLDR plurals, accessibility
17
+ > surfaces, and responsive variants arrive **additively** in `0.2.0` (backed by
18
+ > `@sonenta/i18n-core`) **without any breaking change** to the API below — see
19
+ > [CONTRACT.md](./CONTRACT.md).
20
+
21
+ ## Quick start
22
+
23
+ ```js
24
+ // astro.config.mjs
25
+ import { defineConfig } from "astro/config";
26
+ import sonenta from "@sonenta/astro";
27
+
28
+ export default defineConfig({
29
+ // Astro's native i18n routing — the integration reads Astro.currentLocale.
30
+ i18n: { defaultLocale: "fr", locales: ["fr", "en", "es"] },
31
+ integrations: [
32
+ sonenta({
33
+ project: "your-project-uuid", // from your Sonenta dashboard
34
+ locales: ["fr", "en", "es"],
35
+ defaultLocale: "fr",
36
+ namespaces: ["common"],
37
+ }),
38
+ ],
39
+ });
40
+ ```
41
+
42
+ ```astro
43
+ ---
44
+ // src/pages/index.astro
45
+ import { getT, defaultLocale } from "sonenta:i18n";
46
+
47
+ const t = getT(Astro.currentLocale ?? defaultLocale);
48
+ ---
49
+ <html lang={Astro.currentLocale ?? defaultLocale}>
50
+ <head><title>{t("home.title")}</title></head>
51
+ <body>
52
+ <h1>{t("home.title")}</h1>
53
+ <p>{t("home.greeting", { name: "Ada" })}</p>
54
+ </body>
55
+ </html>
56
+ ```
57
+
58
+ That's it. `astro build` fetches `common.json` for every locale and freezes the
59
+ strings into the page. Nothing ships to the browser.
60
+
61
+ ## The `sonenta:i18n` virtual module
62
+
63
+ The integration exposes a virtual module you can import from any `.astro` file
64
+ (or `.ts`/`.js` run at build time):
65
+
66
+ | Export | Description |
67
+ | --- | --- |
68
+ | `getT(locale)` | Returns a `t(key, vars?)` bound to `locale`. |
69
+ | `locales` | The locales fetched into the build. |
70
+ | `defaultLocale` | The resolved source/default locale. |
71
+ | `getCatalog(locale, ns?)` | Raw fetched dictionary, or `null` if absent. |
72
+
73
+ TypeScript types for the virtual module are injected automatically (Astro's
74
+ `injectTypes`), so `getT` is fully typed with no extra config.
75
+
76
+ ### Key resolution
77
+
78
+ - **Dotted keys** walk nested objects: `t("home.cta.label")`.
79
+ - **Namespaces** use the i18next-style `ns:key` syntax: `t("docs:intro")`.
80
+ Un-prefixed keys resolve against the first namespace (default `"common"`).
81
+ - **Interpolation**: `t("greeting", { name: "Ada" })` replaces `{name}`.
82
+ Unknown placeholders are left intact.
83
+ - **Fallback**: a missing key falls back through `fallbackLng` (default: the
84
+ source locale). A locale whose bundle is absent (e.g. plan-limit) falls back
85
+ the same way. Still missing everywhere → the raw key is returned (i18next
86
+ parity).
87
+
88
+ ## Without the integration (explicit build-time fetch)
89
+
90
+ Prefer an explicit top-level `await`? Use the runtime directly — no virtual
91
+ module, no Vite plugin:
92
+
93
+ ```ts
94
+ // src/i18n.ts
95
+ import { createSonentaI18n } from "@sonenta/astro/runtime";
96
+
97
+ export const i18n = await createSonentaI18n({
98
+ project: "your-project-uuid",
99
+ locales: ["fr", "en", "es"],
100
+ defaultLocale: "fr",
101
+ });
102
+ export const getT = i18n.getT;
103
+ ```
104
+
105
+ ## Configuration
106
+
107
+ | Option | Type | Default | Notes |
108
+ | --- | --- | --- | --- |
109
+ | `project` | `string` | — | **Required.** Project UUID. |
110
+ | `locales` | `string[]` | — | **Required.** Locales to fetch + freeze. |
111
+ | `version` | `string` | `"main"` | Released version slug / pinned hash. |
112
+ | `defaultLocale` | `string` | `locales[0]` | Source / fallback locale. |
113
+ | `fallbackLng` | `string \| string[]` | `[defaultLocale]` | Missing-key fallback chain. |
114
+ | `namespaces` | `string[]` | `["common"]` | Bundle files; first is the default ns. |
115
+ | `cdnBase` | `string` | `https://cdn.sonenta.com` | CDN host (no `/p`). Env: `SONENTA_CDN_BASE`. |
116
+ | `apiBase` | `string` | `https://api.sonenta.dev` | Reserved (forward-compat). |
117
+ | `fetchImpl` | `typeof fetch` | global `fetch` | Custom fetch (runtime API only). |
118
+
119
+ Bundles are fetched from
120
+ `{cdnBase}/p/{project}/{version}/latest/{locale}/{namespace}.json` — the same
121
+ CDN layout as `@sonenta/react-i18next`.
122
+
123
+ ## Notes & limits (v0.1)
124
+
125
+ - **Add-ons are island-only.** `@sonenta/feedback`, `@sonenta/realtime`, and
126
+ `@sonenta/in-context` are runtime/DOM SDKs — they run inside Astro client
127
+ islands (reusing the React bindings), not in static `.astro` output.
128
+ - **SSR/hybrid** is not yet wired; v0.1 is build-time SSG. A request-scoped
129
+ resolver (fetch-cache + revalidate) arrives with the core-backed release.
130
+
131
+ ## License
132
+
133
+ MIT © Sonenta
@@ -0,0 +1,131 @@
1
+ // src/types.ts
2
+ var DEFAULT_CDN_BASE = "https://cdn.sonenta.com";
3
+ var DEFAULT_VERSION = "main";
4
+ var DEFAULT_NAMESPACE = "common";
5
+
6
+ // src/cdn.ts
7
+ function trimSlashes(s) {
8
+ return s.replace(/\/+$/, "");
9
+ }
10
+ function resolveCdnBase(opts) {
11
+ const env = typeof process !== "undefined" ? process.env?.SONENTA_CDN_BASE : void 0;
12
+ return trimSlashes(opts.cdnBase ?? env ?? DEFAULT_CDN_BASE);
13
+ }
14
+ function buildBundleUrl(opts, locale, namespace) {
15
+ const base = resolveCdnBase(opts);
16
+ const version = opts.version ?? DEFAULT_VERSION;
17
+ return `${base}/p/${opts.project}/${version}/latest/${locale}/${namespace}.json`;
18
+ }
19
+ async function fetchBundle(opts, locale, namespace) {
20
+ const url = buildBundleUrl(opts, locale, namespace);
21
+ const doFetch = opts.fetchImpl ?? fetch;
22
+ let res;
23
+ try {
24
+ res = await doFetch(url, { method: "GET" });
25
+ } catch (e) {
26
+ throw new Error(
27
+ `[@sonenta/astro] CDN fetch failed for ${locale}/${namespace}: ${e.message}`
28
+ );
29
+ }
30
+ if (!res.ok) {
31
+ if (res.status === 404) return null;
32
+ throw new Error(`[@sonenta/astro] CDN ${res.status} on ${url}`);
33
+ }
34
+ return await res.json();
35
+ }
36
+ async function fetchNamespace(opts, locales, namespace) {
37
+ const entries = await Promise.all(
38
+ locales.map(
39
+ async (l) => [l, await fetchBundle(opts, l, namespace)]
40
+ )
41
+ );
42
+ return Object.fromEntries(entries);
43
+ }
44
+ async function fetchAll(opts, locales, namespaces) {
45
+ const out = {};
46
+ for (const l of locales) out[l] = {};
47
+ await Promise.all(
48
+ locales.flatMap(
49
+ (l) => namespaces.map(async (ns) => {
50
+ out[l][ns] = await fetchBundle(opts, l, ns);
51
+ })
52
+ )
53
+ );
54
+ return out;
55
+ }
56
+
57
+ // src/resolver.ts
58
+ function normalizeFallback(fallbackLng, defaultLocale) {
59
+ if (fallbackLng == null) return [defaultLocale];
60
+ return Array.isArray(fallbackLng) ? fallbackLng : [fallbackLng];
61
+ }
62
+ function splitKey(key, defaultNamespace) {
63
+ const i = key.indexOf(":");
64
+ if (i === -1) return [defaultNamespace, key];
65
+ return [key.slice(0, i), key.slice(i + 1)];
66
+ }
67
+ function walk(bundle, path) {
68
+ if (!bundle) return void 0;
69
+ let cursor = bundle;
70
+ for (const part of path.split(".")) {
71
+ if (cursor && typeof cursor === "object" && part in cursor) {
72
+ cursor = cursor[part];
73
+ } else {
74
+ return void 0;
75
+ }
76
+ }
77
+ return cursor;
78
+ }
79
+ function interpolate(template, vars) {
80
+ if (!vars) return template;
81
+ return template.replace(
82
+ /\{(\w+)\}/g,
83
+ (_, name) => name in vars ? String(vars[name]) : `{${name}}`
84
+ );
85
+ }
86
+ function createT(data, locale, fallbackChain, defaultNamespace) {
87
+ const order = [locale, ...fallbackChain.filter((l) => l !== locale)];
88
+ return function t(key, vars) {
89
+ const [ns, rest] = splitKey(key, defaultNamespace);
90
+ for (const l of order) {
91
+ const hit = walk(data[l]?.[ns], rest);
92
+ if (typeof hit === "string") return interpolate(hit, vars);
93
+ }
94
+ return key;
95
+ };
96
+ }
97
+ async function createSonentaI18n(options) {
98
+ if (!options.project) {
99
+ throw new Error("[@sonenta/astro] `project` (UUID) is required.");
100
+ }
101
+ if (!options.locales?.length) {
102
+ throw new Error("[@sonenta/astro] `locales` must be a non-empty array.");
103
+ }
104
+ const locales = options.locales;
105
+ const defaultLocale = options.defaultLocale ?? locales[0];
106
+ const namespaces = options.namespaces?.length ? options.namespaces : [DEFAULT_NAMESPACE];
107
+ const defaultNamespace = namespaces[0];
108
+ const fallbackChain = normalizeFallback(options.fallbackLng, defaultLocale);
109
+ const data = await fetchAll(options, locales, namespaces);
110
+ return {
111
+ locales,
112
+ defaultLocale,
113
+ getT(locale) {
114
+ return createT(data, locale, fallbackChain, defaultNamespace);
115
+ },
116
+ getCatalog(locale, namespace) {
117
+ return data[locale]?.[namespace ?? defaultNamespace] ?? null;
118
+ }
119
+ };
120
+ }
121
+
122
+ export {
123
+ resolveCdnBase,
124
+ buildBundleUrl,
125
+ fetchBundle,
126
+ fetchNamespace,
127
+ fetchAll,
128
+ createT,
129
+ createSonentaI18n
130
+ };
131
+ //# sourceMappingURL=chunk-CK2DAB6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/cdn.ts","../src/resolver.ts"],"sourcesContent":["/**\n * Public types for `@sonenta/astro` v0.1 (standalone, pre-core).\n *\n * FORWARD-COMPATIBILITY CONTRACT (frozen day-one — see CONTRACT.md): every\n * option key here is the SAME key the future `@sonenta/i18n-core`-backed\n * release will consume, so the later refactor (0.2.0) is a non-breaking,\n * additive internal swap. New capabilities (surfaces, a11y accessors, CLDR\n * plurals, variants) arrive ADDITIVELY; nothing here changes meaning.\n */\n\n/** A BCP-47 locale code, e.g. `\"fr\"`, `\"en\"`, `\"fr-CA\"`. */\nexport type Locale = string;\n\n/** A bundle namespace (the `{ns}.json` file on the CDN), e.g. `\"common\"`. */\nexport type Namespace = string;\n\n/** Interpolation variables for a `t()` call: `t(\"greeting\", { name: \"Ada\" })`. */\nexport type Vars = Record<string, string | number>;\n\n/** A resolved, per-locale translation function. */\nexport type TFn = (key: string, vars?: Vars) => string;\n\n/**\n * Configuration for the Sonenta Astro integration / runtime.\n *\n * Bundles are fetched at BUILD time from\n * `{cdnBase}/p/{project}/{version}/latest/{locale}/{namespace}.json`\n * (the canonical Sonenta CDN layout, identical to `@sonenta/react-i18next`).\n */\nexport interface SonentaI18nOptions {\n /** Project UUID from your Sonenta dashboard. Required. */\n project: string;\n\n /**\n * Released version slug or pinned content hash. Default `\"main\"`.\n * The CDN serves the latest release of this version under `/latest/`.\n */\n version?: string;\n\n /**\n * Locales to fetch and freeze into the static build. Required, non-empty.\n * A locale whose bundle 404s (e.g. a plan-limit-blocked language) is kept\n * as `null` and transparently falls back to the source language.\n */\n locales: Locale[];\n\n /**\n * Source / default locale. Default = `locales[0]`. Used as the implicit\n * final fallback target and as Astro's source language.\n */\n defaultLocale?: Locale;\n\n /**\n * Ordered fallback chain applied when a key is missing in the active\n * locale. Default = `[defaultLocale]`. v0.1 applies these locales in\n * order; BCP-47 variant→base inheritance (`fr-CA → fr`) is deliberately\n * left to the core-backed release.\n */\n fallbackLng?: Locale | Locale[];\n\n /**\n * Namespaces (bundle files) to fetch. Default `[\"common\"]`. The first\n * entry is the default namespace for un-prefixed keys; address others with\n * the i18next-style `\"ns:key\"` syntax.\n */\n namespaces?: Namespace[];\n\n /**\n * CDN host root for translation bundles, WITHOUT the `/p` segment.\n * Default `\"https://cdn.sonenta.com\"`. Overridable via the\n * `SONENTA_CDN_BASE` env var (also a bare host; for local dev point it at\n * your translation CDN). The `/p/{project}/{version}/latest/...` path is\n * appended by the loader.\n */\n cdnBase?: string;\n\n /**\n * API host root. Reserved for forward-compatibility (the core-backed\n * release uses it for the public language manifest and dev-mode runtime\n * fetch). Default `\"https://api.sonenta.dev\"`. Unused by v0.1's prod\n * build-time path.\n */\n apiBase?: string;\n\n /**\n * Injectable `fetch` implementation (testing / proxies / custom agents).\n * Defaults to the global `fetch`.\n */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * The resolved Sonenta i18n handle returned by `createSonentaI18n` and\n * exposed through the `sonenta:i18n` virtual module.\n */\nexport interface SonentaI18n {\n /** Build a translation function bound to `locale`. */\n getT(locale: Locale): TFn;\n /** The locales that were fetched (the configured `locales`). */\n readonly locales: Locale[];\n /** The resolved source/default locale. */\n readonly defaultLocale: Locale;\n /**\n * Raw fetched dictionary for `locale` / `namespace` (default namespace when\n * omitted), or `null` when that bundle was absent (404 / plan-limit).\n */\n getCatalog(locale: Locale, namespace?: Namespace): Record<string, unknown> | null;\n}\n\n/** Default CDN host (no `/p`). */\nexport const DEFAULT_CDN_BASE = \"https://cdn.sonenta.com\";\n/** Default API host. */\nexport const DEFAULT_API_BASE = \"https://api.sonenta.dev\";\n/** Default version slug. */\nexport const DEFAULT_VERSION = \"main\";\n/** Default namespace. */\nexport const DEFAULT_NAMESPACE = \"common\";\n","/**\n * Build-time CDN loader for Sonenta translation bundles.\n *\n * Mirrors the canonical Sonenta CDN layout used by `@sonenta/react-i18next`:\n * `{cdnBase}/p/{project}/{version}/latest/{locale}/{namespace}.json`\n *\n * Pure data fetch — no DOM, no React, no runtime. Called during `astro build`\n * so the strings inline into the static HTML (zero client JS).\n */\n\nimport {\n DEFAULT_CDN_BASE,\n DEFAULT_VERSION,\n type Locale,\n type Namespace,\n type SonentaI18nOptions,\n} from \"./types\";\n\n/** A fetched bundle (a flat or nested dictionary of message strings). */\nexport type Bundle = Record<string, unknown>;\n\n/** Strip trailing slashes so URL joins never double up. */\nfunction trimSlashes(s: string): string {\n return s.replace(/\\/+$/, \"\");\n}\n\n/**\n * Resolve the effective CDN host (no `/p`): explicit option wins, then the\n * `SONENTA_CDN_BASE` env var, then the production default.\n */\nexport function resolveCdnBase(opts: Pick<SonentaI18nOptions, \"cdnBase\">): string {\n const env =\n typeof process !== \"undefined\" ? process.env?.SONENTA_CDN_BASE : undefined;\n return trimSlashes(opts.cdnBase ?? env ?? DEFAULT_CDN_BASE);\n}\n\n/**\n * Build the bundle URL for one `(locale, namespace)` pair.\n * `{cdnBase}/p/{project}/{version}/latest/{locale}/{namespace}.json`\n */\nexport function buildBundleUrl(\n opts: Pick<SonentaI18nOptions, \"project\" | \"version\" | \"cdnBase\">,\n locale: Locale,\n namespace: Namespace,\n): string {\n const base = resolveCdnBase(opts);\n const version = opts.version ?? DEFAULT_VERSION;\n return `${base}/p/${opts.project}/${version}/latest/${locale}/${namespace}.json`;\n}\n\n/**\n * Fetch a single bundle. Resolves to `null` on 404 (locale absent from the\n * project — e.g. a plan-limit-blocked language) so callers fall back to the\n * source language. Any other non-OK status or transport error throws so a\n * misconfigured build fails loudly rather than silently shipping empty pages.\n */\nexport async function fetchBundle(\n opts: Pick<SonentaI18nOptions, \"project\" | \"version\" | \"cdnBase\" | \"fetchImpl\">,\n locale: Locale,\n namespace: Namespace,\n): Promise<Bundle | null> {\n const url = buildBundleUrl(opts, locale, namespace);\n const doFetch = opts.fetchImpl ?? fetch;\n let res: Response;\n try {\n res = await doFetch(url, { method: \"GET\" });\n } catch (e) {\n throw new Error(\n `[@sonenta/astro] CDN fetch failed for ${locale}/${namespace}: ${\n (e as Error).message\n }`,\n );\n }\n if (!res.ok) {\n if (res.status === 404) return null;\n throw new Error(`[@sonenta/astro] CDN ${res.status} on ${url}`);\n }\n return (await res.json()) as Bundle;\n}\n\n/**\n * Fetch one namespace across every locale, in parallel. Absent locales map to\n * `null`. Returns `Record<Locale, Bundle | null>`.\n */\nexport async function fetchNamespace(\n opts: Pick<\n SonentaI18nOptions,\n \"project\" | \"version\" | \"cdnBase\" | \"fetchImpl\"\n >,\n locales: Locale[],\n namespace: Namespace,\n): Promise<Record<Locale, Bundle | null>> {\n const entries = await Promise.all(\n locales.map(\n async (l) => [l, await fetchBundle(opts, l, namespace)] as const,\n ),\n );\n return Object.fromEntries(entries) as Record<Locale, Bundle | null>;\n}\n\n/**\n * Fetch every `(locale, namespace)` pair. Returns a nested map keyed by\n * locale then namespace: `data[locale][namespace] = Bundle | null`.\n */\nexport async function fetchAll(\n opts: Pick<\n SonentaI18nOptions,\n \"project\" | \"version\" | \"cdnBase\" | \"fetchImpl\"\n >,\n locales: Locale[],\n namespaces: Namespace[],\n): Promise<Record<Locale, Record<Namespace, Bundle | null>>> {\n const out: Record<Locale, Record<Namespace, Bundle | null>> = {};\n for (const l of locales) out[l] = {};\n await Promise.all(\n locales.flatMap((l) =>\n namespaces.map(async (ns) => {\n out[l]![ns] = await fetchBundle(opts, l, ns);\n }),\n ),\n );\n return out;\n}\n","/**\n * Build-time translation resolver.\n *\n * v0.1 SCOPE (frozen — see CONTRACT.md): string resolution + `{var}`\n * interpolation + source-language fallback ONLY. Deliberately NO CLDR\n * plurals, NO surfaces, NO a11y accessors, NO BCP-47 variant→base\n * inheritance — those carry real i18n SEMANTICS owned by `@sonenta/i18n-core`\n * and arrive additively in 0.2.0. Keeping them out of v0.1 means there is no\n * naive semantics to break when the core swaps in underneath this same API.\n */\n\nimport { fetchAll, type Bundle } from \"./cdn\";\nimport {\n DEFAULT_NAMESPACE,\n type Locale,\n type Namespace,\n type SonentaI18n,\n type SonentaI18nOptions,\n type TFn,\n type Vars,\n} from \"./types\";\n\n/** Normalize `fallbackLng` (scalar | array | undefined) into a locale list. */\nfunction normalizeFallback(\n fallbackLng: SonentaI18nOptions[\"fallbackLng\"],\n defaultLocale: Locale,\n): Locale[] {\n if (fallbackLng == null) return [defaultLocale];\n return Array.isArray(fallbackLng) ? fallbackLng : [fallbackLng];\n}\n\n/** Split an i18next-style `\"ns:key\"` into `[namespace, key]`. */\nfunction splitKey(key: string, defaultNamespace: Namespace): [Namespace, string] {\n const i = key.indexOf(\":\");\n if (i === -1) return [defaultNamespace, key];\n return [key.slice(0, i), key.slice(i + 1)];\n}\n\n/** Walk a dotted path (`\"home.title\"`) through a bundle; `undefined` on miss. */\nfunction walk(bundle: Bundle | null | undefined, path: string): unknown {\n if (!bundle) return undefined;\n let cursor: unknown = bundle;\n for (const part of path.split(\".\")) {\n if (cursor && typeof cursor === \"object\" && part in cursor) {\n cursor = (cursor as Record<string, unknown>)[part];\n } else {\n return undefined;\n }\n }\n return cursor;\n}\n\n/** Substitute `{var}` placeholders; unknown placeholders are left intact. */\nfunction interpolate(template: string, vars?: Vars): string {\n if (!vars) return template;\n return template.replace(/\\{(\\w+)\\}/g, (_, name: string) =>\n name in vars ? String(vars[name]) : `{${name}}`,\n );\n}\n\n/**\n * Build a `t()` bound to `locale`, given the fetched data and resolution\n * order. Lookup: active locale's namespace dict → each fallback locale's same\n * namespace dict → the raw key (i18next-parity missing-key behaviour).\n */\nexport function createT(\n data: Record<Locale, Record<Namespace, Bundle | null>>,\n locale: Locale,\n fallbackChain: Locale[],\n defaultNamespace: Namespace,\n): TFn {\n // De-duped resolution order: active locale first, then configured\n // fallbacks (skipping the active one if it reappears).\n const order = [locale, ...fallbackChain.filter((l) => l !== locale)];\n return function t(key: string, vars?: Vars): string {\n const [ns, rest] = splitKey(key, defaultNamespace);\n for (const l of order) {\n const hit = walk(data[l]?.[ns], rest);\n if (typeof hit === \"string\") return interpolate(hit, vars);\n }\n // Missing everywhere → return the raw key (unchanged), i18next-style.\n return key;\n };\n}\n\n/**\n * Fetch every configured bundle at build time and return a resolved\n * {@link SonentaI18n} handle. Call once (top-level `await`) and reuse its\n * `getT(locale)` across pages.\n */\nexport async function createSonentaI18n(\n options: SonentaI18nOptions,\n): Promise<SonentaI18n> {\n if (!options.project) {\n throw new Error(\"[@sonenta/astro] `project` (UUID) is required.\");\n }\n if (!options.locales?.length) {\n throw new Error(\"[@sonenta/astro] `locales` must be a non-empty array.\");\n }\n const locales = options.locales;\n const defaultLocale = options.defaultLocale ?? locales[0]!;\n const namespaces =\n options.namespaces?.length ? options.namespaces : [DEFAULT_NAMESPACE];\n const defaultNamespace = namespaces[0]!;\n const fallbackChain = normalizeFallback(options.fallbackLng, defaultLocale);\n\n const data = await fetchAll(options, locales, namespaces);\n\n return {\n locales,\n defaultLocale,\n getT(locale: Locale): TFn {\n return createT(data, locale, fallbackChain, defaultNamespace);\n },\n getCatalog(locale: Locale, namespace?: Namespace): Bundle | null {\n return data[locale]?.[namespace ?? defaultNamespace] ?? null;\n },\n };\n}\n"],"mappings":";AA8GO,IAAM,mBAAmB;AAIzB,IAAM,kBAAkB;AAExB,IAAM,oBAAoB;;;AC9FjC,SAAS,YAAY,GAAmB;AACtC,SAAO,EAAE,QAAQ,QAAQ,EAAE;AAC7B;AAMO,SAAS,eAAe,MAAmD;AAChF,QAAM,MACJ,OAAO,YAAY,cAAc,QAAQ,KAAK,mBAAmB;AACnE,SAAO,YAAY,KAAK,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AI,CAAC,QAAQ,SAAS;AACpB,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AACA,MAAI,CAAC,QAAQ,SAAS,QAAQ;AAC5B,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AACA,QAAM,UAAU,QAAQ;AACxB,QAAM,gBAAgB,QAAQ,iBAAiB,QAAQ,CAAC;AACxD,QAAM,aACJ,QAAQ,YAAY,SAAS,QAAQ,aAAa,CAAC,iBAAiB;AACtE,QAAM,mBAAmB,WAAW,CAAC;AACrC,QAAM,gBAAgB,kBAAkB,QAAQ,aAAa,aAAa;AAE1E,QAAM,OAAO,MAAM,SAAS,SAAS,SAAS,UAAU;AAExD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,KAAK,QAAqB;AACxB,aAAO,QAAQ,MAAM,QAAQ,eAAe,gBAAgB;AAAA,IAC9D;AAAA,IACA,WAAW,QAAgB,WAAsC;AAC/D,aAAO,KAAK,MAAM,IAAI,aAAa,gBAAgB,KAAK;AAAA,IAC1D;AAAA,EACF;AACF;","names":[]}
package/dist/index.cjs ADDED
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ buildBundleUrl: () => buildBundleUrl,
24
+ createSonentaI18n: () => createSonentaI18n,
25
+ createT: () => createT,
26
+ default: () => index_default,
27
+ fetchAll: () => fetchAll,
28
+ fetchBundle: () => fetchBundle,
29
+ fetchNamespace: () => fetchNamespace,
30
+ resolveCdnBase: () => resolveCdnBase,
31
+ sonenta: () => sonenta
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/virtual.ts
36
+ var VIRTUAL_ID = "sonenta:i18n";
37
+ var RESOLVED_ID = "\0sonenta:i18n";
38
+ function serializableOptions(options) {
39
+ const { fetchImpl: _omit, ...rest } = options;
40
+ return rest;
41
+ }
42
+ function moduleSource(options) {
43
+ const opts = JSON.stringify(serializableOptions(options));
44
+ return [
45
+ `import { createSonentaI18n } from "@sonenta/astro/runtime";`,
46
+ `const __i18n = await createSonentaI18n(${opts});`,
47
+ `export const getT = (locale) => __i18n.getT(locale);`,
48
+ `export const locales = __i18n.locales;`,
49
+ `export const defaultLocale = __i18n.defaultLocale;`,
50
+ `export const getCatalog = (locale, ns) => __i18n.getCatalog(locale, ns);`,
51
+ `export default __i18n;`,
52
+ ``
53
+ ].join("\n");
54
+ }
55
+ function sonentaI18nVitePlugin(options) {
56
+ return {
57
+ name: "sonenta:astro-i18n",
58
+ enforce: "pre",
59
+ resolveId(id) {
60
+ if (id === VIRTUAL_ID) return RESOLVED_ID;
61
+ return null;
62
+ },
63
+ load(id) {
64
+ if (id === RESOLVED_ID) return moduleSource(options);
65
+ return null;
66
+ }
67
+ };
68
+ }
69
+
70
+ // src/integration.ts
71
+ var VIRTUAL_DTS = `declare module "sonenta:i18n" {
72
+ import type { SonentaI18n, TFn, Locale, Namespace } from "@sonenta/astro/runtime";
73
+ /** Translation function bound to \`locale\`. */
74
+ export const getT: (locale: Locale) => TFn;
75
+ /** Locales fetched and frozen into the build. */
76
+ export const locales: Locale[];
77
+ /** Resolved source/default locale. */
78
+ export const defaultLocale: Locale;
79
+ /** Raw fetched dictionary for a locale/namespace, or null when absent. */
80
+ export const getCatalog: (
81
+ locale: Locale,
82
+ namespace?: Namespace,
83
+ ) => Record<string, unknown> | null;
84
+ const i18n: SonentaI18n;
85
+ export default i18n;
86
+ }
87
+ `;
88
+ function sonenta(options) {
89
+ if (!options?.project) {
90
+ throw new Error("[@sonenta/astro] `project` (UUID) is required.");
91
+ }
92
+ if (!options.locales?.length) {
93
+ throw new Error("[@sonenta/astro] `locales` must be a non-empty array.");
94
+ }
95
+ return {
96
+ name: "@sonenta/astro",
97
+ hooks: {
98
+ "astro:config:setup": ({ updateConfig, logger }) => {
99
+ if (options.fetchImpl) {
100
+ logger.warn(
101
+ "`fetchImpl` is ignored by the integration; the build uses the global fetch. Use `@sonenta/astro/runtime` directly if you need a custom fetch."
102
+ );
103
+ }
104
+ updateConfig({
105
+ vite: { plugins: [sonentaI18nVitePlugin(options)] }
106
+ });
107
+ logger.info(
108
+ `i18n wired for project ${options.project} (${options.locales.length} locales, build-time CDN fetch).`
109
+ );
110
+ },
111
+ "astro:config:done": ({ injectTypes }) => {
112
+ injectTypes({ filename: "sonenta-i18n.d.ts", content: VIRTUAL_DTS });
113
+ }
114
+ }
115
+ };
116
+ }
117
+
118
+ // src/types.ts
119
+ var DEFAULT_CDN_BASE = "https://cdn.sonenta.com";
120
+ var DEFAULT_VERSION = "main";
121
+ var DEFAULT_NAMESPACE = "common";
122
+
123
+ // src/cdn.ts
124
+ function trimSlashes(s) {
125
+ return s.replace(/\/+$/, "");
126
+ }
127
+ function resolveCdnBase(opts) {
128
+ const env = typeof process !== "undefined" ? process.env?.SONENTA_CDN_BASE : void 0;
129
+ return trimSlashes(opts.cdnBase ?? env ?? DEFAULT_CDN_BASE);
130
+ }
131
+ function buildBundleUrl(opts, locale, namespace) {
132
+ const base = resolveCdnBase(opts);
133
+ const version = opts.version ?? DEFAULT_VERSION;
134
+ return `${base}/p/${opts.project}/${version}/latest/${locale}/${namespace}.json`;
135
+ }
136
+ async function fetchBundle(opts, locale, namespace) {
137
+ const url = buildBundleUrl(opts, locale, namespace);
138
+ const doFetch = opts.fetchImpl ?? fetch;
139
+ let res;
140
+ try {
141
+ res = await doFetch(url, { method: "GET" });
142
+ } catch (e) {
143
+ throw new Error(
144
+ `[@sonenta/astro] CDN fetch failed for ${locale}/${namespace}: ${e.message}`
145
+ );
146
+ }
147
+ if (!res.ok) {
148
+ if (res.status === 404) return null;
149
+ throw new Error(`[@sonenta/astro] CDN ${res.status} on ${url}`);
150
+ }
151
+ return await res.json();
152
+ }
153
+ async function fetchNamespace(opts, locales, namespace) {
154
+ const entries = await Promise.all(
155
+ locales.map(
156
+ async (l) => [l, await fetchBundle(opts, l, namespace)]
157
+ )
158
+ );
159
+ return Object.fromEntries(entries);
160
+ }
161
+ async function fetchAll(opts, locales, namespaces) {
162
+ const out = {};
163
+ for (const l of locales) out[l] = {};
164
+ await Promise.all(
165
+ locales.flatMap(
166
+ (l) => namespaces.map(async (ns) => {
167
+ out[l][ns] = await fetchBundle(opts, l, ns);
168
+ })
169
+ )
170
+ );
171
+ return out;
172
+ }
173
+
174
+ // src/resolver.ts
175
+ function normalizeFallback(fallbackLng, defaultLocale) {
176
+ if (fallbackLng == null) return [defaultLocale];
177
+ return Array.isArray(fallbackLng) ? fallbackLng : [fallbackLng];
178
+ }
179
+ function splitKey(key, defaultNamespace) {
180
+ const i = key.indexOf(":");
181
+ if (i === -1) return [defaultNamespace, key];
182
+ return [key.slice(0, i), key.slice(i + 1)];
183
+ }
184
+ function walk(bundle, path) {
185
+ if (!bundle) return void 0;
186
+ let cursor = bundle;
187
+ for (const part of path.split(".")) {
188
+ if (cursor && typeof cursor === "object" && part in cursor) {
189
+ cursor = cursor[part];
190
+ } else {
191
+ return void 0;
192
+ }
193
+ }
194
+ return cursor;
195
+ }
196
+ function interpolate(template, vars) {
197
+ if (!vars) return template;
198
+ return template.replace(
199
+ /\{(\w+)\}/g,
200
+ (_, name) => name in vars ? String(vars[name]) : `{${name}}`
201
+ );
202
+ }
203
+ function createT(data, locale, fallbackChain, defaultNamespace) {
204
+ const order = [locale, ...fallbackChain.filter((l) => l !== locale)];
205
+ return function t(key, vars) {
206
+ const [ns, rest] = splitKey(key, defaultNamespace);
207
+ for (const l of order) {
208
+ const hit = walk(data[l]?.[ns], rest);
209
+ if (typeof hit === "string") return interpolate(hit, vars);
210
+ }
211
+ return key;
212
+ };
213
+ }
214
+ async function createSonentaI18n(options) {
215
+ if (!options.project) {
216
+ throw new Error("[@sonenta/astro] `project` (UUID) is required.");
217
+ }
218
+ if (!options.locales?.length) {
219
+ throw new Error("[@sonenta/astro] `locales` must be a non-empty array.");
220
+ }
221
+ const locales = options.locales;
222
+ const defaultLocale = options.defaultLocale ?? locales[0];
223
+ const namespaces = options.namespaces?.length ? options.namespaces : [DEFAULT_NAMESPACE];
224
+ const defaultNamespace = namespaces[0];
225
+ const fallbackChain = normalizeFallback(options.fallbackLng, defaultLocale);
226
+ const data = await fetchAll(options, locales, namespaces);
227
+ return {
228
+ locales,
229
+ defaultLocale,
230
+ getT(locale) {
231
+ return createT(data, locale, fallbackChain, defaultNamespace);
232
+ },
233
+ getCatalog(locale, namespace) {
234
+ return data[locale]?.[namespace ?? defaultNamespace] ?? null;
235
+ }
236
+ };
237
+ }
238
+
239
+ // src/index.ts
240
+ var index_default = sonenta;
241
+ // Annotate the CommonJS export names for ESM import in node:
242
+ 0 && (module.exports = {
243
+ buildBundleUrl,
244
+ createSonentaI18n,
245
+ createT,
246
+ fetchAll,
247
+ fetchBundle,
248
+ fetchNamespace,
249
+ resolveCdnBase,
250
+ sonenta
251
+ });
252
+ //# sourceMappingURL=index.cjs.map