@i18n-micro/route-strategy 1.1.1 → 1.1.2

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.
@@ -1,5 +1,5 @@
1
- import { NuxtPage } from '@nuxt/schema';
2
1
  import { GlobalLocaleRoutes, Locale, Strategies } from '@i18n-micro/types';
2
+ import { NuxtPage } from '@nuxt/schema';
3
3
  import { LocaleRoutesConfig } from '../strategies/types';
4
4
  import { LocalizedPathsMap } from './localized-paths';
5
5
  export interface GeneratorContextOptions {
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("node:path"),S=require("node:fs"),k=require("@i18n-micro/core");function x(l){return l.split("/").map(e=>e.startsWith("[...")&&e.endsWith("]")?`:${e.substring(4,e.length-1)}(.*)*`:e.startsWith("[")&&e.endsWith("]")?`:${e.substring(1,e.length-1)}`:e).join("/")}const R=l=>{if(!l)return"";const e=w.posix.normalize(l).replace(/\/+$/,"");return e==="."?"":e},g=l=>l.startsWith("/")?l.slice(1):l;function O(...l){return w.posix.join(...l)}function H(l){if(!(typeof l>"u"))return l.startsWith("/")&&l.endsWith("/")?l?.slice(1,-1):l}function K(l){return!l||!/[\u0080-\uFFFF]/.test(l)?l:l.split("/").map(e=>!e||e.startsWith(":")||!/[\u0080-\uFFFF]/.test(e)?e:encodeURI(e)).join("/")}function N(l,e,t){const a=H(t?.toString()),o=a||(Array.isArray(l)?l.join("|"):l),s=K(e);return R(w.posix.join("/",`:locale(${o})`,s))}function M(l){const e=K(l);return R(e)}const b=l=>l.map(e=>({...e})),T=l=>!!(l.redirect&&!l.file),F=(l,e,t,a="localized-")=>t?`${a}${l}-${e}`:`${a}${l}`,C=(l,e)=>l??(e??"").replace(/[^a-z0-9]/gi,"-").replace(/^-+|-+$/g,""),V=(l,e,t,a)=>t&&!(l===e.code&&!a),I=(l,e,t)=>(typeof l=="string"?l:l.code)===e.code&&!t,J=[/^\/sitemap.*\.xml$/,/^\/sitemap\.xml$/,/^\/robots\.txt$/,/^\/favicon\.ico$/,/^\/apple-touch-icon.*\.png$/,/^\/manifest\.json$/,/^\/sw\.js$/,/^\/workbox-.*\.js$/,/\.(xml|txt|ico|json|js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/];function E(l,e){if(/(?:^|\/)__[^/]+/.test(l))return!0;for(const t of J)if(t.test(l))return!0;if(e){for(const t of e)if(typeof t=="string"){if(t.includes("*")||t.includes("?")){if(new RegExp(t.replace(/\*/g,".*").replace(/\?/g,".")).test(l))return!0}else if(l===t||l.startsWith(t))return!0}else if(t instanceof RegExp&&t.test(l))return!0}return!1}function Q(l,e){const t=l.reduce((o,s)=>{const i=o.find(r=>r.code===s.code);return i?Object.assign(i,s):o.push(s),o},[]).filter(o=>!o.disabled),a=t.find(o=>o.code===e)??{code:e};return{locales:t,defaultLocale:a}}const X=(l,e)=>l??(e??"").replace(/[^a-z0-9]/gi,"-").replace(/^-+|-+$/g,"");function j(l){return g(l)||"/"}function _(l,e,t,a=""){const o={};return l.forEach(s=>{const i=X(s.name,s.path),r=R(O(a,s.path??"")),c=j(r),d=x(r),n=e[c]||e[d]||e[i];if(n)typeof n=="object"&&(o[c]=n);else{const h=t[i];h&&typeof h=="object"&&!Array.isArray(h)&&(o[c]=h)}if(s.children?.length){const h=R(O(a,s.path??""));Object.assign(o,_(s.children,e,t,h))}}),o}function Y(l){const e={};if(!l)return e;for(const t in l){const a=x(t),o=l[t];if(typeof o=="object"){const s={};for(const i in o){const r=o[i];r&&(s[i]=x(r))}e[a]=s}else e[a]=o}return e}class Z{constructor(e){this.locales=e.locales,this.defaultLocale=this.findLocaleByCode(e.locales,e.defaultLocaleCode)??{code:e.defaultLocaleCode},this.strategy=e.strategy,this.globalLocaleRoutes=Y(e.globalLocaleRoutes??{}),this.filesLocaleRoutes=e.filesLocaleRoutes??{},this.routeLocales=e.routeLocales??{},this.localizedPaths=_(e.pages,this.globalLocaleRoutes,this.filesLocaleRoutes),this.activeLocaleCodes=this.locales.filter(t=>t.code!==this.defaultLocale.code||k.isPrefixAndDefaultStrategy(this.strategy)||k.isPrefixStrategy(this.strategy)).map(t=>t.code),this.excludePatterns=e.excludePatterns,this.customRegex=e.customRegex,this.noPrefixRedirect=e.noPrefixRedirect??!1,this.localizedRouteNamePrefix=e.localizedRouteNamePrefix??"localized-",this.fallbackRedirectComponentPath=e.fallbackRedirectComponentPath,this.rawGlobalLocaleRoutes=e.rawGlobalLocaleRoutes}findLocaleByCode(e,t){return e.find(a=>a.code===t)}getAllowedLocales(e,t){const a=this.routeLocales[e]??this.routeLocales[t];return a?.length?a.filter(o=>this.locales.some(s=>s.code===o)):this.locales.map(o=>o.code)}getCustomPath(e,t){const a=j(e);return this.localizedPaths[a]?.[t]}getCustomPathsForPage(e,t){const a=j(e);return this.localizedPaths[a]??this.localizedPaths[t]}hasLocaleRestrictions(e,t){return!!(this.routeLocales[e]??this.routeLocales[t])}filterLocaleCodesWithoutCustomPaths(e){const t=j(e);return this.activeLocaleCodes.filter(a=>!this.localizedPaths[t]?.[a])}}function z(l,e){const t=(e??"").trim();return t.startsWith("/")?R(t):R(w.posix.join(l||"",t))}function p(l,e){const{path:t,name:a,children:o,meta:s,alias:i}=e,r={...l,path:t};return a!==void 0&&(r.name=a),o!==void 0&&(r.children=o),s!==void 0&&(r.meta={...l.meta,...s}),i!==void 0?(r.alias=i,r.meta={...r.meta,alias:i}):"alias"in e&&(r.alias=void 0,r.meta={...r.meta,alias:void 0}),r}function ee(l){const e=l.alias,t=l.meta?.alias,a=e??t;return Array.isArray(a)?a:[]}function D(l,e,t,a="localized-"){const o=ee(l);if(!o.length)return[];const s=[];for(const i of o){const r=N(e,i,t);s.push(p(l,{path:r,name:`${a}${l.name??""}`,alias:void 0,meta:{alias:void 0},children:l.children}))}return s}class W{processPage(e,t){if(e.path===void 0)throw new Error("page.path is required");if(T(e))return[e];if(e.path&&E(e.path,t.excludePatterns))return[e];const a=e.path??"",o=C(e.name,e.path),s=x(a);return t.globalLocaleRoutes[o]===!1||t.globalLocaleRoutes[s]===!1?[e]:this.generateVariants(e,t)}postProcess(e,t){return e}localizeChildren(e,t,a,o,s,i){return e.flatMap(r=>this.localizeChild(r,t,a,o,s,i))}localizeChildrenAllLocales(e,t,a,o,s){return e.flatMap(i=>this.localizeChildAllLocales(i,t,a,o,s))}localizeChildAllLocales(e,t,a,o,s){const i=z(a,e.path??""),r=z(t,e.path??""),c=j(r),d=s.localizedPaths[c];if(d)return o.flatMap(f=>{const P=d[f]??z(t,e.path??"");return this.localizeChild(e,P,a,f,s,!0)});const n=R(e.path??""),h=g(n),u=this.localizeChildrenAllLocales(b(e.children??[]),r,i,o,s),m=`${s.localizedRouteNamePrefix}${e.name??""}`;return[p(e,{path:h,name:m,children:u})]}localizeChild(e,t,a,o,s,i){const r=z(a,e.path??""),c=s.getCustomPath(r,o),d=g(R(c||(e.path??""))),n=c??z(t,e.path??""),h=this.localizeChildren(b(e.children??[]),n,r,o,s,i),u=C(e.name,e.path),m=`${s.localizedRouteNamePrefix}${u}-${o}`;return[p(e,{path:d,name:m,children:h})]}buildRoutePathForLocales(e,t,a,o,s,i,r){if(o){const c=e.includes(r);return i||!c?N(e,a,s):R(a)}return N(e,t,s)}}class te extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[];if(c.push(e),i)for(const d of s){const n=i[d];if(!n)continue;const h=R(n),u=R(a);if(h===u)continue;const m=M(n),f=F(o,d,!0),P=this.localizeChildrenForNoPrefix(r,h,a,a,d,t,1);c.push(p(e,{path:m,name:f,children:P,alias:[],meta:{alias:[]}})),t.noPrefixRedirect&&d===t.defaultLocale.code&&h!==u&&(e.redirect=h)}return c.push(...D(e,s,t.customRegex,t.localizedRouteNamePrefix)),c}localizeChildrenForNoPrefix(e,t,a,o,s,i,r){return e.map(c=>{const d=z(a,c.path??"");let n,h;if(r===1){const P=i.getCustomPath(d,s);if(P){const L=R(P);n=g(L),h=L}else{const L=R(c.path??"");n=g(L),h=z(t,c.path??"")}}else{const P=R(c.path??"");n=g(P),h=z(t,c.path??"")}const u=this.localizeChildrenForNoPrefix(b(c.children??[]),h,d,o,s,i,r+1),m=C(c.name,c.path),f=F(m,s,!0);return p(c,{path:n,name:f,children:u})})}}function ae(l){const e=l.alias??l.meta?.alias;return Array.isArray(e)?e:[]}class se extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[];if(i)for(const n of s){const h=i[n],u=h?R(h):a,m=N(n,u,t.customRegex),f=F(o,n,!!h,t.localizedRouteNamePrefix),P=h??a,L=this.localizeChildren(r,P,a,n,t,!0);c.push(p(e,{path:m,name:f,children:L,alias:[],meta:{alias:[]}}))}else{const n=N(s,a,t.customRegex),h=F(o,s[0],!1,t.localizedRouteNamePrefix),u=this.localizeChildrenAllLocales(r,a,a,s,t);c.push(p(e,{path:n,name:h,children:u,alias:[],meta:{alias:[]}}))}const d=ae(e);if(d.length)for(const n of d){const h=N(s,n,t.customRegex);c.push(p(e,{path:h,name:`${t.localizedRouteNamePrefix}${e.name??""}`,alias:void 0,meta:{alias:void 0}}))}return c}postProcess(e,t){const a=e.filter(s=>{if(s.name==="index"&&s.path==="/")return!1;const i=s.path??"";return!!(i&&E(i,t.excludePatterns)||t.globalLocaleRoutes[s.name??""]===!1||/^\/:locale/.test(i)||i==="/")}),o=t.defaultLocale.code;for(const[s,i]of Object.entries(t.globalLocaleRoutes)){if(i===!1||typeof i!="object")continue;const r=i[o];if(!r)continue;const c=s.startsWith("/")?s:`/${s}`,d=`/${o}${r.startsWith("/")?r:`/${r}`}`;c!==d&&a.push({path:c,name:`redirect-${s.replace(/\//g,"-")}`,redirect:d})}return t.fallbackRedirectComponentPath&&a.push({path:"/:pathMatch(.*)*",name:"custom-fallback-route",file:t.fallbackRedirectComponentPath,meta:{globalLocaleRoutes:t.rawGlobalLocaleRoutes??t.globalLocaleRoutes}}),a}}class oe extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[],d=t.defaultLocale.code;c.push(e);const n=t.locales.filter(u=>s.includes(u.code));if(n.length>0)if(i)for(const u of n){const m=i[u.code];if(m)if(u.code===d){const f=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!1,u.code,a,t);f&&c.push(f);const P=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!0,u.code,a,t);P&&c.push(P)}else{const f=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!1,u.code,a,t);f&&c.push(f)}else{const f=this.createLocalizedRoute(e,[u.code],r,!1,"",t.customRegex,!1,u.code,a,t);f&&c.push(f)}}else{const u=n.map(f=>f.code),m=this.createLocalizedRoute(e,u,r,!1,"",t.customRegex,!1,!0,a,t);m&&c.push(m)}const h=D(e,s,t.customRegex,t.localizedRouteNamePrefix);return h.length&&c.push(...h),c}postProcess(e,t){const a=[],o=[];for(const s of e){const i=s.name??"";typeof i=="string"&&i.startsWith(t.localizedRouteNamePrefix)?o.push(s):a.push(s)}return[...a,...o]}createLocalizedRoute(e,t,a,o,s="",i,r=!1,c=!1,d,n){const h=this.buildRoutePathForLocales(t,e.path??"",encodeURI(s),o,i,r,n.defaultLocale.code);if(!h||!(o&&s)&&h===e.path||t.length===0)return null;const m=t[0];if(!m)return null;const f=d??e.path??"",P=F(C(e.name??"",f),m,o,n.localizedRouteNamePrefix),L=r||m!==n.defaultLocale.code,y=t.length===1?this.localizeChildren(a,h,f,m,n,L):this.localizeChildrenAllLocales(a,h,f,t,n);return p(e,{path:h,name:P,children:y,alias:[],meta:{alias:[]}})}}class le extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[],d=t.defaultLocale.code;if(s.includes(d)){const u=i?.[d],m=u?R(u):a,f=u?{[d]:u}:{},P=this.createLocalizedChildren(r,a,[d],!1,!1,!1,f,t);c.push(p(e,{path:m,name:e.name,children:P}))}const n=t.locales.filter(u=>s.includes(u.code)&&u.code!==d);if(n.length)if(i)for(const u of n){const m=i[u.code];if(m){const f=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!1,u.code,a,t);f&&c.push(f)}else{const f=this.createLocalizedRoute(e,[u.code],r,!1,"",t.customRegex,!1,u.code,a,t);f&&c.push(f)}}else{const u=n.map(f=>f.code),m=this.createLocalizedRoute(e,u,r,!1,"",t.customRegex,!1,!0,a,t);m&&c.push(m)}const h=D(e,s,t.customRegex,t.localizedRouteNamePrefix);return h.length&&c.push(...h),c}postProcess(e,t){const a=[],o=[];for(const i of e){const r=i.name??"";typeof r=="string"&&r.startsWith(t.localizedRouteNamePrefix)?o.push(i):a.push(i)}const s=[...a,...o];return t.fallbackRedirectComponentPath&&s.push({path:"/:pathMatch(.*)*",name:"custom-fallback-route",file:t.fallbackRedirectComponentPath,meta:{globalLocaleRoutes:t.rawGlobalLocaleRoutes??t.globalLocaleRoutes}}),s}createLocalizedChildren(e,t,a,o=!0,s=!1,i=!1,r={},c){return e.flatMap(d=>this.createLocalizedVariants(d,t,a,o,s,i,r,c))}createLocalizedVariants(e,t,a,o,s,i=!1,r,c){const d=R(e.path??""),n=z(t,e.path??""),h=j(n),u=c.localizedPaths[h],m=!!u,f=[];if(!m){const P=g(d),L=this.createLocalizedChildren(b(e.children??[]),z(t,e.path??""),a,o,s,i,r,c),y=this.buildChildRouteName(e.name,i,c);return f.push(p(e,{path:P,name:y,children:L})),f}for(const P of a){const L=r?.[P],y=!!L,$=u?.[P];let A=R($||(e.path??""));y&&L&&($?A=R($):A=z(L,e.path??""));const v=V(P,c.defaultLocale,s,!1)?N(P,A,c.customRegex):A,q=g(v),G=$?R($):y?L:z(t,e.path??""),B=this.createLocalizedChildren(b(e.children??[]),G,[P],o,s,P,{...r,[P]:G},c),U=this.buildLocalizedRouteName(C(e.name,e.path),P,o,!!u,c);f.push(p(e,{path:q,name:U,children:B}))}return f}buildChildRouteName(e,t,a){return t===!0?`${a.localizedRouteNamePrefix}${e}`:typeof t=="string"?`${a.localizedRouteNamePrefix}${e}-${t}`:e}createLocalizedRoute(e,t,a,o,s="",i,r=!1,c=!1,d,n){const h=this.buildRoutePathForLocales(t,e.path??"",encodeURI(s),o,i,r,n.defaultLocale.code);if(!h||h===e.path||t.length===0)return null;const u=t[0];if(!u)return null;const m=d??e.path??"",f=F(C(e.name??"",m),u,o,n.localizedRouteNamePrefix);return p(e,{path:h,name:f,children:this.createLocalizedChildren(a,m,t,!0,!1,c,{[u]:s},n),alias:[],meta:{alias:[]}})}buildLocalizedRouteName(e,t,a,o=!1,s){return a?o?`${s.localizedRouteNamePrefix}${e}-${t}`:t&&!I(t,s.defaultLocale,!1)?`${s.localizedRouteNamePrefix}${e}-${t}`:`${s.localizedRouteNamePrefix}${e}`:e}}function ie(l){switch(l){case"no_prefix":return new te;case"prefix":return new se;case"prefix_and_default":return new oe;case"prefix_except_default":return new le;default:throw new Error(`Unknown route strategy: ${l}`)}}class re{constructor(e){this.localizedPaths={};const{locales:t,defaultLocaleCode:a,strategy:o,globalLocaleRoutes:s,filesLocaleRoutes:i={},routeLocales:r={},noPrefixRedirect:c,excludePatterns:d,localizedRouteNamePrefix:n="localized-",customRegexMatcher:h,fallbackRedirectComponentPath:u}=e,m=Q(t,a);this.locales=m.locales,this.defaultLocale=m.defaultLocale,this.strategy=o,this.noPrefixRedirect=c,this.excludePatterns=d,this.localizedRouteNamePrefix=n,this.customRegex=h,this.fallbackRedirectComponentPath=u,this.activeLocaleCodes=this.computeActiveLocaleCodes();const f={};for(const P in s){const L=x(P),y=s[P];if(typeof y=="object"){const $={};for(const A in y){const v=y[A];v&&($[A]=x(v))}f[L]=$}else f[L]=y}this.globalLocaleRoutes=f,this.rawGlobalLocaleRoutes=s??{},this.filesLocaleRoutes=i??{},this.routeLocales=r??{}}computeActiveLocaleCodes(){return this.locales.filter(e=>e.code!==this.defaultLocale.code||k.isPrefixAndDefaultStrategy(this.strategy)||k.isPrefixStrategy(this.strategy)).map(e=>e.code)}extendPages(e){const t=new Z({locales:this.locales,defaultLocaleCode:this.defaultLocale.code,strategy:this.strategy,globalLocaleRoutes:this.globalLocaleRoutes,filesLocaleRoutes:this.filesLocaleRoutes,routeLocales:this.routeLocales,pages:e,excludePatterns:this.excludePatterns,customRegex:this.customRegex,noPrefixRedirect:this.noPrefixRedirect,localizedRouteNamePrefix:this.localizedRouteNamePrefix,fallbackRedirectComponentPath:this.fallbackRedirectComponentPath,rawGlobalLocaleRoutes:this.rawGlobalLocaleRoutes});this.localizedPaths=t.localizedPaths;const a=ie(this.strategy),o=[...e],s=[];for(const r of o)s.push(...a.processPage(r,t));const i=a.postProcess(s,t);e.length=0,e.push(...i)}extractLocalizedPaths(e,t=""){return _(e,this.globalLocaleRoutes,this.filesLocaleRoutes,t)}ensureTranslationFilesExist(e,t,a,o){this.locales.forEach(s=>{const i=w.join(a,t,`${s.code}.json`);this.ensureFileExists(i),o||e.forEach(r=>{const c=w.join(a,t,"pages",`${r}/${s.code}.json`);this.ensureFileExists(c)})})}ensureFileExists(e){const t=w.dirname(e);S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),S.existsSync(e)||S.writeFileSync(e,JSON.stringify({}),"utf-8")}resolveLocalizedPath(e,t){const a=x(e),o=g(a)||"/";let s;const i=this.globalLocaleRoutes[o],r=this.globalLocaleRoutes[a];i&&typeof i=="object"&&!Array.isArray(i)?s=i[t]:r&&typeof r=="object"&&!Array.isArray(r)&&(s=r[t]);const c=!!s,d=s?R(s):R(a)||"";let n=!1;if(this.strategy==="no_prefix"?n=!1:this.strategy==="prefix"||this.strategy==="prefix_and_default"?n=!0:this.strategy==="prefix_except_default"&&(n=t!==this.defaultLocale.code),t===this.defaultLocale.code&&!c&&(this.strategy==="prefix_except_default"||this.strategy==="no_prefix")&&(n=!1),!n)return R(d)||"/";const h=g(d);return h?R(`/${t}/${h}`):`/${t}`}generateDataRoutes(e,t,a){const o=[],s=e.map(i=>i.name).filter(i=>typeof i=="string"&&i.length>0);for(const i of this.locales)if(o.push(`/${t}/general/${i.code}/data.json`),!a)for(const r of s)o.push(`/${t}/${r}/${i.code}/data.json`);return o}}exports.RouteGenerator=re;exports.buildFullPath=N;exports.buildFullPathNoPrefix=M;exports.buildRouteName=F;exports.cloneArray=b;exports.extractLocalizedPaths=_;exports.isInternalPath=E;exports.isLocaleDefault=I;exports.isPageRedirectOnly=T;exports.normalizePath=R;exports.normalizeRouteKey=x;exports.removeLeadingSlash=g;exports.shouldAddLocalePrefix=V;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("node:path"),S=require("node:fs"),k=require("@i18n-micro/core"),b=l=>l.map(e=>({...e})),K=l=>!!(l.redirect&&!l.file),F=(l,e,t,a="localized-")=>t?`${a}${l}-${e}`:`${a}${l}`,C=(l,e)=>l??(e??"").replace(/[^a-z0-9]/gi,"-").replace(/^-+|-+$/g,""),M=(l,e,t,a)=>t&&!(l===e.code&&!a),T=(l,e,t)=>(typeof l=="string"?l:l.code)===e.code&&!t,H=[/^\/sitemap.*\.xml$/,/^\/sitemap\.xml$/,/^\/robots\.txt$/,/^\/favicon\.ico$/,/^\/apple-touch-icon.*\.png$/,/^\/manifest\.json$/,/^\/sw\.js$/,/^\/workbox-.*\.js$/,/\.(xml|txt|ico|json|js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/];function E(l,e){if(/(?:^|\/)__[^/]+/.test(l))return!0;for(const t of H)if(t.test(l))return!0;if(e){for(const t of e)if(typeof t=="string"){if(t.includes("*")||t.includes("?")){if(new RegExp(t.replace(/\*/g,".*").replace(/\?/g,".")).test(l))return!0}else if(l===t||l.startsWith(t))return!0}else if(t instanceof RegExp&&t.test(l))return!0}return!1}function J(l,e){const t=l.reduce((o,s)=>{const i=o.find(r=>r.code===s.code);return i?Object.assign(i,s):o.push(s),o},[]).filter(o=>!o.disabled),a=t.find(o=>o.code===e)??{code:e};return{locales:t,defaultLocale:a}}function x(l){return l.split("/").map(e=>e.startsWith("[...")&&e.endsWith("]")?`:${e.substring(4,e.length-1)}(.*)*`:e.startsWith("[")&&e.endsWith("]")?`:${e.substring(1,e.length-1)}`:e).join("/")}const R=l=>{if(!l)return"";const e=w.posix.normalize(l).replace(/\/+$/,"");return e==="."?"":e},g=l=>l.startsWith("/")?l.slice(1):l;function O(...l){return w.posix.join(...l)}function Q(l){if(!(typeof l>"u"))return l.startsWith("/")&&l.endsWith("/")?l?.slice(1,-1):l}function V(l){return!l||!/[\u0080-\uFFFF]/.test(l)?l:l.split("/").map(e=>!e||e.startsWith(":")||!/[\u0080-\uFFFF]/.test(e)?e:encodeURI(e)).join("/")}function N(l,e,t){const a=Q(t?.toString()),o=a||(Array.isArray(l)?l.join("|"):l),s=V(e);return R(w.posix.join("/",`:locale(${o})`,s))}function I(l){const e=V(l);return R(e)}const X=(l,e)=>l??(e??"").replace(/[^a-z0-9]/gi,"-").replace(/^-+|-+$/g,"");function j(l){return g(l)||"/"}function _(l,e,t,a=""){const o={};return l.forEach(s=>{const i=X(s.name,s.path),r=R(O(a,s.path??"")),c=j(r),d=x(r),n=e[c]||e[d]||e[i];if(n)typeof n=="object"&&(o[c]=n);else{const h=t[i];h&&typeof h=="object"&&!Array.isArray(h)&&(o[c]=h)}if(s.children?.length){const h=R(O(a,s.path??""));Object.assign(o,_(s.children,e,t,h))}}),o}function Y(l){const e={};if(!l)return e;for(const t in l){const a=x(t),o=l[t];if(typeof o=="object"){const s={};for(const i in o){const r=o[i];r&&(s[i]=x(r))}e[a]=s}else e[a]=o}return e}class Z{constructor(e){this.locales=e.locales,this.defaultLocale=this.findLocaleByCode(e.locales,e.defaultLocaleCode)??{code:e.defaultLocaleCode},this.strategy=e.strategy,this.globalLocaleRoutes=Y(e.globalLocaleRoutes??{}),this.filesLocaleRoutes=e.filesLocaleRoutes??{},this.routeLocales=e.routeLocales??{},this.localizedPaths=_(e.pages,this.globalLocaleRoutes,this.filesLocaleRoutes),this.activeLocaleCodes=this.locales.filter(t=>t.code!==this.defaultLocale.code||k.isPrefixAndDefaultStrategy(this.strategy)||k.isPrefixStrategy(this.strategy)).map(t=>t.code),this.excludePatterns=e.excludePatterns,this.customRegex=e.customRegex,this.noPrefixRedirect=e.noPrefixRedirect??!1,this.localizedRouteNamePrefix=e.localizedRouteNamePrefix??"localized-",this.fallbackRedirectComponentPath=e.fallbackRedirectComponentPath,this.rawGlobalLocaleRoutes=e.rawGlobalLocaleRoutes}findLocaleByCode(e,t){return e.find(a=>a.code===t)}getAllowedLocales(e,t){const a=this.routeLocales[e]??this.routeLocales[t];return a?.length?a.filter(o=>this.locales.some(s=>s.code===o)):this.locales.map(o=>o.code)}getCustomPath(e,t){const a=j(e);return this.localizedPaths[a]?.[t]}getCustomPathsForPage(e,t){const a=j(e);return this.localizedPaths[a]??this.localizedPaths[t]}hasLocaleRestrictions(e,t){return!!(this.routeLocales[e]??this.routeLocales[t])}filterLocaleCodesWithoutCustomPaths(e){const t=j(e);return this.activeLocaleCodes.filter(a=>!this.localizedPaths[t]?.[a])}}function z(l,e){const t=(e??"").trim();return t.startsWith("/")?R(t):R(w.posix.join(l||"",t))}function p(l,e){const{path:t,name:a,children:o,meta:s,alias:i}=e,r={...l,path:t};return a!==void 0&&(r.name=a),o!==void 0&&(r.children=o),s!==void 0&&(r.meta={...l.meta,...s}),i!==void 0?(r.alias=i,r.meta={...r.meta,alias:i}):"alias"in e&&(r.alias=void 0,r.meta={...r.meta,alias:void 0}),r}function ee(l){const e=l.alias,t=l.meta?.alias,a=e??t;return Array.isArray(a)?a:[]}function D(l,e,t,a="localized-"){const o=ee(l);if(!o.length)return[];const s=[];for(const i of o){const r=N(e,i,t);s.push(p(l,{path:r,name:`${a}${l.name??""}`,alias:void 0,meta:{alias:void 0},children:l.children}))}return s}class W{processPage(e,t){if(e.path===void 0)throw new Error("page.path is required");if(K(e))return[e];if(e.path&&E(e.path,t.excludePatterns))return[e];const a=e.path??"",o=C(e.name,e.path),s=x(a);return t.globalLocaleRoutes[o]===!1||t.globalLocaleRoutes[s]===!1?[e]:this.generateVariants(e,t)}postProcess(e,t){return e}localizeChildren(e,t,a,o,s,i){return e.flatMap(r=>this.localizeChild(r,t,a,o,s,i))}localizeChildrenAllLocales(e,t,a,o,s){return e.flatMap(i=>this.localizeChildAllLocales(i,t,a,o,s))}localizeChildAllLocales(e,t,a,o,s){const i=z(a,e.path??""),r=z(t,e.path??""),c=j(r),d=s.localizedPaths[c];if(d)return o.flatMap(f=>{const P=d[f]??z(t,e.path??"");return this.localizeChild(e,P,a,f,s,!0)});const n=R(e.path??""),h=g(n),u=this.localizeChildrenAllLocales(b(e.children??[]),r,i,o,s),m=`${s.localizedRouteNamePrefix}${e.name??""}`;return[p(e,{path:h,name:m,children:u})]}localizeChild(e,t,a,o,s,i){const r=z(a,e.path??""),c=s.getCustomPath(r,o),d=g(R(c||(e.path??""))),n=c??z(t,e.path??""),h=this.localizeChildren(b(e.children??[]),n,r,o,s,i),u=C(e.name,e.path),m=`${s.localizedRouteNamePrefix}${u}-${o}`;return[p(e,{path:d,name:m,children:h})]}buildRoutePathForLocales(e,t,a,o,s,i,r){if(o){const c=e.includes(r);return i||!c?N(e,a,s):R(a)}return N(e,t,s)}}class te extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[];if(c.push(e),i)for(const d of s){const n=i[d];if(!n)continue;const h=R(n),u=R(a);if(h===u)continue;const m=I(n),f=F(o,d,!0),P=this.localizeChildrenForNoPrefix(r,h,a,a,d,t,1);c.push(p(e,{path:m,name:f,children:P,alias:[],meta:{alias:[]}})),t.noPrefixRedirect&&d===t.defaultLocale.code&&h!==u&&(e.redirect=h)}return c.push(...D(e,s,t.customRegex,t.localizedRouteNamePrefix)),c}localizeChildrenForNoPrefix(e,t,a,o,s,i,r){return e.map(c=>{const d=z(a,c.path??"");let n,h;if(r===1){const P=i.getCustomPath(d,s);if(P){const L=R(P);n=g(L),h=L}else{const L=R(c.path??"");n=g(L),h=z(t,c.path??"")}}else{const P=R(c.path??"");n=g(P),h=z(t,c.path??"")}const u=this.localizeChildrenForNoPrefix(b(c.children??[]),h,d,o,s,i,r+1),m=C(c.name,c.path),f=F(m,s,!0);return p(c,{path:n,name:f,children:u})})}}function ae(l){const e=l.alias??l.meta?.alias;return Array.isArray(e)?e:[]}class se extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[];if(i)for(const n of s){const h=i[n],u=h?R(h):a,m=N(n,u,t.customRegex),f=F(o,n,!!h,t.localizedRouteNamePrefix),P=h??a,L=this.localizeChildren(r,P,a,n,t,!0);c.push(p(e,{path:m,name:f,children:L,alias:[],meta:{alias:[]}}))}else{const n=N(s,a,t.customRegex),h=F(o,s[0],!1,t.localizedRouteNamePrefix),u=this.localizeChildrenAllLocales(r,a,a,s,t);c.push(p(e,{path:n,name:h,children:u,alias:[],meta:{alias:[]}}))}const d=ae(e);if(d.length)for(const n of d){const h=N(s,n,t.customRegex);c.push(p(e,{path:h,name:`${t.localizedRouteNamePrefix}${e.name??""}`,alias:void 0,meta:{alias:void 0}}))}return c}postProcess(e,t){const a=e.filter(s=>{if(s.name==="index"&&s.path==="/")return!1;const i=s.path??"";return!!(i&&E(i,t.excludePatterns)||t.globalLocaleRoutes[s.name??""]===!1||/^\/:locale/.test(i)||i==="/")}),o=t.defaultLocale.code;for(const[s,i]of Object.entries(t.globalLocaleRoutes)){if(i===!1||typeof i!="object")continue;const r=i[o];if(!r)continue;const c=s.startsWith("/")?s:`/${s}`,d=`/${o}${r.startsWith("/")?r:`/${r}`}`;c!==d&&a.push({path:c,name:`redirect-${s.replace(/\//g,"-")}`,redirect:d})}return t.fallbackRedirectComponentPath&&a.push({path:"/:pathMatch(.*)*",name:"custom-fallback-route",file:t.fallbackRedirectComponentPath,meta:{globalLocaleRoutes:t.rawGlobalLocaleRoutes??t.globalLocaleRoutes}}),a}}class oe extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[],d=t.defaultLocale.code;c.push(e);const n=t.locales.filter(u=>s.includes(u.code));if(n.length>0)if(i)for(const u of n){const m=i[u.code];if(m)if(u.code===d){const f=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!1,u.code,a,t);f&&c.push(f);const P=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!0,u.code,a,t);P&&c.push(P)}else{const f=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!1,u.code,a,t);f&&c.push(f)}else{const f=this.createLocalizedRoute(e,[u.code],r,!1,"",t.customRegex,!1,u.code,a,t);f&&c.push(f)}}else{const u=n.map(f=>f.code),m=this.createLocalizedRoute(e,u,r,!1,"",t.customRegex,!1,!0,a,t);m&&c.push(m)}const h=D(e,s,t.customRegex,t.localizedRouteNamePrefix);return h.length&&c.push(...h),c}postProcess(e,t){const a=[],o=[];for(const s of e){const i=s.name??"";typeof i=="string"&&i.startsWith(t.localizedRouteNamePrefix)?o.push(s):a.push(s)}return[...a,...o]}createLocalizedRoute(e,t,a,o,s="",i,r=!1,c=!1,d,n){const h=this.buildRoutePathForLocales(t,e.path??"",encodeURI(s),o,i,r,n.defaultLocale.code);if(!h||!(o&&s)&&h===e.path||t.length===0)return null;const m=t[0];if(!m)return null;const f=d??e.path??"",P=F(C(e.name??"",f),m,o,n.localizedRouteNamePrefix),L=r||m!==n.defaultLocale.code,y=t.length===1?this.localizeChildren(a,h,f,m,n,L):this.localizeChildrenAllLocales(a,h,f,t,n);return p(e,{path:h,name:P,children:y,alias:[],meta:{alias:[]}})}}class le extends W{generateVariants(e,t){const a=e.path??"",o=C(e.name,e.path),s=t.getAllowedLocales(a,o),i=t.getCustomPathsForPage(a,o),r=b(e.children??[]),c=[],d=t.defaultLocale.code;if(s.includes(d)){const u=i?.[d],m=u?R(u):a,f=u?{[d]:u}:{},P=this.createLocalizedChildren(r,a,[d],!1,!1,!1,f,t);c.push(p(e,{path:m,name:e.name,children:P}))}const n=t.locales.filter(u=>s.includes(u.code)&&u.code!==d);if(n.length)if(i)for(const u of n){const m=i[u.code];if(m){const f=this.createLocalizedRoute(e,[u.code],r,!0,m,t.customRegex,!1,u.code,a,t);f&&c.push(f)}else{const f=this.createLocalizedRoute(e,[u.code],r,!1,"",t.customRegex,!1,u.code,a,t);f&&c.push(f)}}else{const u=n.map(f=>f.code),m=this.createLocalizedRoute(e,u,r,!1,"",t.customRegex,!1,!0,a,t);m&&c.push(m)}const h=D(e,s,t.customRegex,t.localizedRouteNamePrefix);return h.length&&c.push(...h),c}postProcess(e,t){const a=[],o=[];for(const i of e){const r=i.name??"";typeof r=="string"&&r.startsWith(t.localizedRouteNamePrefix)?o.push(i):a.push(i)}const s=[...a,...o];return t.fallbackRedirectComponentPath&&s.push({path:"/:pathMatch(.*)*",name:"custom-fallback-route",file:t.fallbackRedirectComponentPath,meta:{globalLocaleRoutes:t.rawGlobalLocaleRoutes??t.globalLocaleRoutes}}),s}createLocalizedChildren(e,t,a,o=!0,s=!1,i=!1,r={},c){return e.flatMap(d=>this.createLocalizedVariants(d,t,a,o,s,i,r,c))}createLocalizedVariants(e,t,a,o,s,i=!1,r,c){const d=R(e.path??""),n=z(t,e.path??""),h=j(n),u=c.localizedPaths[h],m=!!u,f=[];if(!m){const P=g(d),L=this.createLocalizedChildren(b(e.children??[]),z(t,e.path??""),a,o,s,i,r,c),y=this.buildChildRouteName(e.name,i,c);return f.push(p(e,{path:P,name:y,children:L})),f}for(const P of a){const L=r?.[P],y=!!L,$=u?.[P];let A=R($||(e.path??""));y&&L&&($?A=R($):A=z(L,e.path??""));const v=M(P,c.defaultLocale,s,!1)?N(P,A,c.customRegex):A,q=g(v),G=$?R($):y?L:z(t,e.path??""),B=this.createLocalizedChildren(b(e.children??[]),G,[P],o,s,P,{...r,[P]:G},c),U=this.buildLocalizedRouteName(C(e.name,e.path),P,o,!!u,c);f.push(p(e,{path:q,name:U,children:B}))}return f}buildChildRouteName(e,t,a){return t===!0?`${a.localizedRouteNamePrefix}${e}`:typeof t=="string"?`${a.localizedRouteNamePrefix}${e}-${t}`:e}createLocalizedRoute(e,t,a,o,s="",i,r=!1,c=!1,d,n){const h=this.buildRoutePathForLocales(t,e.path??"",encodeURI(s),o,i,r,n.defaultLocale.code);if(!h||h===e.path||t.length===0)return null;const u=t[0];if(!u)return null;const m=d??e.path??"",f=F(C(e.name??"",m),u,o,n.localizedRouteNamePrefix);return p(e,{path:h,name:f,children:this.createLocalizedChildren(a,m,t,!0,!1,c,{[u]:s},n),alias:[],meta:{alias:[]}})}buildLocalizedRouteName(e,t,a,o=!1,s){return a?o?`${s.localizedRouteNamePrefix}${e}-${t}`:t&&!T(t,s.defaultLocale,!1)?`${s.localizedRouteNamePrefix}${e}-${t}`:`${s.localizedRouteNamePrefix}${e}`:e}}function ie(l){switch(l){case"no_prefix":return new te;case"prefix":return new se;case"prefix_and_default":return new oe;case"prefix_except_default":return new le;default:throw new Error(`Unknown route strategy: ${l}`)}}class re{constructor(e){this.localizedPaths={};const{locales:t,defaultLocaleCode:a,strategy:o,globalLocaleRoutes:s,filesLocaleRoutes:i={},routeLocales:r={},noPrefixRedirect:c,excludePatterns:d,localizedRouteNamePrefix:n="localized-",customRegexMatcher:h,fallbackRedirectComponentPath:u}=e,m=J(t,a);this.locales=m.locales,this.defaultLocale=m.defaultLocale,this.strategy=o,this.noPrefixRedirect=c,this.excludePatterns=d,this.localizedRouteNamePrefix=n,this.customRegex=h,this.fallbackRedirectComponentPath=u,this.activeLocaleCodes=this.computeActiveLocaleCodes();const f={};for(const P in s){const L=x(P),y=s[P];if(typeof y=="object"){const $={};for(const A in y){const v=y[A];v&&($[A]=x(v))}f[L]=$}else f[L]=y}this.globalLocaleRoutes=f,this.rawGlobalLocaleRoutes=s??{},this.filesLocaleRoutes=i??{},this.routeLocales=r??{}}computeActiveLocaleCodes(){return this.locales.filter(e=>e.code!==this.defaultLocale.code||k.isPrefixAndDefaultStrategy(this.strategy)||k.isPrefixStrategy(this.strategy)).map(e=>e.code)}extendPages(e){const t=new Z({locales:this.locales,defaultLocaleCode:this.defaultLocale.code,strategy:this.strategy,globalLocaleRoutes:this.globalLocaleRoutes,filesLocaleRoutes:this.filesLocaleRoutes,routeLocales:this.routeLocales,pages:e,excludePatterns:this.excludePatterns,customRegex:this.customRegex,noPrefixRedirect:this.noPrefixRedirect,localizedRouteNamePrefix:this.localizedRouteNamePrefix,fallbackRedirectComponentPath:this.fallbackRedirectComponentPath,rawGlobalLocaleRoutes:this.rawGlobalLocaleRoutes});this.localizedPaths=t.localizedPaths;const a=ie(this.strategy),o=[...e],s=[];for(const r of o)s.push(...a.processPage(r,t));const i=a.postProcess(s,t);e.length=0,e.push(...i)}extractLocalizedPaths(e,t=""){return _(e,this.globalLocaleRoutes,this.filesLocaleRoutes,t)}ensureTranslationFilesExist(e,t,a,o){this.locales.forEach(s=>{const i=w.join(a,t,`${s.code}.json`);this.ensureFileExists(i),o||e.forEach(r=>{const c=w.join(a,t,"pages",`${r}/${s.code}.json`);this.ensureFileExists(c)})})}ensureFileExists(e){const t=w.dirname(e);S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),S.existsSync(e)||S.writeFileSync(e,JSON.stringify({}),"utf-8")}resolveLocalizedPath(e,t){const a=x(e),o=g(a)||"/";let s;const i=this.globalLocaleRoutes[o],r=this.globalLocaleRoutes[a];i&&typeof i=="object"&&!Array.isArray(i)?s=i[t]:r&&typeof r=="object"&&!Array.isArray(r)&&(s=r[t]);const c=!!s,d=s?R(s):R(a)||"";let n=!1;if(this.strategy==="no_prefix"?n=!1:this.strategy==="prefix"||this.strategy==="prefix_and_default"?n=!0:this.strategy==="prefix_except_default"&&(n=t!==this.defaultLocale.code),t===this.defaultLocale.code&&!c&&(this.strategy==="prefix_except_default"||this.strategy==="no_prefix")&&(n=!1),!n)return R(d)||"/";const h=g(d);return h?R(`/${t}/${h}`):`/${t}`}generateDataRoutes(e,t,a){const o=[],s=e.map(i=>i.name).filter(i=>typeof i=="string"&&i.length>0);for(const i of this.locales)if(o.push(`/${t}/general/${i.code}/data.json`),!a)for(const r of s)o.push(`/${t}/${r}/${i.code}/data.json`);return o}}exports.RouteGenerator=re;exports.buildFullPath=N;exports.buildFullPathNoPrefix=I;exports.buildRouteName=F;exports.cloneArray=b;exports.extractLocalizedPaths=_;exports.isInternalPath=E;exports.isLocaleDefault=T;exports.isPageRedirectOnly=K;exports.normalizePath=R;exports.normalizeRouteKey=x;exports.removeLeadingSlash=g;exports.shouldAddLocalePrefix=M;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { RouteGenerator, RouteGeneratorOptions } from './route-generator';
2
1
  import { extractLocalizedPaths, LocalizedPathsMap } from './core/localized-paths';
