UNPKG

@vulppi/intrest

Version:
3 lines (2 loc) 7.39 kB
import{parentPort as U}from"worker_threads";import{createReadStream as Y}from"fs";import{StatusCodes as T}from"http-status-codes";import z from"lodash";import{lookup as Z}from"mime-types";import{join as x}from"path";import{unescape as q}from"querystring";import{pathToFileURL as F}from"url";var _=()=>process.env.NODE_ENV==="development",P={env:[".env",".env{.local,.development,.production}"],entryFolder:["routes","src/routes"],assetsFolder:["assets","src/assets"],staticFolder:["static","src/static","public","src/public"],configFile:"intrest.config.{mjs,cjs,js}",envFile:".env{.local,.development,.production}",bootstrapEntry:"bootstrap.ts",bootstrapCompiled:"bootstrap.mjs",entryPoints:"**/{route,middleware,validation}.ts",identityPoints:"**/__identity.mjs",middlewarePoints:"**/middleware.mjs",routeFile:"route.{mjs,cjs,js,ts}",middlewareFile:"middleware.{mjs,cjs,js,ts}"};var f={compiledFolder:".intrest",compiledRoutes:"routes",workerMultiWorker:"multi.mjs",workerSingleWorker:"single.mjs",workerRouter:"router.mjs",routeIdentity:"__identity.mjs"};import{glob as S}from"glob";import{join as C,normalize as H}from"path";function p(t){return H(t).replace(/[\/\\]+/g,"/")}async function O(...t){let n=await S(p(C(...t)),{ignore:["**/node_modules/**"],windowsPathsNoEscape:!0});return n[0]&&p(n[0])}async function b(...t){return(await S(p(C(...t)),{ignore:["**/node_modules/**"],windowsPathsNoEscape:!0})).map(p)}async function K(...t){let n=t.map(e=>p(C(...e)));return(await S(n.reverse(),{ignore:["**/node_modules/**"],windowsPathsNoEscape:!0})).map(p)}async function L(t,n){return(await K(...n.map(r=>[t,r])))[0]||n[1]}function E(t){return _()?`${t}?update=${Date.now()}`:t}import{StatusCodes as $}from"http-status-codes";import k from"lodash";import X from"range-parser";import{Readable as Q}from"stream";import{isAnyArrayBuffer as V,isUint16Array as W,isUint32Array as G,isUint8Array as J}from"util/types";function N(t){return!!(V(t)||J(t)||W(t)||G(t))}function v(t){return!!(t&&Array.isArray(t)&&t.length&&t.type==="bytes")}async function D(t,n,r,e){let o=Object.keys(t.headers||{}).find(s=>/^content-length$/i.test(s)),l=Object.keys(t.headers||{}).find(s=>/^content-type$/i.test(s)),a=k.get(t.headers||{},o||"Content-Length",1/0),c=k.get(t.headers||{},l||"Content-Type"),d=n.range?X(+a,n.range,{combine:!0}):void 0;v(d)&&(t.status=!t.status||t.status===$.OK?$.PARTIAL_CONTENT:t.status,t.headers={...t.headers,"Content-Range":`bytes ${d[0].start}-${d[0].end}`+(a&&isFinite(+a)?`/${a}`:"")},delete t.headers[o||"Content-Length"]);for(let s of Object.entries(t.headers||{}))e({requestId:r,state:"set",data:s});for(let[s,i]of Object.entries(t.cookies||{}))if(Array.isArray(i))for(let m of i)e({requestId:r,state:"cookie",data:{name:s,value:m.value,options:m.options}});else e({requestId:r,state:"cookie",data:{name:s,value:i.value,options:i.options}});for(let[s,i]of Object.entries(t.clearCookies||{}))if(Array.isArray(i))for(let m of i)e({requestId:r,state:"clear-cookie",data:{name:s,options:m}});else e({requestId:r,state:"clear-cookie",data:{name:s,options:i}});if(e({requestId:r,state:"status",data:t.status||$.OK}),t.body)if(typeof t.body=="string"||N(t.body)){c||e({requestId:r,state:"set",data:["Content-Type","text/plain"]});let s=Buffer.from(t.body);v(d)?e({requestId:r,state:"write",data:s.subarray(d[0].start,d[0].end+1)}):e({requestId:r,state:"write",data:s})}else if(t.body instanceof Q){c||e({requestId:r,state:"set",data:["Content-Type","application/octet-stream"]});let s=t.body;if(v(d)){let i=d[0].start,m=d[0].end,u=0;await new Promise((j,A)=>{s.on("data",R=>{let h=Buffer.from(R);if(h.length+u<i){u+=h.length;return}if(u>m)return s.destroy(),j();let g=Math.max(i-u,0),y=Math.min(m+1-u,h.length);u+=y;let B=h.subarray(g,g+y);e({requestId:r,state:"write",data:B})}),s.on("end",()=>{j()}),s.on("error",R=>{A(R)})})}else await new Promise((i,m)=>{s.on("data",u=>{e({requestId:r,state:"write",data:u})}),s.on("end",()=>{i()}),s.on("error",u=>{m(u)})})}else{c||e({requestId:r,state:"set",data:["Content-Type","application/json"]});let s=JSON.stringify(t.body),i=Buffer.from(s);v(d)?e({requestId:r,state:"write",data:i.subarray(d[0].start,d[0].end+1)}):e({requestId:r,state:"write",data:i})}e({requestId:r,state:"end",data:void 0})}async function M({data:t,config:n,basePath:r},e){let o={...t,params:{},query:new URLSearchParams(t.query||"")},l=await L(r,P.staticFolder);if(l){let a=await O(l,o.path);if(a){let c=Z(a);if(c)return await w({status:T.OK,body:Y(a),headers:{"Content-Type":c}},o.headers,e)}}try{let a=await tt(o.path);if(!a.length)return await w({status:T.NOT_FOUND,body:{message:n.messages?.NOT_FOUND||"Not found"},headers:{"Content-Type":"application/json"}},o.headers,e);let c=o.method,d=p(x(f.compiledFolder,f.compiledRoutes)),i=(await Promise.all(a.map(async g=>{let y=await import(E(F(p(x(d,g.pathname,"route.mjs"))).toString()));return{handler:y[c]||y.ALL||y.default,identity:g}}))).find(g=>typeof g.handler=="function");if(!i?.handler)return await w({status:T.METHOD_NOT_ALLOWED,body:{message:n.messages?.METHOD_NOT_ALLOWED||"Method not allowed"},headers:{"Content-Type":"application/json"}},o.headers,e);let m=i.identity.paramExtract,u=i.identity.pathname,j=i.identity.paramKeys,A=Array.from(t.path.match(m)||[]).slice(1);o.params=z.zipObject(j,A.map(q));let R=await et(u),h=await I({middlewares:R,context:o,config:n,requestHandler:i.handler});if(!h)throw new Error("Response not found");return await w(h,o.headers,e)}catch(a){if(console.error(a),a instanceof Error)return await w({status:T.INTERNAL_SERVER_ERROR,body:{message:a.message},headers:{"Content-Type":"application/json"}},o.headers,e);if(typeof a=="object"&&a!=null)return await w(a,o.headers,e);throw a}}async function w(t,n,r){return await D(t,n,"void",e=>{let{state:o,data:l}=e;r(o,l)})}async function tt(t){let n=p(x(process.cwd(),f.compiledFolder,f.compiledRoutes)),r=await b(n,P.identityPoints);return(await Promise.all(r.map(o=>import(E(F(o).toString())).then(l=>l)))).filter(o=>o.paramExtract.test(t)).sort((o,l)=>o.pathname>l.pathname?1:-1).sort(rt)}async function et(t){let n=p(x(process.cwd(),f.compiledFolder,f.compiledRoutes)),r=t.split("/").map((a,c,d)=>c>0?d.slice(0,c+1).join("/"):"/").map(a=>p(x(n,a,"middleware.mjs"))),o=(await b(n,P.middlewarePoints)).filter(a=>r.some(c=>a===c));return(await Promise.all(o.map(async a=>({handler:await import(E(F(a).toString())).then(c=>c.middleware||c.default),pathname:a.replace(n,"")})))).filter(a=>typeof a.handler=="function")}function rt(t,n){let r=t.pathname.split("/"),e=n.pathname.split("/");for(let o=0;o<r.length;o++)if(!(r[o][0]==="["&&e[o]?.[0]==="[")){if(r[o][0]==="[")return 1;if(e[o]?.[0]==="[")return-1}return n.route.toLowerCase()>t.route.toLowerCase()?-1:n.route.toLowerCase()<t.route.toLowerCase()?1:0}async function I({middlewares:t,context:n,config:r,requestHandler:e}){if(!t.length)return await e(n)||{status:T.NOT_FOUND};let o=t[0],l=setTimeout(()=>{throw new Error(`Middleware handler timeout: ${o.pathname}`)},r.limits?.middleware?.timeout||5e3),a=await o.handler(n,async c=>(clearTimeout(l),n.custom=z.merge(n.custom,c),I({middlewares:t.slice(1),context:n,config:r,requestHandler:e})));return clearTimeout(l),a}U.on("message",async({config:t,basePath:n,data:r,requestId:e})=>{await M({data:r,config:t,basePath:n},(o,l)=>{U?.postMessage({requestId:e,state:o,data:l})})}); //# sourceMappingURL=router.mjs.map