blaizejs 0.3.4 → 0.4.0

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.
Files changed (31) hide show
  1. package/dist/chunk-GP5NAYQS.js +11 -0
  2. package/dist/chunk-GP5NAYQS.js.map +1 -0
  3. package/dist/{chunk-EE2VJ6JY.js → chunk-LI53MJIF.js} +3 -3
  4. package/dist/chunk-LI53MJIF.js.map +1 -0
  5. package/dist/{chunk-HSLLYUVO.js → chunk-LMTJAVHX.js} +3 -3
  6. package/dist/chunk-LMTJAVHX.js.map +1 -0
  7. package/dist/{chunk-TL4GIFTB.js → chunk-N7F6OHDX.js} +3 -3
  8. package/dist/chunk-N7F6OHDX.js.map +1 -0
  9. package/dist/{chunk-VLVWNGUO.js → chunk-ORFAFXHX.js} +3 -3
  10. package/dist/chunk-ORFAFXHX.js.map +1 -0
  11. package/dist/index.cjs +9 -9
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +654 -139
  14. package/dist/index.d.ts +654 -139
  15. package/dist/index.js +9 -9
  16. package/dist/index.js.map +1 -1
  17. package/dist/{internal-server-error-GWBNT3OO.js → internal-server-error-DAEFNRNG.js} +3 -3
  18. package/dist/{payload-too-large-error-EBM5BNWG.js → payload-too-large-error-YO3MSQJF.js} +3 -3
  19. package/dist/{unsupported-media-type-error-YQ7GCZ32.js → unsupported-media-type-error-GW2UC37Q.js} +3 -3
  20. package/dist/{validation-error-6JDCGV2S.js → validation-error-SJTLEIZZ.js} +3 -3
  21. package/package.json +4 -4
  22. package/dist/chunk-DTDGIBMA.js +0 -11
  23. package/dist/chunk-DTDGIBMA.js.map +0 -1
  24. package/dist/chunk-EE2VJ6JY.js.map +0 -1
  25. package/dist/chunk-HSLLYUVO.js.map +0 -1
  26. package/dist/chunk-TL4GIFTB.js.map +0 -1
  27. package/dist/chunk-VLVWNGUO.js.map +0 -1
  28. /package/dist/{internal-server-error-GWBNT3OO.js.map → internal-server-error-DAEFNRNG.js.map} +0 -0
  29. /package/dist/{payload-too-large-error-EBM5BNWG.js.map → payload-too-large-error-YO3MSQJF.js.map} +0 -0
  30. /package/dist/{unsupported-media-type-error-YQ7GCZ32.js.map → unsupported-media-type-error-GW2UC37Q.js.map} +0 -0
  31. /package/dist/{validation-error-6JDCGV2S.js.map → validation-error-SJTLEIZZ.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.4
3
+ * blaizejs v0.4.0
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{a as H}from"./chunk-HSLLYUVO.js";import{a as U}from"./chunk-TL4GIFTB.js";import{a as Et}from"./chunk-EE2VJ6JY.js";import{a as Ct}from"./chunk-VLVWNGUO.js";import{a as A,b as B,c as mo,d as S,e as go,f as oe,g as x}from"./chunk-DTDGIBMA.js";function Me(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let o=e.execute(t,r);return o instanceof Promise?o:Promise.resolve(o)}catch(o){return Promise.reject(o)}}function D(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let o=new Set,n=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return Me(s,t,()=>{if(o.has(i))throw new Error("next() called multiple times");return o.add(i),n(i+1)})};return n(0)}}function ne(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:o,debug:n=!1}=e,i={name:t,execute:r,debug:n};return o!==void 0?{...i,skip:o}:i}function ie(e,t,r,o={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof r!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...o,...i},a={name:e,version:t,register:async u=>{let c=await r(u,s);c&&typeof c=="object"&&Object.assign(a,c)}};return a}}import{fileURLToPath as Ft}from"node:url";var V={};function ze(e){V={...V,...e}}function Be(){if(!V.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return V.routesDir}import*as $e from"node:path";function W(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/"),n=o.endsWith("/")?o:`${o}/`,i=r;r.startsWith(n)?i=r.substring(n.length):r.startsWith(o)?(i=r.substring(o.length),i.startsWith("/")&&(i=i.substring(1))):i=$e.relative(o,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],u=s.map(w=>{if(w.startsWith("[")&&w.endsWith("]")){let d=w.slice(1,-1);return a.push(d),`:${d}`}return w}),c=u.length>0?`/${u.join("/")}`:"/";return c.endsWith("/index")&&(c=c.slice(0,-6)||"/"),{filePath:e,routePath:c,params:a}}function Mt(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let o=r.getFileName();if(!o)throw new Error("Unable to determine caller file name");return o.startsWith("file://")?Ft(o):o}finally{Error.prepareStackTrace=e}}function $(){let e=Mt(),t=Be(),r=W(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var Oe=e=>{O("GET",e);let t=$();return{GET:e,path:t}},ke=e=>{O("POST",e);let t=$();return{POST:e,path:t}},De=e=>{O("PUT",e);let t=$();return{PUT:e,path:t}},Ne=e=>{O("DELETE",e);let t=$();return{DELETE:e,path:t}},Ae=e=>{O("PATCH",e);let t=$();return{PATCH:e,path:t}},He=e=>{O("HEAD",e);let t=$();return{HEAD:e,path:t}},Ue=e=>{O("OPTIONS",e);let t=$();return{OPTIONS:e,path:t}};function O(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&zt(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function zt(e,t){let{params:r,query:o,body:n,response:i}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}import{AsyncLocalStorage as Xr}from"node:async_hooks";import Kr from"node:events";import*as ae from"node:fs";import*as it from"node:http";import*as st from"node:http2";import*as E from"node:fs";import*as G from"node:path";import*as qe from"selfsigned";async function Ie(){let e=G.join(process.cwd(),".blaizejs","certs"),t=G.join(e,"dev.key"),r=G.join(e,"dev.cert");if(E.existsSync(t)&&E.existsSync(r))return{keyFile:t,certFile:r};E.existsSync(e)||E.mkdirSync(e,{recursive:!0});let i=qe.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return E.writeFileSync(t,Buffer.from(i.private,"utf-8")),E.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
10
+ import{a as I}from"./chunk-LMTJAVHX.js";import{a as H}from"./chunk-N7F6OHDX.js";import{a as Ot}from"./chunk-LI53MJIF.js";import{a as Nt}from"./chunk-ORFAFXHX.js";import{a as D,b as qe,c as z,d as w,e as _e,f as Z,g as B,h as Pn,i as v,j as bn}from"./chunk-GP5NAYQS.js";function je(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let n=e.execute(t,r);return n instanceof Promise?n:Promise.resolve(n)}catch(n){return Promise.reject(n)}}function A(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let n=new Set,i=async o=>{if(o>=e.length)return Promise.resolve(r());let s=e[o];return je(s,t,()=>{if(n.has(o))throw new Error("next() called multiple times");return n.add(o),i(o+1)})};return i(0)}}function q(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:n,debug:i=!1}=e;return{name:t,execute:r,debug:i,...n!==void 0&&{skip:n}}}function ae(e){return q({name:"state-middleware",handler:e})}function ue(e){return q({name:"service-middleware",handler:e})}function ce(e,t,r,n={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof r!="function")throw new Error("Plugin setup must be a function");return function(o){let s={...n,...o},a={name:e,version:t,register:async u=>{let l=await r(u,s);l&&typeof l=="object"&&Object.assign(a,l)}};return a}}import{fileURLToPath as At}from"node:url";var J={};function Le(e){J={...J,...e}}function Qe(){if(!J.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return J.routesDir}import*as Ve from"node:path";function Y(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),i=n.endsWith("/")?n:`${n}/`,o=r;r.startsWith(i)?o=r.substring(i.length):r.startsWith(n)?(o=r.substring(n.length),o.startsWith("/")&&(o=o.substring(1))):o=Ve.relative(n,r).replace(/\\/g,"/"),o=o.replace(/\.[^.]+$/,"");let s=o.split("/").filter(Boolean),a=[],u=s.map(S=>{if(S.startsWith("[")&&S.endsWith("]")){let d=S.slice(1,-1);return a.push(d),`:${d}`}return S}),l=u.length>0?`/${u.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:a}}function Ut(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(i,o)=>o;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let n=r.getFileName();if(!n)throw new Error("Unable to determine caller file name");return n.startsWith("file://")?At(n):n}finally{Error.prepareStackTrace=e}}function $(){let e=Ut(),t=Qe(),r=Y(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var le=()=>e=>{O("GET",e);let t=$();return{GET:e,path:t}},de=()=>e=>{O("POST",e);let t=$();return{POST:e,path:t}},pe=()=>e=>{O("PUT",e);let t=$();return{PUT:e,path:t}},fe=()=>e=>{O("DELETE",e);let t=$();return{DELETE:e,path:t}},me=()=>e=>{O("PATCH",e);let t=$();return{PATCH:e,path:t}},ye=()=>e=>{O("HEAD",e);let t=$();return{HEAD:e,path:t}},ge=()=>e=>{O("OPTIONS",e);let t=$();return{OPTIONS:e,path:t}};function O(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&Dt(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function Dt(e,t){let{params:r,query:n,body:i,response:o}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}function We(){return{get:le(),post:de(),put:pe(),delete:fe(),patch:me(),head:ye(),options:ge()}}import{AsyncLocalStorage as un}from"node:async_hooks";import cn from"node:events";import*as Se from"node:fs";import*as ft from"node:http";import*as mt from"node:http2";import*as E from"node:fs";import*as X from"node:path";import*as Ge from"selfsigned";async function Ze(){let e=X.join(process.cwd(),".blaizejs","certs"),t=X.join(e,"dev.key"),r=X.join(e,"dev.cert");if(E.existsSync(t)&&E.existsSync(r))return{keyFile:t,certFile:r};E.existsSync(e)||E.mkdirSync(e,{recursive:!0});let o=Ge.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return E.writeFileSync(t,Buffer.from(o.private,"utf-8")),E.writeFileSync(r,Buffer.from(o.cert,"utf-8")),console.log(`
11
11
  \u{1F512} Generated self-signed certificates for development at ${e}
12
- `),{keyFile:t,certFile:r}}var T=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},q=class extends T{constructor(t="Cannot set header after response has been sent"){super(t)}},Z=class extends T{constructor(t="Cannot set content type after response has been sent"){super(t)}},J=class extends T{constructor(t="Invalide URL"){super(t)}};import{AsyncLocalStorage as Bt}from"node:async_hooks";var $t=new Bt;function Le(e,t){return $t.run(e,t)}import*as Ge from"node:crypto";import{createWriteStream as At}from"node:fs";import{tmpdir as Ht}from"node:os";import{join as Ut}from"node:path";import{Readable as We}from"node:stream";var Ot=/boundary=([^;]+)/i,kt=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,Dt=/Content-Type:\s*([^\r\n]+)/i,Nt=/multipart\/form-data/i;function je(e){let t=e.match(Ot);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function _e(e){let t=e.match(kt);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function Qe(e){let t=e.match(Dt);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function Ve(e){return Nt.test(e)}var qt={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:Ht(),computeHash:!1};function It(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...qt,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function Lt(e,t){let r=Buffer.concat([e.buffer,t]),o={...e,buffer:r};for(;o.buffer.length>0&&!o.isFinished;){let n=await jt(o);if(n===o)break;o=n}return o}async function jt(e){switch(e.stage){case"boundary":return _t(e);case"headers":return Qt(e);case"content":return Vt(e);default:{let{InternalServerError:t}=await import("./internal-server-error-GWBNT3OO.js");throw new t("Invalid parser stage",{operation:e.stage})}}}function _t(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,o=e.buffer.subarray(t+e.boundary.length);return o.length>=2&&o.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:o,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(o.length>=2&&o.subarray(0,2).equals(Buffer.from(`\r
13
- `))&&(o=o.subarray(2)),{...e,buffer:o,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Qt(e){let t=e.buffer.indexOf(`\r
12
+ `),{keyFile:t,certFile:r}}var R=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},_=class extends R{constructor(t="Cannot set header after response has been sent"){super(t)}},K=class extends R{constructor(t="Cannot set content type after response has been sent"){super(t)}},ee=class extends R{constructor(t="Invalide URL"){super(t)}};import{AsyncLocalStorage as It}from"node:async_hooks";var Ht=new It;function Je(e,t){return Ht.run(e,t)}import*as rt from"node:crypto";import{createWriteStream as Qt}from"node:fs";import{tmpdir as Vt}from"node:os";import{join as Wt}from"node:path";import{Readable as tt}from"node:stream";var qt=/boundary=([^;]+)/i,_t=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,jt=/Content-Type:\s*([^\r\n]+)/i,Lt=/multipart\/form-data/i;function Ye(e){let t=e.match(qt);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function Xe(e){let t=e.match(_t);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function Ke(e){let t=e.match(jt);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function et(e){return Lt.test(e)}var Gt={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:Vt(),computeHash:!1};function Zt(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...Gt,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function Jt(e,t){let r=Buffer.concat([e.buffer,t]),n={...e,buffer:r};for(;n.buffer.length>0&&!n.isFinished;){let i=await Yt(n);if(i===n)break;n=i}return n}async function Yt(e){switch(e.stage){case"boundary":return Xt(e);case"headers":return Kt(e);case"content":return er(e);default:{let{InternalServerError:t}=await import("./internal-server-error-DAEFNRNG.js");throw new t("Invalid parser stage",{operation:e.stage})}}}function Xt(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,n=e.buffer.subarray(t+e.boundary.length);return n.length>=2&&n.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:n,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(n.length>=2&&n.subarray(0,2).equals(Buffer.from(`\r
13
+ `))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Kt(e){let t=e.buffer.indexOf(`\r
14
14
  \r
15
- `);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),o=e.buffer.subarray(t+4),n=_e(r);if(!n){let{ValidationError:a}=await import("./validation-error-6JDCGV2S.js");throw new a("Missing or invalid Content-Disposition header")}let i=Qe(r),s=n.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await import("./payload-too-large-error-EBM5BNWG.js");throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:n.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await import("./unsupported-media-type-error-YQ7GCZ32.js");throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:n.filename})}return{...e,buffer:o,stage:"content",currentHeaders:r,currentField:n.name,currentFilename:n.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Vt(e){let t=e.buffer.indexOf(e.boundary),r,o=!1,n=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),n=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),n=e.buffer.subarray(t),o=!0}let i={...e,buffer:n};return r.length>0&&(i=await Wt(i,r)),o&&(i=await Jt(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function Wt(e,t){let r=e.currentContentLength+t.length,o=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>o){let n=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await import("./payload-too-large-error-EBM5BNWG.js"),s=e.currentField?{contentType:n?"file":"field",currentSize:r,maxSize:o,field:e.currentField,filename:e.currentFilename}:{contentType:n?"file":"field",currentSize:r,maxSize:o,filename:e.currentFilename};throw new i(`${n?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?Gt(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function Gt(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await tr(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:o}=await import("./validation-error-6JDCGV2S.js");throw new o("Invalid parsing strategy")}}}async function Zt(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:o=>{t=o}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=Ut(e.options.tempDir,`upload-${Ge.randomUUID()}`),r=At(t),o=async()=>{try{let{unlink:n}=await import("node:fs/promises");await n(t)}catch(n){console.warn(`Failed to cleanup temp file: ${t}`,n)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,o]}}default:{let{ValidationError:t}=await import("./validation-error-6JDCGV2S.js");throw new t("Invalid file processing strategy")}}}async function Jt(e){return e.currentField?e.currentFilename!==void 0?Yt(e):Xt(e):I(e)}async function Yt(e){if(!e.currentField||e.currentFilename===void 0)return I(e);let t,r,o;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=We.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Je(e.currentWriteStream),o=e.currentTempPath,t=We.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await import("./validation-error-6JDCGV2S.js");throw new s("Invalid file finalization strategy")}}let n={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:o},i=Ze(e.files,e.currentField,n);return{...I(e),files:i}}function Xt(e){if(!e.currentField)return I(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=Ze(e.fields,e.currentField,t);return{...I(e),fields:r}}function I(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function Ze(e,t,r){let o=new Map(e),n=o.get(t)||[];return o.set(t,[...n,r]),o}async function Kt(e){if(!e.hasFoundValidBoundary){let{ValidationError:o}=await import("./validation-error-6JDCGV2S.js");throw new o("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:o}=await import("./validation-error-6JDCGV2S.js");throw new o("Empty multipart request")}let t={};for(let[o,n]of e.fields.entries())t[o]=n.length===1?n[0]:n;let r={};for(let[o,n]of e.files.entries())r[o]=n.length===1?n[0]:n;return{fields:t,files:r}}async function er(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Je(e.currentWriteStream)}async function tr(e,t){return new Promise((r,o)=>{e.write(t,n=>{n?o(n):r()})})}async function Je(e){return new Promise(t=>{e.end(()=>t())})}async function Ye(e,t={}){let r=e.headers["content-type"]||"",o=je(r);if(!o){let{UnsupportedMediaTypeError:i}=await import("./unsupported-media-type-error-YQ7GCZ32.js");throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let n=It(o,t);n.currentFilename!==void 0&&(n=await Zt(n));try{for await(let i of e)n=await Lt(n,i);return Kt(n)}finally{await er(n)}}var L="Content-Type",C={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function rr(e){let t=e.url||"/",r=e.headers.host||"localhost",n=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(n),s=i.pathname,a={};return i.searchParams.forEach((u,c)=>{a[c]!==void 0?Array.isArray(a[c])?a[c].push(u):a[c]=[a[c],u]:a[c]=u}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${n}`,i),new J(`Invalid URL: ${n}`)}}function or(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function nr(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function Xe(e,t,r={}){let{path:o,url:n,query:i}=rr(e),s=e.method||"GET",a=or(e),u=nr(e),c={},w={...r.initialState||{}},d={sent:!1},g={request:ir(e,{path:o,url:n,query:i,params:c,method:s,isHttp2:a,protocol:u}),response:{},state:w};return g.response=ar(t,d,g),r.parseBody&&await hr(e,g,r),g}function ir(e,t){return{raw:e,...t,header:Ke(e),headers:sr(e),body:void 0}}function Ke(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function sr(e){let t=Ke(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((o,n)=>(o[n]=t(n),o),{}):Object.entries(e.headers).reduce((o,[n,i])=>(o[n]=Array.isArray(i)?i.join(", "):i||void 0,o),{})}function ar(e,t,r){return{raw:e,get sent(){return t.sent},status:ur(e,t,r),header:lr(e,t,r),headers:cr(e,t,r),type:dr(e,t,r),json:pr(e,t),text:fr(e,t),html:mr(e,t),redirect:gr(e,t),stream:yr(e,t)}}function ur(e,t,r){return function(n){if(t.sent)throw new T;return e.statusCode=n,r.response}}function lr(e,t,r){return function(n,i){if(t.sent)throw new q;return e.setHeader(n,i),r.response}}function cr(e,t,r){return function(n){if(t.sent)throw new q;for(let[i,s]of Object.entries(n))e.setHeader(i,s);return r.response}}function dr(e,t,r){return function(n){if(t.sent)throw new Z;return e.setHeader(L,n),r.response}}function pr(e,t){return function(o,n){if(t.sent)throw new T;n!==void 0&&(e.statusCode=n),e.setHeader(L,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function fr(e,t){return function(o,n){if(t.sent)throw new T;n!==void 0&&(e.statusCode=n),e.setHeader(L,"text/plain"),e.end(o),t.sent=!0}}function mr(e,t){return function(o,n){if(t.sent)throw new T;n!==void 0&&(e.statusCode=n),e.setHeader(L,"text/html"),e.end(o),t.sent=!0}}function gr(e,t){return function(o,n=302){if(t.sent)throw new T;e.statusCode=n,e.setHeader("Location",o),e.end(),t.sent=!0}}function yr(e,t){return function(o,n={}){if(t.sent)throw new T;if(n.status!==void 0&&(e.statusCode=n.status),n.contentType&&e.setHeader(L,n.contentType),n.headers)for(let[i,s]of Object.entries(n.headers))e.setHeader(i,s);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",i=>{console.error("Stream error:",i),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function hr(e,t,r={}){if(wr(e.method))return;let o=e.headers["content-type"]||"",n=parseInt(e.headers["content-length"]||"0",10);if(n===0)return;let i={json:r.bodyLimits?.json??C.json,form:r.bodyLimits?.form??C.form,text:r.bodyLimits?.text??C.text,raw:r.bodyLimits?.raw??C.raw,multipart:{maxFileSize:r.bodyLimits?.multipart?.maxFileSize??C.multipart.maxFileSize,maxFiles:r.bodyLimits?.multipart?.maxFiles??C.multipart.maxFiles,maxFieldSize:r.bodyLimits?.multipart?.maxFieldSize??C.multipart.maxFieldSize,maxTotalSize:r.bodyLimits?.multipart?.maxTotalSize??C.multipart.maxTotalSize}};try{if(o.includes("application/json")){if(n>i.json)throw new Error(`JSON body too large: ${n} > ${i.json} bytes`);await Rr(e,t)}else if(o.includes("application/x-www-form-urlencoded")){if(n>i.form)throw new Error(`Form body too large: ${n} > ${i.form} bytes`);await Sr(e,t)}else if(o.includes("text/")){if(n>i.text)throw new Error(`Text body too large: ${n} > ${i.text} bytes`);await br(e,t)}else if(Ve(o))await Tr(e,t,i.multipart);else{if(n>i.raw)throw new Error(`Request body too large: ${n} > ${i.raw} bytes`);return}}catch(s){let a=o.includes("multipart")?"multipart_parse_error":"body_read_error";Y(t,a,"Error reading request body",s)}}function wr(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function Rr(e,t){let r=await se(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let o=JSON.parse(r);t.request.body=o}catch(o){t.request.body=null,Y(t,"json_parse_error","Invalid JSON in request body",o)}}async function Sr(e,t){let r=await se(e);if(r)try{t.request.body=xr(r)}catch(o){t.request.body=null,Y(t,"form_parse_error","Invalid form data in request body",o)}}function xr(e){let t=new URLSearchParams(e),r={};return t.forEach((o,n)=>{r[n]!==void 0?Array.isArray(r[n])?r[n].push(o):r[n]=[r[n],o]:r[n]=o}),r}async function br(e,t){let r=await se(e);r&&(t.request.body=r)}async function Tr(e,t,r){try{let o=r||C.multipart,n=await Ye(e,{strategy:"stream",maxFileSize:o.maxFileSize,maxFiles:o.maxFiles,maxFieldSize:o.maxFieldSize});t.request.multipart=n,t.request.files=n.files,t.request.body=n.fields}catch(o){t.request.body=null,Y(t,"multipart_parse_error","Failed to parse multipart data",o)}}function Y(e,t,r,o){let n={type:t,message:r,error:o};e.state._bodyError=n}async function se(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>{o.push(Buffer.isBuffer(n)?n:Buffer.from(n))}),e.on("end",()=>{t(Buffer.concat(o).toString("utf8"))}),e.on("error",n=>{r(n)})})}var k=class extends S{constructor(t,r=void 0,o=void 0){super("NOT_FOUND",t,404,o??x(),r)}};function Pr(e){return e instanceof S}function et(e){if(Pr(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=oe(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let o=new H("Internal Server Error",{originalMessage:r},t);return{type:o.type,title:o.title,status:o.status,correlationId:o.correlationId,timestamp:o.timestamp.toISOString(),details:o.details}}function tt(e){return e("x-correlation-id")??oe()}function rt(e,t){e("x-correlation-id",t)}function ot(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(o,n)=>{try{await n()}catch(i){if(o.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=tt(o.request.header),a=et(i);a.correlationId=s,rt(o.response.header,s),o.response.status(a.status).json(a)}},debug:t}}function nt(e){return async(t,r)=>{try{let o=await Xe(t,r,{parseBody:!0}),i=[ot(),...e.middleware],s=D(i);await Le(o,async()=>{await s(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!o.response.sent))throw new k(`Route not found: ${o.request.method} ${o.request.path}`)})})}catch(o){console.error("Error creating context:",o),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request"}))}}}async function vr(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,o=process.env.NODE_ENV==="development",n=!t||!r;if(n&&o)return await Ie();if(n)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function Er(e,t){if(!e)return it.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=ae.readFileSync(t.keyFile)),t.certFile&&(r.cert=ae.readFileSync(t.certFile))}catch(o){throw new Error(`Failed to read certificate files: ${o instanceof Error?o.message:String(o)}`)}return st.createSecureServer(r)}function Cr(e,t,r,o){return new Promise((n,i)=>{e.listen(t,r,()=>{let a=`${o?"https":"http"}://${r}:${t}`;console.log(`
15
+ `);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),i=Xe(r);if(!i){let{ValidationError:a}=await import("./validation-error-SJTLEIZZ.js");throw new a("Missing or invalid Content-Disposition header")}let o=Ke(r),s=i.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await import("./payload-too-large-error-YO3MSQJF.js");throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:i.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(o)){let{UnsupportedMediaTypeError:a}=await import("./unsupported-media-type-error-GW2UC37Q.js");throw new a("File type not allowed",{receivedMimeType:o,allowedMimeTypes:e.options.allowedMimeTypes,filename:i.filename})}return{...e,buffer:n,stage:"content",currentHeaders:r,currentField:i.name,currentFilename:i.filename,currentMimetype:o,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function er(e){let t=e.buffer.indexOf(e.boundary),r,n=!1,i=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),i=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),i=e.buffer.subarray(t),n=!0}let o={...e,buffer:i};return r.length>0&&(o=await tr(o,r)),n&&(o=await or(o),o={...o,stage:"boundary",hasProcessedAnyPart:!0}),o}async function tr(e,t){let r=e.currentContentLength+t.length,n=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>n){let i=e.currentFilename!==void 0,{PayloadTooLargeError:o}=await import("./payload-too-large-error-YO3MSQJF.js"),s=e.currentField?{contentType:i?"file":"field",currentSize:r,maxSize:n,field:e.currentField,filename:e.currentFilename}:{contentType:i?"file":"field",currentSize:r,maxSize:n,filename:e.currentFilename};throw new o(`${i?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?rr(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function rr(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await cr(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await import("./validation-error-SJTLEIZZ.js");throw new n("Invalid parsing strategy")}}}async function nr(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:n=>{t=n}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=Wt(e.options.tempDir,`upload-${rt.randomUUID()}`),r=Qt(t),n=async()=>{try{let{unlink:i}=await import("node:fs/promises");await i(t)}catch(i){console.warn(`Failed to cleanup temp file: ${t}`,i)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,n]}}default:{let{ValidationError:t}=await import("./validation-error-SJTLEIZZ.js");throw new t("Invalid file processing strategy")}}}async function or(e){return e.currentField?e.currentFilename!==void 0?ir(e):sr(e):j(e)}async function ir(e){if(!e.currentField||e.currentFilename===void 0)return j(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=tt.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await ot(e.currentWriteStream),n=e.currentTempPath,t=tt.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await import("./validation-error-SJTLEIZZ.js");throw new s("Invalid file finalization strategy")}}let i={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:n},o=nt(e.files,e.currentField,i);return{...j(e),files:o}}function sr(e){if(!e.currentField)return j(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=nt(e.fields,e.currentField,t);return{...j(e),fields:r}}function j(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function nt(e,t,r){let n=new Map(e),i=n.get(t)||[];return n.set(t,[...i,r]),n}async function ar(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await import("./validation-error-SJTLEIZZ.js");throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await import("./validation-error-SJTLEIZZ.js");throw new n("Empty multipart request")}let t={};for(let[n,i]of e.fields.entries())t[n]=i.length===1?i[0]:i;let r={};for(let[n,i]of e.files.entries())r[n]=i.length===1?i[0]:i;return{fields:t,files:r}}async function ur(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await ot(e.currentWriteStream)}async function cr(e,t){return new Promise((r,n)=>{e.write(t,i=>{i?n(i):r()})})}async function ot(e){return new Promise(t=>{e.end(()=>t())})}async function it(e,t={}){let r=e.headers["content-type"]||"",n=Ye(r);if(!n){let{UnsupportedMediaTypeError:o}=await import("./unsupported-media-type-error-GW2UC37Q.js");throw new o("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let i=Zt(n,t);i.currentFilename!==void 0&&(i=await nr(i));try{for await(let o of e)i=await Jt(i,o);return ar(i)}finally{await ur(i)}}var L="Content-Type",C={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function lr(e){let t=e.url||"/",r=e.headers.host||"localhost",i=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let o=new URL(i),s=o.pathname,a={};return o.searchParams.forEach((u,l)=>{a[l]!==void 0?Array.isArray(a[l])?a[l].push(u):a[l]=[a[l],u]:a[l]=u}),{path:s,url:o,query:a}}catch(o){throw console.warn(`Invalid URL: ${i}`,o),new ee(`Invalid URL: ${i}`)}}function dr(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function pr(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function st(e,t,r={}){let{path:n,url:i,query:o}=lr(e),s=e.method||"GET",a=dr(e),u=pr(e),l={},S={...r.initialState||{}},d={...r.initialServices||{}},g={sent:!1},m={request:fr(e,{path:n,url:i,query:o,params:l,method:s,isHttp2:a,protocol:u}),response:{},state:S,services:d};return m.response=yr(t,g,m),r.parseBody&&await br(e,m,r),m}function fr(e,t){return{raw:e,...t,header:at(e),headers:mr(e),body:void 0}}function at(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function mr(e){let t=at(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((n,i)=>(n[i]=t(i),n),{}):Object.entries(e.headers).reduce((n,[i,o])=>(n[i]=Array.isArray(o)?o.join(", "):o||void 0,n),{})}function Q(e,t){if(t.correlationId){let r=z(),n=String(t.correlationId);e.setHeader(r,n)}}function yr(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:gr(e,t,r),header:hr(e,t,r),headers:Sr(e,t,r),type:wr(e,t,r),json:Tr(e,t,r.state),text:xr(e,t,r.state),html:vr(e,t,r.state),redirect:Rr(e,t,r.state),stream:Pr(e,t,r.state)}}function gr(e,t,r){return function(i){if(t.sent)throw new R;return e.statusCode=i,r.response}}function hr(e,t,r){return function(i,o){if(t.sent)throw new _;return e.setHeader(i,o),r.response}}function Sr(e,t,r){return function(i){if(t.sent)throw new _;for(let[o,s]of Object.entries(i))e.setHeader(o,s);return r.response}}function wr(e,t,r){return function(i){if(t.sent)throw new K;return e.setHeader(L,i),r.response}}function Tr(e,t,r){return function(i,o){if(t.sent)throw new R;o!==void 0&&(e.statusCode=o),Q(e,r),e.setHeader(L,"application/json"),e.end(JSON.stringify(i)),t.sent=!0}}function xr(e,t,r){return function(i,o){if(t.sent)throw new R;o!==void 0&&(e.statusCode=o),Q(e,r),e.setHeader(L,"text/plain"),e.end(i),t.sent=!0}}function vr(e,t,r){return function(i,o){if(t.sent)throw new R;o!==void 0&&(e.statusCode=o),Q(e,r),e.setHeader(L,"text/html"),e.end(i),t.sent=!0}}function Rr(e,t,r){return function(i,o=302){if(t.sent)throw new R;Q(e,r),e.statusCode=o,e.setHeader("Location",i),e.end(),t.sent=!0}}function Pr(e,t,r){return function(i,o={}){if(t.sent)throw new R;if(o.status!==void 0&&(e.statusCode=o.status),Q(e,r),o.contentType&&e.setHeader(L,o.contentType),o.headers)for(let[s,a]of Object.entries(o.headers))e.setHeader(s,a);i.pipe(e),i.on("end",()=>{t.sent=!0}),i.on("error",s=>{console.error("Stream error:",s),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function br(e,t,r={}){if(Er(e.method))return;let n=e.headers["content-type"]||"",i=parseInt(e.headers["content-length"]||"0",10);if(i===0)return;let o={json:r.bodyLimits?.json??C.json,form:r.bodyLimits?.form??C.form,text:r.bodyLimits?.text??C.text,raw:r.bodyLimits?.raw??C.raw,multipart:{maxFileSize:r.bodyLimits?.multipart?.maxFileSize??C.multipart.maxFileSize,maxFiles:r.bodyLimits?.multipart?.maxFiles??C.multipart.maxFiles,maxFieldSize:r.bodyLimits?.multipart?.maxFieldSize??C.multipart.maxFieldSize,maxTotalSize:r.bodyLimits?.multipart?.maxTotalSize??C.multipart.maxTotalSize}};try{if(n.includes("application/json")){if(i>o.json)throw new Error(`JSON body too large: ${i} > ${o.json} bytes`);await Cr(e,t)}else if(n.includes("application/x-www-form-urlencoded")){if(i>o.form)throw new Error(`Form body too large: ${i} > ${o.form} bytes`);await Mr(e,t)}else if(n.includes("text/")){if(i>o.text)throw new Error(`Text body too large: ${i} > ${o.text} bytes`);await kr(e,t)}else if(et(n))await zr(e,t,o.multipart);else{if(i>o.raw)throw new Error(`Request body too large: ${i} > ${o.raw} bytes`);return}}catch(s){let a=n.includes("multipart")?"multipart_parse_error":"body_read_error";te(t,a,"Error reading request body",s)}}function Er(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function Cr(e,t){let r=await he(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let n=JSON.parse(r);t.request.body=n}catch(n){t.request.body=null,te(t,"json_parse_error","Invalid JSON in request body",n)}}async function Mr(e,t){let r=await he(e);if(r)try{t.request.body=Fr(r)}catch(n){t.request.body=null,te(t,"form_parse_error","Invalid form data in request body",n)}}function Fr(e){let t=new URLSearchParams(e),r={};return t.forEach((n,i)=>{r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n}),r}async function kr(e,t){let r=await he(e);r&&(t.request.body=r)}async function zr(e,t,r){try{let n=r||C.multipart,i=await it(e,{strategy:"stream",maxFileSize:n.maxFileSize,maxFiles:n.maxFiles,maxFieldSize:n.maxFieldSize});t.request.multipart=i,t.request.files=i.files,t.request.body=i.fields}catch(n){t.request.body=null,te(t,"multipart_parse_error","Failed to parse multipart data",n)}}function te(e,t,r,n){let i={type:t,message:r,error:n};e.state._bodyError=i}async function he(e){return new Promise((t,r)=>{let n=[];e.on("data",i=>{n.push(Buffer.isBuffer(i)?i:Buffer.from(i))}),e.on("end",()=>{t(Buffer.concat(n).toString("utf8"))}),e.on("error",i=>{r(i)})})}var N=class extends v{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??w(),r)}};function Br(e){return e instanceof v}function ut(e){if(Br(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=w(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let n=new I("Internal Server Error",{originalMessage:r},t);return{type:n.type,title:n.title,status:n.status,correlationId:n.correlationId,timestamp:n.timestamp.toISOString(),details:n.details}}function ct(e){let t=z(),r={[t]:e(t)};return Z(r)}function lt(e,t){let r=z();e(r,t)}function dt(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(n,i)=>{try{await i()}catch(o){if(n.response.sent){t&&console.error("Error occurred after response was sent:",o);return}t&&console.error("Error boundary caught error:",o);let s=ct(n.request.header),a=ut(o);a.correlationId=s,lt(n.response.header,s),n.response.status(a.status).json(a)}},debug:t}}function pt(e){return async(t,r)=>{let n=Z(t.headers);try{await _e(n,async()=>{let i=await st(t,r,{parseBody:!0,initialState:{correlationId:n}}),s=[dt(),...e.middleware],a=A(s);await Je(i,async()=>{await a(i,async()=>{if(!i.response.sent&&(await e.router.handleRequest(i),!i.response.sent))throw new N(`Route not found: ${i.request.method} ${i.request.path}`)})})})}catch(i){console.error("Error creating context:",i);let o=z();"stream"in r&&typeof r.stream?.respond=="function"?(r.stream.respond({":status":500,"content-type":"application/json",[o.toLowerCase()]:n}),r.stream.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n}))):(r.setHeader(o,n),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n})))}}}async function $r(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,n=process.env.NODE_ENV==="development",i=!t||!r;if(i&&n)return await Ze();if(i)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function Or(e,t){if(!e)return ft.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=Se.readFileSync(t.keyFile)),t.certFile&&(r.cert=Se.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return mt.createSecureServer(r)}function Nr(e,t,r,n){return new Promise((i,o)=>{e.listen(t,r,()=>{let a=`${n?"https":"http"}://${r}:${t}`;console.log(`
16
16
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
17
17
 
18
18
  \u26A1 BlaizeJS DEVELOPMENT SERVER HOT AND READY \u26A1
@@ -24,8 +24,8 @@ import{a as H}from"./chunk-HSLLYUVO.js";import{a as U}from"./chunk-TL4GIFTB.js";
24
24
  Time to build something amazing! \u{1F680}
25
25
 
26
26
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
27
- `),n()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function Fr(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function at(e,t){if(!e.server)try{let r=t.port,o=t.host;await Fr(e);let n=t.http2||{enabled:!0},i=!!n.enabled,s=await vr(n);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=Er(i,s);e.server=a,e.port=r,e.host=o;let u=nt(e);a.on("request",u),await Cr(a,r,o,i)}catch(r){throw console.error("Failed to start server:",r),r}}var X=!1;async function ut(e,t={}){let r=e.server,o=e.events;if(X){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;X=!0;let n=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),o.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,u)=>{r.close(c=>{if(c)return u(c);a()})}),s=new Promise((a,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},n)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),o.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),X=!1}catch(i){throw X=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),o.emit("error",i),i}}function lt(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},o=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",o),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",o)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},o=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",o),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",o)}}}}import{z as b}from"zod";var Mr=b.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),zr=b.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),Br=b.object({enabled:b.boolean().optional().default(!0),keyFile:b.string().optional(),certFile:b.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),$r=b.object({port:b.number().int().positive().optional().default(3e3),host:b.string().optional().default("localhost"),routesDir:b.string().optional().default("./routes"),http2:Br.optional().default({enabled:!0}),middleware:b.array(Mr).optional().default([]),plugins:b.array(zr).optional().default([])});function ct(e){try{return $r.parse(e)}catch(t){if(t instanceof b.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function dt(e={}){let{continueOnError:t=!0,debug:r=!1,onError:o}=e;function n(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,u){let c=`Plugin ${s.name} failed during ${a}: ${u.message}`;if(o?o(s,a,u):console.error(c,u),!t)throw new Error(c)}return{async initializePlugins(s){n("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{n(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(u){i(a,"initialize",u)}n(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){n("Terminating plugins...");let a=[...s.plugins].reverse();for(let u of a)if(u.terminate)try{n(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(c){i(u,"terminate",c)}n(`Terminated ${a.length} plugins`)},async onServerStart(s,a){n("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{n(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(a)}catch(c){i(u,"onServerStart",c)}},async onServerStop(s,a){n("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let c of u)if(c.onServerStop)try{n(`Notifying plugin of server stop: ${c.name}`),await c.onServerStop(a)}catch(w){i(c,"onServerStop",w)}}}}var P=class extends Error{constructor(r,o){super(`Plugin validation error${r?` for "${r}"`:""}: ${o}`);this.pluginName=r;this.name="PluginValidationError"}};var Or=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),kr=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Dr=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function pt(e,t={}){let{requireVersion:r=!0,validateNameFormat:o=!0,checkReservedNames:n=!0}=t;if(!e||typeof e!="object")throw new P("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new P("","Plugin must have a name (string)");if(o&&!kr.test(i.name))throw new P(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(n&&Or.has(i.name.toLowerCase()))throw new P(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new P(i.name,"Plugin must have a version (string)");if(!Dr.test(i.version))throw new P(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new P(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new P(i.name,`Plugin ${a} must be a function if provided`)}import*as mt from"node:crypto";import*as gt from"node:fs/promises";import{createRequire as Hr}from"node:module";import*as yt from"node:path";async function Nr(e){let t=`?t=${Date.now()}`,r=e+t;try{let o=await import(r);return console.log("\u2705 Successfully imported module"),o}catch(o){let n=o instanceof Error?o.message:String(o);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",n),import(e)}}async function ft(e,t){try{let r=W(e,t),o=await Nr(e);console.log("\u{1F4E6} Module exports:",Object.keys(o));let n=[];if(o.default&&typeof o.default=="object"){let i={...o.default,path:r.routePath};n.push(i)}return Object.entries(o).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(Ar(a)){let u={...a,path:r.routePath};n.push(u)}}),n.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${n.length} route(s)`),n)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function Ar(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(o=>e[o]&&typeof e[o]=="object"&&e[o].handler)}var j=new Map;async function _(e,t,r=!0){let n=(await gt.stat(e)).mtime.getTime(),i=j.get(e);if(r&&i&&i.timestamp===n)return i.routes;Ur(e);let s=await ft(e,t);if(r){let a=wt(s);j.set(e,{routes:s,timestamp:n,hash:a})}return s}function ht(e,t){let r=j.get(e);if(!r)return!0;let o=wt(t);return r.hash!==o}function ue(e){e?j.delete(e):j.clear()}function wt(e){let t=e.map(n=>({path:n.path,methods:Object.keys(n).filter(i=>i!=="path").sort().map(i=>{let s=n[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return mt.createHash("md5").update(r).digest("hex")}function Ur(e){try{let t=yt.resolve(e);if(typeof A<"u"){delete A.cache[t];try{let r=A.resolve(t);delete A.cache[r]}catch(r){let o=r instanceof Error?r.message:String(r);console.log(`\u26A0\uFE0F Could not resolve path: ${o}`)}}else try{let r=Hr(import.meta.url);delete r.cache[t];try{let o=r.resolve(t);delete r.cache[o]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}import*as Rt from"node:os";import*as K from"node:fs/promises";import*as N from"node:path";async function ee(e,t={}){let r=N.isAbsolute(e)?e:N.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await K.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let o=[],n=t.ignore||["node_modules",".git"];async function i(s){let a=await K.readdir(s,{withFileTypes:!0});for(let u of a){let c=N.join(s,u.name);u.isDirectory()&&n.includes(u.name)||(u.isDirectory()?await i(c):qr(u.name)&&o.push(c))}}return await i(r),o}function qr(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function Ir(e,t,r=Math.max(1,Math.floor(Rt.cpus().length/2))){let o=Lr(e,r),n=[];for(let i of o){let a=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);n.push(...a)}return n}async function St(e){let t=await ee(e);return(await Ir(t,o=>_(o,e))).flat()}function Lr(e,t){let r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r}var F={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function xt(e,t){let r=Date.now()-t;if(F.fileChanges++,F.totalReloadTime+=r,F.averageReloadTime=F.totalReloadTime/F.fileChanges,r>100&&(F.slowReloads.push({file:e,time:r}),F.slowReloads.length>10&&F.slowReloads.shift()),process.env.NODE_ENV==="development"){let o=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${o} Route reload: ${e} (${r}ms)`)}}function le(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let o=Date.now();try{let n=await e(...r);return xt(t,o),n}catch(n){throw xt(t,o),n}}}import*as ce from"node:path";import{watch as jr}from"chokidar";function de(e,t={}){let r=t.debounceMs||16,o=new Map;function n(d,g){return(...y)=>{let l=o.get(g);l&&clearTimeout(l);let p=setTimeout(()=>{d(...y),o.delete(g)},r);o.set(g,p)}}let i=new Map;async function s(){try{let d=await ee(e,{ignore:t.ignore});for(let g of d)await a(g)}catch(d){c(d)}}async function a(d){try{let g=i.get(d),y=await _(d,e,!1);if(!y||y.length===0||g&&!ht(d,y))return;await _(d,e,!0);let l=ce.normalize(d);g?(i.set(d,y),t.onRouteChanged&&t.onRouteChanged(l,y)):(i.set(d,y),t.onRouteAdded&&t.onRouteAdded(l,y))}catch(g){console.log(`\u26A0\uFE0F Error processing file ${d}:`,g),c(g)}}function u(d){let g=ce.normalize(d),y=i.get(g);y&&y.length>0&&t.onRouteRemoved&&t.onRouteRemoved(g,y),i.delete(g)}function c(d){t.onError&&d instanceof Error?t.onError(d):console.error("\u26A0\uFE0F Route watcher error:",d)}let w=jr(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return w.on("add",d=>{n(a,d)(d)}).on("change",d=>{n(a,d)(d)}).on("unlink",d=>{n(u,d)(d)}).on("error",c),s().catch(c),{close:()=>(o.forEach(d=>clearTimeout(d)),o.clear(),w.close()),getRoutes:()=>{let d=[];for(let g of i.values())d.push(...g);return d},getRoutesByFile:()=>new Map(i)}}import{z as Gr}from"zod";import{z as _r}from"zod";function pe(e,t){return t instanceof _r.ZodObject?t.strict().parse(e):t.parse(e)}import{z as Qr}from"zod";function fe(e,t){return t instanceof Qr.ZodObject?t.strict().parse(e):t.parse(e)}import{z as Vr}from"zod";function me(e,t){return t instanceof Vr.ZodObject?t.strict().parse(e):t.parse(e)}import{z as Wr}from"zod";function ge(e,t){return t instanceof Wr.ZodObject?t.strict().parse(e):t.parse(e)}function ye(e,t=!1){return{name:"RequestValidator",execute:async(o,n)=>{if(e.params&&o.request.params)try{o.request.params=fe(o.request.params,e.params)}catch(i){let s=te(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new U("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&o.request.query)try{o.request.query=me(o.request.query,e.query)}catch(i){let s=te(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new U("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{o.request.body=pe(o.request.body,e.body)}catch(i){let s=te(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new U("Request validation failed",{fields:s,errorCount:a,section:"body"})}await n()},debug:t}}function he(e,t=!1){return{name:"ResponseValidator",execute:async(o,n)=>{let i=o.response.json;o.response.json=(s,a)=>{try{let u=ge(s,e);return o.response.json=i,i.call(o.response,u,a)}catch(u){throw o.response.json=i,new H("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:te(u),originalResponse:s})}},await n()},debug:t}}function te(e){if(e instanceof Gr.ZodError){let t=new Map;for(let r of e.issues){let o=r.path.length>0?r.path.join("."):"root";t.has(o)||t.set(o,[]),t.get(o).push(r.message)}return Array.from(t.entries()).map(([r,o])=>({field:r,messages:o}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function we(e,t,r){let o=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&o.unshift(ye(t.schema)),t.schema.response&&o.push(he(t.schema.response))),await D([...o])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function re(e,t,r){let o=t.exec(e);if(!o)return{};let n={};for(let i=0;i<r.length;i++)n[r[i]]=o[i+1]||"";return n}function Re(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(n,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(n,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function Se(){let e=[];return{add(t,r,o){let{pattern:n,paramNames:i}=Re(t),s={path:t,method:r,pattern:n,paramNames:i,routeOptions:o},a=e.findIndex(u=>i.length<u.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let o=t.split("?")[0];if(!o)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(o)){let a=re(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:a}}}return e.find(i=>i.method!==r&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:re(t,r.pattern,r.paramNames)}))}}}function bt(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function M(e,t,r){console.log(`Updating routes from file: ${t}`);let o=e.routesByFile.get(t)||new Set,n=new Set(r.map(c=>c.path)),i=r.filter(c=>!o.has(c.path)),s=Array.from(o).filter(c=>!n.has(c)),u=r.filter(c=>o.has(c.path)).filter(c=>{let w=e.routesByPath.get(c.path);return!w||!Jr(w,c)});return Zr(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function Tt(e){return Array.from(e.routesByPath.values())}function Zr(e,t,r){let{added:o,removed:n,changed:i}=r;n.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...o,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...o.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!n.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Jr(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(n=>n!=="path").sort(),o=Object.keys(t).filter(n=>n!=="path").sort();return r.length!==o.length?!1:r.every(n=>{let i=e[n],s=t[n];return typeof i==typeof s})}function xe(e,t){Object.entries(e).forEach(([r,o])=>{r==="path"||!o||t.add(e.path,r,o)})}function Q(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function Pt(e,t){Q(e.path,t),xe(e,t)}var Yr={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function vt(e){let t={...Yr,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=bt(),o=Se(),n=!1,i=null,s=null,a=new Set([t.routesDir]);function u(l){console.log(`
28
- \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${l.added.length} routes`),console.log(` Removing ${l.removed.length} routes`),console.log(` Updating ${l.changed.length} routes`),l.removed.forEach(p=>{console.log(` \u2796 Removing: ${p}`),Q(p,o)}),l.added.forEach(p=>{let m=Object.keys(p).filter(f=>f!=="path");console.log(` \u2795 Adding: ${p.path} [${m.join(", ")}]`),xe(p,o)}),l.changed.forEach(p=>{let m=Object.keys(p).filter(f=>f!=="path");console.log(` \u{1F504} Updating: ${p.path} [${m.join(", ")}]`),Pt(p,o)}),console.log(`\u2705 Matcher changes applied
29
- `)}function c(l,p){try{let m=M(r,p,l);return u(m),m}catch(m){throw console.error(`\u26A0\uFE0F Route conflicts from ${p}:`,m),m}}async function w(l,p,m){try{let f=await St(l),h=f.map(v=>m?{...v,path:`${m}${v.path}`}:v),R=c(h,p);console.log(`Loaded ${f.length} routes from ${p}${m?` with prefix ${m}`:""} (${R.added.length} added, ${R.changed.length} changed, ${R.removed.length} removed)`)}catch(f){throw console.error(`\u26A0\uFE0F Failed to load routes from ${p}:`,f),f}}async function d(){return n||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(l=>w(l,l))),t.watchMode&&g(),n=!0}catch(l){throw console.error("\u26A0\uFE0F Failed to initialize router:",l),l}})()),i}function g(){s||(s=new Map);for(let l of a)if(!s.has(l)){let p=de(l,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(m,f)=>{try{let h=M(r,m,f);u(h)}catch(h){console.error(`Error adding routes from ${l}:`,h)}},onRouteChanged:le(async(m,f)=>{try{console.log(`Processing changes for ${m}`);let h=M(r,m,f);console.log(`Changes detected: ${h.added.length} added, ${h.changed.length} changed, ${h.removed.length} removed`),u(h),console.log(`Route changes applied: ${h.added.length} added, ${h.changed.length} changed, ${h.removed.length} removed`)}catch(h){console.error(`\u26A0\uFE0F Error updating routes from ${l}:`,h)}},l),onRouteRemoved:(m,f)=>{console.log(`File removed: ${m} with ${f.length} routes`);try{f.forEach(h=>{Q(h.path,o)}),ue(m)}catch(h){console.error(`\u26A0\uFE0F Error removing routes from ${m}:`,h)}},onError:m=>{console.error(`\u26A0\uFE0F Route watcher error for ${l}:`,m)}});s.set(l,p)}}function y(l,p){s||(s=new Map);let m=de(l,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(f,h)=>{try{let R=h.map(z=>p?{...z,path:`${p}${z.path}`}:z),v=M(r,f,R);u(v)}catch(R){console.error(`\u26A0\uFE0F Error adding routes from ${l}:`,R)}},onRouteChanged:le(async(f,h)=>{try{let R=h.map(z=>p?{...z,path:`${p}${z.path}`}:z),v=M(r,f,R);u(v)}catch(R){console.error(`\u26A0\uFE0F Error updating routes from ${l}:`,R)}},l),onRouteRemoved:(f,h)=>{try{h.forEach(R=>{let v=p?`${p}${R.path}`:R.path;Q(v,o)}),ue(f)}catch(R){console.error(`Error removing routes from ${f}:`,R)}},onError:f=>{console.error(`\u26A0\uFE0F Route watcher error for ${l}:`,f)}});return s.set(l,m),m}return d().catch(l=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",l)}),{async handleRequest(l){n||(console.log("\u{1F504} Router not initialized, initializing..."),await d());let{method:p,path:m}=l.request;console.log(`
30
- \u{1F4E5} Handling request: ${p} ${m}`);let f=o.match(m,p);if(!f)throw console.log(`\u274C No match found for: ${p} ${m}`),new k("Not found");if(console.log(`\u2705 Route matched: ${p} ${m}`),console.log(` Params: ${JSON.stringify(f.params)}`),f.methodNotAllowed){l.response.status(405).json({error:"\u274C Method Not Allowed",allowed:f.allowedMethods}),f.allowedMethods&&f.allowedMethods.length>0&&l.response.header("Allow",f.allowedMethods.join(", "));return}l.request.params=f.params,await we(l,f.route,f.params)},getRoutes(){return Tt(r)},addRoute(l){let p=M(r,"programmatic",[l]);u(p)},addRoutes(l){let p=M(r,"programmatic",l);return u(p),p},async addRouteDirectory(l,p={}){if(a.has(l)){console.warn(`Route directory ${l} already registered`);return}a.add(l),n&&(await w(l,l,p.prefix),t.watchMode&&y(l,p.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let l of s.values())await l.close();s.clear()}}}}var eo={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function to(e={}){let t={...eo};return ze({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]]}}function ro(e,t,r,o){return async()=>(await oo(e,r,o),await e.pluginManager.initializePlugins(e),await at(e,t),await e.pluginManager.onServerStart(e,e.server),no(e),e)}async function oo(e,t,r){for(let o of t)e.use(o);for(let o of r)await e.register(o)}function no(e){let t=lt(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function io(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await ut(e,r)}}function so(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function ao(e){return async t=>(pt(t),e.plugins.push(t),await t.register(e),e)}function be(e={}){let t=to(e),r;try{r=ct(t)}catch(l){throw l instanceof Error?new Error(`Failed to create server: ${l.message}`):new Error(`Failed to create server: ${String(l)}`)}let{port:o,host:n,middleware:i,plugins:s}=r,a=Array.isArray(i)?[...i]:[],u=Array.isArray(s)?[...s]:[],c=new Xr,w=vt({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),d=dt({debug:process.env.NODE_ENV==="development",continueOnError:!0}),g=new Kr,y={server:null,port:o,host:n,context:c,events:g,plugins:[],middleware:[],_signalHandlers:{unregister:()=>{}},use:()=>y,register:async()=>y,listen:async()=>y,close:async()=>{},router:w,pluginManager:d};return y.listen=ro(y,r,a,u),y.close=io(y),y.use=so(y),y.register=ao(y),y}var Te=class extends S{constructor(t,r=void 0,o=void 0){super("UNAUTHORIZED",t,401,o??x(),r)}};var Pe=class extends S{constructor(t,r=void 0,o=void 0){super("FORBIDDEN",t,403,o??x(),r)}};var ve=class extends S{constructor(t,r=void 0,o=void 0){super("CONFLICT",t,409,o??x(),r)}};var Ee=class extends S{constructor(t,r=void 0,o=void 0){super("RATE_LIMITED",t,429,o??x(),r)}};var Ce=class extends S{constructor(t,r,o){super("UPLOAD_TIMEOUT",t,408,o??x(),r)}};var Fe=class extends S{constructor(t,r,o){super("UNPROCESSABLE_ENTITY",t,422,o??x(),r)}};var uo="0.1.0",lo={createServer:be},co={createDeleteRoute:Ne,createGetRoute:Oe,createHeadRoute:He,createOptionsRoute:Ue,createPatchRoute:Ae,createPostRoute:ke,createPutRoute:De},po={createMiddleware:ne,compose:D},fo={createPlugin:ie},ys={createServer:be,createMiddleware:ne,createPlugin:ie,Server:lo,Router:co,Middleware:po,Plugins:fo,VERSION:uo};export{ys as Blaize,S as BlaizeError,ve as ConflictError,mo as ErrorSeverity,B as ErrorType,Pe as ForbiddenError,H as InternalServerError,po as MiddlewareAPI,k as NotFoundError,Et as PayloadTooLargeError,fo as PluginsAPI,Ee as RateLimitError,Ce as RequestTimeoutError,co as RouterAPI,lo as ServerAPI,Te as UnauthorizedError,Fe as UnprocessableEntityError,Ct as UnsupportedMediaTypeError,uo as VERSION,U as ValidationError,D as compose,Ne as createDeleteRoute,Oe as createGetRoute,He as createHeadRoute,ne as createMiddleware,Ue as createOptionsRoute,Ae as createPatchRoute,ie as createPlugin,ke as createPostRoute,De as createPutRoute,be as createServer,go as isBodyParseError};
27
+ `),i()}),e.on("error",s=>{console.error("Server error:",s),o(s)})})}async function Ar(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function yt(e,t){if(!e.server)try{let r=t.port,n=t.host;await Ar(e);let i=t.http2||{enabled:!0},o=!!i.enabled,s=await $r(i);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=Or(o,s);e.server=a,e.port=r,e.host=n;let u=pt(e);a.on("request",u),await Nr(a,r,n,o)}catch(r){throw console.error("Failed to start server:",r),r}}var re=!1;async function gt(e,t={}){let r=e.server,n=e.events;if(re){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;re=!0;let i=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),n.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let o=new Promise((a,u)=>{r.close(l=>{if(l)return u(l);a()})}),s=new Promise((a,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},i)});await Promise.race([o,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),n.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),re=!1}catch(o){throw re=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",o),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),n.emit("error",o),o}}function ht(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},n=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},n=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}}import{z as T}from"zod";var Ur=T.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),Dr=T.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),Ir=T.object({enabled:T.boolean().optional().default(!0),keyFile:T.string().optional(),certFile:T.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),Hr=T.object({headerName:T.string().regex(/^[a-z][a-z0-9-]*$/,{message:"Header name must start with a letter and contain only lowercase letters, numbers, and hyphens"}).optional(),generator:T.function().args().returns(T.string()).optional()}).optional(),qr=T.object({port:T.number().int().positive().optional().default(3e3),host:T.string().optional().default("localhost"),routesDir:T.string().optional().default("./routes"),http2:Ir.optional().default({enabled:!0}),middleware:T.array(Ur).optional().default([]),plugins:T.array(Dr).optional().default([]),correlation:Hr});function St(e){try{return qr.parse(e)}catch(t){if(t instanceof T.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function wt(e={}){let{continueOnError:t=!0,debug:r=!1,onError:n}=e;function i(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function o(s,a,u){let l=`Plugin ${s.name} failed during ${a}: ${u.message}`;if(n?n(s,a,u):console.error(l,u),!t)throw new Error(l)}return{async initializePlugins(s){i("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{i(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(u){o(a,"initialize",u)}i(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){i("Terminating plugins...");let a=[...s.plugins].reverse();for(let u of a)if(u.terminate)try{i(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(l){o(u,"terminate",l)}i(`Terminated ${a.length} plugins`)},async onServerStart(s,a){i("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{i(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(a)}catch(l){o(u,"onServerStart",l)}},async onServerStop(s,a){i("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let l of u)if(l.onServerStop)try{i(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(a)}catch(S){o(l,"onServerStop",S)}}}}var P=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var _r=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),jr=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Lr=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function we(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:i=!0}=t;if(!e||typeof e!="object")throw new P("","Plugin must be an object");let o=e;if(!o.name||typeof o.name!="string")throw new P("","Plugin must have a name (string)");if(n&&!jr.test(o.name))throw new P(o.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(i&&_r.has(o.name.toLowerCase()))throw new P(o.name,`Plugin name "${o.name}" is reserved`);if(r){if(!o.version||typeof o.version!="string")throw new P(o.name,"Plugin must have a version (string)");if(!Lr.test(o.version))throw new P(o.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!o.register||typeof o.register!="function")throw new P(o.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(o[a]&&typeof o[a]!="function")throw new P(o.name,`Plugin ${a} must be a function if provided`)}import*as xt from"node:crypto";import*as vt from"node:fs/promises";import{createRequire as Wr}from"node:module";import*as Rt from"node:path";async function Qr(e){let t=`?t=${Date.now()}`,r=e+t;try{let n=await import(r);return console.log("\u2705 Successfully imported module"),n}catch(n){let i=n instanceof Error?n.message:String(n);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",i),import(e)}}async function Tt(e,t){try{let r=Y(e,t),n=await Qr(e);console.log("\u{1F4E6} Module exports:",Object.keys(n));let i=[];if(n.default&&typeof n.default=="object"){let o={...n.default,path:r.routePath};i.push(o)}return Object.entries(n).forEach(([o,s])=>{if(o==="default"||!s||typeof s!="object")return;let a=s;if(Vr(a)){let u={...a,path:r.routePath};i.push(u)}}),i.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${i.length} route(s)`),i)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function Vr(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(n=>e[n]&&typeof e[n]=="object"&&e[n].handler)}var V=new Map;async function W(e,t,r=!0){let i=(await vt.stat(e)).mtime.getTime(),o=V.get(e);if(r&&o&&o.timestamp===i)return o.routes;Gr(e);let s=await Tt(e,t);if(r){let a=bt(s);V.set(e,{routes:s,timestamp:i,hash:a})}return s}function Pt(e,t){let r=V.get(e);if(!r)return!0;let n=bt(t);return r.hash!==n}function Te(e){e?V.delete(e):V.clear()}function bt(e){let t=e.map(i=>({path:i.path,methods:Object.keys(i).filter(o=>o!=="path").sort().map(o=>{let s=i[o],a=s?.handler?s.handler.toString():null;return{method:o,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return xt.createHash("md5").update(r).digest("hex")}function Gr(e){try{let t=Rt.resolve(e);if(typeof D<"u"){delete D.cache[t];try{let r=D.resolve(t);delete D.cache[r]}catch(r){let n=r instanceof Error?r.message:String(r);console.log(`\u26A0\uFE0F Could not resolve path: ${n}`)}}else try{let r=Wr(import.meta.url);delete r.cache[t];try{let n=r.resolve(t);delete r.cache[n]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}import*as Et from"node:os";import*as ne from"node:fs/promises";import*as U from"node:path";async function oe(e,t={}){let r=U.isAbsolute(e)?e:U.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await ne.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let n=[],i=t.ignore||["node_modules",".git"];async function o(s){let a=await ne.readdir(s,{withFileTypes:!0});for(let u of a){let l=U.join(s,u.name);u.isDirectory()&&i.includes(u.name)||(u.isDirectory()?await o(l):Zr(u.name)&&n.push(l))}}return await o(r),n}function Zr(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function Jr(e,t,r=Math.max(1,Math.floor(Et.cpus().length/2))){let n=Yr(e,r),i=[];for(let o of n){let a=(await Promise.allSettled(o.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);i.push(...a)}return i}async function Ct(e){let t=await oe(e);return(await Jr(t,n=>W(n,e))).flat()}function Yr(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var M={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Mt(e,t){let r=Date.now()-t;if(M.fileChanges++,M.totalReloadTime+=r,M.averageReloadTime=M.totalReloadTime/M.fileChanges,r>100&&(M.slowReloads.push({file:e,time:r}),M.slowReloads.length>10&&M.slowReloads.shift()),process.env.NODE_ENV==="development"){let n=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${n} Route reload: ${e} (${r}ms)`)}}function xe(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let i=await e(...r);return Mt(t,n),i}catch(i){throw Mt(t,n),i}}}import*as ve from"node:path";import{watch as Xr}from"chokidar";function Re(e,t={}){let r=t.debounceMs||16,n=new Map;function i(d,g){return(...m)=>{let c=n.get(g);c&&clearTimeout(c);let p=setTimeout(()=>{d(...m),n.delete(g)},r);n.set(g,p)}}let o=new Map;async function s(){try{let d=await oe(e,{ignore:t.ignore});for(let g of d)await a(g)}catch(d){l(d)}}async function a(d){try{let g=o.get(d),m=await W(d,e,!1);if(!m||m.length===0||g&&!Pt(d,m))return;await W(d,e,!0);let c=ve.normalize(d);g?(o.set(d,m),t.onRouteChanged&&t.onRouteChanged(c,m)):(o.set(d,m),t.onRouteAdded&&t.onRouteAdded(c,m))}catch(g){console.log(`\u26A0\uFE0F Error processing file ${d}:`,g),l(g)}}function u(d){let g=ve.normalize(d),m=o.get(g);m&&m.length>0&&t.onRouteRemoved&&t.onRouteRemoved(g,m),o.delete(g)}function l(d){t.onError&&d instanceof Error?t.onError(d):console.error("\u26A0\uFE0F Route watcher error:",d)}let S=Xr(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return S.on("add",d=>{i(a,d)(d)}).on("change",d=>{i(a,d)(d)}).on("unlink",d=>{i(u,d)(d)}).on("error",l),s().catch(l),{close:()=>(n.forEach(d=>clearTimeout(d)),n.clear(),S.close()),getRoutes:()=>{let d=[];for(let g of o.values())d.push(...g);return d},getRoutesByFile:()=>new Map(o)}}import{z as nn}from"zod";import{z as Kr}from"zod";function Pe(e,t){return t instanceof Kr.ZodObject?t.strict().parse(e):t.parse(e)}import{z as en}from"zod";function be(e,t){return t instanceof en.ZodObject?t.strict().parse(e):t.parse(e)}import{z as tn}from"zod";function Ee(e,t){return t instanceof tn.ZodObject?t.strict().parse(e):t.parse(e)}import{z as rn}from"zod";function Ce(e,t){return t instanceof rn.ZodObject?t.strict().parse(e):t.parse(e)}function Me(e,t=!1){return{name:"RequestValidator",execute:async(n,i)=>{if(e.params&&n.request.params)try{n.request.params=be(n.request.params,e.params)}catch(o){let s=ie(o),a=s.reduce((u,l)=>u+l.messages.length,0);throw new H("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&n.request.query)try{n.request.query=Ee(n.request.query,e.query)}catch(o){let s=ie(o),a=s.reduce((u,l)=>u+l.messages.length,0);throw new H("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{n.request.body=Pe(n.request.body,e.body)}catch(o){let s=ie(o),a=s.reduce((u,l)=>u+l.messages.length,0);throw new H("Request validation failed",{fields:s,errorCount:a,section:"body"})}await i()},debug:t}}function Fe(e,t=!1){return{name:"ResponseValidator",execute:async(n,i)=>{let o=n.response.json;n.response.json=(s,a)=>{try{let u=Ce(s,e);return n.response.json=o,o.call(n.response,u,a)}catch(u){throw n.response.json=o,new I("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:ie(u),originalResponse:s})}},await i()},debug:t}}function ie(e){if(e instanceof nn.ZodError){let t=new Map;for(let r of e.issues){let n=r.path.length>0?r.path.join("."):"root";t.has(n)||t.set(n,[]),t.get(n).push(r.message)}return Array.from(t.entries()).map(([r,n])=>({field:r,messages:n}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function ke(e,t,r){let n=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&n.unshift(Me(t.schema)),t.schema.response&&n.push(Fe(t.schema.response))),await A([...n])(e,async()=>{let o=await t.handler(e,r);!e.response.sent&&o!==void 0&&e.response.json(o)})}function se(e,t,r){let n=t.exec(e);if(!n)return{};let i={};for(let o=0;o<r.length;o++)i[r[o]]=n[o+1]||"";return i}function ze(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(i,o)=>(t.push(o),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(i,o)=>(t.push(o),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function Be(){let e=[];return{add(t,r,n){let{pattern:i,paramNames:o}=ze(t),s={path:t,method:r,pattern:i,paramNames:o,routeOptions:n},a=e.findIndex(u=>o.length<u.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let n=t.split("?")[0];if(!n)return null;for(let o of e){if(o.method!==r)continue;if(o.pattern.exec(n)){let a=se(t,o.pattern,o.paramNames);return{route:o.routeOptions,params:a}}}return e.find(o=>o.method!==r&&o.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(o=>o.pattern.test(t)).map(o=>o.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:se(t,r.pattern,r.paramNames)}))}}}function Ft(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function F(e,t,r){console.log(`Updating routes from file: ${t}`);let n=e.routesByFile.get(t)||new Set,i=new Set(r.map(l=>l.path)),o=r.filter(l=>!n.has(l.path)),s=Array.from(n).filter(l=>!i.has(l)),u=r.filter(l=>n.has(l.path)).filter(l=>{let S=e.routesByPath.get(l.path);return!S||!sn(S,l)});return on(e,t,{added:o,removed:s,changed:u}),{added:o,removed:s,changed:u}}function kt(e){return Array.from(e.routesByPath.values())}function on(e,t,r){let{added:n,removed:i,changed:o}=r;i.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...n,...o].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...n.map(a=>a.path),...o.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!i.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function sn(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(i=>i!=="path").sort(),n=Object.keys(t).filter(i=>i!=="path").sort();return r.length!==n.length?!1:r.every(i=>{let o=e[i],s=t[i];return typeof o==typeof s})}function $e(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function G(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function zt(e,t){G(e.path,t),$e(e,t)}var an={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function Bt(e){let t={...an,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=Ft(),n=Be(),i=!1,o=null,s=null,a=new Set([t.routesDir]);function u(c){console.log(`
28
+ \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${c.added.length} routes`),console.log(` Removing ${c.removed.length} routes`),console.log(` Updating ${c.changed.length} routes`),c.removed.forEach(p=>{console.log(` \u2796 Removing: ${p}`),G(p,n)}),c.added.forEach(p=>{let y=Object.keys(p).filter(f=>f!=="path");console.log(` \u2795 Adding: ${p.path} [${y.join(", ")}]`),$e(p,n)}),c.changed.forEach(p=>{let y=Object.keys(p).filter(f=>f!=="path");console.log(` \u{1F504} Updating: ${p.path} [${y.join(", ")}]`),zt(p,n)}),console.log(`\u2705 Matcher changes applied
29
+ `)}function l(c,p){try{let y=F(r,p,c);return u(y),y}catch(y){throw console.error(`\u26A0\uFE0F Route conflicts from ${p}:`,y),y}}async function S(c,p,y){try{let f=await Ct(c),h=f.map(b=>y?{...b,path:`${y}${b.path}`}:b),x=l(h,p);console.log(`Loaded ${f.length} routes from ${p}${y?` with prefix ${y}`:""} (${x.added.length} added, ${x.changed.length} changed, ${x.removed.length} removed)`)}catch(f){throw console.error(`\u26A0\uFE0F Failed to load routes from ${p}:`,f),f}}async function d(){return i||o||(o=(async()=>{try{await Promise.all(Array.from(a).map(c=>S(c,c))),t.watchMode&&g(),i=!0}catch(c){throw console.error("\u26A0\uFE0F Failed to initialize router:",c),c}})()),o}function g(){s||(s=new Map);for(let c of a)if(!s.has(c)){let p=Re(c,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(y,f)=>{try{let h=F(r,y,f);u(h)}catch(h){console.error(`Error adding routes from ${c}:`,h)}},onRouteChanged:xe(async(y,f)=>{try{console.log(`Processing changes for ${y}`);let h=F(r,y,f);console.log(`Changes detected: ${h.added.length} added, ${h.changed.length} changed, ${h.removed.length} removed`),u(h),console.log(`Route changes applied: ${h.added.length} added, ${h.changed.length} changed, ${h.removed.length} removed`)}catch(h){console.error(`\u26A0\uFE0F Error updating routes from ${c}:`,h)}},c),onRouteRemoved:(y,f)=>{console.log(`File removed: ${y} with ${f.length} routes`);try{f.forEach(h=>{G(h.path,n)}),Te(y)}catch(h){console.error(`\u26A0\uFE0F Error removing routes from ${y}:`,h)}},onError:y=>{console.error(`\u26A0\uFE0F Route watcher error for ${c}:`,y)}});s.set(c,p)}}function m(c,p){s||(s=new Map);let y=Re(c,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(f,h)=>{try{let x=h.map(k=>p?{...k,path:`${p}${k.path}`}:k),b=F(r,f,x);u(b)}catch(x){console.error(`\u26A0\uFE0F Error adding routes from ${c}:`,x)}},onRouteChanged:xe(async(f,h)=>{try{let x=h.map(k=>p?{...k,path:`${p}${k.path}`}:k),b=F(r,f,x);u(b)}catch(x){console.error(`\u26A0\uFE0F Error updating routes from ${c}:`,x)}},c),onRouteRemoved:(f,h)=>{try{h.forEach(x=>{let b=p?`${p}${x.path}`:x.path;G(b,n)}),Te(f)}catch(x){console.error(`Error removing routes from ${f}:`,x)}},onError:f=>{console.error(`\u26A0\uFE0F Route watcher error for ${c}:`,f)}});return s.set(c,y),y}return d().catch(c=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",c)}),{async handleRequest(c){i||(console.log("\u{1F504} Router not initialized, initializing..."),await d());let{method:p,path:y}=c.request;console.log(`
30
+ \u{1F4E5} Handling request: ${p} ${y}`);let f=n.match(y,p);if(!f)throw console.log(`\u274C No match found for: ${p} ${y}`),new N("Not found");if(console.log(`\u2705 Route matched: ${p} ${y}`),console.log(` Params: ${JSON.stringify(f.params)}`),f.methodNotAllowed){c.response.status(405).json({error:"\u274C Method Not Allowed",allowed:f.allowedMethods}),f.allowedMethods&&f.allowedMethods.length>0&&c.response.header("Allow",f.allowedMethods.join(", "));return}c.request.params=f.params,await ke(c,f.route,f.params)},getRoutes(){return kt(r)},addRoute(c){let p=F(r,"programmatic",[c]);u(p)},addRoutes(c){let p=F(r,"programmatic",c);return u(p),p},async addRouteDirectory(c,p={}){if(a.has(c)){console.warn(`Route directory ${c} already registered`);return}a.add(c),i&&(await S(c,c,p.prefix),t.watchMode&&m(c,p.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let c of s.values())await c.close();s.clear()}}}}var ln={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function dn(e={}){let t={...ln};return Le({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]],correlation:e.correlation}}function pn(e){e.correlation&&qe(e.correlation.headerName,e.correlation.generator)}function fn(e,t){return async()=>(pn(t),await mn(e),await e.pluginManager.initializePlugins(e),await yt(e,t),await e.pluginManager.onServerStart(e,e.server),yn(e),e)}async function mn(e){for(let t of e.plugins)await t.register(e)}function yn(e){let t=ht(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function gn(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await gt(e,r)}}function hn(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function Sn(e){return async t=>{if(Array.isArray(t))for(let r of t)we(r),e.plugins.push(r),await r.register(e);else we(t),e.plugins.push(t),await t.register(e);return e}}function Oe(e={}){let t=dn(e),r;try{r=St(t)}catch(c){throw c instanceof Error?new Error(`Failed to create server: ${c.message}`):new Error(`Failed to create server: ${String(c)}`)}let{port:n,host:i,middleware:o,plugins:s}=r,a=Array.isArray(o)?[...o]:[],u=Array.isArray(s)?[...s]:[],l=new un,S=Bt({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),d=wt({debug:process.env.NODE_ENV==="development",continueOnError:!0}),g=new cn,m={server:null,port:n,host:i,context:l,events:g,plugins:[...u],middleware:[...a],_signalHandlers:{unregister:()=>{}},use:()=>m,register:async()=>m,listen:async()=>m,close:async()=>{},router:S,pluginManager:d};return m.listen=fn(m,r),m.close=gn(m),m.use=hn(m),m.register=Sn(m),m}function $t(e){return{}}function Xi(e){return typeof e=="object"&&e!==null&&"name"in e&&"execute"in e&&typeof e.name=="string"&&typeof e.execute=="function"}function Ki(e){return typeof e=="object"&&e!==null&&"name"in e&&"version"in e&&"register"in e&&typeof e.name=="string"&&typeof e.version=="string"&&typeof e.register=="function"}function es(e){return e}function ts(e){return e}function rs(...e){return e}function ns(...e){return e}var Ne=class extends v{constructor(t,r=void 0,n=void 0){super("UNAUTHORIZED",t,401,n??w(),r)}};var Ae=class extends v{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??w(),r)}};var Ue=class extends v{constructor(t,r=void 0,n=void 0){super("CONFLICT",t,409,n??w(),r)}};var De=class extends v{constructor(t,r=void 0,n=void 0){super("RATE_LIMITED",t,429,n??w(),r)}};var Ie=class extends v{constructor(t,r,n){super("UPLOAD_TIMEOUT",t,408,n??w(),r)}};var He=class extends v{constructor(t,r,n){super("UNPROCESSABLE_ENTITY",t,422,n??w(),r)}};var wn="0.1.0",Tn={createServer:Oe,inferContext:$t},xn={createDeleteRoute:fe,createGetRoute:le,createHeadRoute:ye,createOptionsRoute:ge,createPatchRoute:me,createPostRoute:de,createPutRoute:pe,createRouteFactory:We},vn={createMiddleware:q,createServiceMiddleware:ue,createStateMiddleware:ae,compose:A},Rn={createPlugin:ce},Hs={createServer:Oe,createMiddleware:q,createServiceMiddleware:ue,createStateMiddleware:ae,createPlugin:ce,getCorrelationId:w,Server:Tn,Router:xn,Middleware:vn,Plugins:Rn,VERSION:wn};export{Hs as Blaize,v as BlaizeError,Ue as ConflictError,Pn as ErrorSeverity,B as ErrorType,Ae as ForbiddenError,I as InternalServerError,vn as MiddlewareAPI,N as NotFoundError,Ot as PayloadTooLargeError,Rn as PluginsAPI,De as RateLimitError,Ie as RequestTimeoutError,xn as RouterAPI,Tn as ServerAPI,Ne as UnauthorizedError,He as UnprocessableEntityError,Nt as UnsupportedMediaTypeError,wn as VERSION,H as ValidationError,es as asMiddlewareArray,ts as asPluginArray,A as compose,fe as createDeleteRoute,le as createGetRoute,ye as createHeadRoute,q as createMiddleware,rs as createMiddlewareArray,ge as createOptionsRoute,me as createPatchRoute,ce as createPlugin,ns as createPluginArray,de as createPostRoute,pe as createPutRoute,We as createRouteFactory,Oe as createServer,ue as createServiceMiddleware,ae as createStateMiddleware,w as getCorrelationId,$t as inferContext,bn as isBodyParseError,Xi as isMiddleware,Ki as isPlugin};
31
31
  //# sourceMappingURL=index.js.map