3
- import { isInternalPath, normalizeRouteKey, normalizePath, cloneArray, isPageRedirectOnly, removeLeadingSlash, buildRouteName, shouldAddLocalePrefix, isLocaleDefault, buildFullPath, buildFullPathNoPrefix } from './utils';
2
+ import { RouteGenerator, RouteGeneratorOptions } from './route-generator';
3
+ import { buildFullPath, buildFullPathNoPrefix, buildRouteName, cloneArray, isInternalPath, isLocaleDefault, isPageRedirectOnly, normalizePath, normalizeRouteKey, removeLeadingSlash, shouldAddLocalePrefix } from './utils';
4
4
  export { RouteGenerator, type RouteGeneratorOptions, extractLocalizedPaths, type LocalizedPathsMap, isInternalPath, normalizeRouteKey, normalizePath, cloneArray, isPageRedirectOnly, removeLeadingSlash, buildRouteName, shouldAddLocalePrefix, isLocaleDefault, buildFullPath, buildFullPathNoPrefix, };
package/dist/index.mjs CHANGED
@@ -1,34 +1,7 @@
1
1
  import N from "node:path";
2
2
  import { existsSync as E, mkdirSync as B, writeFileSync as U } from "node:fs";
3
3
  import { isPrefixAndDefaultStrategy as D, isPrefixStrategy as O } from "@i18n-micro/core";
