@i18n-micro/astro 1.0.1 → 1.2.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/dist/client/core.d.ts +23 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.js +17 -0
- package/dist/client/preact.d.ts +30 -0
- package/dist/client/preact.js +51 -0
- package/dist/client/react.d.ts +26 -0
- package/dist/client/react.js +51 -0
- package/dist/client/svelte.d.ts +28 -0
- package/dist/client/svelte.js +70 -0
- package/dist/client/vue.d.ts +27 -0
- package/dist/client/vue.js +1558 -0
- package/dist/composer.d.ts +9 -18
- package/dist/core-Bx9n-eFD.cjs +1 -0
- package/dist/core-D32Y48CN.js +42 -0
- package/dist/env.d.ts +2 -0
- package/dist/index.cjs +17 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.mjs +431 -297
- package/dist/integration.d.ts +5 -1
- package/dist/load-translations.d.ts +44 -0
- package/dist/middleware.d.ts +3 -1
- package/dist/router/adapter.d.ts +8 -0
- package/dist/router/types.d.ts +65 -0
- package/dist/utils.d.ts +17 -1
- package/package.json +57 -13
- package/src/client/core.ts +121 -0
- package/src/client/index.ts +15 -0
- package/src/client/preact.tsx +114 -0
- package/src/client/react.tsx +111 -0
- package/src/client/svelte.ts +124 -0
- package/src/client/vue.ts +128 -0
- package/src/components/i18n-link.astro +37 -4
- package/src/components/i18n-switcher.astro +209 -17
- package/src/components/index.ts +8 -2
- package/src/composer.ts +138 -0
- package/src/env.d.ts +20 -0
- package/src/index.ts +59 -0
- package/src/integration.ts +120 -0
- package/src/load-translations.ts +130 -0
- package/src/middleware.ts +203 -0
- package/src/router/adapter.ts +184 -0
- package/src/router/types.ts +66 -0
- package/src/routing.ts +108 -0
- package/src/utils.ts +401 -0
- package/dist/bridge/astro-bridge.d.ts +0 -13
- package/dist/index-C-UMdqSG.cjs +0 -1
- package/dist/index-CVhedN6W.js +0 -146
- package/dist/toolbar-app.d.ts +0 -2
package/dist/composer.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Translations,
|
|
1
|
+
import { BaseI18n, TranslationStorage } from '@i18n-micro/core';
|
|
2
|
+
import { Translations, PluralFunc } from '@i18n-micro/types';
|
|
3
3
|
export interface AstroI18nOptions {
|
|
4
4
|
locale: string;
|
|
5
5
|
fallbackLocale?: string;
|
|
@@ -7,35 +7,26 @@ export interface AstroI18nOptions {
|
|
|
7
7
|
plural?: PluralFunc;
|
|
8
8
|
missingWarn?: boolean;
|
|
9
9
|
missingHandler?: (locale: string, key: string, routeName: string) => void;
|
|
10
|
-
|
|
10
|
+
_storage?: TranslationStorage;
|
|
11
11
|
}
|
|
12
|
-
export declare class AstroI18n {
|
|
12
|
+
export declare class AstroI18n extends BaseI18n {
|
|
13
13
|
private _locale;
|
|
14
14
|
private _fallbackLocale;
|
|
15
15
|
private _currentRoute;
|
|
16
|
-
|
|
17
|
-
private formatter;
|
|
18
|
-
private pluralFunc;
|
|
19
|
-
private missingWarn;
|
|
20
|
-
private missingHandler?;
|
|
21
|
-
readonly cache: TranslationCache;
|
|
16
|
+
readonly storage: TranslationStorage;
|
|
22
17
|
private initialMessages;
|
|
23
18
|
constructor(options: AstroI18nOptions);
|
|
19
|
+
private cloneStorage;
|
|
24
20
|
clone(newLocale?: string): AstroI18n;
|
|
25
21
|
get locale(): string;
|
|
26
22
|
set locale(val: string);
|
|
27
23
|
get fallbackLocale(): string;
|
|
28
24
|
set fallbackLocale(val: string);
|
|
29
|
-
get currentRoute(): string;
|
|
30
25
|
setRoute(routeName: string): void;
|
|
26
|
+
getLocale(): string;
|
|
27
|
+
getFallbackLocale(): string;
|
|
31
28
|
getRoute(): string;
|
|
32
|
-
|
|
33
|
-
ts(key: TranslationKey, params?: Params, defaultValue?: string, routeName?: string): string;
|
|
34
|
-
tc(key: TranslationKey, count: number | Params, defaultValue?: string): string;
|
|
35
|
-
tn(value: number, options?: Intl.NumberFormatOptions): string;
|
|
36
|
-
td(value: Date | number | string, options?: Intl.DateTimeFormatOptions): string;
|
|
37
|
-
tdr(value: Date | number | string, options?: Intl.RelativeTimeFormatOptions): string;
|
|
38
|
-
has(key: TranslationKey, _routeName?: string): boolean;
|
|
29
|
+
getRouteTranslations(locale: string, routeName: string): Translations | null;
|
|
39
30
|
addTranslations(locale: string, translations: Translations, merge?: boolean): void;
|
|
40
31
|
addRouteTranslations(locale: string, routeName: string, translations: Translations, merge?: boolean): void;
|
|
41
32
|
mergeTranslations(locale: string, routeName: string, translations: Translations): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const s=require("@i18n-micro/core");function u(n,t){if(n===null||typeof t!="string")return null;let o=n;if(n[t])o=n[t];else{const l=t.toString().split(".");for(const e of l)if(o&&typeof o=="object"&&o!==null&&e in o)o=o[e];else return null}return o??null}function a(n,t,o,l,e){if(!t)return l||t||"";const i=e||n.currentRoute;let r=null;return n.translations[i]&&(r=u(n.translations[i],t)),!r&&n.translations.general&&(r=u(n.translations.general,t)),r||(r=l===void 0?t:l||t),typeof r=="string"&&o?s.interpolate(r,o):r}function f(n,t,o){const l=o||n.currentRoute,e=n.translations[l],i=n.translations.general;if(e){const r=u(e,t);if(r!==null&&typeof r!="object")return!0}if(i){const r=u(i,t);if(r!==null&&typeof r!="object")return!0}return!1}exports.hasTranslation=f;exports.translate=a;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { interpolate as s } from "@i18n-micro/core";
|
|
2
|
+
function u(n, t) {
|
|
3
|
+
if (n === null || typeof t != "string")
|
|
4
|
+
return null;
|
|
5
|
+
let o = n;
|
|
6
|
+
if (n[t])
|
|
7
|
+
o = n[t];
|
|
8
|
+
else {
|
|
9
|
+
const l = t.toString().split(".");
|
|
10
|
+
for (const i of l)
|
|
11
|
+
if (o && typeof o == "object" && o !== null && i in o)
|
|
12
|
+
o = o[i];
|
|
13
|
+
else
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
return o ?? null;
|
|
17
|
+
}
|
|
18
|
+
function a(n, t, o, l, i) {
|
|
19
|
+
if (!t)
|
|
20
|
+
return l || t || "";
|
|
21
|
+
const e = i || n.currentRoute;
|
|
22
|
+
let r = null;
|
|
23
|
+
return n.translations[e] && (r = u(n.translations[e], t)), !r && n.translations.general && (r = u(n.translations.general, t)), r || (r = l === void 0 ? t : l || t), typeof r == "string" && o ? s(r, o) : r;
|
|
24
|
+
}
|
|
25
|
+
function c(n, t, o) {
|
|
26
|
+
const l = o || n.currentRoute, i = n.translations[l], e = n.translations.general;
|
|
27
|
+
if (i) {
|
|
28
|
+
const r = u(i, t);
|
|
29
|
+
if (r !== null && typeof r != "object")
|
|
30
|
+
return !0;
|
|
31
|
+
}
|
|
32
|
+
if (e) {
|
|
33
|
+
const r = u(e, t);
|
|
34
|
+
if (r !== null && typeof r != "object")
|
|
35
|
+
return !0;
|
|
36
|
+
}
|
|
37
|
+
return !1;
|
|
38
|
+
}
|
|
39
|
+
export {
|
|
40
|
+
c as h,
|
|
41
|
+
a as t
|
|
42
|
+
};
|
package/dist/env.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AstroI18n } from './composer';
|
|
2
2
|
import { Locale } from '@i18n-micro/types';
|
|
3
|
+
import { I18nRoutingStrategy } from './router/types';
|
|
3
4
|
declare global {
|
|
4
5
|
namespace App {
|
|
5
6
|
interface Locals {
|
|
@@ -8,6 +9,7 @@ declare global {
|
|
|
8
9
|
defaultLocale: string
|
|
9
10
|
locales: Locale[]
|
|
10
11
|
currentUrl: URL
|
|
12
|
+
routingStrategy?: I18nRoutingStrategy
|
|
11
13
|
}
|
|
12
14
|
}
|
|
13
15
|
}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1,17 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@i18n-micro/core"),D=require("node:fs"),R=require("node:path");function $(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const b=$(D),y=$(R);class S{constructor(e){if(this.formatter=new L.FormatService,this.initialMessages={},this._locale=e.locale,this._fallbackLocale=e.fallbackLocale||e.locale,this._currentRoute="general",this.pluralFunc=e.plural||L.defaultPlural,this.missingWarn=e.missingWarn??!1,this.missingHandler=e.missingHandler,this.cache=e._cache||{generalLocaleCache:{},routeLocaleCache:{},dynamicTranslationsCaches:[],serverTranslationCache:{}},this.helper=L.useTranslationHelper(this.cache),e.messages){this.initialMessages={...e.messages};for(const[t,r]of Object.entries(e.messages))this.helper.loadTranslations(t,r)}}clone(e){return new S({locale:e||this._locale,fallbackLocale:this._fallbackLocale,plural:this.pluralFunc,missingWarn:this.missingWarn,missingHandler:this.missingHandler,_cache:this.cache})}get locale(){return this._locale}set locale(e){this._locale=e}get fallbackLocale(){return this._fallbackLocale}set fallbackLocale(e){this._fallbackLocale=e}get currentRoute(){return this._currentRoute}setRoute(e){this._currentRoute=e}getRoute(){return this._currentRoute}t(e,t,r,o){if(!e)return"";const l=o||this._currentRoute,a=this._locale;let n=this.helper.getTranslation(a,l,e);return!n&&a!==this._fallbackLocale&&(n=this.helper.getTranslation(this._fallbackLocale,l,e)),n||(this.missingHandler?this.missingHandler(a,e,l):this.missingWarn&&console.warn(`[i18n] Translation key '${e}' not found for locale '${a}' (route: '${l}').`),n=r===void 0?e:r||e),typeof n=="string"&&t?L.interpolate(n,t):n||e}ts(e,t,r,o){const l=this.t(e,t,r,o);return(l==null?void 0:l.toString())??r??e}tc(e,t,r){const{count:o,...l}=typeof t=="number"?{count:t}:t;if(o===void 0)return r??e;const a=(i,c,u)=>{const h=this.t(i,c,u);return typeof h=="string"?h:""};return this.pluralFunc(e,Number.parseInt(o.toString()),l,this._locale,a)??r??e}tn(e,t){return this.formatter.formatNumber(e,this._locale,t)}td(e,t){return this.formatter.formatDate(e,this._locale,t)}tdr(e,t){return this.formatter.formatRelativeTime(e,this._locale,t)}has(e,t){return this.helper.hasTranslation(this._locale,e)}addTranslations(e,t,r=!0){r?this.helper.mergeGlobalTranslation(e,t,!0):this.helper.loadTranslations(e,t)}addRouteTranslations(e,t,r,o=!0){o?this.helper.mergeTranslation(e,t,r,!0):this.helper.loadPageTranslations(e,t,r)}mergeTranslations(e,t,r){this.helper.mergeTranslation(e,t,r,!0)}mergeGlobalTranslations(e,t){this.helper.mergeGlobalTranslation(e,t,!0)}clearCache(){const e={...this.initialMessages};if(this.helper.clearCache(),Object.keys(e).length>0)for(const[t,r]of Object.entries(e))this.helper.loadTranslations(t,r)}}const F='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';function C(s){const{locale:e,fallbackLocale:t,translationDir:r}=s;return{name:"@i18n-micro/astro",hooks:{"astro:config:setup":async({addDevToolbarApp:o,command:l,injectTypes:a})=>{if(a&&a({filename:"i18n-micro-env.d.ts",content:'/// <reference types="@i18n-micro/astro/env" />'}),r)try{const{I18n:n}=await Promise.resolve().then(()=>require("./index-C-UMdqSG.cjs"));await new n({locale:e,fallbackLocale:t||e,translationDir:r,disablePageLocales:s.disablePageLocales??!1}).loadTranslations()}catch(n){console.warn("[i18n] Could not load translations from directory:",n)}l==="dev"&&o({id:"i18n-micro",name:"i18n Micro",icon:F,entrypoint:"@i18n-micro/astro/toolbar-app"})},"astro:server:setup":async({toolbar:o,logger:l})=>{if(!o)return;const a=process.cwd(),n=y.join(a,r||"src/locales"),i=()=>{const c={};if(!b.existsSync(n))return l.warn(`[i18n] Locales directory does not exist: ${n}`),c;const u=h=>{b.readdirSync(h).forEach(d=>{const f=y.join(h,d);if(d.startsWith("."))return;if(b.lstatSync(f).isDirectory())u(f);else if(d.endsWith(".json"))try{const g=y.relative(n,f),m=JSON.parse(b.readFileSync(f,"utf-8"));m&&typeof m=="object"&&!Array.isArray(m)?c[g]=m:l.warn(`[i18n] Invalid content format in ${f}, expected object`)}catch(g){l.warn(`Error parsing locale file ${f}: ${g instanceof Error?g.message:String(g)}`)}})};return u(n),c};o.on("i18n:get-locales",async()=>{try{const c=i(),u=Object.keys(c);l.info(`[i18n] Sending locales data: ${u.length} files`),l.info(`[i18n] Locales keys: ${u.join(", ")}`),u.length>0&&u[0]&&l.info(`[i18n] Sample file content keys: ${Object.keys(c[u[0]]).slice(0,5).join(", ")}`),o.send("i18n:locales-data",c)}catch(c){l.error(`Error in i18n:get-locales handler: ${c}`),o.send("i18n:locales-data",{})}}),o.on("i18n:get-configs",()=>{o.send("i18n:configs-data",{defaultLocale:e,fallbackLocale:t||e,locales:s.locales||[],translationDir:r||"src/locales",...s})}),o.on("i18n:save",async c=>{try{const u=y.join(n,c.file);if(!u.startsWith(n))throw new Error("Access denied: Cannot write outside locales directory");b.existsSync(u)?(b.writeFileSync(u,JSON.stringify(c.content,null,2),"utf-8"),o.send("i18n:save-result",{success:!0}),o.send("i18n:updated",i())):o.send("i18n:save-result",{success:!1,error:`File not found: ${c.file}`})}catch(u){l.error(`Error saving translation: ${u instanceof Error?u.message:String(u)}`),o.send("i18n:save-result",{success:!1,error:String(u)})}})}}}}function M(s){return new S(s)}function P(s,e=[]){const t=s.replace(/^\//,"").replace(/\/$/,"");if(!t)return"index";const r=t.split("/").filter(Boolean),o=r[0];return o&&e.includes(o)&&r.shift(),r.length===0?"index":r.join("-")}function v(s,e="en",t=[]){const o=s.split("/").filter(Boolean)[0];return o&&t.includes(o)?o:e}function w(s,e,t=[],r){const o=s.split("/").filter(Boolean),l=o[0];return l&&t.includes(l)&&o.shift(),(e!==r||r===void 0)&&o.unshift(e),`/${o.join("/")}`}function k(s,e,t=[],r){const l=(s.replace(/^\//,"").replace(/\/$/,"")||"").split("/").filter(Boolean),a=l[0];return a&&t.includes(a)&&l.shift(),(e!==r||r===void 0)&&l.unshift(e),`/${l.join("/")}`}function N(s,e=[]){const t=s.split("/").filter(Boolean),r=t[0];return r&&e.includes(r)&&t.shift(),`/${t.join("/")}`}function B(s){const{i18n:e,defaultLocale:t,locales:r,localeObjects:o,autoDetect:l=!0,redirectToDefault:a=!1}=s;return async(n,i)=>{if(n.locals.locale&&n.locals.i18n)return i();const c=n.url,u=c.pathname,d=u.split("/").filter(Boolean)[0],f=d!==void 0&&r.includes(d);let p;f&&d?p=d:p=t;const g=e.clone(p),m=P(u,r);return g.setRoute(m),n.locals.i18n=g,n.locals.locale=p,n.locals.defaultLocale=t,n.locals.locales=o||r.map(O=>({code:O})),n.locals.currentUrl=c,i()}}function q(s){var r;const e=[],t=s.split(",");for(const o of t){const[l,a="1.0"]=o.trim().split(";q=");if(Number.parseFloat(a)>0&&l){const i=(r=l.split("-")[0])==null?void 0:r.toLowerCase();i&&(e.push(i),l!==i&&e.push(l.toLowerCase()))}}return e}function A(s,e,t,r,o,l="i18n-locale"){var n;let a=v(s,r,o);if(a===r&&e.get(l)){const i=(n=e.get(l))==null?void 0:n.value;i&&o.includes(i)&&(a=i)}if(a===r)try{const i=t.get("accept-language");if(i){const c=q(i);for(const u of c)if(o.includes(u)){a=u;break}}}catch{}return a}function I(s){const e=s.locals.i18n;if(!e)throw new Error("i18n instance not found. Make sure i18n middleware is configured.");return e}function T(s){return s.locals.locale||"en"}function _(s){return s.locals.defaultLocale||"en"}function j(s){return s.locals.locales||[]}function E(s){const e=I(s),t=T(s),r=_(s),o=j(s),l=o.map(a=>a.code);return{locale:t,defaultLocale:r,locales:o,t:(a,n,i,c)=>e.t(a,n,i,c),ts:(a,n,i,c)=>e.ts(a,n,i,c),tc:(a,n,i)=>e.tc(a,n,i),tn:(a,n)=>e.tn(a,n),td:(a,n)=>e.td(a,n),tdr:(a,n)=>e.tdr(a,n),has:(a,n)=>e.has(a,n),getRoute:()=>e.getRoute(),getRouteName:a=>P(a||s.url.pathname,l),getLocaleFromPath:a=>v(a||s.url.pathname,r,l),switchLocalePath:a=>w(s.url.pathname,a,l,r),localizePath:(a,n)=>k(a,n||t,l,r),getI18n:()=>e,getBasePath:a=>{const c=(a||s.url).pathname.split("/").filter(Boolean),u=c[0];return u&&l.includes(u)&&c.shift(),c.length>0?`/${c.join("/")}`:"/"},addTranslations:(a,n,i=!0)=>{e.addTranslations(a,n,i)},addRouteTranslations:(a,n,i,c=!0)=>{e.addRouteTranslations(a,n,i,c)},mergeTranslations:(a,n,i)=>{e.mergeTranslations(a,n,i)},mergeGlobalTranslations:(a,n)=>{e.mergeGlobalTranslations(a,n)},clearCache:()=>{e.clearCache()}}}function H(s,e={}){const{baseUrl:t="/",addDirAttribute:r=!0,addSeoAttributes:o=!0}=e,l=T(s),a=_(s),n=j(s),i=n.find(f=>f.code===l);if(!i)return{htmlAttrs:{},link:[],meta:[]};const c=i.iso||l,u=i.dir||"auto",h={htmlAttrs:{lang:c,...r?{dir:u}:{}},link:[],meta:[]};if(!o)return h;const d=`${t}${s.url.pathname}`;h.link.push({rel:"canonical",href:d});for(const f of n){if(f.code===l)continue;const p=w(s.url.pathname,f.code,n.map(m=>m.code),a),g=`${t}${p}`;h.link.push({rel:"alternate",href:g,hreflang:f.code}),f.iso&&f.iso!==f.code&&h.link.push({rel:"alternate",href:g,hreflang:f.iso})}h.meta.push({property:"og:locale",content:c}),h.meta.push({property:"og:url",content:d});for(const f of n)f.code!==l&&h.meta.push({property:"og:locale:alternate",content:f.iso||f.code});return h}Object.defineProperty(exports,"FormatService",{enumerable:!0,get:()=>L.FormatService});Object.defineProperty(exports,"defaultPlural",{enumerable:!0,get:()=>L.defaultPlural});Object.defineProperty(exports,"interpolate",{enumerable:!0,get:()=>L.interpolate});exports.AstroI18n=S;exports.createI18n=M;exports.createI18nMiddleware=B;exports.detectLocale=A;exports.getDefaultLocale=_;exports.getI18n=I;exports.getLocale=T;exports.getLocaleFromPath=v;exports.getLocales=j;exports.getRouteName=P;exports.i18nIntegration=C;exports.localizePath=k;exports.removeLocaleFromPath=N;exports.switchLocalePath=w;exports.useI18n=E;exports.useLocaleHead=H;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("@i18n-micro/core"),b=require("node:fs"),I=require("node:path");class j extends T.BaseI18n{constructor(e){const s=e._storage||{translations:new Map};if(super({storage:s,plural:e.plural,missingWarn:e.missingWarn,missingHandler:e.missingHandler}),this.initialMessages={},this.storage=s,this._locale=e.locale,this._fallbackLocale=e.fallbackLocale||e.locale,this._currentRoute="general",e.messages){this.initialMessages={...e.messages};for(const[a,i]of Object.entries(e.messages))this.helper.loadTranslations(a,i)}}cloneStorage(e){const s=new Map;for(const[a,i]of e.translations)s.set(a,{...i});return{translations:s}}clone(e){const s=this.cloneStorage(this.storage);return new j({locale:e||this._locale,fallbackLocale:this._fallbackLocale,plural:this.pluralFunc,missingWarn:this.missingWarn,missingHandler:this.missingHandler,_storage:s})}get locale(){return this._locale}set locale(e){this._locale=e}get fallbackLocale(){return this._fallbackLocale}set fallbackLocale(e){this._fallbackLocale=e}setRoute(e){this._currentRoute=e}getLocale(){return this._locale}getFallbackLocale(){return this._fallbackLocale}getRoute(){return this._currentRoute}getRouteTranslations(e,s){const a=`${e}:${s}`;return this.storage.translations.get(a)??null}addTranslations(e,s,a=!0){super.loadTranslationsCore(e,s,a)}addRouteTranslations(e,s,a,i=!0){super.loadRouteTranslationsCore(e,s,a,i)}mergeTranslations(e,s,a){this.helper.mergeTranslation(e,s,a,!0)}mergeGlobalTranslations(e,s){this.helper.mergeGlobalTranslation(e,s,!0)}clearCache(){const e={...this.initialMessages};if(super.clearCache(),Object.keys(e).length>0)for(const[s,a]of Object.entries(e))this.helper.loadTranslations(s,a)}}let $=null;function D(){return $}function C(n){const{locale:e,fallbackLocale:s,translationDir:a,routingStrategy:i}=n;return $=i||null,{name:"@i18n-micro/astro",hooks:{"astro:config:setup":c=>{const{updateConfig:f}=c,t="virtual:i18n-micro/config",l="\0"+t,r={defaultLocale:e,fallbackLocale:s||e,locales:n.locales||[],localeCodes:(n.locales||[]).map(o=>o.code),translationDir:a||null,autoDetect:n.autoDetect??!0,redirectToDefault:n.redirectToDefault??!1,localeCookie:n.localeCookie===null?null:n.localeCookie||"i18n-locale",missingWarn:n.missingWarn??!1};f({vite:{plugins:[{name:"vite-plugin-i18n-micro-config",resolveId(o){if(o===t)return l},load(o){if(o===l)return`export const config = ${JSON.stringify(r)}`}}]}})},"astro:config:done":c=>{const{injectTypes:f}=c;f({filename:"i18n-micro-env.d.ts",content:`
|
|
2
|
+
/// <reference types="@i18n-micro/astro/env" />
|
|
3
|
+
|
|
4
|
+
declare module 'virtual:i18n-micro/config' {
|
|
5
|
+
export const config: {
|
|
6
|
+
defaultLocale: string;
|
|
7
|
+
fallbackLocale: string;
|
|
8
|
+
locales: import('@i18n-micro/types').Locale[];
|
|
9
|
+
localeCodes: string[];
|
|
10
|
+
translationDir: string | null;
|
|
11
|
+
autoDetect: boolean;
|
|
12
|
+
redirectToDefault: boolean;
|
|
13
|
+
localeCookie: string | null;
|
|
14
|
+
missingWarn: boolean | null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
`})}}}}function N(n){return new j(n)}function q(n){const{i18n:e,defaultLocale:s,locales:a,localeObjects:i,autoDetect:c=!0,redirectToDefault:f=!1,routingStrategy:t}=n,l=t||D();return async(r,o)=>{if(r.locals.locale&&r.locals.i18n)return o();const u=r.url,h=u.pathname;if(!l){const S=e.clone(s),O=h==="/"||h===""?"index":h.split("/").filter(Boolean).join("-");return S.setRoute(O),r.locals.i18n=S,r.locals.locale=s,r.locals.defaultLocale=s,r.locals.locales=i||a.map(_=>({code:_})),r.locals.currentUrl=u,o()}const d={...l,getCurrentPath:()=>h,getRoute:()=>({fullPath:u.pathname+u.search,query:Object.fromEntries(u.searchParams)})},g=h.split("/").filter(Boolean)[0],p=g!==void 0&&a.includes(g);let P;p&&g?P=g:d.getLocaleFromPath?P=d.getLocaleFromPath(h,s,a):P=s;const L=e.clone(P),y=d.getRouteName?d.getRouteName(h,a):"general";return L.setRoute(y),r.locals.i18n=L,r.locals.locale=P,r.locals.defaultLocale=s,r.locals.locales=i||a.map(S=>({code:S})),r.locals.currentUrl=u,r.locals.routingStrategy=d,o()}}function M(n){const e=[],s=n.split(",");for(const a of s){const[i,c="1.0"]=a.trim().split(";q=");if(Number.parseFloat(c)>0&&i){const t=i.split("-")[0]?.toLowerCase();t&&(e.push(t),i!==t&&e.push(i.toLowerCase()))}}return e}function A(n,e,s,a,i,c="i18n-locale"){const f=D();let t=a;if(f?.getLocaleFromPath)t=f.getLocaleFromPath(n,a,i);else{const r=n.split("/").filter(Boolean)[0];r&&i.includes(r)&&(t=r)}if(c!==null&&t===a&&e.get(c)){const l=e.get(c)?.value;l&&i.includes(l)&&(t=l)}if(t===a)try{const l=s.get("accept-language");if(l){const r=M(l);for(const o of r)if(i.includes(o)){t=o;break}}}catch{}return t}function v(n){const e=n.locals.i18n;if(!e)throw new Error("i18n instance not found. Make sure i18n middleware is configured.");return e}function w(n){return n.locals.locale||"en"}function R(n){return n.locals.defaultLocale||"en"}function k(n){return n.locals.locales||[]}function F(n){return n.locals.routingStrategy||null}function W(n){const e=v(n),s=w(n),a=R(n),i=k(n),c=i.map(t=>t.code),f=F(n);return{locale:s,defaultLocale:a,locales:i,t:(t,l,r,o)=>e.t(t,l,r,o),ts:(t,l,r,o)=>e.ts(t,l,r,o),tc:(t,l,r)=>e.tc(t,l,r),tn:(t,l)=>e.tn(t,l),td:(t,l)=>e.td(t,l),tdr:(t,l)=>e.tdr(t,l),has:(t,l)=>e.has(t,l),getRoute:()=>e.getRoute(),getRouteName:t=>{const l=t||n.url.pathname;if(f?.getRouteName)return f.getRouteName(l,c);const r=l.replace(/^\//,"").replace(/\/$/,"");if(!r)return"index";const o=r.split("/").filter(Boolean),u=o[0];return u&&c.includes(u)&&o.shift(),o.length===0?"index":o.join("-")},getLocaleFromPath:t=>{const l=t||n.url.pathname;if(f?.getLocaleFromPath)return f.getLocaleFromPath(l,a,c);const o=l.split("/").filter(Boolean)[0];return o&&c.includes(o)?o:a},switchLocalePath:t=>{if(f?.switchLocalePath)return f.switchLocalePath(n.url.pathname,t,c,a);const l=n.url.pathname.split("/").filter(Boolean),r=l[0];return r&&c.includes(r)&&l.shift(),t!==a&&l.unshift(t),`/${l.join("/")}`},localizePath:(t,l)=>{if(f?.localizePath)return f.localizePath(t,l||s,c,a);const o=(t.replace(/^\//,"").replace(/\/$/,"")||"").split("/").filter(Boolean),u=o[0];return u&&c.includes(u)&&o.shift(),l&&l!==a&&o.unshift(l),`/${o.join("/")}`},getI18n:()=>e,getBasePath:t=>{const o=(t||n.url).pathname.split("/").filter(Boolean),u=o[0];return u&&c.includes(u)&&o.shift(),o.length>0?`/${o.join("/")}`:"/"},addTranslations:(t,l,r=!0)=>{e.addTranslations(t,l,r)},addRouteTranslations:(t,l,r,o=!0)=>{e.addRouteTranslations(t,l,r,o)},mergeTranslations:(t,l,r)=>{e.mergeTranslations(t,l,r)},mergeGlobalTranslations:(t,l)=>{e.mergeGlobalTranslations(t,l)},clearCache:()=>{e.clearCache()}}}function z(n,e={}){const{baseUrl:s="/",addDirAttribute:a=!0,addSeoAttributes:i=!0}=e,c=w(n),f=R(n),t=k(n),l=t.find(g=>g.code===c);if(!l)return{htmlAttrs:{},link:[],meta:[]};const r=l.iso||c,o=l.dir||"auto",u={htmlAttrs:{lang:r,...a?{dir:o}:{}},link:[],meta:[]};if(!i)return u;const h=`${s}${n.url.pathname}`;u.link.push({rel:"canonical",href:h});const d=F(n),m=t.map(g=>g.code);for(const g of t){if(g.code===c)continue;let p=n.url.pathname;if(d?.switchLocalePath)p=d.switchLocalePath(n.url.pathname,g.code,m,f);else{const L=n.url.pathname.split("/").filter(Boolean),y=L[0];y&&m.includes(y)&&L.shift(),g.code!==f&&L.unshift(g.code),p=`/${L.join("/")}`}const P=`${s}${p}`;u.link.push({rel:"alternate",href:P,hreflang:g.code}),g.iso&&g.iso!==g.code&&u.link.push({rel:"alternate",href:P,hreflang:g.iso})}u.meta.push({property:"og:locale",content:r}),u.meta.push({property:"og:url",content:h});for(const g of t)g.code!==c&&u.meta.push({property:"og:locale:alternate",content:g.iso||g.code});return u}function H(n,e,s){const a=e.split(".");let i=n;for(let f=0;f<a.length-1;f++){const t=a[f];i[t]||(i[t]={}),i=i[t]}const c=a[a.length-1];c!==void 0&&(i[c]=s)}function G(n,e){const s=v(n),a=w(n),i=R(n),c=s.getRoute(),f={};if(e&&e.length>0){const t={};for(const l of e){const r=s.t(l,void 0,void 0,c);r!=null&&r!==l&&H(t,l,r)}Object.keys(t).length>0&&(f[c]=t)}else{const t=s.getRouteTranslations(a,c);t&&(f[c]=t)}return{locale:a,fallbackLocale:i,currentRoute:c,translations:f}}function U(n,e,s){const a=n.map(o=>o.code),i=(o,u=[])=>{const h=o.replace(/^\//,"").replace(/\/$/,"");if(!h)return"index";const d=h.split("/").filter(Boolean),m=d[0];return m&&u.includes(m)&&d.shift(),d.length===0?"index":d.join("-")},c=(o,u="en",h=[])=>{const m=o.split("/").filter(Boolean)[0];return m&&h.includes(m)?m:u},f=(o,u,h=[],d)=>{const m=o.split("/").filter(Boolean),g=m[0];return g&&h.includes(g)&&m.shift(),(u!==d||d===void 0)&&m.unshift(u),`/${m.join("/")}`},t=(o,u,h=[],d)=>{const g=(o.replace(/^\//,"").replace(/\/$/,"")||"").split("/").filter(Boolean),p=g[0];return p&&h.includes(p)&&g.shift(),(u!==d||d===void 0)&&g.unshift(u),`/${g.join("/")}`};return{getCurrentPath:()=>s?s().pathname:typeof window<"u"?window.location.pathname:"/",getRouteName:i,getLocaleFromPath:c,switchLocalePath:f,localizePath:t,removeLocaleFromPath:(o,u=[])=>{const h=o.split("/").filter(Boolean),d=h[0];return d&&u.includes(d)&&h.shift(),`/${h.join("/")}`},resolvePath:(o,u)=>{const h=typeof o=="string"?o:o.path||"/";return t(h,u,a,e)},getRoute:()=>{if(s){const o=s();return{fullPath:o.pathname+o.search,query:Object.fromEntries(o.searchParams)}}if(typeof window<"u"){const o=new URL(window.location.href);return{fullPath:o.pathname+o.search,query:Object.fromEntries(o.searchParams)}}return{fullPath:"/",query:{}}},push:o=>{typeof window<"u"&&(window.location.href=o.path)},replace:o=>{typeof window<"u"&&window.location.replace(o.path)}}}function E(n,e=[]){const s=n.replace(/^\//,"").replace(/\/$/,"");if(!s)return"index";const a=s.split("/").filter(Boolean),i=a[0];return i&&e.includes(i)&&a.shift(),a.length===0?"index":a.join("-")}function J(n,e="en",s=[]){const i=n.split("/").filter(Boolean)[0];return i&&s.includes(i)?i:e}function V(n,e,s=[],a){const i=n.split("/").filter(Boolean),c=i[0];return c&&s.includes(c)&&i.shift(),(e!==a||a===void 0)&&i.unshift(e),`/${i.join("/")}`}function K(n,e,s=[],a){const c=(n.replace(/^\//,"").replace(/\/$/,"")||"").split("/").filter(Boolean),f=c[0];return f&&s.includes(f)&&c.shift(),(e!==a||a===void 0)&&c.unshift(e),`/${c.join("/")}`}function Q(n,e=[]){const s=n.split("/").filter(Boolean),a=s[0];return a&&e.includes(a)&&s.shift(),`/${s.join("/")}`}function B(n){const{translationDir:e,rootDir:s=process.cwd(),disablePageLocales:a=!1}=n,i=I.resolve(s,e);if(!b.existsSync(i))return console.warn(`[i18n] Translation directory not found: ${i}`),{general:{},routes:{}};const c={},f={},t=(l,r="")=>{if(!b.existsSync(l))return;const o=b.readdirSync(l);for(const u of o){const h=I.join(l,u);if(b.statSync(h).isDirectory())u==="pages"&&!a?t(h,""):r||a?t(h,r):t(h,u);else if(u.endsWith(".json")){const m=u.replace(".json","");try{const g=b.readFileSync(h,"utf-8"),p=JSON.parse(g);r&&!a?(f[r]||(f[r]={}),f[r][m]=p):c[m]=p}catch(g){console.error(`[i18n] Failed to load translation file: ${h}`,g)}}}};return t(i),{general:c,routes:f}}function X(n,e){const{general:s,routes:a}=B(e);for(const[i,c]of Object.entries(s))n.addTranslations(i,c,!1);for(const[i,c]of Object.entries(a))for(const[f,t]of Object.entries(c))n.addRouteTranslations(f,i,t,!1)}Object.defineProperty(exports,"FormatService",{enumerable:!0,get:()=>T.FormatService});Object.defineProperty(exports,"defaultPlural",{enumerable:!0,get:()=>T.defaultPlural});Object.defineProperty(exports,"interpolate",{enumerable:!0,get:()=>T.interpolate});exports.AstroI18n=j;exports.createAstroRouterAdapter=U;exports.createI18n=N;exports.createI18nMiddleware=q;exports.detectLocale=A;exports.getDefaultLocale=R;exports.getI18n=v;exports.getI18nProps=G;exports.getLocale=w;exports.getLocaleFromPath=J;exports.getLocales=k;exports.getRouteName=E;exports.i18nIntegration=C;exports.loadTranslationsFromDir=B;exports.loadTranslationsIntoI18n=X;exports.localizePath=K;exports.removeLocaleFromPath=Q;exports.switchLocalePath=V;exports.useI18n=W;exports.useLocaleHead=z;
|
package/dist/index.d.ts
CHANGED
|
@@ -2,9 +2,13 @@ export { i18nIntegration, createI18n } from './integration';
|
|
|
2
2
|
export { AstroI18n, type AstroI18nOptions } from './composer';
|
|
3
3
|
export { createI18nMiddleware, detectLocale } from './middleware';
|
|
4
4
|
export type { I18nMiddlewareOptions } from './middleware';
|
|
5
|
-
export { useI18n, getI18n, getLocale, getDefaultLocale, getLocales, useLocaleHead, } from './utils';
|
|
6
|
-
export type { LocaleHeadOptions, LocaleHeadResult } from './utils';
|
|
5
|
+
export { useI18n, getI18n, getLocale, getDefaultLocale, getLocales, useLocaleHead, getI18nProps, } from './utils';
|
|
6
|
+
export type { LocaleHeadOptions, LocaleHeadResult, I18nClientProps } from './utils';
|
|
7
|
+
export type { I18nRoutingStrategy } from './router/types';
|
|
8
|
+
export { createAstroRouterAdapter } from './router/adapter';
|
|
7
9
|
export { getRouteName, getLocaleFromPath, switchLocalePath, localizePath, removeLocaleFromPath, } from './routing';
|
|
8
10
|
export type { Translations, Params, PluralFunc, Getter, Locale, LocaleCode, CleanTranslation, } from '@i18n-micro/types';
|
|
9
11
|
export { interpolate, FormatService, defaultPlural } from '@i18n-micro/core';
|
|
10
12
|
export type { I18nIntegrationOptions } from './integration';
|
|
13
|
+
export { loadTranslationsFromDir, loadTranslationsIntoI18n, } from './load-translations';
|
|
14
|
+
export type { LoadTranslationsOptions, LoadedTranslations } from './load-translations';
|