next-redirect-generator
Version:
Tool to generate redirects from Next.js dynamic routes - for use with next export.
8 lines • 1.97 kB
JavaScript
import{resolve as E}from"path";import{writeFileSync as F}from"fs";import{readdirSync as S,statSync as j}from"fs";var A=/(?<=pages\/)(.*)(?=.tsx|jsx)/gm,C=/\[(.*?)\]/gm,p=function(e){let n=[];return S(e).forEach(function(s){s=e+"/"+s;let t=j(s);t&&t.isDirectory()?n=n.concat(p(s)):n.push(s)}),n},u=e=>e.includes("["),l=e=>e.toPath.startsWith("/[..."),f=e=>e.toPath.includes("/[..."),R=(e,n)=>{let i=[];p(e).forEach(t=>{if(!u(t))return;let r;for(;(r=A.exec(t))!==null;){let a=r[0],c=[],m;for(;(m=C.exec(a))!==null;){let o=m[0];o&&c.push(o)}let P=[];a.split("/").forEach(o=>{if(o==="index")return;let $=c.findIndex(h=>h===o),g=c[$];if(g){let h=g.replace(/(\[|\])/gm,"");h.includes("...")?o="*":o=`:${h}`}P.push(o)});let y="/"+P.join("/"),d=[];a.split("/").forEach(o=>{o!=="index"&&d.push(o)});let w="/"+d.join("/")+".html";i.push({fromPath:y,fromPathParts:P,toPath:w,toPathParts:d,status:200})}}),i.sort((t,r)=>{if(l(t)&&!l(r))return 1;if(!l(t)&&l(r))return-1;if(f(t)&&!f(r))return 1;if(!f(t)&&f(r)||t.toPathParts.length>r.toPathParts.length)return-1;if(t.toPathParts.length<r.toPathParts.length)return 1;let a=t.toPathParts[t.toPathParts.length-1],c=r.toPathParts[r.toPathParts.length-1];return u(a)&&!u(c)?1:!u(a)&&u(c)?-1:0});let s="";if(n==="_redirects")i.forEach(t=>{s+=`${t.fromPath} ${t.toPath} ${t.status}
`});else if(n==="json"){let t=i.map(r=>({from:r.fromPath,to:r.toPath,status:r.status}));s=JSON.stringify(t,null," ")}else s=i.map(r=>`[[redirects]]
from = "${r.fromPath}"
to = "${r.toPath}"
status = ${r.status}
`).join(`
`);return s};function x(e){if(!e.cwd)throw new Error("args.cwd is undefined");let n=E(e.cwd,e.path||"pages"),i=e.format||"_redirects",s=R(n,i);if(console.log(`[ Generating redirects from: ${n} to ${e.output||"console"} ]`,`format: ${i}`),s.length===0){console.warn("No dynamic routes found.");return}e.output?F(e.output,s):process.stdout.write(s)}var D=x;export{D as default,R as generateRedirects};
//# sourceMappingURL=index.js.map