4
- function w(l) {
5
- return l.split("/").map((e) => e.startsWith("[...") && e.endsWith("]") ? `:${e.substring(4, e.length - 1)}(.*)*` : e.startsWith("[") && e.endsWith("]") ? `:${e.substring(1, e.length - 1)}` : e).join("/");
6
- }
7
- const R = (l) => {
8
- if (!l)
9
- return "";
10
- const e = N.posix.normalize(l).replace(/\/+$/, "");
11
- return e === "." ? "" : e;
12
- }, y = (l) => l.startsWith("/") ? l.slice(1) : l;
13
- function G(...l) {
14
- return N.posix.join(...l);
15
- }
16
- function q(l) {
17
- if (!(typeof l > "u"))
18
- return l.startsWith("/") && l.endsWith("/") ? l?.slice(1, -1) : l;
19
- }
20
- function K(l) {
21
- return !l || !/[\u0080-\uFFFF]/.test(l) ? l : l.split("/").map((e) => !e || e.startsWith(":") || !/[\u0080-\uFFFF]/.test(e) ? e : encodeURI(e)).join("/");
22
- }
23
- function A(l, e, t) {
24
- const a = q(t?.toString()), o = a || (Array.isArray(l) ? l.join("|") : l), s = K(e);
25
- return R(N.posix.join("/", `:locale(${o})`, s));
26
- }
27
- function H(l) {
28
- const e = K(l);
29
- return R(e);
30
- }
31
- const $ = (l) => l.map((e) => ({ ...e })), J = (l) => !!(l.redirect && !l.file), j = (l, e, t, a = "localized-") => t ? `${a}${l}-${e}` : `${a}${l}`, b = (l, e) => l ?? (e ?? "").replace(/[^a-z0-9]/gi, "-").replace(/^-+|-+$/g, ""), Q = (l, e, t, a) => t && !(l === e.code && !a), X = (l, e, t) => (typeof l == "string" ? l : l.code) === e.code && !t, Y = [
4
+ const $ = (l) => l.map((e) => ({ ...e })), q = (l) => !!(l.redirect && !l.file), j = (l, e, t, a = "localized-") => t ? `${a}${l}-${e}` : `${a}${l}`, b = (l, e) => l ?? (e ?? "").replace(/[^a-z0-9]/gi, "-").replace(/^-+|-+$/g, ""), H = (l, e, t, a) => t && !(l === e.code && !a), J = (l, e, t) => (typeof l == "string" ? l : l.code) === e.code && !t, Q = [
32
5
  /^\/sitemap.*\.xml$/,
33
6
  /^\/sitemap\.xml$/,
34
7
  /^\/robots\.txt$/,
@@ -39,10 +12,10 @@ const $ = (l) => l.map((e) => ({ ...e })), J = (l) => !!(l.redirect && !l.file),
39
12
  /^\/workbox-.*\.js$/,
40
13
  /\.(xml|txt|ico|json|js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/
41
14
  ];
42
- function M(l, e) {
15
+ function K(l, e) {
43
16
  if (/(?:^|\/)__[^/]+/.test(l))
44
17
  return !0;
45
- for (const t of Y)
18
+ for (const t of Q)
46
19
  if (t.test(l))
47
20
  return !0;
48
21
  if (e) {
@@ -57,13 +30,40 @@ function M(l, e) {
57
30
  }
58
31
  return !1;
59
32
  }
60
- function Z(l, e) {
33
+ function X(l, e) {
61
34
  const t = l.reduce((o, s) => {
62
35
  const i = o.find((r) => r.code === s.code);
63
36
  return i ? Object.assign(i, s) : o.push(s), o;
64
37
  }, []).filter((o) => !o.disabled), a = t.find((o) => o.code === e) ?? { code: e };
65
38
  return { locales: t, defaultLocale: a };
66
39
  }
40
+ function w(l) {
41
+ return l.split("/").map((e) => e.startsWith("[...") && e.endsWith("]") ? `:${e.substring(4, e.length - 1)}(.*)*` : e.startsWith("[") && e.endsWith("]") ? `:${e.substring(1, e.length - 1)}` : e).join("/");
42
+ }
43
+ const R = (l) => {
44
+ if (!l)
45
+ return "";
46
+ const e = N.posix.normalize(l).replace(/\/+$/, "");
47
+ return e === "." ? "" : e;
48
+ }, y = (l) => l.startsWith("/") ? l.slice(1) : l;
49
+ function G(...l) {
50
+ return N.posix.join(...l);
51
+ }
52
+ function Y(l) {
53
+ if (!(typeof l > "u"))
54
+ return l.startsWith("/") && l.endsWith("/") ? l?.slice(1, -1) : l;
55
+ }
56
+ function M(l) {
57
+ return !l || !/[\u0080-\uFFFF]/.test(l) ? l : l.split("/").map((e) => !e || e.startsWith(":") || !/[\u0080-\uFFFF]/.test(e) ? e : encodeURI(e)).join("/");
58
+ }
59
+ function A(l, e, t) {
60
+ const a = Y(t?.toString()), o = a || (Array.isArray(l) ? l.join("|") : l), s = M(e);
61
+ return R(N.posix.join("/", `:locale(${o})`, s));
62
+ }
63
+ function Z(l) {
64
+ const e = M(l);
65
+ return R(e);
66
+ }
67
67
  const ee = (l, e) => l ?? (e ?? "").replace(/[^a-z0-9]/gi, "-").replace(/^-+|-+$/g, "");
68
68
  function F(l) {
69
69
  return y(l) || "/";
@@ -103,13 +103,7 @@ function te(l) {
103
103
  }
104
104
  class ae {
105
105
  constructor(e) {
106
- this.locales = e.locales, this.defaultLocale = this.findLocaleByCode(e.locales, e.defaultLocaleCode) ?? { code: e.defaultLocaleCode }, this.strategy = e.strategy, this.globalLocaleRoutes = te(e.globalLocaleRoutes ?? {}), this.filesLocaleRoutes = e.filesLocaleRoutes ?? {}, this.routeLocales = e.routeLocales ?? {}, this.localizedPaths = S(
107
- e.pages,
108
- this.globalLocaleRoutes,
109
- this.filesLocaleRoutes
110
- ), this.activeLocaleCodes = this.locales.filter(
111
- (t) => t.code !== this.defaultLocale.code || D(this.strategy) || O(this.strategy)
112
- ).map((t) => t.code), this.excludePatterns = e.excludePatterns, this.customRegex = e.customRegex, this.noPrefixRedirect = e.noPrefixRedirect ?? !1, this.localizedRouteNamePrefix = e.localizedRouteNamePrefix ?? "localized-", this.fallbackRedirectComponentPath = e.fallbackRedirectComponentPath, this.rawGlobalLocaleRoutes = e.rawGlobalLocaleRoutes;
106
+ this.locales = e.locales, this.defaultLocale = this.findLocaleByCode(e.locales, e.defaultLocaleCode) ?? { code: e.defaultLocaleCode }, this.strategy = e.strategy, this.globalLocaleRoutes = te(e.globalLocaleRoutes ?? {}), this.filesLocaleRoutes = e.filesLocaleRoutes ?? {}, this.routeLocales = e.routeLocales ?? {}, this.localizedPaths = S(e.pages, this.globalLocaleRoutes, this.filesLocaleRoutes), this.activeLocaleCodes = this.locales.filter((t) => t.code !== this.defaultLocale.code || D(this.strategy) || O(this.strategy)).map((t) => t.code), this.excludePatterns = e.excludePatterns, this.customRegex = e.customRegex, this.noPrefixRedirect = e.noPrefixRedirect ?? !1, this.localizedRouteNamePrefix = e.localizedRouteNamePrefix ?? "localized-", this.fallbackRedirectComponentPath = e.fallbackRedirectComponentPath, this.rawGlobalLocaleRoutes = e.rawGlobalLocaleRoutes;
113
107
  }
114
108
  findLocaleByCode(e, t) {
115
109
  return e.find((a) => a.code === t);
@@ -119,9 +113,7 @@ class ae {
119
113
  */
120
114
  getAllowedLocales(e, t) {
121
115
  const a = this.routeLocales[e] ?? this.routeLocales[t];
122
- return a?.length ? a.filter(
123
- (o) => this.locales.some((s) => s.code === o)
124
- ) : this.locales.map((o) => o.code);
116
+ return a?.length ? a.filter((o) => this.locales.some((s) => s.code === o)) : this.locales.map((o) => o.code);
125
117
  }
126
118
  /**
127
119
  * Returns a custom path for a given locale by original page path, if any.
@@ -185,9 +177,9 @@ class k {
185
177
  processPage(e, t) {
186
178
  if (e.path === void 0)
187
179
  throw new Error("page.path is required");
188
- if (J(e))
180
+ if (q(e))
189
181
  return [e];
190
- if (e.path && M(e.path, t.excludePatterns))
182
+ if (e.path && K(e.path, t.excludePatterns))
191
183
  return [e];
192
184
  const a = e.path ?? "", o = b(e.name, e.path), s = w(a);
193
185
  return t.globalLocaleRoutes[o] === !1 || t.globalLocaleRoutes[s] === !1 ? [e] : this.generateVariants(e, t);
@@ -218,13 +210,7 @@ class k {
218
210
  const P = d[f] ?? z(t, e.path ?? "");
219
211
  return this.localizeChild(e, P, a, f, s, !0);
220
212
  });
221
- const n = R(e.path ?? ""), h = y(n), u = this.localizeChildrenAllLocales(
222
- $(e.children ?? []),
223
- r,
224
- i,
225
- o,
226
- s
227
- ), m = `${s.localizedRouteNamePrefix}${e.name ?? ""}`;
213
+ const n = R(e.path ?? ""), h = y(n), u = this.localizeChildrenAllLocales($(e.children ?? []), r, i, o, s), m = `${s.localizedRouteNamePrefix}${e.name ?? ""}`;
228
214
  return [
229
215
  p(e, {
230
216
  path: h,
@@ -234,14 +220,7 @@ class k {
234
220
  ];
235
221
  }
236
222
  localizeChild(e, t, a, o, s, i) {
237
- const r = z(a, e.path ?? ""), c = s.getCustomPath(r, o), d = y(R(c || (e.path ?? ""))), n = c ?? z(t, e.path ?? ""), h = this.localizeChildren(
238
- $(e.children ?? []),
239
- n,
240
- r,
241
- o,
242
- s,
243
- i
244
- ), u = b(e.name, e.path), m = `${s.localizedRouteNamePrefix}${u}-${o}`;
223
+ const r = z(a, e.path ?? ""), c = s.getCustomPath(r, o), d = y(R(c || (e.path ?? ""))), n = c ?? z(t, e.path ?? ""), h = this.localizeChildren($(e.children ?? []), n, r, o, s, i), u = b(e.name, e.path), m = `${s.localizedRouteNamePrefix}${u}-${o}`;
245
224
  return [
246
225
  p(e, {
247
226
  path: d,
@@ -275,15 +254,7 @@ class oe extends k {
275
254
  const h = R(n), u = R(a);
276
255
  if (h === u)
277
256
  continue;
278
- const m = H(n), f = j(o, d, !0), P = this.localizeChildrenForNoPrefix(
279
- r,
280
- h,
281
- a,
282
- a,
283
- d,
284
- t,
285
- 1
286
- );
257
+ const m = Z(n), f = j(o, d, !0), P = this.localizeChildrenForNoPrefix(r, h, a, a, d, t, 1);
287
258
  c.push(
288
259
  p(e, {
289
260
  path: m,
@@ -345,14 +316,7 @@ class ie extends k {
345
316
  const a = e.path ?? "", o = b(e.name, e.path), s = t.getAllowedLocales(a, o), i = t.getCustomPathsForPage(a, o), r = $(e.children ?? []), c = [];
346
317
  if (i)
347
318
  for (const n of s) {
348
- const h = i[n], u = h ? R(h) : a, m = A(n, u, t.customRegex), f = j(o, n, !!h, t.localizedRouteNamePrefix), P = h ?? a, L = this.localizeChildren(
349
- r,
350
- P,
351
- a,
352
- n,
353
- t,
354
- !0
355
- );
319
+ const h = i[n], u = h ? R(h) : a, m = A(n, u, t.customRegex), f = j(o, n, !!h, t.localizedRouteNamePrefix), P = h ?? a, L = this.localizeChildren(r, P, a, n, t, !0);
356
320
  c.push(
357
321
  p(e, {
358
322
  path: m,
@@ -364,13 +328,7 @@ class ie extends k {
364
328
  );
365
329
  }
366
330
  else {
367
- const n = A(s, a, t.customRegex), h = j(o, s[0], !1, t.localizedRouteNamePrefix), u = this.localizeChildrenAllLocales(
368
- r,
369
- a,
370
- a,
371
- s,
372
- t
373
- );
331
+ const n = A(s, a, t.customRegex), h = j(o, s[0], !1, t.localizedRouteNamePrefix), u = this.localizeChildrenAllLocales(r, a, a, s, t);
374
332
  c.push(
375
333
  p(e, {
376
334
  path: n,
@@ -400,7 +358,7 @@ class ie extends k {
400
358
  const a = e.filter((s) => {
401
359
  if (s.name === "index" && s.path === "/") return !1;
402
360
  const i = s.path ?? "";
403
- return !!(i && M(i, t.excludePatterns) || t.globalLocaleRoutes[s.name ?? ""] === !1 || /^\/:locale/.test(i) || i === "/");
361
+ return !!(i && K(i, t.excludePatterns) || t.globalLocaleRoutes[s.name ?? ""] === !1 || /^\/:locale/.test(i) || i === "/");
404
362
  }), o = t.defaultLocale.code;
405
363
  for (const [s, i] of Object.entries(t.globalLocaleRoutes)) {
406
364
  if (i === !1 || typeof i != "object") continue;
@@ -530,7 +488,12 @@ class re extends k {
530
488
  if (!h || !(o && s) && h === e.path || t.length === 0) return null;
531
489
  const m = t[0];
532
490
  if (!m) return null;
533
- const f = d ?? e.path ?? "", P = j(b(e.name ?? "", f), m, o, n.localizedRouteNamePrefix), L = r || m !== n.defaultLocale.code, g = t.length === 1 ? this.localizeChildren(a, h, f, m, n, L) : this.localizeChildrenAllLocales(a, h, f, t, n);
491
+ const f = d ?? e.path ?? "", P = j(
492
+ b(e.name ?? "", f),
493
+ m,
494
+ o,
495
+ n.localizedRouteNamePrefix
496
+ ), L = r || m !== n.defaultLocale.code, g = t.length === 1 ? this.localizeChildren(a, h, f, m, n, L) : this.localizeChildrenAllLocales(a, h, f, t, n);
534
497
  return p(e, {
535
498
  path: h,
536
499
  name: P,
@@ -562,9 +525,7 @@ class ce extends k {
562
525
  })
563
526
  );
564
527
  }
565
- const n = t.locales.filter(
566
- (u) => s.includes(u.code) && u.code !== d
567
- );
528
+ const n = t.locales.filter((u) => s.includes(u.code) && u.code !== d);
568
529
  if (n.length)
569
530
  if (i)
570
531
  for (const u of n) {
@@ -635,16 +596,7 @@ class ce extends k {
635
596
  }
636
597
  createLocalizedChildren(e, t, a, o = !0, s = !1, i = !1, r = {}, c) {
637
598
  return e.flatMap(
638
- (d) => this.createLocalizedVariants(
639
- d,
640
- t,
641
- a,
642
- o,
643
- s,
644
- i,
645
- r,
646
- c
647
- )
599
+ (d) => this.createLocalizedVariants(d, t, a, o, s, i, r, c)
648
600
  );
649
601
  }
650
602
  createLocalizedVariants(e, t, a, o, s, i = !1, r, c) {
@@ -672,12 +624,7 @@ class ce extends k {
672
624
  const L = r?.[P], g = !!L, C = u?.[P];
673
625
  let x = R(C || (e.path ?? ""));
674
626
  g && L && (C ? x = R(C) : x = z(L, e.path ?? ""));
675
- const v = Q(
676
- P,
677
- c.defaultLocale,
678
- s,
679
- !1
680
- ) ? A(P, x, c.customRegex) : x, T = y(v), W = C ? R(C) : g ? L : z(t, e.path ?? ""), V = this.createLocalizedChildren(
627
+ const v = H(P, c.defaultLocale, s, !1) ? A(P, x, c.customRegex) : x, T = y(v), W = C ? R(C) : g ? L : z(t, e.path ?? ""), V = this.createLocalizedChildren(
681
628
  $(e.children ?? []),
682
629
  W,
683
630
  [P],
@@ -722,7 +669,12 @@ class ce extends k {
722
669
  if (!h || h === e.path || t.length === 0) return null;
723
670
  const u = t[0];
724
671
  if (!u) return null;
725
- const m = d ?? e.path ?? "", f = j(b(e.name ?? "", m), u, o, n.localizedRouteNamePrefix);
672
+ const m = d ?? e.path ?? "", f = j(
673
+ b(e.name ?? "", m),
674
+ u,
675
+ o,
676
+ n.localizedRouteNamePrefix
677
+ );
726
678
  return p(e, {
727
679
  path: h,
728
680
  name: f,
@@ -741,7 +693,7 @@ class ce extends k {
741
693
  });
742
694
  }
743
695
  buildLocalizedRouteName(e, t, a, o = !1, s) {
744
- return a ? o ? `${s.localizedRouteNamePrefix}${e}-${t}` : t && !X(t, s.defaultLocale, !1) ? `${s.localizedRouteNamePrefix}${e}-${t}` : `${s.localizedRouteNamePrefix}${e}` : e;
696
+ return a ? o ? `${s.localizedRouteNamePrefix}${e}-${t}` : t && !J(t, s.defaultLocale, !1) ? `${s.localizedRouteNamePrefix}${e}-${t}` : `${s.localizedRouteNamePrefix}${e}` : e;
745
697
  }
746
698
  }
747
699
  function ne(l) {
@@ -773,7 +725,7 @@ class de {
773
725
  localizedRouteNamePrefix: n = "localized-",
774
726
  customRegexMatcher: h,
775
727
  fallbackRedirectComponentPath: u
776
- } = e, m = Z(t, a);
728
+ } = e, m = X(t, a);
777
729
  this.locales = m.locales, this.defaultLocale = m.defaultLocale, this.strategy = o, this.noPrefixRedirect = c, this.excludePatterns = d, this.localizedRouteNamePrefix = n, this.customRegex = h, this.fallbackRedirectComponentPath = u, this.activeLocaleCodes = this.computeActiveLocaleCodes();
778
730
  const f = {};
779
731
  for (const P in s) {
@@ -817,12 +769,7 @@ class de {
817
769
  e.length = 0, e.push(...i);
818
770
  }
819
771
  extractLocalizedPaths(e, t = "") {
820
- return S(
821
- e,
822
- this.globalLocaleRoutes,
823
- this.filesLocaleRoutes,
824
- t
825
- );
772
+ return S(e, this.globalLocaleRoutes, this.filesLocaleRoutes, t);
826
773
  }
827
774
  /**
828
775
  * Creates global and per-page translation JSON files for the current resolved locales.
@@ -872,15 +819,15 @@ class de {
872
819
  export {
873
820
  de as RouteGenerator,
874
821
  A as buildFullPath,
875
- H as buildFullPathNoPrefix,
822
+ Z as buildFullPathNoPrefix,
876
823
  j as buildRouteName,
877
824
  $ as cloneArray,
878
825
  S as extractLocalizedPaths,
879
- M as isInternalPath,
880
- X as isLocaleDefault,
881
- J as isPageRedirectOnly,
826
+ K as isInternalPath,
827
+ J as isLocaleDefault,
828
+ q as isPageRedirectOnly,
882
829
  R as normalizePath,
883
830
  w as normalizeRouteKey,
884
831
  y as removeLeadingSlash,
885
- Q as shouldAddLocalePrefix
832
+ H as shouldAddLocalePrefix
886
833
  };
@@ -1,7 +1,7 @@
1
- import { NuxtPage } from '@nuxt/schema';
2
1
  import { GlobalLocaleRoutes, Locale, Strategies } from '@i18n-micro/types';
3
- import { LocaleRoutesConfig } from './strategies/types';
2
+ import { NuxtPage } from '@nuxt/schema';
4
3
  import { LocalizedPathsMap } from './core/localized-paths';
4
+ import { LocaleRoutesConfig } from './strategies/types';
5
5
  export interface RouteGeneratorOptions {
6
6
  locales: Locale[];
7
7
  defaultLocaleCode: string;
@@ -1,5 +1,5 @@
1
- import { NuxtPage } from '@nuxt/schema';
2
1
  import { Locale } from '@i18n-micro/types';
2
+ import { NuxtPage } from '@nuxt/schema';
3
3
  export declare const cloneArray: <T extends object>(array: T[]) => T[];
4
4
  export declare const isPageRedirectOnly: (page: NuxtPage) => boolean;
5
5
  export declare const buildRouteName: (baseName: string, localeCode: string, isCustom: boolean, prefix?: string) => string;
@@ -1,3 +1,3 @@
1
- export { normalizePath, normalizeRouteKey, removeLeadingSlash, joinPath, buildFullPath, buildFullPathNoPrefix, } from './path';
2
- export { cloneArray, isPageRedirectOnly, buildRouteName, buildRouteNameFromRoute, shouldAddLocalePrefix, isLocaleDefault, isInternalPath, } from './common';
3
- export { resolveLocales, type ResolvedLocales } from './locales';
1
+ export { buildRouteName, buildRouteNameFromRoute, cloneArray, isInternalPath, isLocaleDefault, isPageRedirectOnly, shouldAddLocalePrefix, } from './common';
2
+ export { type ResolvedLocales, resolveLocales } from './locales';
3
+ export { buildFullPath, buildFullPathNoPrefix, joinPath, normalizePath, normalizeRouteKey, removeLeadingSlash, } from './path';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@i18n-micro/route-strategy",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Locale-aware route generator for Nuxt i18n micro",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -55,8 +55,8 @@
55
55
  "sideEffects": false,
56
56
  "dependencies": {
57
57
  "@nuxt/schema": "^3.18.1 || ^4.0.0",
58
- "@i18n-micro/core": "1.1.1",
59
- "@i18n-micro/types": "1.1.0"
58
+ "@i18n-micro/types": "1.1.1",
59
+ "@i18n-micro/core": "1.1.2"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/jest": "^29.5.14",