UNPKG

next-wayfinder

Version:

Apply multiple next.js middlewares with ease

2 lines (1 loc) 1.9 kB
import{a as x,d as g,e as P,g as b,h as T,i as R}from"./chunk-4BQ5CTJK.mjs";import{a as i}from"./chunk-PICCCJ5T.mjs";import{NextResponse as u}from"next/server";import{match as N}from"ts-pattern";var k=h=>x(h).hostname;function y(h,{response:l,...e}={}){return async function(a,o){var w;e.debug&&e.beforeAll&&console.debug("[BeforeAll] >> Executing...");let c;l instanceof Function?c=l(a,o):l?c=l:c=u.next();let d=await((w=e.beforeAll)==null?void 0:w.call(e,a,c))||c;if(d.redirected)return e.debug&&console.debug("[BeforeAll] >> Redirected!"),d;let{pathname:m,hostname:p}=((e==null?void 0:e.parser)??x)(a),t=g(h,{path:m,hostname:p,method:a.method.toUpperCase()});if(e!=null&&e.debug&&(console.debug(`Middleware ${t?"":"Not "}Found!`),t&&console.debug(t)),!t)return d;if(e!=null&&e.context){let r;e.context instanceof Function?r=await e.context(a):r=e.context,e.debug&&console.debug("[Context] >> Injecting: ",r),b(a,r),e.debug&&console.debug("[Context] >> Injected: ",a.ctx)}if(i.isRewrite(t)||i.isRedirect(t)){let r=T(a,t.path,m),n=r.nextUrl.clone();return n.pathname=N(t).when(i.isRedirect,s=>s.redirectTo instanceof Function?s.redirectTo(r):R(s.redirectTo,r.params)).when(i.isRewrite,s=>s.rewriteTo instanceof Function?s.rewriteTo(r):R(s.rewriteTo,r.params)).otherwise(()=>""),i.isRewrite(t)?u.rewrite(n):(t.includeOrigin&&n.searchParams.set(t.includeOrigin===!0?"origin":t.includeOrigin,r.nextUrl.pathname),u.redirect(n))}if(Array.isArray(t.handler))return y(t.handler,e)(a,o);if(i.isHostname(t))return Object.defineProperty(a,"params",P({})),t.handler(a,d,o);let f=T(a,t.path,m);if(t.pre){let r=await t.pre(f);if(r!==!0){if(!r)return d;if(typeof r.redirectTo=="string"){let n=f.nextUrl.clone();return n.pathname=r.redirectTo,u.redirect(n,{status:r.statusCode})}return u.redirect(new URL(r.redirectTo,f.nextUrl),{status:r.statusCode})}}return t.handler(f,d,o)}}export{k as getHost,y as handlePaths};