@i18n-micro/astro 1.3.12 → 1.3.18

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.
@@ -0,0 +1 @@
1
+ let e=require("@i18n-micro/core");function t(e,t){if(e===null||typeof t!=`string`)return null;let n=e;if(e[t])n=e[t];else{let e=t.toString().split(`.`);for(let t of e)if(n&&typeof n==`object`&&n&&t in n)n=n[t];else return null}return n??null}function n(n,r,i,a,o){if(!r)return a||r||``;let s=o||n.currentRoute,c=null;return n.translations[s]&&(c=t(n.translations[s],r)),c||=a===void 0?r:a||r,typeof c==`string`&&i?(0,e.interpolate)(c,i):c}function r(e,n,r){let i=r||e.currentRoute,a=e.translations[i];if(a){let e=t(a,n);if(e!==null&&typeof e!=`object`)return!0}return!1}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
@@ -0,0 +1,28 @@
1
+ import { interpolate as e } from "@i18n-micro/core";
2
+ //#region src/client/core.ts
3
+ function t(e, t) {
4
+ if (e === null || typeof t != "string") return null;
5
+ let n = e;
6
+ if (e[t]) n = e[t];
7
+ else {
8
+ let e = t.toString().split(".");
9
+ for (let t of e) if (n && typeof n == "object" && n && t in n) n = n[t];
10
+ else return null;
11
+ }
12
+ return n ?? null;
13
+ }
14
+ function n(n, r, i, a, o) {
15
+ if (!r) return a || r || "";
16
+ let s = o || n.currentRoute, c = null;
17
+ return n.translations[s] && (c = t(n.translations[s], r)), c ||= a === void 0 ? r : a || r, typeof c == "string" && i ? e(c, i) : c;
18
+ }
19
+ function r(e, n, r) {
20
+ let i = r || e.currentRoute, a = e.translations[i];
21
+ if (a) {
22
+ let e = t(a, n);
23
+ if (e !== null && typeof e != "object") return !0;
24
+ }
25
+ return !1;
26
+ }
27
+ //#endregion
28
+ export { n, r as t };
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("@i18n-micro/core"),G=require("node:async_hooks"),R=require("node:fs"),$=require("node:path"),M=require("@i18n-micro/utils/parse-path"),V=require("@i18n-micro/utils/accept-language");class v extends j.BaseI18n{constructor(e){const r=e._storage||{translations:new Map};if(super({storage:r,plural:e.plural,missingWarn:e.missingWarn,missingHandler:e.missingHandler,numberFormats:e.numberFormats,datetimeFormats:e.datetimeFormats}),this.initialMessages={},this.storage=r,this._locale=e.locale,this._fallbackLocale=e.fallbackLocale||e.locale,this._currentRoute="index",e.messages){this.initialMessages={...e.messages};for(const[l,c]of Object.entries(e.messages))this.helper.loadTranslations(l,c)}}cloneStorage(e){const r=new Map;for(const[l,c]of e.translations)r.set(l,{...c});return{translations:r}}clone(e){const r=this.cloneStorage(this.storage);return new v({locale:e||this._locale,fallbackLocale:this._fallbackLocale,plural:this.pluralFunc,missingWarn:this.missingWarn,missingHandler:this.missingHandler,numberFormats:this.formatter.getNumberFormats(),datetimeFormats:this.formatter.getDateTimeFormats(),_storage:r})}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,r){const l=`${e}:${r}`;return this.storage.translations.get(l)??null}addTranslations(e,r,l=!0){super.loadTranslationsCore(e,r,l)}addRouteTranslations(e,r,l,c=!0){super.loadRouteTranslationsCore(e,r,l,c)}mergeTranslations(e,r,l){this.helper.mergeTranslation(e,r,l,!0)}clearCache(){const e={...this.initialMessages};if(super.clearCache(),Object.keys(e).length>0)for(const[r,l]of Object.entries(e))this.helper.loadTranslations(r,l)}}let q=null;const W=new G.AsyncLocalStorage;function _(){const t=W.getStore();return t!==void 0?t:q}function U(t){q=t}function H(t,e){return W.run(t,e)}function J(t){const{locale:e,fallbackLocale:r,translationDir:l,routingStrategy:c}=t;return U(c||null),{name:"@i18n-micro/astro",hooks:{"astro:config:setup":u=>{const{updateConfig:i}=u,o="virtual:i18n-micro/config",s=`\0${o}`,a={defaultLocale:e,fallbackLocale:r||e,locales:t.locales||[],localeCodes:(t.locales||[]).map(n=>n.code),translationDir:l||null,autoDetect:t.autoDetect??!0,redirectToDefault:t.redirectToDefault??!1,localeCookie:t.localeCookie===null?null:t.localeCookie||"i18n-locale",missingWarn:t.missingWarn??!1};i({vite:{plugins:[{name:"vite-plugin-i18n-micro-config",resolveId(n){if(n===o)return s},load(n){if(n===s)return`export const config = ${JSON.stringify(a)}`}}]}})},"astro:config:done":u=>{const{injectTypes:i}=u;i({filename:"i18n-micro-env.d.ts",content:`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@i18n-micro/core"),t=require("node:async_hooks"),n=require("node:fs"),r=require("node:path"),i=require("@i18n-micro/utils/parse-path"),a=require("@i18n-micro/utils/accept-language");var o=class t extends e.BaseI18n{constructor(e){let t=e._storage||{translations:new Map};if(super({storage:t,plural:e.plural,missingWarn:e.missingWarn,missingHandler:e.missingHandler,numberFormats:e.numberFormats,datetimeFormats:e.datetimeFormats}),this.initialMessages={},this.storage=t,this._locale=e.locale,this._fallbackLocale=e.fallbackLocale||e.locale,this._currentRoute=`index`,e.messages){this.initialMessages={...e.messages};for(let[t,n]of Object.entries(e.messages))this.helper.loadTranslations(t,n)}}cloneStorage(e){let t=new Map;for(let[n,r]of e.translations)t.set(n,{...r});return{translations:t}}clone(e){let n=this.cloneStorage(this.storage);return new t({locale:e||this._locale,fallbackLocale:this._fallbackLocale,plural:this.pluralFunc,missingWarn:this.missingWarn,missingHandler:this.missingHandler,numberFormats:this.formatter.getNumberFormats(),datetimeFormats:this.formatter.getDateTimeFormats(),_storage:n})}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,t){let n=`${e}:${t}`;return this.storage.translations.get(n)??null}addTranslations(e,t,n=!0){super.loadTranslationsCore(e,t,n)}addRouteTranslations(e,t,n,r=!0){super.loadRouteTranslationsCore(e,t,n,r)}mergeTranslations(e,t,n){this.helper.mergeTranslation(e,t,n,!0)}clearCache(){let e={...this.initialMessages};if(super.clearCache(),Object.keys(e).length>0)for(let[t,n]of Object.entries(e))this.helper.loadTranslations(t,n)}},s=null,c=new t.AsyncLocalStorage;function l(){let e=c.getStore();return e===void 0?s:e}function u(e){s=e}function d(e,t){return c.run(e,t)}function f(e){let{locale:t,fallbackLocale:n,translationDir:r,routingStrategy:i}=e;return u(i||null),{name:`@i18n-micro/astro`,hooks:{"astro:config:setup":i=>{let{updateConfig:a}=i,o=`virtual:i18n-micro/config`,s=`\0${o}`,c={defaultLocale:t,fallbackLocale:n||t,locales:e.locales||[],localeCodes:(e.locales||[]).map(e=>e.code),translationDir:r||null,autoDetect:e.autoDetect??!0,redirectToDefault:e.redirectToDefault??!1,localeCookie:e.localeCookie===null?null:e.localeCookie||`i18n-locale`,missingWarn:e.missingWarn??!1};a({vite:{plugins:[{name:`vite-plugin-i18n-micro-config`,resolveId(e){if(e===o)return s},load(e){if(e===s)return`export const config = ${JSON.stringify(c)}`}}]}})},"astro:config:done":e=>{let{injectTypes:t}=e;t({filename:`i18n-micro-env.d.ts`,content:`
2
2
  /// <reference types="@i18n-micro/astro/env" />
3
3
 
4
4
  declare module 'virtual:i18n-micro/config' {
@@ -14,4 +14,4 @@
14
14
  missingWarn: boolean | null;
15
15
  }
16
16
  }
17
- `})}}}}function Z(t){return new v(t)}function z(t,e){if(R.existsSync(t))for(const r of R.readdirSync(t)){const l=$.join(t,r);if(R.statSync(l).isDirectory()){z(l,e);continue}r.endsWith(".json")&&e(l)}}function E(t){const{translationDir:e,rootDir:r=process.cwd(),disablePageLocales:l=!1}=t,c=$.resolve(r,e);if(!R.existsSync(c))return console.warn(`[i18n] Translation directory not found: ${c}`),{root:{},routes:{}};const u={root:{},routes:{}};return z(c,i=>{const o=$.relative(c,i).split($.sep).join("/");try{const s=R.readFileSync(i,"utf-8"),a=JSON.parse(s);M.storeLoadedTranslationFile(u,o,a,l)}catch(s){console.error(`[i18n] Failed to load translation file: ${i}`,s)}}),u}function K(t,e){const{root:r,routes:l}=E(e);for(const[c,u]of Object.entries(r))t.addTranslations(c,u,!1);for(const[c,u]of Object.entries(l))for(const[i,o]of Object.entries(u))t.addRouteTranslations(i,c,M.mergeRouteTranslationsWithRoot(r[i],o),!1)}function Q(t){const{i18n:e,defaultLocale:r,locales:l,localeObjects:c,autoDetect:u=!0,redirectToDefault:i=!1,routingStrategy:o}=t,s=o||_();return async(a,n)=>{if(a.locals.locale&&a.locals.i18n)return n();const f=a.url,d=f.pathname;if(!s){const w=e.clone(r),g=d==="/"||d===""?"index":d.split("/").filter(Boolean).join("-");return w.setRoute(g),a.locals.i18n=w,a.locals.locale=r,a.locals.defaultLocale=r,a.locals.locales=c||l.map(L=>({code:L})),a.locals.currentUrl=f,n()}const h={...s,getCurrentPath:()=>d,getRoute:()=>({fullPath:f.pathname+f.search,query:Object.fromEntries(f.searchParams)})},m=d.split("/").filter(Boolean)[0],P=m!==void 0&&l.includes(m);let S;P&&m?S=m:h.getLocaleFromPath?S=h.getLocaleFromPath(d,r,l):S=r;const y=e.clone(S),T=h.getRouteName?h.getRouteName(d,l):"index";return y.setRoute(T),a.locals.i18n=y,a.locals.locale=S,a.locals.defaultLocale=r,a.locals.locales=c||l.map(w=>({code:w})),a.locals.currentUrl=f,a.locals.routingStrategy=h,H(h,()=>n())}}function X(t,e,r,l,c,u="i18n-locale",i){const o=i??_();let s=l;if(o?.getLocaleFromPath)s=o.getLocaleFromPath(t,l,c);else{const n=t.split("/").filter(Boolean)[0];n&&c.includes(n)&&(s=n)}if(u!==null&&s===l&&e.get(u)){const a=e.get(u)?.value;a&&c.includes(a)&&(s=a)}if(s===l)try{const a=V.detectLocaleFromAcceptLanguage(r.get("accept-language")??void 0,c);a&&(s=a)}catch{}return s}function Y(t,e,r){const l=t.map(n=>n.code),c=(n,f=[])=>{const d=n.replace(/^\//,"").replace(/\/$/,"");if(!d)return"index";const h=d.split("/").filter(Boolean),p=h[0];return p&&f.includes(p)&&h.shift(),h.length===0?"index":h.join("-")},u=(n,f="en",d=[])=>{const p=n.split("/").filter(Boolean)[0];return p&&d.includes(p)?p:f},i=(n,f,d=[],h)=>{const p=n.split("/").filter(Boolean),m=p[0];return m&&d.includes(m)&&p.shift(),(f!==h||h===void 0)&&p.unshift(f),`/${p.join("/")}`},o=(n,f,d=[],h)=>{const m=(n.replace(/^\//,"").replace(/\/$/,"")||"").split("/").filter(Boolean),P=m[0];return P&&d.includes(P)&&m.shift(),(f!==h||h===void 0)&&m.unshift(f),`/${m.join("/")}`};return{getCurrentPath:()=>r?r().pathname:typeof window<"u"?window.location.pathname:"/",getRouteName:c,getLocaleFromPath:u,switchLocalePath:i,localizePath:o,removeLocaleFromPath:(n,f=[])=>{const d=n.split("/").filter(Boolean),h=d[0];return h&&f.includes(h)&&d.shift(),`/${d.join("/")}`},resolvePath:(n,f)=>{const d=typeof n=="string"?n:n.path||"/";return o(d,f,l,e)},getRoute:()=>{if(r){const n=r();return{fullPath:n.pathname+n.search,query:Object.fromEntries(n.searchParams)}}if(typeof window<"u"){const n=new URL(window.location.href);return{fullPath:n.pathname+n.search,query:Object.fromEntries(n.searchParams)}}return{fullPath:"/",query:{}}},push:n=>{typeof window<"u"&&(window.location.href=n.path)},replace:n=>{typeof window<"u"&&window.location.replace(n.path)}}}function D(t){return t.iso?.trim()||String(t.code)}function N(t){const e=t.match(/^([A-Za-z]{2,3})(?:[-_](.+))?$/);return e?{language:e[1],region:e[2]}:{language:t}}function ee(t,e={}){const{hreflangBaseLanguage:r=!1}=e;if(!r)return t.map(i=>{const o=String(i.code);return{hreflang:D(i),localeCode:o}});const l=new Map;for(const i of t){const o=String(i.code),s=D(i),{language:a,region:n}=N(s);a&&n&&!l.has(a)&&l.set(a,o),l.set(s,o)}const c=new Set,u=[];for(const i of t){const o=String(i.code),s=D(i),{language:a,region:n}=N(s);a&&n&&l.get(a)===o&&!c.has(a)&&(c.add(a),u.push({hreflang:a,localeCode:o})),c.has(s)||(c.add(s),u.push({hreflang:s,localeCode:o}))}return u}function I(t){const e=t.og?.trim();if(e)return e;const r=t.iso?.trim();if(!r)return null;const l=r.indexOf("_");if(l>0){const u=r.slice(0,l),i=r.slice(l+1);if(u.length>=2&&i.length===2)return`${u.toLowerCase()}_${i.toUpperCase()}`}const c=r.indexOf("-");if(c>0){const u=r.slice(0,c),i=r.slice(c+1);if(u.length>=2&&i.length===2&&/^[A-Za-z]{2}$/.test(i))return`${u.toLowerCase()}_${i.toUpperCase()}`}return null}function A(t,e={}){if(I(t)!==null||e.missingWarn===!1||process.env.NODE_ENV==="production")return;const r=e.tag??"og:locale",l=String(t.code??"unknown"),c=t.iso?`, iso: '${t.iso}'`:"";console.warn(`[i18n] Cannot derive ${r} for locale '${l}'${c}. Set locale.og (e.g. 'en_US') or use iso with a 2-letter region (e.g. 'en-US').`)}function O(t){const e=t.locals.i18n;if(!e)throw new Error("i18n instance not found. Make sure i18n middleware is configured.");return e}function F(t){return t.locals.locale||"en"}function k(t){return t.locals.defaultLocale||"en"}function C(t){return t.locals.locales||[]}function x(t){return t.locals.routingStrategy||null}function te(t){const e=O(t),r=F(t),l=k(t),c=C(t),u=c.map(o=>o.code),i=x(t);return{locale:r,defaultLocale:l,locales:c,t:(o,s,a,n)=>e.t(o,s,a,n),ts:(o,s,a,n)=>e.ts(o,s,a,n),tc:(o,s,a)=>e.tc(o,s,a),tn:e.tn.bind(e),td:e.td.bind(e),tdr:e.tdr.bind(e),has:(o,s)=>e.has(o,s),getRoute:()=>e.getRoute(),getRouteName:o=>{const s=o||t.url.pathname;if(i?.getRouteName)return i.getRouteName(s,u);const a=s.replace(/^\//,"").replace(/\/$/,"");if(!a)return"index";const n=a.split("/").filter(Boolean),f=n[0];return f&&u.includes(f)&&n.shift(),n.length===0?"index":n.join("-")},getLocaleFromPath:o=>{const s=o||t.url.pathname;if(i?.getLocaleFromPath)return i.getLocaleFromPath(s,l,u);const n=s.split("/").filter(Boolean)[0];return n&&u.includes(n)?n:l},switchLocalePath:o=>{if(i?.switchLocalePath)return i.switchLocalePath(t.url.pathname,o,u,l);const s=t.url.pathname.split("/").filter(Boolean),a=s[0];return a&&u.includes(a)&&s.shift(),o!==l&&s.unshift(o),`/${s.join("/")}`},localizePath:(o,s)=>{if(i?.localizePath)return i.localizePath(o,s||r,u,l);const n=(o.replace(/^\//,"").replace(/\/$/,"")||"").split("/").filter(Boolean),f=n[0];return f&&u.includes(f)&&n.shift(),s&&s!==l&&n.unshift(s),`/${n.join("/")}`},getI18n:()=>e,getBasePath:o=>{const n=(o||t.url).pathname.split("/").filter(Boolean),f=n[0];return f&&u.includes(f)&&n.shift(),n.length>0?`/${n.join("/")}`:"/"},addTranslations:(o,s,a=!0)=>{e.addTranslations(o,s,a)},addRouteTranslations:(o,s,a,n=!0)=>{e.addRouteTranslations(o,s,a,n)},mergeTranslations:(o,s,a)=>{e.mergeTranslations(o,s,a)},clearCache:()=>{e.clearCache()}}}function ne(t,e={}){const{baseUrl:r="/",addDirAttribute:l=!0,addSeoAttributes:c=!0,hreflangBaseLanguage:u=!1}=e,i=F(t),o=k(t),a=C(t).filter(g=>!g.disabled),n=a.filter(g=>g.seo!==!1),f=a.find(g=>g.code===i);if(!f)return{htmlAttrs:{},link:[],meta:[]};const d=f.iso||i,h=I(f),p=f.dir||"auto",m={htmlAttrs:{lang:d,...l?{dir:p}:{}},link:[],meta:[]};if(!c)return m;const P=`${r}${t.url.pathname}`;m.link.push({rel:"canonical",href:P});const S=x(t),y=a.map(g=>g.code),T=new Map;for(const g of n){let L=t.url.pathname;if(S?.switchLocalePath)L=S.switchLocalePath(t.url.pathname,g.code,y,o);else{const b=t.url.pathname.split("/").filter(Boolean),B=b[0];B&&y.includes(B)&&b.shift(),g.code!==o&&b.unshift(g.code),L=`/${b.join("/")}`}T.set(String(g.code),`${r}${L}`)}for(const{hreflang:g,localeCode:L}of ee(n,{hreflangBaseLanguage:u})){const b=T.get(L);b&&m.link.push({rel:"alternate",href:b,hreflang:g})}if(a.find(g=>g.code===o)?.seo!==!1){let g=t.url.pathname;if(S?.switchLocalePath)g=S.switchLocalePath(t.url.pathname,o,y,o);else{const L=t.url.pathname.split("/").filter(Boolean),b=L[0];b&&y.includes(b)&&L.shift(),g=`/${L.join("/")}`}m.link.push({rel:"alternate",href:`${r}${g}`,hreflang:"x-default"})}h?m.meta.push({property:"og:locale",content:h}):A(f,{tag:"og:locale"}),m.meta.push({property:"og:url",content:P});for(const g of n){if(g.code===i)continue;const L=I(g);if(!L){A(g,{tag:"og:locale:alternate"});continue}m.meta.push({property:"og:locale:alternate",content:L})}return m}function oe(t,e,r){const l=e.split(".");let c=t;for(let i=0;i<l.length-1;i++){const o=l[i];c[o]||(c[o]={}),c=c[o]}const u=l[l.length-1];u!==void 0&&(c[u]=r)}function ae(t,e){const r=O(t),l=F(t),c=k(t),u=r.getRoute(),i={};if(e&&e.length>0){const o={};for(const s of e){const a=r.t(s,void 0,void 0,u);a!=null&&a!==s&&oe(o,s,a)}Object.keys(o).length>0&&(i[u]=o)}else{const o=r.getRouteTranslations(l,u);o&&(i[u]=o)}return{locale:l,fallbackLocale:c,currentRoute:u,translations:i}}Object.defineProperty(exports,"FormatService",{enumerable:!0,get:()=>j.FormatService});Object.defineProperty(exports,"defaultPlural",{enumerable:!0,get:()=>j.defaultPlural});Object.defineProperty(exports,"interpolate",{enumerable:!0,get:()=>j.interpolate});exports.AstroI18n=v;exports.createAstroRouterAdapter=Y;exports.createI18n=Z;exports.createI18nMiddleware=Q;exports.detectLocale=X;exports.getDefaultLocale=k;exports.getGlobalRoutingStrategy=_;exports.getI18n=O;exports.getI18nProps=ae;exports.getLocale=F;exports.getLocales=C;exports.i18nIntegration=J;exports.loadTranslationsFromDir=E;exports.loadTranslationsIntoI18n=K;exports.runWithRoutingStrategy=H;exports.setGlobalRoutingStrategy=U;exports.useI18n=te;exports.useLocaleHead=ne;
17
+ `})}}}}function p(e){return new o(e)}function m(e,t){if((0,n.existsSync)(e))for(let i of(0,n.readdirSync)(e)){let a=(0,r.join)(e,i);if((0,n.statSync)(a).isDirectory()){m(a,t);continue}i.endsWith(`.json`)&&t(a)}}function h(e){let{translationDir:t,rootDir:a=process.cwd(),disablePageLocales:o=!1}=e,s=(0,r.resolve)(a,t);if(!(0,n.existsSync)(s))return console.warn(`[i18n] Translation directory not found: ${s}`),{root:{},routes:{}};let c={root:{},routes:{}};return m(s,e=>{let t=(0,r.relative)(s,e).split(r.sep).join(`/`);try{let r=(0,n.readFileSync)(e,`utf-8`),a=JSON.parse(r);(0,i.storeLoadedTranslationFile)(c,t,a,o)}catch(t){console.error(`[i18n] Failed to load translation file: ${e}`,t)}}),c}function g(e,t){let{root:n,routes:r}=h(t);for(let[t,r]of Object.entries(n))e.addTranslations(t,r,!1);for(let[t,a]of Object.entries(r))for(let[r,o]of Object.entries(a))e.addRouteTranslations(r,t,(0,i.mergeRouteTranslationsWithRoot)(n[r],o),!1)}function _(e){let{i18n:t,defaultLocale:n,locales:r,localeObjects:i,autoDetect:a=!0,redirectToDefault:o=!1,routingStrategy:s}=e,c=s||l();return async(e,a)=>{if(e.locals.locale&&e.locals.i18n)return a();let o=e.url,s=o.pathname;if(!c){let c=t.clone(n),l=s===`/`||s===``?`index`:s.split(`/`).filter(Boolean).join(`-`);return c.setRoute(l),e.locals.i18n=c,e.locals.locale=n,e.locals.defaultLocale=n,e.locals.locales=i||r.map(e=>({code:e})),e.locals.currentUrl=o,a()}let l={...c,getCurrentPath:()=>s,getRoute:()=>({fullPath:o.pathname+o.search,query:Object.fromEntries(o.searchParams)})},u=s.split(`/`).filter(Boolean)[0],f=u!==void 0&&r.includes(u),p;p=f&&u?u:l.getLocaleFromPath?l.getLocaleFromPath(s,n,r):n;let m=t.clone(p),h=l.getRouteName?l.getRouteName(s,r):`index`;return m.setRoute(h),e.locals.i18n=m,e.locals.locale=p,e.locals.defaultLocale=n,e.locals.locales=i||r.map(e=>({code:e})),e.locals.currentUrl=o,e.locals.routingStrategy=l,d(l,()=>a())}}function v(e,t,n,r,i,o=`i18n-locale`,s){let c=s??l(),u=r;if(c?.getLocaleFromPath)u=c.getLocaleFromPath(e,r,i);else{let t=e.split(`/`).filter(Boolean)[0];t&&i.includes(t)&&(u=t)}if(o!==null&&u===r&&t.get(o)){let e=t.get(o)?.value;e&&i.includes(e)&&(u=e)}if(u===r)try{let e=(0,a.detectLocaleFromAcceptLanguage)(n.get(`accept-language`)??void 0,i);e&&(u=e)}catch{}return u}function y(e,t,n){let r=e.map(e=>e.code),i=(e,t=[])=>{let n=e.replace(/^\//,``).replace(/\/$/,``);if(!n)return`index`;let r=n.split(`/`).filter(Boolean),i=r[0];return i&&t.includes(i)&&r.shift(),r.length===0?`index`:r.join(`-`)},a=(e,t=`en`,n=[])=>{let r=e.split(`/`).filter(Boolean)[0];return r&&n.includes(r)?r:t},o=(e,t,n=[],r)=>{let i=e.split(`/`).filter(Boolean),a=i[0];return a&&n.includes(a)&&i.shift(),(t!==r||r===void 0)&&i.unshift(t),`/${i.join(`/`)}`},s=(e,t,n=[],r)=>{let i=(e.replace(/^\//,``).replace(/\/$/,``)||``).split(`/`).filter(Boolean),a=i[0];return a&&n.includes(a)&&i.shift(),(t!==r||r===void 0)&&i.unshift(t),`/${i.join(`/`)}`};return{getCurrentPath:()=>n?n().pathname:typeof window<`u`?window.location.pathname:`/`,getRouteName:i,getLocaleFromPath:a,switchLocalePath:o,localizePath:s,removeLocaleFromPath:(e,t=[])=>{let n=e.split(`/`).filter(Boolean),r=n[0];return r&&t.includes(r)&&n.shift(),`/${n.join(`/`)}`},resolvePath:(e,n)=>{let i=typeof e==`string`?e:e.path||`/`;return s(i,n,r,t)},getRoute:()=>{if(n){let e=n();return{fullPath:e.pathname+e.search,query:Object.fromEntries(e.searchParams)}}if(typeof window<`u`){let e=new URL(window.location.href);return{fullPath:e.pathname+e.search,query:Object.fromEntries(e.searchParams)}}return{fullPath:`/`,query:{}}},push:e=>{typeof window<`u`&&(window.location.href=e.path)},replace:e=>{typeof window<`u`&&window.location.replace(e.path)}}}function b(e){return e.iso?.trim()||String(e.code)}function x(e){let t=e.match(/^([A-Za-z]{2,3})(?:[-_](.+))?$/);return t?{language:t[1],region:t[2]}:{language:e}}function S(e,t={}){let{hreflangBaseLanguage:n=!1}=t;if(!n)return e.map(e=>{let t=String(e.code);return{hreflang:b(e),localeCode:t}});let r=new Map;for(let t of e){let e=String(t.code),n=b(t),{language:i,region:a}=x(n);i&&a&&!r.has(i)&&r.set(i,e),r.set(n,e)}let i=new Set,a=[];for(let t of e){let e=String(t.code),n=b(t),{language:o,region:s}=x(n);o&&s&&r.get(o)===e&&!i.has(o)&&(i.add(o),a.push({hreflang:o,localeCode:e})),i.has(n)||(i.add(n),a.push({hreflang:n,localeCode:e}))}return a}function C(e){let t=e.og?.trim();if(t)return t;let n=e.iso?.trim();if(!n)return null;let r=n.indexOf(`_`);if(r>0){let e=n.slice(0,r),t=n.slice(r+1);if(e.length>=2&&t.length===2)return`${e.toLowerCase()}_${t.toUpperCase()}`}let i=n.indexOf(`-`);if(i>0){let e=n.slice(0,i),t=n.slice(i+1);if(e.length>=2&&t.length===2&&/^[A-Za-z]{2}$/.test(t))return`${e.toLowerCase()}_${t.toUpperCase()}`}return null}function w(e,t={}){if(C(e)!==null||t.missingWarn===!1||process.env.NODE_ENV===`production`)return;let n=t.tag??`og:locale`,r=String(e.code??`unknown`),i=e.iso?`, iso: '${e.iso}'`:``;console.warn(`[i18n] Cannot derive ${n} for locale '${r}'${i}. Set locale.og (e.g. 'en_US') or use iso with a 2-letter region (e.g. 'en-US').`)}function T(e){let t=e.locals.i18n;if(!t)throw Error(`i18n instance not found. Make sure i18n middleware is configured.`);return t}function E(e){return e.locals.locale||`en`}function D(e){return e.locals.defaultLocale||`en`}function O(e){return e.locals.locales||[]}function k(e){return e.locals.routingStrategy||null}function A(e){let t=T(e),n=E(e),r=D(e),i=O(e),a=i.map(e=>e.code),o=k(e);return{locale:n,defaultLocale:r,locales:i,t:(e,n,r,i)=>t.t(e,n,r,i),ts:(e,n,r,i)=>t.ts(e,n,r,i),tc:(e,n,r)=>t.tc(e,n,r),tn:t.tn.bind(t),td:t.td.bind(t),tdr:t.tdr.bind(t),has:(e,n)=>t.has(e,n),getRoute:()=>t.getRoute(),getRouteName:t=>{let n=t||e.url.pathname;if(o?.getRouteName)return o.getRouteName(n,a);let r=n.replace(/^\//,``).replace(/\/$/,``);if(!r)return`index`;let i=r.split(`/`).filter(Boolean),s=i[0];return s&&a.includes(s)&&i.shift(),i.length===0?`index`:i.join(`-`)},getLocaleFromPath:t=>{let n=t||e.url.pathname;if(o?.getLocaleFromPath)return o.getLocaleFromPath(n,r,a);let i=n.split(`/`).filter(Boolean)[0];return i&&a.includes(i)?i:r},switchLocalePath:t=>{if(o?.switchLocalePath)return o.switchLocalePath(e.url.pathname,t,a,r);let n=e.url.pathname.split(`/`).filter(Boolean),i=n[0];return i&&a.includes(i)&&n.shift(),t!==r&&n.unshift(t),`/${n.join(`/`)}`},localizePath:(e,t)=>{if(o?.localizePath)return o.localizePath(e,t||n,a,r);let i=(e.replace(/^\//,``).replace(/\/$/,``)||``).split(`/`).filter(Boolean),s=i[0];return s&&a.includes(s)&&i.shift(),t&&t!==r&&i.unshift(t),`/${i.join(`/`)}`},getI18n:()=>t,getBasePath:t=>{let n=(t||e.url).pathname.split(`/`).filter(Boolean),r=n[0];return r&&a.includes(r)&&n.shift(),n.length>0?`/${n.join(`/`)}`:`/`},addTranslations:(e,n,r=!0)=>{t.addTranslations(e,n,r)},addRouteTranslations:(e,n,r,i=!0)=>{t.addRouteTranslations(e,n,r,i)},mergeTranslations:(e,n,r)=>{t.mergeTranslations(e,n,r)},clearCache:()=>{t.clearCache()}}}function j(e){let t=e.locals.currentUrl??e.url;return A(e).getBasePath(t)}function M(e){let{locale:t}=e.params,n=O(e).map(e=>e.code);if(!t||!n.includes(t))return new Response(null,{status:404});let r=e.locals.i18n;return r&&(r.locale=t,e.locals.locale=t),j(e)}function N(e,t={}){let{baseUrl:n=`/`,addDirAttribute:r=!0,addSeoAttributes:i=!0,hreflangBaseLanguage:a=!1}=t,o=E(e),s=D(e),c=O(e).filter(e=>!e.disabled),l=c.filter(e=>e.seo!==!1),u=c.find(e=>e.code===o);if(!u)return{htmlAttrs:{},link:[],meta:[]};let d=u.iso||o,f=C(u),p=u.dir||`auto`,m={htmlAttrs:{lang:d,...r?{dir:p}:{}},link:[],meta:[]};if(!i)return m;let h=`${n}${e.url.pathname}`;m.link.push({rel:`canonical`,href:h});let g=k(e),_=c.map(e=>e.code),v=new Map;for(let t of l){let r=e.url.pathname;if(g?.switchLocalePath)r=g.switchLocalePath(e.url.pathname,t.code,_,s);else{let n=e.url.pathname.split(`/`).filter(Boolean),i=n[0];i&&_.includes(i)&&n.shift(),t.code!==s&&n.unshift(t.code),r=`/${n.join(`/`)}`}v.set(String(t.code),`${n}${r}`)}for(let{hreflang:e,localeCode:t}of S(l,{hreflangBaseLanguage:a})){let n=v.get(t);n&&m.link.push({rel:`alternate`,href:n,hreflang:e})}if(c.find(e=>e.code===s)?.seo!==!1){let t=e.url.pathname;if(g?.switchLocalePath)t=g.switchLocalePath(e.url.pathname,s,_,s);else{let n=e.url.pathname.split(`/`).filter(Boolean),r=n[0];r&&_.includes(r)&&n.shift(),t=`/${n.join(`/`)}`}m.link.push({rel:`alternate`,href:`${n}${t}`,hreflang:`x-default`})}f?m.meta.push({property:`og:locale`,content:f}):w(u,{tag:`og:locale`}),m.meta.push({property:`og:url`,content:h});for(let e of l){if(e.code===o)continue;let t=C(e);if(!t){w(e,{tag:`og:locale:alternate`});continue}m.meta.push({property:`og:locale:alternate`,content:t})}return m}function P(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];i[t]||(i[t]={}),i=i[t]}let a=r[r.length-1];a!==void 0&&(i[a]=n)}function F(e,t){let n=T(e),r=E(e),i=D(e),a=n.getRoute(),o={};if(t&&t.length>0){let e={};for(let r of t){let t=n.t(r,void 0,void 0,a);t!=null&&t!==r&&P(e,r,t)}Object.keys(e).length>0&&(o[a]=e)}else{let e=n.getRouteTranslations(r,a);e&&(o[a]=e)}return{locale:r,fallbackLocale:i,currentRoute:a,translations:o}}exports.AstroI18n=o,Object.defineProperty(exports,"FormatService",{enumerable:!0,get:function(){return e.FormatService}}),exports.createAstroRouterAdapter=y,exports.createI18n=p,exports.createI18nMiddleware=_,Object.defineProperty(exports,"defaultPlural",{enumerable:!0,get:function(){return e.defaultPlural}}),exports.detectLocale=v,exports.getDefaultLocale=D,exports.getGlobalRoutingStrategy=l,exports.getI18n=T,exports.getI18nProps=F,exports.getLocale=E,exports.getLocaleRewritePath=j,exports.getLocales=O,exports.i18nIntegration=f,Object.defineProperty(exports,"interpolate",{enumerable:!0,get:function(){return e.interpolate}}),exports.loadTranslationsFromDir=h,exports.loadTranslationsIntoI18n=g,exports.prepareLocaleRewrite=M,exports.runWithRoutingStrategy=d,exports.setGlobalRoutingStrategy=u,exports.useI18n=A,exports.useLocaleHead=N;
package/dist/index.d.cts CHANGED
@@ -11,4 +11,4 @@ export { createI18nMiddleware, detectLocale } from './middleware';
11
11
  export { createAstroRouterAdapter } from './router/adapter';
12
12
  export type { I18nRoutingStrategy } from './router/types';
13
13
  export type { I18nClientProps, LocaleHeadOptions, LocaleHeadResult } from './utils';
14
- export { getDefaultLocale, getI18n, getI18nProps, getLocale, getLocales, useI18n, useLocaleHead } from './utils';
14
+ export { getDefaultLocale, getI18n, getI18nProps, getLocale, getLocaleRewritePath, getLocales, prepareLocaleRewrite, useI18n, useLocaleHead, } from './utils';
package/dist/index.d.ts CHANGED
@@ -11,4 +11,4 @@ export { createI18nMiddleware, detectLocale } from './middleware';
11
11
  export { createAstroRouterAdapter } from './router/adapter';
12
12
  export type { I18nRoutingStrategy } from './router/types';
13
13
  export type { I18nClientProps, LocaleHeadOptions, LocaleHeadResult } from './utils';
14
- export { getDefaultLocale, getI18n, getI18nProps, getLocale, getLocales, useI18n, useLocaleHead } from './utils';
14
+ export { getDefaultLocale, getI18n, getI18nProps, getLocale, getLocaleRewritePath, getLocales, prepareLocaleRewrite, useI18n, useLocaleHead, } from './utils';