@stacksjs/router 0.70.45 → 0.70.54
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.
- package/LICENSE.md +21 -0
- package/dist/api-shape.d.ts +24 -0
- package/dist/encrypted-session-store.d.ts +19 -0
- package/dist/error-handler.d.ts +10 -4
- package/dist/index.d.ts +57 -11
- package/dist/index.js +33 -32
- package/dist/middleware.d.ts +1 -0
- package/dist/path-sanitize.d.ts +64 -0
- package/dist/request-augmentation.d.ts +67 -0
- package/dist/request-context.d.ts +32 -9
- package/dist/route-loader.d.ts +1 -1
- package/dist/route-types.d.ts +12 -0
- package/dist/security-headers.d.ts +20 -0
- package/dist/session-factory.d.ts +57 -0
- package/dist/signed-url.d.ts +50 -0
- package/dist/stacks-router.d.ts +93 -0
- package/package.json +11 -11
package/dist/index.js
CHANGED
|
@@ -1,49 +1,50 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var{defineProperty:
|
|
3
|
-
${
|
|
4
|
-
Hint: load related rows with .with('relation') or eager-load via includes() before iterating.`)}).catch(()=>{})}function
|
|
5
|
-
`).slice(0,10),
|
|
2
|
+
var{defineProperty:L8,getOwnPropertyNames:v$,getOwnPropertyDescriptor:y$}=Object,f$=Object.prototype.hasOwnProperty;function g$($){return this[$]}var h$=($)=>{var Z=(X9??=new WeakMap).get($),W;if(Z)return Z;if(Z=L8({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of v$($))if(!f$.call(Z,X))L8(Z,X,{get:g$.bind($,X),enumerable:!(W=y$($,X))||W.enumerable})}return X9.set($,Z),Z},X9;var m$=($)=>$;function p$($,Z){this[$]=m$.bind(null,Z)}var Y9=($,Z)=>{for(var W in Z)L8($,W,{get:Z[W],enumerable:!0,configurable:!0,set:p$.bind(Z,W)})};var u=($,Z)=>()=>($&&(Z=$($=0)),Z);var x=import.meta.require;class f5{name;priority;handle;constructor($){this.name=$.name,this.priority=$.priority??10,this.handle=$.handle}toRouterHandler(){let $=this.handle.bind(this);return async(Z,W)=>{try{await $(Z)}catch(X){if(X instanceof Response)return X;throw X}return W()}}}import c$ from"process";import{AsyncLocalStorage as G9}from"async_hooks";import{log as d$}from"@stacksjs/logging";function u$(){let $=z9.getStore();if($)return $;return M5.getStore()?._requestId}function l$($,Z){return z9.run($,Z)}function n$(){let $=M5.getStore();if(!$)return;let Z=$[J9];if(!Z)Z={map:new Map},$[J9]=Z;return Z}async function i$($,Z){let W=n$();if(!W)return Z();let X=W.map.get($);if(X)return X;let Y=Promise.resolve().then(()=>Z());return W.map.set($,Y),Y.catch(()=>W.map.delete($)),Y}function s$($){d$.debug(`[request] ${$.method} ${new URL($.url).pathname}`),M5.enterWith($)}function _8($,Z){return M5.run($,Z)}function o(){return M5.getStore()}var M5,z9,J9,o$;var S5=u(()=>{M5=new G9,z9=new G9;J9=Symbol.for("stacks.requestQueryCache");o$=new Proxy({},{get($,Z){let W=o();if(!W){if(c$.env.NODE_ENV!=="production")console.warn(`[RequestContext] Accessing request.${String(Z)} outside of request context`);if(Z==="bearerToken")return()=>null;if(Z==="user"||Z==="userToken")return async()=>{return};if(Z==="tokenCan"||Z==="tokenCant")return async()=>!1;if(Z==="headers")return new Headers;if(Z==="url")return"";if(Z==="method")return"GET";return}let X=W[Z];if(typeof X==="function")return X.bind(W);return X}})});function t($){let Z=$.headers,W=Z.get("content-type")||"";if(g5.test(W))return!0;if(Z.get("sec-fetch-dest")==="document")return!1;if((Z.get("accept")||"").includes("text/html"))return!1;return!0}var g5;var h5=u(()=>{g5=/^application\/(?:json|.+\+json)(?:;|$)/i});var _9={};Y9(_9,{trackQuery:()=>j9,getQueryShapeCounts:()=>H9,createValidationErrorResponse:()=>L9,createNotFoundResponse:()=>F9,createMiddlewareErrorResponse:()=>U5,createErrorResponse:()=>l,clearTrackedQueries:()=>d5});import a from"process";import{log as t$}from"@stacksjs/logging";import{createErrorHandler as a$,renderProductionErrorPage as B9}from"@stacksjs/error-handling";function B5($){let Z={error:$.error,message:$.message,status:$.status,timestamp:new Date().toISOString()};if($.details)Z.details=$.details;return JSON.stringify(Z)}function Q5(){let $=(a.env.APP_ENV??"").toLowerCase();if($==="development")return!0;if(!$&&a.env.NODE_ENV==="development")return!0;return!1}function r(){return{"Content-Type":"application/json"}}function r$(){return r()}function m5(){return{buffer:Array(N5).fill(null),writeIndex:0,count:0,shapeCounts:new Map,n1Warned:new Set}}function A8(){let $=o();if(!$)return U9;let Z=$[p5];if(!Z)Z=m5(),$[p5]=Z;return Z}function $Z($){return $.replace(/'(?:[^']|'')*'/g,"?").replace(/"(?:[^"]|"")*"/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/IN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toUpperCase()}function j9($,Z,W){let X=A8();if(X.buffer[X.writeIndex]={query:$,time:Z,connection:W},X.writeIndex=(X.writeIndex+1)%N5,X.count<N5)X.count++;if(!Q5())return;let Y=$Z($);if(Y.startsWith("INSERT INTO QUERY_LOGS")||Y.startsWith("EXPLAIN"))return;let J=(X.shapeCounts.get(Y)??0)+1;if(X.shapeCounts.set(Y,J),J===e$+1&&!X.n1Warned.has(Y))X.n1Warned.add(Y),import("@stacksjs/logging").then(({log:G})=>{G.warn(`[orm] Possible N+1 \u2014 query shape ran ${J}\xD7 in this request:
|
|
3
|
+
${Y}
|
|
4
|
+
Hint: load related rows with .with('relation') or eager-load via includes() before iterating.`)}).catch(()=>{})}function Q9(){let $=A8();if($.count===0)return[];let Z=[],W=$.count<N5?0:$.writeIndex;for(let X=0;X<$.count;X++){let Y=$.buffer[(W+X)%N5];if(Y)Z.push(Y)}return Z}function H9(){return new Map(A8().shapeCounts)}function d5(){let $=o();if($&&$[p5]){$[p5]=m5();return}U9=m5()}function ZZ(){return{appName:"Stacks",theme:"auto",showEnvironment:!0,showQueries:!0,showRequest:!0,enableCopyMarkdown:!0,snippetLines:8,basePaths:[a.cwd()]}}function c5($,Z=0,W=new WeakSet){if(!$||typeof $!=="object"||Z>=XZ)return $;if(W.has($))return YZ;if(W.add($),Array.isArray($))return $.map((Y)=>c5(Y,Z+1,W));let X={};for(let[Y,J]of Object.entries($)){let G=Y.toLowerCase();if(WZ.some((z)=>G.includes(z)))X[Y]="********";else if(typeof J==="object"&&J!==null)X[Y]=c5(J,Z+1,W);else X[Y]=J}return X}function JZ($){let Z=$;if(Z.jsonBody)return c5(Z.jsonBody);if(Z.formBody)return c5(Z.formBody);return}async function GZ($){let W=$._authenticatedUser;if(W)return{id:W.id,email:W.email,name:W.name||W.username};return}async function l($,Z,W){let X=W?.status||500;if(t$.debug(`[error] ${X} ${$.message}`),!Q5()){if(t(Z)){let J=X>=400&&X<500,G=$.details;return new Response(B5({error:J?$.name||"Client Error":"Internal Server Error",message:J?$.message:"An unexpected error occurred.",status:X,details:J&&G&&typeof G==="object"?G:void 0}),{status:X,headers:r()})}return new Response(B9(X),{status:X,headers:{"Content-Type":"text/html; charset=utf-8"}})}try{let J=a$(ZZ());J.setFramework("Stacks","0.70.0");let G=JZ(Z);if(G){let U=new URL(Z.url);J.setRequest({method:Z.method,url:Z.url,headers:Object.fromEntries(Z.headers.entries()),queryParams:Object.fromEntries(U.searchParams.entries()),body:G})}else J.setRequest(Z);let z=await GZ(Z);if(z)J.setUser(z);if(W?.routingContext)J.setRouting(W.routingContext);else if(W?.handlerPath)J.setRouting({controller:W.handlerPath});for(let U of Q9())J.addQuery(U.query,U.time,U.connection);if(t(Z)){let U={handler:W?.handlerPath};if(Q5())U.stack=$.stack?.split(`
|
|
5
|
+
`).slice(0,10),U.queries=Q9().slice(-10);return new Response(B5({error:$.name||"Error",message:$.message,status:X,details:U}),{status:X,headers:r$()})}let Q=a.env.APP_URL?a.env.APP_URL.startsWith("http")?a.env.APP_URL:`https://${a.env.APP_URL}`:Q5()?"*":Z.headers.get("origin")??"null",B=await J.render($,X);return new Response(B,{status:X,headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":Q}})}catch(J){console.error("[Error Handler] Failed to render error page:",J);let G=(z)=>z.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return new Response(`
|
|
6
6
|
<html>
|
|
7
7
|
<head><title>Error</title></head>
|
|
8
8
|
<body>
|
|
9
9
|
<h1>Error</h1>
|
|
10
|
-
<p>${
|
|
11
|
-
<pre>${
|
|
10
|
+
<p>${G($.message)}</p>
|
|
11
|
+
<pre>${G($.stack||"")}</pre>
|
|
12
12
|
</body>
|
|
13
13
|
</html>
|
|
14
|
-
`,{status:X,headers:{"Content-Type":"text/html; charset=utf-8"}})}}async function x1($,Z){let Y=$.statusCode??$.status??500,X=O.env.APP_ENV!=="production"&&O.env.NODE_ENV!=="production";if(Y>=400&&Y<500)return new Response(B1({error:$.name||"ClientError",message:$.message,status:Y}),{status:Y,headers:_1()});if(X)return await u($,Z,{status:Y});return new Response(B1({error:"Internal Server Error",message:"An unexpected error occurred.",status:Y}),{status:Y,headers:_1()})}function f5($,Z){return new Response(B1({error:"ValidationError",message:"Validation failed",status:422,details:{errors:$}}),{status:422,headers:_1()})}async function g5($,Z){if(O.env.APP_ENV!=="production"&&O.env.NODE_ENV!=="production"){let X=Error(`Route not found: ${$}`);return X.name="NotFoundError",await u(X,Z,{status:404})}return new Response(k5(404),{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}var A1=50,r1,U1=0,o=0,N1,J8=5,a1,Q8,z8=10,U8="[Circular]";var b1=M1(()=>{r1=Array(A1).fill(null),N1=new Map,a1=new Set;Q8=["password","secret","token","api_key","apikey","access_key","accesskey","private_key","privatekey","credit_card","creditcard","card_number","cardnumber","cvv","ssn","authorization","credential","aws_secret","aws_access","database_password","db_password","encryption_key","signing_key","bearer","session_id","sessionid","cookie"]});var p5={};x5(p5,{loadRoutes:()=>d5});import{log as A8}from"@stacksjs/logging";async function d5($){for(let[Z,Y]of Object.entries($)){let X=L8(Y),J=X.prefix!==void 0?X.prefix?X.prefix.startsWith("/")?X.prefix:`/${X.prefix}`:void 0:H8.includes(Z)?void 0:`/${Z}`,G=F8(X.middleware);A8.debug(`[route-loader] Loading: ${X.path} prefix=${J||"/"} middleware=[${G.join(", ")}]`);try{if(J||G.length>0)await t.group({prefix:J,middleware:G.length>0?G:void 0},async()=>{await m5(X.path)});else await m5(X.path)}catch(W){let Q=W instanceof Error?W.message:String(W);throw console.error(`[Routes] Failed to load route file '${X.path}': ${Q}`),Error(`Route loading failed for '${X.path}': ${Q}`)}}await j8()}async function j8(){try{let{frameworkPath:$}=await import("@stacksjs/path"),Z=$("defaults/bootstrap.ts");if(await Bun.file(Z).exists())await import(Z)}catch($){let Z=$ instanceof Error?$.message:String($);if(!Z.includes("Cannot find module")&&!Z.includes("MODULE_NOT_FOUND"))console.error(`[Routes] Failed to load framework bootstrap: ${Z}`)}}async function m5($){let Z=$.replace(/\.ts$/,"");if(Z.includes("..")||Z.startsWith("/"))throw Error(`Invalid route path: ${Z}`);let{projectPath:Y}=await import("@stacksjs/path");await import(Y(`routes/${Z}`))}function L8($){if(typeof $==="string")return{path:$};return $}function F8($){if(!$)return[];if(typeof $==="string")return[$];return $}var H8;var e1=M1(()=>{w1();H8=["api","web"]});import V from"process";import{log as D}from"@stacksjs/logging";import{path as T}from"@stacksjs/path";import{UploadedFile as q1}from"@stacksjs/storage";import{applyRequestEnhancements as D8,Router as I8}from"@stacksjs/bun-router";function O8($){let Z=K8($),Y=new Map;for(let X of Z)Y.set(X,new RegExp(`(^|/):${X}(?=$|/)`,"g"));return{path:$,paramNames:Z,colonRegex:Y}}function K8($){let Z=new Set;for(let Y of $.matchAll(/\{(\w+)\}/g))if(Y[1])Z.add(Y[1]);for(let Y of $.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(Y[1])Z.add(Y[1]);return[...Z]}function T8($,Z={}){let Y=L1.get($);if(!Y)throw Error(`Route '${$}' is not defined. Available routes: ${[...L1.keys()].join(", ")}`);let X=Y.paramNames.filter((z)=>!(z in Z)||Z[z]===void 0);if(X.length>0)throw Error(`url('${$}'): missing required path param${X.length>1?"s":""} [${X.join(", ")}] for path '${Y.path}'. Pass them as the second argument: url('${$}', { ${Y.paramNames.join(", ")} })`);let J;try{J=V.env.APP_URL||"https://localhost"}catch{J="https://localhost"}if(J=J.replace(/\/$/,""),!J.startsWith("http"))J=`https://${J}`;let G=Y.path,W={};for(let[z,U]of Object.entries(Z)){let B=`{${z}}`;if(G.includes(B))G=G.replaceAll(B,encodeURIComponent(String(U)));else{let _=Y.colonRegex.get(z);if(_&&_.test(G))_.lastIndex=0,G=G.replace(_,`$1${encodeURIComponent(String(U))}`);else W[z]=String(U)}}let Q=Object.keys(W).length>0?`?${new URLSearchParams(W).toString()}`:"";return`${J}${G}${Q}`}function M8($){let Z=L1.get($);return Z?[...Z.paramNames]:[]}function t5(){let $=[],Z=new Set;for(let Y of a.keys()){if(Z.has(Y))continue;Z.add(Y);let X=Y.indexOf(":");if(X===-1)continue;let J=Y.slice(0,X),G=Y.slice(X+1),W;for(let[Q,z]of L1.entries())if(z.path===G){W=Q;break}$.push({method:J,path:G,name:W})}return $.sort((Y,X)=>Y.path.localeCompare(X.path))}async function S8(){if(j1)return j1;return j1=(async()=>{try{return(await import(T.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(T.storagePath("framework/defaults/app/Middleware.ts"))).default||{}}catch{return{}}}})(),j1}function N8($){if(!$)return $;let Z=c5.get($);if(Z!==void 0)return Z;let Y=$.split(E8).filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("");return c5.set($,Y),Y}async function C8($){let Y=(await S8())[$]||N8($);return D.debug(`[middleware] Resolved: ${$} \u2192 ${Y}`),Y}async function R8($){if(H1.has($))return H1.get($)??null;let Z=await C8($);try{let J=(await import(T.appPath(`Middleware/${Z}.ts`))).default;return H1.set($,J),J}catch{try{let J=(await import(T.storagePath(`framework/defaults/app/Middleware/${Z}.ts`))).default;return H1.set($,J),J}catch(Y){return D.error(`[Router] Failed to load middleware '${$}' (resolved to '${Z}'):`,Y),null}}}function a5(){H1.clear(),j1=null}function x8(){if(V.env.APP_ENV==="production"||V.env.NODE_ENV==="production")return()=>{};let $=[];return(async()=>{try{let Z=await import("fs"),Y=[T.appPath("Middleware"),T.appPath("Middleware.ts")];for(let X of Y)try{if(!Z.existsSync(X))continue;let J=Z.watch(X,{recursive:!0},()=>{D.debug("[middleware] hot-reload: clearing cache"),a5()});$.push(J)}catch{}}catch{}})(),()=>{for(let Z of $)try{Z.close()}catch{}$=[]}}function b8($){let Z=$.indexOf(":");if(Z===-1)return{name:$};return{name:$.substring(0,Z),params:$.substring(Z+1)}}function l($,Z){let Y=k8(Z,!0),X=null;if(typeof Z==="string")X=r5(Z).then(()=>{return}).catch(()=>{return});return async(J)=>{await $6(J);let G=e5(J);if(X)await X;return t1(G,async()=>{let W=a.get($)||[],Q=J.method.toUpperCase(),z=[...W],U=W.some((K)=>K==="csrf"||K.startsWith("csrf:")),B=n5.has($),_=o5.get($),H=_?s5.get(_)===!0:!1;if(V8.has(Q)&&!U&&!B&&!H)z.unshift("csrf");if(z.length>0){let K=new URL(J.url).pathname;D.debug(`[middleware] Executing chain: [${z.join(", ")}] for ${Q} ${K}`)}let A=[];for(let K of z){let{name:E,params:b}=b8(K);if(b)G._middlewareParams=G._middlewareParams||{},G._middlewareParams[E]=b;let g=await R8(E);if(g&&typeof g.handle==="function"){let C5=V.hrtime.bigint();try{let n1=new Promise((T1,p)=>setTimeout(()=>p(Error(`Middleware '${E}' exceeded 30000ms`)),30000));await Promise.race([g.handle(G),n1]);let d=Number(V.hrtime.bigint()-C5)/1e6;A.push({name:E,ms:d})}catch(h){let n1=Number(V.hrtime.bigint()-C5)/1e6;if(A.push({name:E,ms:n1}),D.debug(`[middleware] Blocked by: ${E}`),h instanceof Response){try{let{_requestId:p,_startNs:G1}=G,W1=G1!=null?Number(V.hrtime.bigint()-G1)/1e6:null,c=W1!=null?[`total;dur=${W1.toFixed(1)}`]:[];for(let Q1 of A){let s1=Q1.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);c.push(`mw_${s1};dur=${Q1.ms.toFixed(1)}`)}if(c.length>0)h.headers.set("Server-Timing",c.join(", "));if(p)h.headers.set("X-Request-ID",p)}catch{}return h}let d=h instanceof Error?h:Error(String(h)),T1="statusCode"in d||"status"in d?await x1(d,G):await(()=>{return D.error(`[Router] Middleware '${E}' threw an unexpected error:`,d),u(d,G,{status:500})})();try{let{_requestId:p,_startNs:G1}=G,W1=G1!=null?Number(V.hrtime.bigint()-G1)/1e6:null,c=W1!=null?[`total;dur=${W1.toFixed(1)}`]:[];for(let Q1 of A){let s1=Q1.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);c.push(`mw_${s1};dur=${Q1.ms.toFixed(1)}`)}if(c.length>0)T1.headers.set("Server-Timing",c.join(", "));if(p)T1.headers.set("X-Request-ID",p)}catch{}return T1}}}let j=await Y(G);if(R1(),G._corsConfig&&j)try{let{applyCorsHeaders:K}=await import(T.storagePath("framework/defaults/app/Middleware/Cors.ts"));j=K(G,j,G._corsConfig)}catch(K){D.warn("[router] CORS header injection failed",{error:K})}let{_requestId:I,_startNs:N}=G,s=N!=null?Number(V.hrtime.bigint()-N)/1e6:null,J1=(K)=>{if(I)K.set("X-Request-ID",I);if(s!=null){let E=[`total;dur=${s.toFixed(1)}`];for(let b of A){let g=b.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);E.push(`mw_${g};dur=${b.ms.toFixed(1)}`)}K.set("Server-Timing",E.join(", "))}};if(j&&typeof j.headers?.set==="function"){if(j.status>=400&&(j.headers.get("content-type")||"").includes("json")&&I)try{let E=await j.clone().text(),b=JSON.parse(E);if(b&&typeof b==="object"){let g=new Headers(j.headers);return J1(g),new Response(JSON.stringify({...b,request_id:I}),{status:j.status,statusText:j.statusText,headers:g})}}catch{}try{J1(j.headers)}catch{try{let E=j.clone(),b=new Headers(j.headers);return J1(b),new Response(E.body,{status:j.status,statusText:j.statusText,headers:b})}catch{}}}if(G._compress===!0&&j)try{let{applyCompression:K}=await import(T.storagePath("framework/defaults/app/Middleware/Compress.ts"));return await K(G,j)}catch(K){D.warn(`[router] Compression failed; sending uncompressed response: ${K instanceof Error?K.message:String(K)}`)}return j})}}function i($){if(!a.has($))a.set($,[]);let Z=$.includes(":")?$.substring($.indexOf(":")+1):$,Y={middleware(X){let J=a.get($);if(J)J.push(X);return Y},name(X){return L1.set(X,O8(Z)),Y},skipCsrf(){return n5.add($),Y}};return Y}async function $5($){try{return await Bun.file($).exists()}catch{return!1}}function w8($){if(typeof $!=="string"||$.length===0)throw Error(`[Router] Refusing to resolve handler '${String($)}': empty or non-string`);if($.includes("\x00"))throw Error("[Router] Refusing to resolve handler with null byte");if($.startsWith("/")||/^[A-Za-z]:[\\/]/.test($))throw Error(`[Router] Refusing to resolve absolute handler path '${$}'`);if($.split(/[/\\]/).some((Y)=>Y===".."))throw Error(`[Router] Refusing to resolve handler path '${$}' (contains '..' segment)`)}function l5($){let Z=u5.get($);if(!Z)Z=import($),u5.set($,Z);return Z}async function r5($){w8($);let Z=$;if(Z=Z.endsWith(".ts")?Z.slice(0,-3):Z,Z.includes("Controller")){let[X,J="index"]=Z.split("@"),G=T.appPath(`${X}.ts`),W=T.storagePath(`framework/defaults/app/${X}.ts`),Q=await $5(G)?G:W;try{let z=await l5(Q);if(!z.default||typeof z.default!=="function")throw Error(`Controller ${X} does not export a default class`);let U=new z.default;if(typeof U[J]!=="function")throw Error(`Method ${J} not found in controller ${X}`);return async(B)=>{let _=await U[J](B);return i5(_)}}catch(z){throw D.error(`[Router] Failed to load controller '${Q}':`,z),z}}let Y;if(Z.includes("storage/framework/orm"))Y=Z;else if(Z.includes("OrmAction"))Y=T.storagePath(`framework/actions/src/${Z}.ts`);else if(Z.includes("Actions")){let X=T.projectPath(`app/${Z}.ts`),J=T.storagePath(`framework/defaults/app/${Z}.ts`);Y=await $5(X)?X:J}else{let X=T.appPath(`${Z}.ts`),J=T.storagePath(`framework/defaults/app/${Z}.ts`);Y=await $5(X)?X:J}try{let J=(await l5(Y)).default;if(!J)throw Error(`Action '${$}' has no default export`);if(typeof J.handle!=="function")throw D.error(`[Router] Action '${$}' structure:`,Object.keys(J)),Error(`Action '${$}' has no handle() method. Got: ${typeof J.handle}`);let G=J.skipCsrf===!0||J.csrf===!1;return s5.set($,G),async(W)=>{if(G)W._skipCsrf=!0;try{if(J.validations){let z=await q8(W,J.validations);if(!z.valid)return new Response(JSON.stringify({error:"Validation failed",errors:z.errors}),{status:422,headers:{"Content-Type":"application/json"}})}let Q=await J.handle(W);return i5(Q)}catch(Q){let z=Q instanceof Error?Q.stack||Q.message:String(Q);throw D.error(`[Router] Error in action.handle() for '${$}': ${z}`),Q}}}catch(X){throw D.error(`[Router] Failed to import action '${Y}':`,X),X}}async function q8($,Z){let Y={},X=await P8($);for(let[J,G]of Object.entries(Z)){let W=X[J],Q;try{Q=G.rule.validate(W)}catch{Q={valid:!1,errors:[{message:`${J} validation failed`}]}}if(!Q.valid){let z=[],U=J.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(_)=>_.toUpperCase()),B=(_)=>_.toLowerCase().startsWith(J.toLowerCase())||_.includes(U)?_:`${U} ${_}`;if(Q.errors&&Q.errors.length>0)if(G.message){let _=Q.errors[0]?.message??"";z.push(typeof G.message==="string"?G.message:G.message[J]||B(_))}else Q.errors.forEach((_)=>z.push(B(_.message)));else z.push(G.message?typeof G.message==="string"?G.message:`${U} is invalid`:`${U} is invalid`);Y[J]=z}}return{valid:Object.keys(Y).length===0,errors:Y}}async function P8($){let Z={};if(new URL($.url).searchParams.forEach((X,J)=>{Z[J]=X}),$.params)Object.assign(Z,$.params);if($.jsonBody&&typeof $.jsonBody==="object")Object.assign(Z,$.jsonBody);else if($.formBody&&typeof $.formBody==="object")Object.assign(Z,$.formBody);return Z}function i5($){if($ instanceof Response)return $;if(typeof $==="object"&&$!==null)return Response.json($);return new Response(String($),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function e5($){D8($,$.params||{});let Z=$.query;if(!Z){let J=new URL($.url);Z={},J.searchParams.forEach((G,W)=>{Z[W]=G}),$.query=Z}let Y=null,X=()=>{if(Y)return Y;let J={};for(let[G,W]of Object.entries(Z||{}))J[G]=W;if($.jsonBody&&typeof $.jsonBody==="object")for(let[G,W]of Object.entries($.jsonBody))J[G]=W;if($.formBody&&typeof $.formBody==="object")for(let[G,W]of Object.entries($.formBody))J[G]=W;if($.params&&typeof $.params==="object")for(let[G,W]of Object.entries($.params))J[G]=W;return Y=J,J};return $.get=(J,G)=>{let Q=X()[J];return Q!==void 0?Q:G},$.input=(J,G)=>{let Q=X()[J];return Q!==void 0?Q:G},$.all=()=>X(),$.only=(J)=>{let G=X(),W={};for(let Q of J)if(Q in G)W[Q]=G[Q];return W},$.except=(J)=>{let W={...X()};for(let Q of J)delete W[Q];return W},$.has=(J)=>{let G=X();if(Array.isArray(J))return J.every((W)=>(W in G)&&G[W]!==void 0);return J in G&&G[J]!==void 0},$.hasAny=(J)=>{let G=X();return J.some((W)=>(W in G)&&G[W]!==void 0)},$.filled=(J)=>{let G=X(),W=(Q)=>{let z=G[Q];return z!==void 0&&z!==null&&z!==""&&!(Array.isArray(z)&&z.length===0)};if(Array.isArray(J))return J.every(W);return W(J)},$.missing=(J)=>{let G=X();if(Array.isArray(J))return J.every((W)=>!(W in G)||G[W]===void 0);return!(J in G)||G[J]===void 0},$.string=(J,G="")=>{let Q=X()[J];return Q!==void 0&&Q!==null?String(Q):G},$.integer=(J,G=0)=>{let Q=X()[J];if(Q===void 0||Q===null||Q==="")return G;if(typeof Q==="number")return Number.isFinite(Q)?Math.trunc(Q):G;let z=String(Q).trim();if(!/^-?\d+$/.test(z))return G;let U=Number.parseInt(z,10);return Number.isFinite(U)?U:G},$.float=(J,G=0)=>{let Q=X()[J];if(Q===void 0||Q===null||Q==="")return G;if(typeof Q==="number")return Number.isFinite(Q)?Q:G;let z=String(Q).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(z))return G;let U=Number.parseFloat(z);return Number.isFinite(U)?U:G},$.boolean=(J,G=!1)=>{let Q=X()[J];if(Q===void 0||Q===null)return G;if(typeof Q==="boolean")return Q;if(Q==="true"||Q==="1"||Q===1)return!0;if(Q==="false"||Q==="0"||Q===0)return!1;return G},$.array=(J)=>{let W=X()[J];if(Array.isArray(W))return W;return W!==void 0&&W!==null?[W]:[]},$.file=(J)=>{let W=($.files||{})[J];if(!W)return null;let Q=Array.isArray(W)?W[0]:W;return Q?new q1(Q):null},$.getFiles=(J)=>{let W=($.files||{})[J];if(!W)return[];return(Array.isArray(W)?W:[W]).map((z)=>new q1(z))},$.hasFile=(J)=>{let G=$.files||{};return J in G&&G[J]!==void 0},$.allFiles=()=>{let J=$.files||{},G={};for(let[W,Q]of Object.entries(J))if(Array.isArray(Q))G[W]=Q.map((z)=>new q1(z));else G[W]=new q1(Q);return G},$.user=async()=>{return $._authenticatedUser},$.userToken=async()=>{return $._currentAccessToken},$.tokenCan=async(J)=>{if(typeof J!=="string"||J.length===0)return!1;let G=$._currentAccessToken;if(!G||typeof G!=="object")return!1;if(!Array.isArray(G.abilities))return!1;if(G.abilities.includes("*"))return!0;return G.abilities.includes(J)},$.tokenCant=async(J)=>{return!await $.tokenCan(J)},$}function k8($,Z=!1){if(typeof $==="string"){let Y=$;return async(X)=>{try{if(!Z)await $6(X),X=e5(X);return await(await r5(Y))(X)}catch(J){return D.error(`[Router] Error handling request for '${Y}':`,J),await u(J instanceof Error?J:Error(String(J)),X,{handlerPath:Y})}}}return $}async function $6($){if($._bodyParsed)return;$._bodyParsed=!0;let Z=$.headers.get("content-type")||"";try{if(Z.includes("application/json")){let Y=await $.clone().json();$.jsonBody=Y}else if(Z.includes("application/x-www-form-urlencoded")){let Y=await $.clone().text(),X=new URLSearchParams(Y),J={};X.forEach((G,W)=>{J[W]=G}),$.formBody=J}else if(Z.includes("multipart/form-data")){let Y=await $.clone().formData(),X={},J={};Y.forEach((G,W)=>{if(G instanceof File)if(J[W])if(Array.isArray(J[W]))J[W].push(G);else J[W]=[J[W],G];else J[W]=G;else X[W]=G}),$.formBody=X,$.files=J}}catch(Y){D.debug("[stacks-router] Body parsing failed:",Y)}}function Z6($={}){let Z=new I8({verbose:$.verbose??!1}),Y="",X=[];function J(W,Q,z){let U=Y+Q,B=`${W}:${U}`;if(D.debug(`[router] ${W} ${U} \u2192 ${typeof z==="string"?z:"function"}`),X.length>0)a.set(B,[...X]);if(typeof z==="string")o5.set(B,z);return{fullPath:U,routeKey:B}}let G={bunRouter:Z,get routes(){return Z.routes},get(W,Q){let{fullPath:z,routeKey:U}=J("GET",W,Q);return Z.get(z,l(U,Q)),i(U)},post(W,Q){let{fullPath:z,routeKey:U}=J("POST",W,Q);return Z.post(z,l(U,Q)),i(U)},put(W,Q){let{fullPath:z,routeKey:U}=J("PUT",W,Q);return Z.put(z,l(U,Q)),i(U)},patch(W,Q){let{fullPath:z,routeKey:U}=J("PATCH",W,Q);return Z.patch(z,l(U,Q)),i(U)},delete(W,Q){let{fullPath:z,routeKey:U}=J("DELETE",W,Q);return Z.delete(z,l(U,Q)),i(U)},options(W,Q){let{fullPath:z,routeKey:U}=J("OPTIONS",W,Q);return Z.options(z,l(U,Q)),i(U)},group(W,Q){let z=Y,U=[...X];if(W.prefix)Y=z+W.prefix;let B=W.middleware?Array.isArray(W.middleware)?W.middleware:[W.middleware]:void 0;if(B)X=[...X,...B];D.debug(`[router] Entering group: prefix=${W.prefix||"/"} middleware=[${B?.join(", ")||""}]`);let _=Q();if(_ instanceof Promise)return _.then(()=>{return Y=z,X=U,G}).catch((H)=>{throw Y=z,X=U,H});return Y=z,X=U,G},resource(W,Q,z){let U=["index","store","show","update","destroy"],B=z?.only?U.filter((A)=>z.only.includes(A)):z?.except?U.filter((A)=>!z.except.includes(A)):U,_=Q.replace(/Action$/,"");D.debug(`[router] Resource: /${W} \u2192 ${Q} [${B.join(", ")}]`);let H=()=>{for(let A of B)switch(A){case"index":G.get(`/${W}`,`${_}IndexAction`);break;case"store":G.post(`/${W}`,`${_}StoreAction`);break;case"show":G.get(`/${W}/:id`,`${_}ShowAction`);break;case"update":G.put(`/${W}/:id`,`${_}UpdateAction`);break;case"destroy":G.delete(`/${W}/:id`,`${_}DestroyAction`);break}};if(z?.middleware)G.group({middleware:z.middleware},H);else H();return G},match(W,Q,z){D.debug(`[router] Match: [${W.join(", ")}] ${Q} \u2192 ${typeof z==="string"?z:"function"}`);for(let U of W){let B=U.toUpperCase(),{fullPath:_,routeKey:H}=J(B,Q,z),A=l(H,z);switch(B){case"GET":Z.get(_,A);break;case"POST":Z.post(_,A);break;case"PUT":Z.put(_,A);break;case"PATCH":Z.patch(_,A);break;case"DELETE":Z.delete(_,A);break;case"OPTIONS":Z.options(_,A);break}}return i(`${W[0]}:${Y}${Q}`)},health(){return Z.get("/health",async()=>{let W={},Q=async(B,_)=>{let H=Date.now();try{let A=new AbortController,j=setTimeout(()=>A.abort(),1500);await Promise.race([_(),new Promise((I,N)=>A.signal.addEventListener("abort",()=>N(Error("timeout"))))]),clearTimeout(j),W[B]={ok:!0,ms:Date.now()-H}}catch(A){W[B]={ok:!1,ms:Date.now()-H,message:A instanceof Error?A.message:String(A)}}};await Promise.all([Q("database",async()=>{let{db:B}=await import("@stacksjs/database");await B.unsafe?.("SELECT 1")}),Q("cache",async()=>{let{cache:B}=await import("@stacksjs/cache"),_=`__health__:${Date.now()}`;await B.set(_,1,5),await B.del(_)})]);let z=Object.values(W).every((B)=>B.ok),U={status:z?"healthy":"degraded",checks:W,timestamp:Date.now()};return Response.json(U,{status:z?200:503})}),Z.get("/__routes",()=>{if(((V.env.APP_ENV??"").toLowerCase()==="production"||V.env.NODE_ENV==="production")&&V.env.STACKS_EXPOSE_ROUTES!=="1")return Response.json({error:"disabled in production"},{status:404});return Response.json(t5())}),Z.get("/__storage/:path",async(W)=>{let Q=new URL(W.url),z=Q.searchParams.get("token"),U=W.params,B=U?.path?decodeURIComponent(U.path):decodeURIComponent(Q.pathname.replace(/^\/__storage\//,""));if(!z||typeof B!=="string"||B.length===0)return new Response("Forbidden",{status:403});let{verifySignedStorageToken:_,Storage:H}=await import("@stacksjs/storage");if(!_(z,B).valid)return new Response("Forbidden",{status:403});try{let j=H.disk();if(!await j.fileExists(B))return new Response("Not Found",{status:404});let N=await j.readToBuffer(B),s=await j.mimeType(B).catch(()=>"application/octet-stream");return new Response(N,{status:200,headers:{"Content-Type":s,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(j){return D.error("[storage] signed-url fetch failed:",j),new Response("Internal Error",{status:500})}}),Z.get("/__openapi.json",async()=>{if(((V.env.APP_ENV??"").toLowerCase()==="production"||V.env.NODE_ENV==="production")&&V.env.STACKS_EXPOSE_ROUTES!=="1")return Response.json({error:"disabled in production"},{status:404});try{let{generateOpenApi:z}=await import("@stacksjs/api"),U=await z();return Response.json(U)}catch(z){return Response.json({error:"OpenAPI generation failed",message:z instanceof Error?z.message:String(z)},{status:500})}}),G},use(W){return Z.globalMiddleware.push(W),G},async serve(W={}){return Z.serve(W)},async handleRequest(W){return Z.handleRequest(W)},async register(W,Q){D.debug(`[router] Register: ${W} prefix=${Q?.prefix||"none"}`);let z=async()=>{await import(W)};if(Q?.prefix||Q?.middleware)await G.group({prefix:Q.prefix,middleware:Q.middleware},z);else await z();return G},async importRoutes(){D.debug("[router] Loading user routes from registry...");try{let{loadRoutes:Q}=await Promise.resolve().then(() => (e1(),p5)),{appPath:z}=await import("@stacksjs/path"),U=(await import(z("Routes.ts"))).default;await Q(U)}catch(Q){throw D.error("Failed to load route registry:",Q),Q}D.debug("[router] Loading ORM routes...");let W=[T.frameworkPath("orm/routes.ts"),T.frameworkPath("core/orm/routes.ts")];for(let Q of W)try{if(await Bun.file(Q).exists()){await import(Q);break}}catch(z){D.debug(`ORM routes load failed for ${Q}:`,z)}D.debug("[router] Loading discovered package routes...");try{await G.loadDiscoveredRoutes()}catch(Q){D.debug("Package route discovery skipped:",Q)}},async loadDiscoveredRoutes(){try{let W=T.storagePath("framework/discovered-packages.json"),Q=Bun.file(W);if(!await Q.exists())return;let U=(await Q.json())?.packages;if(!U)return;let B=T.projectPath("pantry");for(let[_,H]of Object.entries(U)){let A=H?.routes;if(!A)continue;let j=Array.isArray(A)?A:[A],I=`${B}/${_}`;for(let N of j){D.debug(`[router] Discovered route: ${_} \u2192 ${N}`);let s=N.startsWith("/")?N:`${I}/${N}`,J1=H?.routePrefix,K=H?.routeMiddleware;try{await G.register(s,{prefix:J1,middleware:K})}catch(E){D.warn(`Failed to load routes from package '${_}': ${E}`)}}}}catch{}}};return G}async function v8($,Z){if(!P1)D.debug("[router] Loading routes for first time..."),P1=t.importRoutes().catch((X)=>{throw P1=null,X});await P1;let Y=await t.handleRequest($);if(Y.status===404&&Y.headers.get("content-type")?.includes("json"))try{let X=await Y.clone().json();if(X?.message==="Not Found"||X?.error==="Not Found"){let G=new URL($.url),W={...X,path:G.pathname,method:$.method};return new Response(JSON.stringify(W),{status:404,headers:Y.headers})}}catch{}return Y}async function y8($={}){return t.serve($)}var n5,s5,o5,V8,L1,H1,j1=null,E8,c5,a,u5,t,P1=null;var w1=M1(()=>{E1();b1();n5=new Set,s5=new Map,o5=new Map,V8=new Set(["POST","PUT","PATCH","DELETE"]),L1=new Map;H1=new Map;E8=/[-_\s]+/,c5=new Map;a=new Map;u5=new Map;t=Z6()});w1();E1();export*from"@stacksjs/bun-router";class Y6{name;priority;handle;constructor($){this.name=$.name,this.priority=$.priority??10,this.handle=$.handle}}e1();b1();w1();import{HttpError as l9}from"@stacksjs/error-handling";import{existsSync as X6,statSync as J6}from"fs";import{join as f8,relative as g8,resolve as G6}from"path";import m1 from"process";import{Buffer as k}from"buffer";import{createCipheriv as h8,createDecipheriv as m8,randomBytes as Z5}from"crypto";import{closeSync as Y5,createReadStream as W6,createWriteStream as d8,existsSync as k1,fsyncSync as Q6,openSync as z6,writeFileSync as p8}from"fs";import{access as c8,constants as U6,mkdir as u8,readdir as v1,rename as B6,stat as r,unlink as y1,writeFile as X5}from"fs/promises";import{isAbsolute as l8,join as e,resolve as i8}from"path";import L from"process";import{pipeline as n8}from"stream/promises";import{createGzip as _6}from"zlib";import $1 from"process";import v from"process";import f1 from"process";import{existsSync as g1}from"fs";import{resolve as J5}from"path";import{existsSync as s8}from"fs";import{existsSync as U5,mkdirSync as o8,readdirSync as t8,readFileSync as a8,writeFileSync as r8}from"fs";import{homedir as Z1}from"os";import{dirname as A6,resolve as R}from"path";import n from"process";import{existsSync as e8,readdirSync as $9}from"fs";import{extname as G5,resolve as H6}from"path";import Z9 from"process";var Y9=Object.defineProperty,X9=($)=>$;function J9($,Z){this[$]=X9.bind(null,Z)}var G9=($,Z)=>{for(var Y in Z)Y9($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:J9.bind(Z,Y)})},f=($,Z)=>()=>($&&(Z=$($=0)),Z),W9=import.meta.require;class I5{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let Y=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,X])=>Y.timestamp.getTime()-X.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let Y=0;Y<Z;Y++)this.cache.delete($[Y][0])}set($,Z,Y,X){if(!this.options.enabled)return;let J=this.generateKey($,Y),G=X??this.options.ttl,W=this.estimateSize(Z);this.cache.set(J,{value:Z,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,Z),X=this.cache.get(Y);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(Y),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified($,Z){try{if(!X6($))return!0;return J6($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let Y=this.get($,Z);if(!Y)return;if(this.isFileModified(Z,Y.fileTimestamp)){this.delete($,Z);return}return Y.value}setWithFileCheck($,Z,Y,X){try{let J=X6(Y)?J6(Y):null,G=J?J.mtime:new Date;this.set($,{value:Z,fileTimestamp:G},Y,X)}catch{this.set($,Z,Y,X)}}delete($,Z){let Y=this.generateKey($,Z);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((X,J)=>X+J.size,0),Y=$.map((X)=>X.timestamp).sort();return{size:Z,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[Z,Y]of this.cache.entries())$[Z]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[Z,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let X=Y;this.cache.set(Z,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class V5{metrics=[];maxMetrics=1000;async track($,Z,Y={}){let X=performance.now(),J=new Date;try{let G=await Z(),W=performance.now()-X;return this.recordMetric({operation:$,duration:W,timestamp:J,...Y}),G}catch(G){let W=performance.now()-X;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:J,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=Z.map((J)=>J.duration),X=Y.reduce((J,G)=>J+G,0);return{count:Z.length,averageDuration:X/Z.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:X,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function Q9($,Z={}){let X=Object.keys(Z).sort().map((J)=>`${J}:${Z[J]}`).join("|");return X?`${$}:${X}`:$}function z9($,Z){try{return JSON.stringify($)===JSON.stringify(Z)}catch{return $===Z}}function U9($){return $.getStats().size*2}var Y1,O1,O6,K1=f(()=>{Y1=new I5,O1=new V5,O6={createKey:Q9,isEquivalent:z9,estimateMemoryUsage:U9}});function B9($,Z={}){let Y=m1.cwd();while(Y.includes("storage"))Y=G6(Y,"..");let X=G6(Y,$||"");if(Z?.relative)return g8(m1.cwd(),X);return X}function M(){if(v.env.NODE_ENV==="test"||v.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _9(){if(v.env.NODE_ENV==="test"||v.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v<"u"){let $=v.type;if($==="renderer"||$==="worker")return!1;return!!(v.versions&&(v.versions.node||v.versions.bun))}return!1}class K6{async format($){let Z=await _9(),Y=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:$1.pid,hostname:Z(),environment:$1.env.NODE_ENV||"development",platform:$1.platform,version:$1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$1.env.NODE_ENV||$1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class c1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,Z={}){this.name=$,this.config={...D1},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new K6,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let Y={...Z},X=Z.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...h1,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...h1};return{...h1,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:D1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...Z,...Object.fromEntries(Object.entries($).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=Z.level;return Y}shouldWriteToFile(){return!M()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let J,G=0,W=3,Q=1000;while(G<W)try{try{try{await c8(this.config.logDirectory,U6.F_OK|U6.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await u8(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k.from($);try{if(!k1(this.currentLogFile))await X5(this.currentLogFile,"",{mode:420});if(J=z6(this.currentLogFile,"a",420),p8(J,z,{flag:"a"}),Q6(J),J!==void 0)Y5(J),J=void 0;if((await r(this.currentLogFile)).size===0){if(await X5(this.currentLogFile,z,{flag:"w",mode:420}),(await r(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(U){let B=U;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(G<W-1){let _=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,_);let H=Q*2**G;await new Promise((A)=>setTimeout(A,H)),G++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(J!==void 0)try{Y5(J)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(z){if(G===W-1){let B=z,_=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),z}G++;let U=Q*2**(G-1);await new Promise((B)=>setTimeout(B,U))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return e(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return e(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return e(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let Y=typeof Z.interval==="number"?Z.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,z])=>z.createdAt.getTime()-Q.createdAt.getTime()),G=typeof Z.maxKeys==="number"?Z.maxKeys:1,W=Math.max(1,G);if(J.length>W)for(let[Q]of J.slice(W))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return Z5(16).toString("hex")}generateKey(){return Z5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),Y=Z5(16),X=h8("aes-256-gcm",Z,Y),J=k.isBuffer($)?$:k.from($,"utf8"),G=X.update(J),W=X.final(),Q=G.length+W.length,z=X.getAuthTag(),U=k.allocUnsafe(16+Q+16);return Y.copy(U,0),G.copy(U,16),W.copy(U,16+G.length),z.copy(U,16+Q),{encrypted:U,iv:Y}}async compressData($){return new Promise((Z,Y)=>{let X=_6(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>Z(k.from(k.concat(J)))),X.on("error",Y),X.write($),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(M())return;if(!this.shouldWriteToFile())return;let $=await r(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await v1(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,U)=>{let B=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${W}`;if(await r(Y).catch(()=>null))try{if(await B6(Y,Q),Z.compress)try{let z=`${Q}.gz`;await this.compressLogFile(Q,z),await y1(Q)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await X5(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await r(Y).catch(()=>null))await B6(Y,G)}if(this.currentLogFile=X,Z.maxFiles){let G=(await v1(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,Q)=>Q.localeCompare(W));for(let W of G.slice(Z.maxFiles))await y1(e(this.config.logDirectory,W))}}}async compressLogFile($,Z){let Y=W6($),X=d8(Z),J=_6();await n8(Y,J,X)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),k1(this.currentLogFile))try{let $=z6(this.currentLogFile,"r+");Q6($),Y5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await v1(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of Z)try{await y1(e(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?F.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M())return!1;let $=typeof L.env.NO_COLOR<"u",Z=L.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:Y="",tag:X="",message:J,level:G,showTimestamp:W=!0}=$,Q=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(W)A.push(Z);if(G==="warning")A.push("WARN");else if(G==="error")A.push("ERROR");else if(Y)A.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)A.push(X.replace(/[[\]]/g,""));return A.push(J),A.join(" ")}let z=L.stdout.columns||120,U="";if(G==="warning"||G==="error")U=`${Y} ${J}`;else if(G==="info"||G==="success")U=`${Y} ${X} ${J}`;else U=`${Y} ${X} ${F.cyan(J)}`;if(!W)return U.trim();let B=Q(U).trim().length,_=Q(Z).length,H=Math.max(1,z-2-B-_);return`${U.trim()}${" ".repeat(H)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let Q=Number.parseInt(W,10);return Q<Z[0].length?String(Z[0][Q]):G});let Y=/%([sdijfo%])/g,X=0,J=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(X>=Z.length)return G;let Q=Z[X++];switch(W){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return G}});if(X<Z.length)J+=` ${Z.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,X,J)=>{let G=F.underline(F.blue(X)),W=this.toAbsoluteFilePath(J);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(W)}`,z="\x1B]8;;",U="\x1B\\";return`\x1B]8;;${Q}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),Z=Z.replace(/`([^`]+)`/g,(Y,X)=>F.bgGray(X)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(Y,X)=>F.bold(X)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,X)=>F.italic(X)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,X)=>F.italic(X)),Z=Z.replace(/~([^~]+)~/g,(Y,X)=>F.strikethrough(X)),Z}supportsHyperlinks(){if(M())return!1;let $=L.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let Y=L.env.HOME||"";if(Y)Z=Z.replace(/^~(?=$|\/)/,Y)}if(l8(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=i8(Z);else return null;return k1(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:Y}}async log($,Z,...Y){if(!this.shouldLog($))return;let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),W,Q;if(Z instanceof Error)W=Z.message,Q=Z.stack;else W=this.formatMessage(Z,Y);let{consoleText:z,fileText:U}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":T6[$],H=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",A;switch($){case"debug":A=this.formatConsoleMessage({timestamp:J,icon:_,tag:H,message:F.gray(z),level:$}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:J,icon:_,tag:H,message:z,level:$}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:J,icon:_,tag:H,message:F.green(z),level:$}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:J,icon:_,tag:H,message:z,level:$}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:J,icon:_,tag:H,message:z,level:$}),console.error(A),Q){let j=Q.split(`
|
|
15
|
-
`);for(let I of
|
|
16
|
-
`;if(
|
|
17
|
-
`;if(
|
|
18
|
-
`);if(this[
|
|
19
|
-
`,
|
|
20
|
-
`),
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
22
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
23
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||M()||!L.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await v1(this.config.logDirectory),Y=[];for(let X of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=e(this.config.logDirectory,X);if($.before)try{if((await r(G)).mtime>=$.before)continue}catch(W){console.error(`Failed to get stats for file ${G}:`,W);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await y1(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}var j6,W5,D1,A9,S,F,H9,L6,j9,F6,L9,F9,Q5,D9,D6,I6,I9,z5,V9,O9,K9,T9,M9,h1,T6,S9,E9=f(()=>{j6=m1.env.CLARITY_LOG_DIR||f8(B9(),"logs"),W5={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:j6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},D1={...W5},A9=(async()=>{try{let{loadConfig:$}=await Promise.resolve().then(()=>(f6(),y6)),Z=await $({name:"clarity",alias:"logging",defaultConfig:W5,cwd:m1.cwd()});if(Z)Object.assign(D1,Z)}catch{}return D1})(),S={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},F=S,H9=S.red,L6=S.green,j9=S.yellow,F6=S.blue,L9=S.magenta,F9=S.cyan,Q5=S.white,D9=S.gray,D6=S.bgRed,I6=S.bgYellow,I9=S.bgGray,z5=S.bold,V9=S.dim,O9=S.italic,K9=S.underline,T9=S.strikethrough,M9=S.reset,h1={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},T6={debug:"\uD83D\uDD0D",info:F6("\u2139"),success:L6("\u2713"),warning:I6(Q5(z5(" WARN "))),error:D6(Q5(z5(" ERROR ")))},S9=new c1("stacks")}),N9="0.15.9",C9=()=>{};async function M6($,Z={}){let{maxRetries:Y=3,retryDelay:X=1000,isRetryable:J=()=>!0,fallback:G}=Z,W=Error("Unknown error occurred");for(let Q=0;Q<=Y;Q++)try{return await $()}catch(z){if(W=z instanceof Error?z:Error(String(z)),Q===Y||!J(W))break;if(X>0)await new Promise((U)=>setTimeout(U,X))}if(G!==void 0)return G;throw W instanceof Error?W:Error(`Unknown error: ${String(W)}`)}function S6($){return $ instanceof x}function R9($){return $ instanceof d1}function x9($){if(S6($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}var x,d1,I1,B5,_5,p1,A5,H5,V1,j5,L5,m,X1=f(()=>{x=class extends Error{timestamp;context;constructor(Z,Y={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,X])=>`${Y}: ${X}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},d1=class extends x{code="CONFIG_NOT_FOUND";constructor(Z,Y,X){let J=X===void 0?[]:Array.isArray(X)?X.filter(Boolean):[X],G="";if(J.length===1)G=` or alias "${J[0]}"`;else if(J.length>1)G=` or aliases ${J.map((W)=>`"${W}"`).join(", ")}`;super(`Configuration "${Z}"${G} not found`,{configName:Z,alias:X,searchPaths:Y,searchPathCount:Y.length})}},I1=class extends x{code="CONFIG_LOAD_ERROR";constructor(Z,Y,X){super(`Failed to load configuration from "${Z}": ${Y.message}`,{configPath:Z,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B5=class extends x{code="CONFIG_VALIDATION_ERROR";constructor(Z,Y,X){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:X,validationErrors:Y,errorCount:Y.length})}},_5=class extends x{code="CONFIG_MERGE_ERROR";constructor(Z,Y,X,J){super(`Failed to merge configuration from "${Z}" with "${Y}": ${X.message}`,{sourcePath:Z,targetPath:Y,configName:J,originalError:X.name,originalMessage:X.message});this.cause=X}},p1=class extends x{code="ENV_VAR_ERROR";constructor(Z,Y,X,J){super(`Failed to parse environment variable "${Z}" with value "${Y}" as ${X}`,{envKey:Z,envValue:Y,expectedType:X,configName:J})}},A5=class extends x{code="FILE_SYSTEM_ERROR";constructor(Z,Y,X){super(`File system ${Z} failed for "${Y}": ${X.message}`,{operation:Z,path:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},H5=class extends x{code="TYPE_GENERATION_ERROR";constructor(Z,Y,X){super(`Failed to generate types from "${Z}" to "${Y}": ${X.message}`,{configDir:Z,outputPath:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},V1=class extends x{code="SCHEMA_VALIDATION_ERROR";constructor(Z,Y,X){super(`Schema validation failed${X?` for config "${X}"`:""}`,{schemaPath:Z,configName:X,validationErrors:Y,errorCount:Y.length})}},j5=class extends x{code="BROWSER_CONFIG_ERROR";constructor(Z,Y,X,J){super(`Failed to fetch configuration from "${Z}": ${Y} ${X}`,{endpoint:Z,status:Y,statusText:X,configName:J})}},L5=class extends x{code="PLUGIN_ERROR";constructor(Z,Y,X){super(`Plugin "${Z}" failed during ${Y}: ${X.message}`,{pluginName:Z,operation:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},m={configNotFound($,Z,Y){return new d1($,Z,Y)},configLoad($,Z,Y){return new I1($,Z,Y)},configValidation($,Z,Y){return new B5($,Z,Y)},configMerge($,Z,Y,X){return new _5($,Z,Y,X)},envVar($,Z,Y,X){return new p1($,Z,Y,X)},fileSystem($,Z,Y){return new A5($,Z,Y)},typeGeneration($,Z,Y){return new H5($,Z,Y)},schemaValidation($,Z,Y){return new V1($,Z,Y)},browserConfig($,Z,Y,X){return new j5($,Z,Y,X)},plugin($,Z,Y){return new L5($,Z,Y)}}});class u1{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,Y={}){let{prefix:X,useCamelCase:J=!0,useBackwardCompatibility:G=!0,customParsers:W={},verbose:Q=!1,trackPerformance:z=!0}=Y,U=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let B=X||this.generateEnvPrefix($),_={...Z};return this.processObject(_,[],B,{useCamelCase:J,useBackwardCompatibility:G,customParsers:W,verbose:Q,configName:$}),{config:_,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return O1.track("applyEnvironmentVariables",U,{configName:$});return U()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,Y,X){for(let[J,G]of Object.entries($)){let W=[...Z,J],Q=W.map((B)=>this.formatEnvKey(B,X.useCamelCase)),z=`${Y}_${Q.join("_")}`,U=X.useBackwardCompatibility?`${Y}_${W.map((B)=>B.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,W,Y,X);else{let B=f1.env[z]||(U?f1.env[U]:void 0);if(B!==void 0){if(X.verbose){let _=f1.env[z]?z:U}try{$[J]=this.parseEnvironmentValue(B,typeof G,z,X.customParsers,X.configName)}catch(_){if(_ instanceof p1)throw _;throw m.envVar(z,B,typeof G,X.configName)}}}}}parseEnvironmentValue($,Z,Y,X,J){for(let[G,W]of Object.entries(X))try{return W($)}catch{continue}for(let G of this.defaultParsers)if(G.canParse($,Z))try{return G.parse($)}catch{throw m.envVar(Y,$,`${Z} (via ${G.name} parser)`,J)}return $}getEnvironmentVariables($){let Z={},Y=$.toUpperCase();for(let[X,J]of Object.entries(f1.env))if(X.startsWith(Y)&&J!==void 0)Z[X]=J;return Z}validateEnvironmentVariable($,Z,Y){let X=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))X.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,Z,Y,{})}catch(J){X.push(`Cannot parse value "${Z}" as ${Y}: ${J}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs($,Z,Y={}){let{prefix:X,format:J="text"}=Y,G=X||this.generateEnvPrefix($),W=[];switch(this.extractEnvVarInfo(Z,[],G,W),J){case"markdown":return this.formatAsMarkdown(W,$);case"json":return JSON.stringify(W,null,2);default:return this.formatAsText(W,$)}}extractEnvVarInfo($,Z,Y,X){for(let[J,G]of Object.entries($)){let W=[...Z,J],Q=`${Y}_${W.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,W,Y,X);else X.push({key:Q,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${W.join(".")}`,example:this.generateExample(G)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let Y=`Environment Variables for ${Z}:
|
|
14
|
+
`,{status:X,headers:{"Content-Type":"text/html; charset=utf-8"}})}}async function U5($,Z){let W=$.statusCode??$.status??500,X=Q5();if(W>=400&&W<500){let Y=$.headers?{...$.headers,...r()}:r();return new Response(B5({error:$.name||"ClientError",message:$.message,status:W}),{status:W,headers:Y})}if(X)return await l($,Z,{status:W});return new Response(B5({error:"Internal Server Error",message:"An unexpected error occurred.",status:W}),{status:W,headers:r()})}function L9($,Z){return new Response(B5({error:"ValidationError",message:"Validation failed",status:422,details:{errors:$}}),{status:422,headers:r()})}async function F9($,Z){if(Q5()){let X=Error(`Route not found: ${$}`);return X.name="NotFoundError",await l(X,Z,{status:404})}if(t(Z))return new Response(B5({error:"NotFound",message:`Route not found: ${$}`,status:404}),{status:404,headers:r()});return new Response(B9(404),{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}var N5=50,e$=5,p5,U9,WZ,XZ=10,YZ="[Circular]";var u5=u(()=>{h5();S5();p5=Symbol.for("stacks.queryTracking"),U9=m5();WZ=["password","secret","token","api_key","apikey","access_key","accesskey","private_key","privatekey","credit_card","creditcard","card_number","cardnumber","cvv","ssn","authorization","credential","aws_secret","aws_access","database_password","db_password","encryption_key","signing_key","bearer","session_id","sessionid","cookie"]});import{existsSync as A9,statSync as V9}from"fs";import{join as zZ,relative as QZ,resolve as I9}from"path";import a5 from"process";import{Buffer as m}from"buffer";import{createCipheriv as BZ,createDecipheriv as UZ,randomBytes as V8}from"crypto";import{closeSync as I8,createReadStream as D9,createWriteStream as jZ,existsSync as l5,fsyncSync as O9,openSync as K9,writeFileSync as HZ}from"fs";import{access as LZ,constants as T9,mkdir as FZ,readdir as n5,rename as M9,stat as j5,unlink as i5,writeFile as D8}from"fs/promises";import{isAbsolute as _Z,join as H5,resolve as AZ}from"path";import A from"process";import{pipeline as VZ}from"stream/promises";import{createGzip as S9}from"zlib";import L5 from"process";import p from"process";import s5 from"process";import{existsSync as o5}from"fs";import{resolve as O8}from"path";import{existsSync as IZ}from"fs";import{existsSync as N8,mkdirSync as DZ,readdirSync as OZ,readFileSync as KZ,writeFileSync as TZ}from"fs";import{homedir as F5}from"os";import{dirname as N9,resolve as q}from"path";import e from"process";import{existsSync as MZ,readdirSync as SZ}from"fs";import{extname as K8,resolve as C9}from"path";import NZ from"process";function EZ($,Z){this[$]=xZ.bind(null,Z)}class k8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let W=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${W}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,W],[,X])=>W.timestamp.getTime()-X.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let W=0;W<Z;W++)this.cache.delete($[W][0])}set($,Z,W,X){if(!this.options.enabled)return;let Y=this.generateKey($,W),J=X??this.options.ttl,G=this.estimateSize(Z);this.cache.set(Y,{value:Z,timestamp:new Date,ttl:J,hits:0,size:G}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let W=this.generateKey($,Z),X=this.cache.get(W);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(W),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified($,Z){try{if(!A9($))return!0;return V9($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let W=this.get($,Z);if(!W)return;if(this.isFileModified(Z,W.fileTimestamp)){this.delete($,Z);return}return W.value}setWithFileCheck($,Z,W,X){try{let Y=A9(W)?V9(W):null,J=Y?Y.mtime:new Date;this.set($,{value:Z,fileTimestamp:J},W,X)}catch{this.set($,Z,W,X)}}delete($,Z){let W=this.generateKey($,Z);return this.cache.delete(W)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,W]of this.cache.entries())if(this.isExpired(W))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((X,Y)=>X+Y.size,0),W=$.map((X)=>X.timestamp).sort();return{size:Z,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:W[0],newestEntry:W[W.length-1]}}export(){let $={};for(let[Z,W]of this.cache.entries())$[Z]={value:W.value,timestamp:W.timestamp.toISOString(),ttl:W.ttl,hits:W.hits,size:W.size};return $}import($){this.cache.clear();for(let[Z,W]of Object.entries($))if(typeof W==="object"&&W!==null){let X=W;this.cache.set(Z,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class v8{metrics=[];maxMetrics=1000;async track($,Z,W={}){let X=performance.now(),Y=new Date;try{let J=await Z(),G=performance.now()-X;return this.recordMetric({operation:$,duration:G,timestamp:Y,...W}),J}catch(J){let G=performance.now()-X;throw this.recordMetric({operation:`${$}:error`,duration:G,timestamp:Y,...W}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let W=Z.map((Y)=>Y.duration),X=W.reduce((Y,J)=>Y+J,0);return{count:Z.length,averageDuration:X/Z.length,minDuration:Math.min(...W),maxDuration:Math.max(...W),totalDuration:X,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function bZ($,Z={}){let X=Object.keys(Z).sort().map((Y)=>`${Y}:${Z[Y]}`).join("|");return X?`${$}:${X}`:$}function wZ($,Z){try{return JSON.stringify($)===JSON.stringify(Z)}catch{return $===Z}}function PZ($){return $.getStats().size*2}function kZ($,Z={}){let W=a5.cwd();while(W.includes("storage"))W=I9(W,"..");let X=I9(W,$||"");if(Z?.relative)return QZ(a5.cwd(),X);return X}function N(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vZ(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p<"u"){let $=p.type;if($==="renderer"||$==="worker")return!1;return!!(p.versions&&(p.versions.node||p.versions.bun))}return!1}class k9{async format($){let Z=await vZ(),W=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:W})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:L5.pid,hostname:Z(),environment:L5.env.NODE_ENV||"development",platform:L5.platform,version:L5.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:L5.env.NODE_ENV||L5.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,Z={}){this.name=$,this.config={...x5},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new k9,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??A.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let W={...Z},X=Z.timestamp!==void 0;if(X)delete W.timestamp;if(this.config={...this.config,...W,timestamp:X||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),J=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,J),this.encryptionKeys.set(Y,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},W=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[W]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...t5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...t5};return{...t5,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:x5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},W={...Z,...Object.fromEntries(Object.entries($).filter(([,X])=>X!==void 0))};if(!W.level||!["debug","info","success","warning","error"].includes(W.level))W.level=Z.level;return W}shouldWriteToFile(){return!N()&&this.config.writeToFile===!0}async writeToFile($){let W=(async()=>{let Y,J=0,G=3,z=1000;while(J<G)try{try{try{await LZ(this.config.logDirectory,T9.F_OK|T9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await FZ(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:m.from($);try{if(!l5(this.currentLogFile))await D8(this.currentLogFile,"",{mode:420});if(Y=K9(this.currentLogFile,"a",420),HZ(Y,Q,{flag:"a"}),O9(Y),Y!==void 0)I8(Y),Y=void 0;if((await j5(this.currentLogFile)).size===0){if(await D8(this.currentLogFile,Q,{flag:"w",mode:420}),(await j5(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let U=B;if(U.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(U.code)){if(J<G-1){let j=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${G}:`,j);let H=z*2**J;await new Promise((L)=>setTimeout(L,H)),J++;continue}}if(U?.code&&["ENOSPC","EDQUOT"].includes(U.code))throw Error(`Disk quota exceeded or no space left on device: ${U.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",U),U}finally{if(Y!==void 0)try{I8(Y)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===G-1){let U=Q,j=typeof U.message==="string"?U.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),Q}J++;let B=z*2**(J-1);await new Promise((U)=>setTimeout(U,B))}})();this.pendingOperations.push(W);let X=this.pendingOperations.length-1;try{await W}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return H5(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return H5(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return H5(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(N())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let W=typeof Z.interval==="number"?Z.interval:60,X=Math.max(W,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,W=this.generateKeyId(),X=this.generateKey();this.currentKeyId=W,this.keys.set(W,X),this.encryptionKeys.set(W,{key:X,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,z],[,Q])=>Q.createdAt.getTime()-z.createdAt.getTime()),J=typeof Z.maxKeys==="number"?Z.maxKeys:1,G=Math.max(1,J);if(Y.length>G)for(let[z]of Y.slice(G))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return V8(16).toString("hex")}generateKey(){return V8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),W=V8(16),X=BZ("aes-256-gcm",Z,W),Y=m.isBuffer($)?$:m.from($,"utf8"),J=X.update(Y),G=X.final(),z=J.length+G.length,Q=X.getAuthTag(),B=m.allocUnsafe(16+z+16);return W.copy(B,0),J.copy(B,16),G.copy(B,16+J.length),Q.copy(B,16+z),{encrypted:B,iv:W}}async compressData($){return new Promise((Z,W)=>{let X=S9(),Y=[];X.on("data",(J)=>Y.push(J)),X.on("end",()=>Z(m.from(m.concat(Y)))),X.on("error",W),X.write($),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(N())return;if(!this.shouldWriteToFile())return;let $=await j5(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let W=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await n5(this.config.logDirectory),J=Y.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let U=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),G=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${W}.${G}`;if(await j5(W).catch(()=>null))try{if(await M9(W,z),Z.compress)try{let Q=`${z}.gz`;await this.compressLogFile(z,Q),await i5(z)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!Y.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${W}.1`;await D8(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),J=W.replace(/\.log$/,`-${Y}.log`);if(await j5(W).catch(()=>null))await M9(W,J)}if(this.currentLogFile=X,Z.maxFiles){let J=(await n5(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,z)=>z.localeCompare(G));for(let G of J.slice(Z.maxFiles))await i5(H5(this.config.logDirectory,G))}}}async compressLogFile($,Z){let W=D9($),X=jZ(Z),Y=S9();await VZ(W,Y,X)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let W of this.logBuffer){let X=await this.formatter.format(W);if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),l5(this.currentLogFile))try{let $=K9(this.currentLogFile,"r+");O9($),I8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!N()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await n5(this.config.logDirectory)).filter((W)=>(W.includes("temp")||W.includes(".tmp"))&&W.includes(this.name));for(let W of Z)try{await i5(H5(this.config.logDirectory,W))}catch(X){console.error(`Failed to delete temp file ${W}:`,X)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?V.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N())return!1;let $=typeof A.env.NO_COLOR<"u",Z=A.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof A.stderr<"u"&&A.stderr.isTTY||typeof A.stdout<"u"&&A.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:W="",tag:X="",message:Y,level:J,showTimestamp:G=!0}=$,z=(L)=>L.replace(this.ANSI_PATTERN,"");if(!this.fancy){let L=[];if(G)L.push(Z);if(J==="warning")L.push("WARN");else if(J==="error")L.push("ERROR");else if(W)L.push(W.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)L.push(X.replace(/[[\]]/g,""));return L.push(Y),L.join(" ")}let Q=A.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${W} ${Y}`;else if(J==="info"||J==="success")B=`${W} ${X} ${Y}`;else B=`${W} ${X} ${V.cyan(Y)}`;if(!G)return B.trim();let U=z(B).trim().length,j=z(Z).length,H=Math.max(1,Q-2-U-j);return`${B.trim()}${" ".repeat(H)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(J,G)=>{let z=Number.parseInt(G,10);return z<Z[0].length?String(Z[0][z]):J});let W=/%([sdijfo%])/g,X=0,Y=$.replace(W,(J,G)=>{if(G==="%")return"%";if(X>=Z.length)return J;let z=Z[X++];switch(G){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return J}});if(X<Z.length)Y+=` ${Z.slice(X).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(W,X,Y)=>{let J=V.underline(V.blue(X)),G=this.toAbsoluteFilePath(Y);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(G)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${z}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),Z=Z.replace(/`([^`]+)`/g,(W,X)=>V.bgGray(X)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(W,X)=>V.bold(X)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(W,X)=>V.italic(X)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(W,X)=>V.italic(X)),Z=Z.replace(/~([^~]+)~/g,(W,X)=>V.strikethrough(X)),Z}supportsHyperlinks(){if(N())return!1;let $=A.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let W=A.env.HOME||"";if(W)Z=Z.replace(/^~(?=$|\/)/,W)}if(_Z(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=AZ(Z);else return null;return l5(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,W=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:W}}async log($,Z,...W){if(!this.shouldLog($))return;let X=new Date,Y=this.formatConsoleTimestamp(X),J=this.formatFileTimestamp(X),G,z;if(Z instanceof Error)G=Z.message,z=Z.stack;else G=this.formatMessage(Z,W);let{consoleText:Q,fileText:B}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":v9[$],H=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",L;switch($){case"debug":L=this.formatConsoleMessage({timestamp:Y,icon:j,tag:H,message:V.gray(Q),level:$}),console.error(L);break;case"info":L=this.formatConsoleMessage({timestamp:Y,icon:j,tag:H,message:Q,level:$}),console.warn(L);break;case"success":L=this.formatConsoleMessage({timestamp:Y,icon:j,tag:H,message:V.green(Q),level:$}),console.error(L);break;case"warning":L=this.formatConsoleMessage({timestamp:Y,icon:j,tag:H,message:Q,level:$}),console.warn(L);break;case"error":if(L=this.formatConsoleMessage({timestamp:Y,icon:j,tag:H,message:Q,level:$}),console.error(L),z){let F=z.split(`
|
|
15
|
+
`);for(let I of F)if(I.trim()&&!I.includes(G))console.error(this.formatConsoleMessage({timestamp:Y,message:V.gray(` ${I}`),level:$,showTimestamp:!1}))}break}}else if(!N()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${G}`),z)console.error(z)}let U=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
16
|
+
`;if(z)U+=`${z}
|
|
17
|
+
`;if(U=U.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(U)}progress($,Z=""){let W={update:(z,Q)=>{},finish:(z)=>{},interrupt:(z,Q)=>{}};if(!this.enabled)return W;let X=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:X,lastRenderedLine:""},this.shouldStyleConsole()&&!N()&&A.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(z,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,z),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!N()&&A.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,Q="info")=>{if(!N()&&A.stdout.isTTY)A.stdout.write(`
|
|
18
|
+
`);if(this[Q==="warning"?"warn":Q](z),this.activeProgressBar&&this.shouldStyleConsole()&&!N()&&A.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":V.blue("\u25D0"),tag:W,message:`${V.cyan($)}...`}))}return async(W)=>{if(!this.enabled)return;let X=performance.now(),Y=Math.round(X-Z),J=`${$} completed in ${Y}ms`,G=new Date,z=this.formatConsoleTimestamp(G),B=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${J}`;if(W)B+=` ${JSON.stringify(W)}`;if(B+=`
|
|
19
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:this.options.showIcons===!1?"":V.green("\u2713"),tag:U,message:`${J}${W?` ${JSON.stringify(W)}`:""}`}))}else if(!N())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...Z){await this.log("debug",$,...Z)}async info($,...Z){await this.log("info",$,...Z)}async success($,...Z){await this.log("success",$,...Z)}async warn($,...Z){await this.log("warning",$,...Z)}async error($,...Z){await this.log("error",$,...Z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,W=new $8(Z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(W),W}createReadStream(){if(N())throw Error("createReadStream is not supported in browser environments");if(!l5(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return D9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let W=this.keys.get(this.currentKeyId);try{let X=m.isBuffer($)?$:m.from($,"base64"),Y=X.subarray(0,16),J=X.subarray(X.length-16),G=X.subarray(16,X.length-16),z=UZ("aes-256-gcm",W,Y);z.setAuthTag(J);let Q=z.update(G),B=z.final(),U=Q.length+B.length,j=m.allocUnsafe(U);return Q.copy(j,0),B.copy(j,Q.length),j.toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N()}isServerMode(){return!N()}setTestEncryptionKey($,Z){this.currentKeyId=$,this.keys.set($,Z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let Z=new Date,W=this.formatConsoleTimestamp(Z),X=this.formatFileTimestamp(Z),{consoleText:Y,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let z=Y.split(`
|
|
20
|
+
`),Q=Math.max(...z.map((H)=>H.length))+2,B=`\u250C${"\u2500".repeat(Q)}\u2510`,U=`\u2514${"\u2500".repeat(Q)}\u2518`,j=z.map((H)=>{return this.formatConsoleMessage({timestamp:W,message:V.cyan(H),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:W,message:V.cyan(B),showTimestamp:!1})),j.forEach((H)=>console.error(H)),console.error(this.formatConsoleMessage({timestamp:W,message:V.cyan(U),showTimestamp:!1}))}else if(!N())console.error(`${X} ${this.environment}.INFO: [BOX] ${J}`);let G=`${X} ${this.environment}.INFO: [BOX] ${J}
|
|
21
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt($){if(N())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${V.cyan("?")} ${$} (y/n) `);let W=(X)=>{let Y=X.toString().trim().toLowerCase();A.stdin.removeListener("data",W);try{if(typeof A.stdin.setRawMode==="function")A.stdin.setRawMode(!1)}catch{}A.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof A.stdin.setRawMode==="function")A.stdin.setRawMode(!0)}catch{}A.stdin.resume(),A.stdin.once("data",W)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let W=$;if(Z&&Z.length>0){let Q=/%([sdijfo%])/g,B=0;if(W=$.replace(Q,(U,j)=>{if(j==="%")return"%";if(B>=Z.length)return U;let H=Z[B++];switch(j){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return U}}),B<Z.length)W+=` ${Z.slice(B).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}let{consoleText:X,fileText:Y}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${V.blue("\u25D0")} `;console.error(`${B}${Q} ${V.cyan(X)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
22
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!A.stdout.isTTY)return;let W=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),X=Math.round($.barLength*W/100),Y=$.barLength-X,J=V.green("\u2501".repeat(X)),G=V.gray("\u2501".repeat(Y)),z=`[${J}${G}]`,Q=`${W}%`.padStart(4),B=$.message?` ${$.message}`:"",U=this.options.showIcons===!1?"":Z||W===100?V.green("\u2713"):V.blue("\u25B6"),j=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",H=`\r${U}${j} ${z} ${Q}${B}`,L=A.stdout.columns||80,F=" ".repeat(Math.max(0,L-H.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${H}${F}`,A.stdout.write($.lastRenderedLine),Z)A.stdout.write(`
|
|
23
|
+
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||N()||!A.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(N()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await n5(this.config.logDirectory),W=[];for(let X of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let J=H5(this.config.logDirectory,X);if($.before)try{if((await j5(J)).mtime>=$.before)continue}catch(G){console.error(`Failed to get stats for file ${J}:`,G);continue}W.push(J)}if(W.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${W.length} log file(s)...`);for(let X of W)try{await i5(X),console.warn(`Deleted log file: ${X}`)}catch(Y){console.error(`Failed to delete log file ${X}:`,Y)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function y9($,Z={}){let{maxRetries:W=3,retryDelay:X=1000,isRetryable:Y=()=>!0,fallback:J}=Z,G=Error("Unknown error occurred");for(let z=0;z<=W;z++)try{return await $()}catch(Q){if(G=Q instanceof Error?Q:Error(String(Q)),z===W||!Y(G))break;if(X>0)await new Promise((B)=>setTimeout(B,X))}if(J!==void 0)return J;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function f9($){return $ instanceof P}function rZ($){return $ instanceof r5}function eZ($){if(f9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((W)=>$.message.toLowerCase().includes(W.toLowerCase()))}class Z8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,W={}){let{prefix:X,useCamelCase:Y=!0,useBackwardCompatibility:J=!0,customParsers:G={},verbose:z=!1,trackPerformance:Q=!0}=W,B=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let U=X||this.generateEnvPrefix($),j={...Z};return this.processObject(j,[],U,{useCamelCase:Y,useBackwardCompatibility:J,customParsers:G,verbose:z,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return q5.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,W,X){for(let[Y,J]of Object.entries($)){let G=[...Z,Y],z=G.map((U)=>this.formatEnvKey(U,X.useCamelCase)),Q=`${W}_${z.join("_")}`,B=X.useBackwardCompatibility?`${W}_${G.map((U)=>U.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,G,W,X);else{let U=s5.env[Q]||(B?s5.env[B]:void 0);if(U!==void 0){if(X.verbose){let j=s5.env[Q]?Q:B}try{$[Y]=this.parseEnvironmentValue(U,typeof J,Q,X.customParsers,X.configName)}catch(j){if(j instanceof e5)throw j;throw n.envVar(Q,U,typeof J,X.configName)}}}}}parseEnvironmentValue($,Z,W,X,Y){for(let[J,G]of Object.entries(X))try{return G($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,Z))try{return J.parse($)}catch{throw n.envVar(W,$,`${Z} (via ${J.name} parser)`,Y)}return $}getEnvironmentVariables($){let Z={},W=$.toUpperCase();for(let[X,Y]of Object.entries(s5.env))if(X.startsWith(W)&&Y!==void 0)Z[X]=Y;return Z}validateEnvironmentVariable($,Z,W){let X=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))X.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(W)try{this.parseEnvironmentValue($,Z,W,{})}catch(Y){X.push(`Cannot parse value "${Z}" as ${W}: ${Y}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs($,Z,W={}){let{prefix:X,format:Y="text"}=W,J=X||this.generateEnvPrefix($),G=[];switch(this.extractEnvVarInfo(Z,[],J,G),Y){case"markdown":return this.formatAsMarkdown(G,$);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,$)}}extractEnvVarInfo($,Z,W,X){for(let[Y,J]of Object.entries($)){let G=[...Z,Y],z=`${W}_${G.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,G,W,X);else X.push({key:z,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${G.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let W=`Environment Variables for ${Z}:
|
|
24
24
|
|
|
25
|
-
`;for(let X of $)
|
|
26
|
-
`,
|
|
27
|
-
`,
|
|
28
|
-
`,
|
|
25
|
+
`;for(let X of $)W+=`${X.key}
|
|
26
|
+
`,W+=` Type: ${X.type}
|
|
27
|
+
`,W+=` Description: ${X.description}
|
|
28
|
+
`,W+=` Example: ${X.example}
|
|
29
29
|
|
|
30
|
-
`;return
|
|
30
|
+
`;return W}formatAsMarkdown($,Z){let W=`# Environment Variables for ${Z}
|
|
31
31
|
|
|
32
|
-
`;
|
|
33
|
-
`,
|
|
34
|
-
`;for(let X of $)
|
|
35
|
-
`;return Y}}var E6=f(()=>{K1(),X1()});function b9($,Z){let Y=W9("process");if(typeof Y>"u"||!Y.env)return Z;let X=Y.env[$];return X!==void 0?X:Z}function N6($,Z,Y={}){return C6($,Z,Y,new WeakMap)}function C6($,Z,Y,X){let{arrayMergeMode:J="replace",skipNullish:G=!1,customMerger:W}=Y;if(Z===null||Z===void 0)return G?$:Z;if(W){let Q=W($,Z);if(Q!==void 0)return Q}if(Array.isArray(Z)||Array.isArray($))return R6($,Z,J,X);if(!P(Z)||!P($))return Z;return k9($,Z,Y,X)}function R6($,Z,Y,X){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(Y){case"replace":return Z;case"concat":return w9($,Z);case"smart":return q9($,Z,X);default:return Z}return Z}function w9($,Z){let Y=[...Z];for(let X of $)if(!Y.some((J)=>F5(J,X)))Y.push(X);return Y}function q9($,Z,Y){if(Z.length===0)return $;if($.length===0)return Z;if(P(Z[0])&&P($[0]))return P9($,Z,Y);if(Z.every((X)=>typeof X==="string")&&$.every((X)=>typeof X==="string")){let X=[...Z];for(let J of $)if(!X.includes(J))X.push(J);return X}return Z}function P9($,Z,Y){let X=[...Z];for(let J of $){if(!P(J)){X.push(J);continue}let G=["id","name","key","path","type"],W=!1;for(let Q of G)if(Q in J){if(X.find((U)=>P(U)&&(Q in U)&&U[Q]===J[Q])){W=!0;break}}if(!W)X.push(J)}return X}function k9($,Z,Y,X){let J=Z;if(P(J)&&X.has(J))return X.get(J);let G={...$};if(P(J))X.set(J,G);for(let W in J){if(!Object.prototype.hasOwnProperty.call(J,W))continue;let Q=J[W],z=G[W];if(Y.skipNullish&&(Q===null||Q===void 0))continue;if(Q===null||Q===void 0){G[W]=Q;continue}if(P(Q)&&P(z))G[W]=C6(z,Q,Y,X);else if(Array.isArray(Q)||Array.isArray(z))G[W]=R6(z,Q,Y.arrayMergeMode||"smart",X);else G[W]=Q}return G}function O5($,Z,Y="replace"){return N6($,Z,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function F5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let Y=0;Y<$.length;Y++)if(!F5($[Y],Z[Y]))return!1;return!0}if(P($)&&P(Z)){let Y=Object.keys($),X=Object.keys(Z);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call(Z,J))return!1;if(!F5($[J],Z[J]))return!1}return!0}return!1}function P($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}var x6,K5=f(()=>{x6={replace:"replace",concat:"concat",smart:"smart"}});class l1{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,Y={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:G,trackPerformance:W=!0,verbose:Q=!1}=Y;if(J){let U=Y1.getWithFileCheck("file",$);if(U){if(Q)console.log(`Configuration loaded from cache: ${$}`);return U}}let z=async()=>{if(!g1($))return null;try{let U=`?t=${Date.now()}`,B=await import($+U),_=B.default||B,H="default"in B,A=Object.keys(B).length>0;if(!H&&!A)throw new I1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new I1($,Error("Configuration must export a valid object"),"unknown");let N={config:O5(Z,_,X),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)Y1.setWithFileCheck("file",N,$,G);return N}catch(U){throw U instanceof Error?m.configLoad($,U):m.configLoad($,Error(String(U)))}};if(W)return O1.track("loadFromPath",z,{path:$});return z()}async tryLoadFromPaths($,Z,Y={}){for(let X of $)try{let J=await this.loadFromPath(X,Z,Y);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Y.verbose)console.warn(`Failed to load config from ${X}:`,J)}return null}generateConfigPaths($,Z,Y){let X=this.generateNamePatterns($,Y),J=[];for(let G of X)for(let W of this.extensions)J.push(J5(Z,`${G}${W}`));return J}generateNamePatterns($,Z){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let X=Z===void 0?[]:Array.isArray(Z)?Z:[Z];for(let G of X){if(!G)continue;if(Y.push(G,`.${G}.config`,`${G}.config`,`.${G}`),$)Y.push(`${$}.${G}.config`,`.${$}.${G}.config`)}let J=new Set;return Y.filter((G)=>{if(!G||J.has(G))return!1;return J.add(G),!0})}checkFileAccess($){return M6(async()=>{return g1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,Y){let X=[];if(!g1($))return X;if(Z||Y){let J=this.generateNamePatterns(Z||"",Y);for(let G of J)for(let W of this.extensions){let Q=J5($,`${G}${W}`);if(await this.checkFileAccess(Q))X.push(Q)}}else try{let{readdirSync:J}=await import("fs"),G=J($);for(let W of G)if(this.looksLikeConfigFile(W)){let Q=J5($,W);if(await this.checkFileAccess(Q))X.push(Q)}}catch{return[]}return X}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let Z=[];try{if(!g1($))return Z.push("Configuration file does not exist"),Z;let Y=await import($),X=Y.default||Y;if(X===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof X!=="object"||X===null)Z.push("Configuration must be an object");else if(Array.isArray(X))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),G=J($,"utf8");JSON.parse(G)}catch(J){Z.push(`Invalid JSON syntax: ${J}`)}}catch(Y){Z.push(`Failed to load configuration file: ${Y}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let Y=new Map;return await Promise.allSettled($.map(async(X)=>{try{let J=await this.loadFromPath(X,{},Z);if(J)Y.set(X,J.config)}catch(J){if(Z.verbose)console.warn(`Failed to preload ${X}:`,J)}})),Y}}var b6=f(()=>{K1(),X1(),K5()});class T5{async validateConfiguration($,Z,Y={}){let{stopOnFirstError:X=!1,validateRequired:J=!0,validateTypes:G=!0,customRules:W=[],trackPerformance:Q=!0,verbose:z=!1}=Y,U=async()=>{let B=[],_=[],H={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:W,trackPerformance:Q,verbose:z};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,H);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...W],H);else return this.validateWithJSONSchema($,Z,H)}catch(A){return B.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:B,warnings:_}}};if(Q)return await O1.track("validateConfiguration",U);return U()}async validateWithSchemaFile($,Z,Y){try{if(!s8(Z))throw new V1(Z,[{path:"",message:"Schema file does not exist"}]);let X=await import(Z),J=X.default||X;if(Array.isArray(J))return this.validateWithRules($,J,Y);else return this.validateWithJSONSchema($,J,Y)}catch(X){throw new V1(Z,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema($,Z,Y){let X=[],J=[];return this.validateObjectAgainstSchema($,Z,"",X,J,Y),{isValid:X.length===0,errors:X,warnings:J}}validateObjectAgainstSchema($,Z,Y,X,J,G){if(G.validateTypes&&Z.type){let W=Array.isArray($)?"array":typeof $,Q=Array.isArray(Z.type)?Z.type:[Z.type];if(!Q.includes(W)){if(X.push({path:Y,message:`Expected type ${Q.join(" or ")}, got ${W}`,expected:Q.join(" or "),actual:W,rule:"type"}),G.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(X.push({path:Y,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),G.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)X.push({path:Y,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)X.push({path:Y,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))X.push({path:Y,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)X.push({path:Y,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)X.push({path:Y,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let W=0;W<$.length;W++){let Q=Y?`${Y}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema($[W],Z.items,Q,X,J,G),G.stopOnFirstError&&X.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let W=$;if(G.validateRequired&&Z.required){for(let Q of Z.required)if(!(Q in W)){if(X.push({path:Y?`${Y}.${Q}`:Q,message:`Missing required property '${Q}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if(Z.properties){for(let[Q,z]of Object.entries(Z.properties))if(Q in W){let U=Y?`${Y}.${Q}`:Q;if(this.validateObjectAgainstSchema(W[Q],z,U,X,J,G),G.stopOnFirstError&&X.length>0)return}}if(Z.additionalProperties===!1){let Q=new Set(Object.keys(Z.properties||{}));for(let z of Object.keys(W))if(!Q.has(z))J.push({path:Y?`${Y}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,Y){let X=[],J=[];for(let G of Z)try{let W=this.getValueByPath($,G.path),Q=this.validateWithRule(W,G,G.path);if(X.push(...Q),Y.stopOnFirstError&&X.length>0)break}catch(W){X.push({path:G.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:J}}validateWithRule($,Z,Y){let X=[];if(Z.required&&($===void 0||$===null))return X.push({path:Y,message:Z.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),X;if($===void 0||$===null)return X;if(Z.type){let J=Array.isArray($)?"array":typeof $;if(J!==Z.type)X.push({path:Y,message:Z.message||`Expected type ${Z.type}, got ${J}`,expected:Z.type,actual:J,rule:"type"})}if(Z.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<Z.min)X.push({path:Y,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:J,rule:"min"})}if(Z.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>Z.max)X.push({path:Y,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:J,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))X.push({path:Y,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))X.push({path:Y,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let J=Z.validator($);if(J)X.push({path:Y,message:Z.message||J,rule:"custom"})}return X}getValueByPath($,Z){if(!Z)return $;let Y=Z.split("."),X=$;for(let J of Y)if(X&&typeof X==="object"&&J in X)X=X[J];else return;return X}generateRulesFromInterface($){let Z=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of Y){let[,J,G,W]=X;Z.push({path:J,required:!G,type:this.mapTypeScriptType(W)})}return Z}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:w6},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var w6,q6=f(()=>{K1(),X1(),w6=/^https?:\/\//});function v9($){if(!$)return"";let Z=Array.isArray($)?$.filter(Boolean):[$];if(Z.length===0)return"";if(Z.length===1)return` or alias "${Z[0]}"`;return` or aliases ${Z.map((Y)=>`"${Y}"`).join(", ")}`}class M5{fileLoader=new l1;envProcessor=new u1;validator=new T5;async loadConfig($){let Z=Date.now(),{cache:Y,performance:X,schema:J,validate:G,...W}=$;try{if(Y?.enabled){let z=this.checkCache(W.name||"",W);if(z)return z}let Q;try{Q=await this.loadConfigurationStrategies(W,!0,Y)}catch(z){let U=W.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(U)throw z;Q={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let B=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),_=!B&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),H=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(U&&(H||B))throw z;if(_&&(!U||!H))Q={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!U)Q={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else Q={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(J||G)await this.validateConfiguration(Q.config,J,G,W.name);if(Y?.enabled&&Q)this.cacheResult(W.name||"",Q,Y,W);if(X?.enabled){let z={operation:"loadConfig",duration:Date.now()-Z,configName:W.name,timestamp:new Date};if(X.onMetrics)X.onMetrics(z);if(X.slowThreshold&&z.duration>X.slowThreshold)q.warn(`Slow configuration loading detected: ${z.duration}ms for ${W.name}`);Q.metrics=z}return Q}catch(Q){let z=Date.now()-Z;throw q.error(`Configuration loading failed after ${z}ms:`,[Q instanceof Error?Q:Error(String(Q))]),Q}}async loadConfigurationStrategies($,Z=!1,Y){let{name:X="",alias:J,cwd:G,configDir:W,defaultConfig:Q,checkEnv:z=!0,arrayStrategy:U="replace",verbose:B=!1}=$,_=G||n.cwd(),H=[],A=await this.loadLocalConfiguration(X,J,_,W,Q,U,B,z,Y);if(A)return H.push(...this.getLocalSearchPaths(X,J,_,W)),this.finalizeResult(A,H,z,X,B);let j=await this.loadHomeConfiguration(X,J,Q,U,B,z);if(j)return H.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(j,H,z,X,B);let I=await this.loadPackageJsonConfiguration(X,J,_,Q,U,B,z);if(I)return H.push(R(_,"package.json")),this.finalizeResult(I,H,z,X,B);if(H.push(...this.getAllSearchPaths(X,J,_,W)),Z)throw m.configNotFound(X,H,J);return{...await this.applyEnvironmentVariables(X,Q,z,B),warnings:[`No configuration file found for "${X}"${v9(J)}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,Y,X,J,G,W,Q,z){let U=Q?F1($,J,W):J,B=this.getLocalDirectories(Y,X);for(let _ of B){if(W)q.info(`Searching for configuration in: ${_}`);let H=this.fileLoader.generateConfigPaths($,_,Z),A=await this.fileLoader.tryLoadFromPaths(H,U,{arrayStrategy:G,verbose:W,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(A){if(W)q.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration($,Z,Y,X,J,G){if(!$)return null;let W=G?F1($,Y,J):Y,Q=[R(Z1(),".config",$),R(Z1(),".config"),Z1()];for(let z of Q){if(J)q.info(`Checking home directory: ${z}`);let U=this.fileLoader.generateConfigPaths($,z,Z),B=await this.fileLoader.tryLoadFromPaths(U,W,{arrayStrategy:X,verbose:J});if(B){if(J)q.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,Z,Y,X,J,G,W){let Q=W?F1($,X,G):X;try{let z=R(Y,"package.json");if(!U5(z))return null;let U={};try{U=JSON.parse(a8(z,"utf8"))}catch(H){if(G)q.warn("Failed to parse package.json:",[H instanceof Error?H:Error(String(H))]);return null}let B=U[$],_=$;if(!B&&Z){let H=Array.isArray(Z)?Z:[Z];for(let A of H){if(!A)continue;if(U[A]){B=U[A],_=A;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(G)q.success(`Configuration loaded from package.json: ${_}`);return{config:O5(Q,B,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)q.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables($,Z,Y,X){if(!Y||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:F1($,Z,X),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,Y,X,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,Y,X){let J=[];if(Y){let G=Y($);if(G)J.push(...G)}if(Z){let G=await this.validator.validateConfiguration($,Z);if(!G.isValid)J.push(...G.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(J.length>0)throw m.configValidation(X||"unknown",J,X)}checkCache($,Z){let Y=this.generateCacheKey($,Z);return Y1.get(Y)||null}cacheResult($,Z,Y,X){let J=this.generateCacheKey($,X);Y1.set(J,Z,void 0,Y.ttl)}generateCacheKey($,Z){let Y=[$];if(Z.alias){let X=Array.isArray(Z.alias)?Z.alias.join(","):Z.alias;Y.push(`alias:${X}`)}if(Z.cwd)Y.push(`cwd:${Z.cwd}`);if(Z.configDir)Y.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)Y.push(`checkEnv:${Z.checkEnv}`);return Y.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,R($,"config"),R($,".config"),Z?R($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,Y,X){let J=[];return J.push(...this.getLocalSearchPaths($,Z,Y,X)),J.push(...this.getHomeSearchPaths($,Z)),J.push(R(Y,"package.json")),J}getLocalSearchPaths($,Z,Y,X){let J=this.getLocalDirectories(Y,X),G=[];for(let W of J)G.push(...this.fileLoader.generateConfigPaths($,W,Z));return G}getHomeSearchPaths($,Z){if(!$)return[];let Y=[R(Z1(),".config",$),R(Z1(),".config"),Z1()],X=[];for(let J of Y)X.push(...this.fileLoader.generateConfigPaths($,J,Z));return X}async loadConfigWithResult($){return this.loadConfig($)}}function V6($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),X=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||X}async function y9($){return y.loadConfig({...$,__strictErrorHandling:!0})}async function P6($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let X;if(Y)X=await y.loadConfig($);else X=await y.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return X?.config??Z}catch(X){let J=X instanceof Error?X.name:"UnknownError",G=X instanceof Error?X.message:String(X);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||G.includes("config"))&&$.verbose)q.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let Q=Y?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await y.applyEnvironmentVariables(Q.name||"",Z,!0,Q.verbose||!1))?.config??Z;return Z}}async function f9($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:Z}=await import("process");try{return(await y.loadConfig({name:$,cwd:Z(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&V6(Y)))return(await y.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await y.loadConfig({...$,cwd:$.cwd||n.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&V6(Z)))return(await y.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw Z}}async function g9($,Z,Y="replace"){let X=new l1;try{let J=await X.loadFromPath($,Z,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function F1($,Z,Y=!1){let X=new u1,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(W,Q=[]){let z={...W};for(let[U,B]of Object.entries(W)){let _=[...Q,U],H=[`${J}_${_.join("_").toUpperCase()}`,`${J}_${_.map((I)=>I.toUpperCase()).join("")}`,`${J}_${_.map((I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,j;for(let I of H)if(A=n.env[I],A!==void 0){j=I;break}if(A!==void 0&&j)if(typeof B==="boolean")z[U]=["true","1","yes"].includes(A.toLowerCase());else if(typeof B==="number"){let I=Number(A);if(!Number.isNaN(I))z[U]=I}else if(Array.isArray(B))try{z[U]=JSON.parse(A)}catch{z[U]=A.split(",").map((I)=>I.trim())}else z[U]=A;else if(B&&typeof B==="object"&&!Array.isArray(B))z[U]=G(B,_)}return z}return G(Z)}function h9($){let Z=R(n.cwd(),$.configDir),Y=R(n.cwd(),$.generatedDir),X=R(Y,"config-types.ts");if(!U5(A6(X)))o8(A6(X),{recursive:!0,mode:511});let J=U5(Z)?t8(Z).map((W)=>W.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],G=`// Generated by bunfig v${N9}
|
|
36
|
-
export type ConfigNames = ${
|
|
37
|
-
`;
|
|
38
|
-
${
|
|
32
|
+
`;W+=`| Variable | Type | Description | Example |
|
|
33
|
+
`,W+=`|----------|------|-------------|----------|
|
|
34
|
+
`;for(let X of $)W+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
|
|
35
|
+
`;return W}}function $1($,Z){let W=qZ("process");if(typeof W>"u"||!W.env)return Z;let X=W.env[$];return X!==void 0?X:Z}function h9($,Z,W={}){return m9($,Z,W,new WeakMap)}function m9($,Z,W,X){let{arrayMergeMode:Y="replace",skipNullish:J=!1,customMerger:G}=W;if(Z===null||Z===void 0)return J?$:Z;if(G){let z=G($,Z);if(z!==void 0)return z}if(Array.isArray(Z)||Array.isArray($))return p9($,Z,Y,X);if(!y(Z)||!y($))return Z;return Y1($,Z,W,X)}function p9($,Z,W,X){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(W){case"replace":return Z;case"concat":return Z1($,Z);case"smart":return W1($,Z,X);default:return Z}return Z}function Z1($,Z){let W=[...Z];for(let X of $)if(!W.some((Y)=>w8(Y,X)))W.push(X);return W}function W1($,Z,W){if(Z.length===0)return $;if($.length===0)return Z;if(y(Z[0])&&y($[0]))return X1($,Z,W);if(Z.every((X)=>typeof X==="string")&&$.every((X)=>typeof X==="string")){let X=[...Z];for(let Y of $)if(!X.includes(Y))X.push(Y);return X}return Z}function X1($,Z,W){let X=[...Z];for(let Y of $){if(!y(Y)){X.push(Y);continue}let J=["id","name","key","path","type"],G=!1;for(let z of J)if(z in Y){if(X.find((B)=>y(B)&&(z in B)&&B[z]===Y[z])){G=!0;break}}if(!G)X.push(Y)}return X}function Y1($,Z,W,X){let Y=Z;if(y(Y)&&X.has(Y))return X.get(Y);let J={...$};if(y(Y))X.set(Y,J);for(let G in Y){if(!Object.prototype.hasOwnProperty.call(Y,G))continue;let z=Y[G],Q=J[G];if(W.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){J[G]=z;continue}if(y(z)&&y(Q))J[G]=m9(Q,z,W,X);else if(Array.isArray(z)||Array.isArray(Q))J[G]=p9(Q,z,W.arrayMergeMode||"smart",X);else J[G]=z}return J}function y8($,Z,W="replace"){return h9($,Z,{arrayMergeMode:W==="replace"?"replace":"smart",skipNullish:!0})}function w8($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let W=0;W<$.length;W++)if(!w8($[W],Z[W]))return!1;return!0}if(y($)&&y(Z)){let W=Object.keys($),X=Object.keys(Z);if(W.length!==X.length)return!1;for(let Y of W){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!w8($[Y],Z[Y]))return!1}return!0}return!1}function y($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class W8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,W={}){let{arrayStrategy:X="replace",useCache:Y=!0,cacheTtl:J,trackPerformance:G=!0,verbose:z=!1}=W;if(Y){let B=_5.getWithFileCheck("file",$);if(B){if(z)console.log(`Configuration loaded from cache: ${$}`);return B}}let Q=async()=>{if(!o5($))return null;try{let B=`?t=${Date.now()}`,U=await import($+B),j=U.default||U,H="default"in U,L=Object.keys(U).length>0;if(!H&&!L)throw new E5($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new E5($,Error("Configuration must export a valid object"),"unknown");let f={config:y8(Z,j,X),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)_5.setWithFileCheck("file",f,$,J);return f}catch(B){throw B instanceof Error?n.configLoad($,B):n.configLoad($,Error(String(B)))}};if(G)return q5.track("loadFromPath",Q,{path:$});return Q()}async tryLoadFromPaths($,Z,W={}){for(let X of $)try{let Y=await this.loadFromPath(X,Z,W);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(W.verbose)console.warn(`Failed to load config from ${X}:`,Y)}return null}generateConfigPaths($,Z,W){let X=this.generateNamePatterns($,W),Y=[];for(let J of X)for(let G of this.extensions)Y.push(O8(Z,`${J}${G}`));return Y}generateNamePatterns($,Z){let W=[];if(W.push("config",".config"),$)W.push($,`.${$}.config`,`${$}.config`,`.${$}`);let X=Z===void 0?[]:Array.isArray(Z)?Z:[Z];for(let J of X){if(!J)continue;if(W.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)W.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let Y=new Set;return W.filter((J)=>{if(!J||Y.has(J))return!1;return Y.add(J),!0})}checkFileAccess($){return y9(async()=>{return o5($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,W){let X=[];if(!o5($))return X;if(Z||W){let Y=this.generateNamePatterns(Z||"",W);for(let J of Y)for(let G of this.extensions){let z=O8($,`${J}${G}`);if(await this.checkFileAccess(z))X.push(z)}}else try{let{readdirSync:Y}=await import("fs"),J=Y($);for(let G of J)if(this.looksLikeConfigFile(G)){let z=O8($,G);if(await this.checkFileAccess(z))X.push(z)}}catch{return[]}return X}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((W)=>W.test($))}async validateConfigFile($){let Z=[];try{if(!o5($))return Z.push("Configuration file does not exist"),Z;let W=await import($),X=W.default||W;if(X===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof X!=="object"||X===null)Z.push("Configuration must be an object");else if(Array.isArray(X))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Y}=await import("fs"),J=Y($,"utf8");JSON.parse(J)}catch(Y){Z.push(`Invalid JSON syntax: ${Y}`)}}catch(W){Z.push(`Failed to load configuration file: ${W}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let W=new Map;return await Promise.allSettled($.map(async(X)=>{try{let Y=await this.loadFromPath(X,{},Z);if(Y)W.set(X,Y.config)}catch(Y){if(Z.verbose)console.warn(`Failed to preload ${X}:`,Y)}})),W}}class g8{async validateConfiguration($,Z,W={}){let{stopOnFirstError:X=!1,validateRequired:Y=!0,validateTypes:J=!0,customRules:G=[],trackPerformance:z=!0,verbose:Q=!1}=W,B=async()=>{let U=[],j=[],H={stopOnFirstError:X,validateRequired:Y,validateTypes:J,customRules:G,trackPerformance:z,verbose:Q};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,H);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...G],H);else return this.validateWithJSONSchema($,Z,H)}catch(L){return U.push({path:"",message:`Validation failed: ${L}`,rule:"system"}),{isValid:!1,errors:U,warnings:j}}};if(z)return await q5.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,Z,W){try{if(!IZ(Z))throw new R5(Z,[{path:"",message:"Schema file does not exist"}]);let X=await import(Z),Y=X.default||X;if(Array.isArray(Y))return this.validateWithRules($,Y,W);else return this.validateWithJSONSchema($,Y,W)}catch(X){throw new R5(Z,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema($,Z,W){let X=[],Y=[];return this.validateObjectAgainstSchema($,Z,"",X,Y,W),{isValid:X.length===0,errors:X,warnings:Y}}validateObjectAgainstSchema($,Z,W,X,Y,J){if(J.validateTypes&&Z.type){let G=Array.isArray($)?"array":typeof $,z=Array.isArray(Z.type)?Z.type:[Z.type];if(!z.includes(G)){if(X.push({path:W,message:`Expected type ${z.join(" or ")}, got ${G}`,expected:z.join(" or "),actual:G,rule:"type"}),J.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(X.push({path:W,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)X.push({path:W,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)X.push({path:W,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))X.push({path:W,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)X.push({path:W,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)X.push({path:W,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let G=0;G<$.length;G++){let z=W?`${W}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema($[G],Z.items,z,X,Y,J),J.stopOnFirstError&&X.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let G=$;if(J.validateRequired&&Z.required){for(let z of Z.required)if(!(z in G)){if(X.push({path:W?`${W}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(Z.properties){for(let[z,Q]of Object.entries(Z.properties))if(z in G){let B=W?`${W}.${z}`:z;if(this.validateObjectAgainstSchema(G[z],Q,B,X,Y,J),J.stopOnFirstError&&X.length>0)return}}if(Z.additionalProperties===!1){let z=new Set(Object.keys(Z.properties||{}));for(let Q of Object.keys(G))if(!z.has(Q))Y.push({path:W?`${W}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,W){let X=[],Y=[];for(let J of Z)try{let G=this.getValueByPath($,J.path),z=this.validateWithRule(G,J,J.path);if(X.push(...z),W.stopOnFirstError&&X.length>0)break}catch(G){X.push({path:J.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:Y}}validateWithRule($,Z,W){let X=[];if(Z.required&&($===void 0||$===null))return X.push({path:W,message:Z.message||`Property '${W}' is required`,expected:"required",rule:"required"}),X;if($===void 0||$===null)return X;if(Z.type){let Y=Array.isArray($)?"array":typeof $;if(Y!==Z.type)X.push({path:W,message:Z.message||`Expected type ${Z.type}, got ${Y}`,expected:Z.type,actual:Y,rule:"type"})}if(Z.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<Z.min)X.push({path:W,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:Y,rule:"min"})}if(Z.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>Z.max)X.push({path:W,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:Y,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))X.push({path:W,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))X.push({path:W,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let Y=Z.validator($);if(Y)X.push({path:W,message:Z.message||Y,rule:"custom"})}return X}getValueByPath($,Z){if(!Z)return $;let W=Z.split("."),X=$;for(let Y of W)if(X&&typeof X==="object"&&Y in X)X=X[Y];else return;return X}generateRulesFromInterface($){let Z=[],W=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of W){let[,Y,J,G]=X;Z.push({path:Y,required:!J,type:this.mapTypeScriptType(G)})}return Z}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:u9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function J1($){if(!$)return"";let Z=Array.isArray($)?$.filter(Boolean):[$];if(Z.length===0)return"";if(Z.length===1)return` or alias "${Z[0]}"`;return` or aliases ${Z.map((W)=>`"${W}"`).join(", ")}`}class h8{fileLoader=new W8;envProcessor=new Z8;validator=new g8;async loadConfig($){let Z=Date.now(),{cache:W,performance:X,schema:Y,validate:J,...G}=$;try{if(W?.enabled){let Q=this.checkCache(G.name||"",G);if(Q)return Q}let z;try{z=await this.loadConfigurationStrategies(G,!0,W)}catch(Q){let B=G.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;z={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let U=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),j=!U&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),H=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(H||U))throw Q;if(j&&(!B||!H))z={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)z={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else z={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(Y||J)await this.validateConfiguration(z.config,Y,J,G.name);if(W?.enabled&&z)this.cacheResult(G.name||"",z,W,G);if(X?.enabled){let Q={operation:"loadConfig",duration:Date.now()-Z,configName:G.name,timestamp:new Date};if(X.onMetrics)X.onMetrics(Q);if(X.slowThreshold&&Q.duration>X.slowThreshold)v.warn(`Slow configuration loading detected: ${Q.duration}ms for ${G.name}`);z.metrics=Q}return z}catch(z){let Q=Date.now()-Z;throw v.error(`Configuration loading failed after ${Q}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,Z=!1,W){let{name:X="",alias:Y,cwd:J,configDir:G,defaultConfig:z,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:U=!1}=$,j=J||e.cwd(),H=[],L=await this.loadLocalConfiguration(X,Y,j,G,z,B,U,Q,W);if(L)return H.push(...this.getLocalSearchPaths(X,Y,j,G)),this.finalizeResult(L,H,Q,X,U);let F=await this.loadHomeConfiguration(X,Y,z,B,U,Q);if(F)return H.push(...this.getHomeSearchPaths(X,Y)),this.finalizeResult(F,H,Q,X,U);let I=await this.loadPackageJsonConfiguration(X,Y,j,z,B,U,Q);if(I)return H.push(q(j,"package.json")),this.finalizeResult(I,H,Q,X,U);if(H.push(...this.getAllSearchPaths(X,Y,j,G)),Z)throw n.configNotFound(X,H,Y);return{...await this.applyEnvironmentVariables(X,z,Q,U),warnings:[`No configuration file found for "${X}"${J1(Y)}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,W,X,Y,J,G,z,Q){let B=z?C5($,Y,G):Y,U=this.getLocalDirectories(W,X);for(let j of U){if(G)v.info(`Searching for configuration in: ${j}`);let H=this.fileLoader.generateConfigPaths($,j,Z),L=await this.fileLoader.tryLoadFromPaths(H,B,{arrayStrategy:J,verbose:G,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(L){if(G)v.success(`Configuration loaded from: ${L.source.path}`);return L}}return null}async loadHomeConfiguration($,Z,W,X,Y,J){if(!$)return null;let G=J?C5($,W,Y):W,z=[q(F5(),".config",$),q(F5(),".config"),F5()];for(let Q of z){if(Y)v.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths($,Q,Z),U=await this.fileLoader.tryLoadFromPaths(B,G,{arrayStrategy:X,verbose:Y});if(U){if(Y)v.success(`Configuration loaded from home directory: ${U.source.path}`);return U}}return null}async loadPackageJsonConfiguration($,Z,W,X,Y,J,G){let z=G?C5($,X,J):X;try{let Q=q(W,"package.json");if(!N8(Q))return null;let B={};try{B=JSON.parse(KZ(Q,"utf8"))}catch(H){if(J)v.warn("Failed to parse package.json:",[H instanceof Error?H:Error(String(H))]);return null}let U=B[$],j=$;if(!U&&Z){let H=Array.isArray(Z)?Z:[Z];for(let L of H){if(!L)continue;if(B[L]){U=B[L],j=L;break}}}if(U&&typeof U==="object"&&!Array.isArray(U)){if(J)v.success(`Configuration loaded from package.json: ${j}`);return{config:y8(z,U,Y),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)v.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables($,Z,W,X){if(!W||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:C5($,Z,X),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,W,X,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,W,X){let Y=[];if(W){let J=W($);if(J)Y.push(...J)}if(Z){let J=await this.validator.validateConfiguration($,Z);if(!J.isValid)Y.push(...J.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(Y.length>0)throw n.configValidation(X||"unknown",Y,X)}checkCache($,Z){let W=this.generateCacheKey($,Z);return _5.get(W)||null}cacheResult($,Z,W,X){let Y=this.generateCacheKey($,X);_5.set(Y,Z,void 0,W.ttl)}generateCacheKey($,Z){let W=[$];if(Z.alias){let X=Array.isArray(Z.alias)?Z.alias.join(","):Z.alias;W.push(`alias:${X}`)}if(Z.cwd)W.push(`cwd:${Z.cwd}`);if(Z.configDir)W.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)W.push(`checkEnv:${Z.checkEnv}`);return W.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,q($,"config"),q($,".config"),Z?q($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,W,X){let Y=[];return Y.push(...this.getLocalSearchPaths($,Z,W,X)),Y.push(...this.getHomeSearchPaths($,Z)),Y.push(q(W,"package.json")),Y}getLocalSearchPaths($,Z,W,X){let Y=this.getLocalDirectories(W,X),J=[];for(let G of Y)J.push(...this.fileLoader.generateConfigPaths($,G,Z));return J}getHomeSearchPaths($,Z){if(!$)return[];let W=[q(F5(),".config",$),q(F5(),".config"),F5()],X=[];for(let Y of W)X.push(...this.fileLoader.generateConfigPaths($,Y,Z));return X}async loadConfigWithResult($){return this.loadConfig($)}}function w9($){let W=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),X=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return W||X}async function G1($){return c.loadConfig({...$,__strictErrorHandling:!0})}async function n9($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},W="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let X;if(W)X=await c.loadConfig($);else X=await c.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return X?.config??Z}catch(X){let Y=X instanceof Error?X.name:"UnknownError",J=X instanceof Error?X.message:String(X);if(!(Y==="ConfigNotFoundError"||Y==="ConfigLoadError"||Y==="ConfigValidationError"||J.includes("config"))&&$.verbose)v.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let z=W?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await c.applyEnvironmentVariables(z.name||"",Z,!0,z.verbose||!1))?.config??Z;return Z}}async function z1($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:Z}=await import("process");try{return(await c.loadConfig({name:$,cwd:Z(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(W){if(W instanceof Error&&(W.name==="ConfigNotFoundError"||W.name==="ConfigLoadError"&&w9(W)))return(await c.applyEnvironmentVariables($,{},!0,!1)).config;throw W}}try{return(await c.loadConfig({...$,cwd:$.cwd||e.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&w9(Z)))return(await c.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw Z}}async function Q1($,Z,W="replace"){let X=new W8;try{let Y=await X.loadFromPath($,Z,{arrayStrategy:W,useCache:!1,trackPerformance:!1});return Y?Y.config:null}catch{return null}}function C5($,Z,W=!1){let X=new Z8,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(G,z=[]){let Q={...G};for(let[B,U]of Object.entries(G)){let j=[...z,B],H=[`${Y}_${j.join("_").toUpperCase()}`,`${Y}_${j.map((I)=>I.toUpperCase()).join("")}`,`${Y}_${j.map((I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],L,F;for(let I of H)if(L=e.env[I],L!==void 0){F=I;break}if(L!==void 0&&F)if(typeof U==="boolean")Q[B]=["true","1","yes"].includes(L.toLowerCase());else if(typeof U==="number"){let I=Number(L);if(!Number.isNaN(I))Q[B]=I}else if(Array.isArray(U))try{Q[B]=JSON.parse(L)}catch{Q[B]=L.split(",").map((I)=>I.trim())}else Q[B]=L;else if(U&&typeof U==="object"&&!Array.isArray(U))Q[B]=J(U,j)}return Q}return J(Z)}function B1($){let Z=q(e.cwd(),$.configDir),W=q(e.cwd(),$.generatedDir),X=q(W,"config-types.ts");if(!N8(N9(X)))DZ(N9(X),{recursive:!0,mode:511});let Y=N8(Z)?OZ(Z).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${tZ}
|
|
36
|
+
export type ConfigNames = ${Y.length?`'${Y.join("' | '")}'`:"string"}
|
|
37
|
+
`;TZ(X,J,{mode:438})}function U1($){let Z=null,W=null,X=()=>{if(!W)W=n9($).then((J)=>{return Z=J,J},(J)=>{let G="defaultConfig"in $?$.defaultConfig:{};if(Z=G,"verbose"in $&&$.verbose)v.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return G});return W},Y="defaultConfig"in $?$.defaultConfig:{};return Z=Y,X(),new Proxy({},{get(J,G){if(Z)return Z[G];let z=Y[G];return X(),z},has(J,G){return G in(Z||Y)},ownKeys(){return Object.keys(Z||Y)},getOwnPropertyDescriptor(J,G){return Object.getOwnPropertyDescriptor(Z||Y,G)},set(J,G,z){if(!Z)Z={...Y};return Z[G]=z,!0}})}function H1($){let Z=C9(NZ.cwd(),$?.configDir||"./config");function W(){if(!MZ(Z))return[];let Y=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=SZ(Z).filter((Q)=>Y.has(K8(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),z=new Map;for(let{base:Q,file:B}of G){let U=K8(B).toLowerCase(),j=z.get(Q);if(!j){z.set(Q,B);continue}let H=K8(j).toLowerCase();if(J.indexOf(U)<J.indexOf(H))z.set(Q,B)}return Array.from(z.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function X(){let Y=W(),J=Y.map((B)=>B.base),G=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",z=Y.length?`{
|
|
38
|
+
${Y.map((B)=>{let U=C9(Z,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${U}').default`}).join(`,
|
|
39
39
|
`)}
|
|
40
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
41
|
-
export type ConfigByName = ${
|
|
40
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${G}
|
|
41
|
+
export type ConfigByName = ${z}
|
|
42
42
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
43
43
|
export type ConfigOf = Config
|
|
44
|
-
`}return{name:"bunfig-plugin",setup(
|
|
44
|
+
`}return{name:"bunfig-plugin",setup(Y){Y.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),Y.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:X(),loader:"ts"}})}}}class P8{records;timestamps;cleanupTimer;enableAutoCleanup;cleanupIntervalMs;constructor($){this.records=new Map,this.timestamps=new Map;let Z=k.memoryStorage||{};if(this.enableAutoCleanup=$?.enableAutoCleanup??Z.enableAutoCleanup??!1,this.cleanupIntervalMs=$?.cleanupIntervalMs??Z.cleanupIntervalMs??60000,this.cleanupTimer=null,this.enableAutoCleanup)this.startCleanupTimer()}async increment($,Z){let W=Date.now(),X=this.records.get($);if(!X||W>X.resetTime){let J={count:1,resetTime:W+Z};return this.records.set($,J),this.timestamps.set($,[W]),J}X.count+=1;let Y=this.timestamps.get($)||[];return Y.push(W),this.timestamps.set($,Y),X}async reset($){this.records.delete($),this.timestamps.delete($)}async getCount($){return this.records.get($)?.count||0}async getSlidingWindowCount($,Z){let W=this.timestamps.get($)||[],Y=Date.now()-Z;return W.filter((J)=>J>Y).length}async batchIncrement($,Z){let W=new Map;for(let X of $){let Y=await this.increment(X,Z);W.set(X,Y)}return W}cleanExpired(){let $=Date.now();for(let[W,X]of this.records.entries())if($>X.resetTime)this.records.delete(W);let Z=$-3600000;for(let[W,X]of this.timestamps.entries()){let Y=X.filter((J)=>J>Z);if(Y.length===0)this.timestamps.delete(W);else if(Y.length!==X.length)this.timestamps.set(W,Y)}}dispose(){if(this.cleanupTimer)clearInterval(this.cleanupTimer)}startCleanupTimer(){this.cleanupTimer=setInterval(()=>this.cleanExpired(),this.cleanupIntervalMs)}}class m8{windowMs;maxRequests;storage;keyGenerator;skipFailedRequests;algorithm;standardHeaders;legacyHeaders;skipFn;handler;draftMode;tokenBucketOptions;tokenBuckets;constructor($){if(this.windowMs=$.windowMs||k.windowMs||60000,this.maxRequests=$.maxRequests||k.maxRequests||100,$.maxRequests===0)this.maxRequests=0;if($.storage)this.storage=$.storage;else if(k.storage==="redis"&&k.redis)throw Error("Redis client must be provided explicitly when using Redis storage");else this.storage=new P8(k.memoryStorage);if(this.skipFailedRequests=$.skipFailedRequests??!1,this.keyGenerator=$.keyGenerator||this.defaultKeyGenerator,this.algorithm=$.algorithm||k.algorithm||"fixed-window",this.standardHeaders=$.standardHeaders??k.standardHeaders??!0,this.legacyHeaders=$.legacyHeaders??k.legacyHeaders??!0,this.skipFn=$.skip,this.handler=$.handler,this.draftMode=$.draftMode??k.draftMode??!1,this.tokenBuckets=new Map,this.algorithm==="token-bucket")this.tokenBucketOptions={capacity:this.maxRequests,refillRate:this.maxRequests/(this.windowMs/1000)/1000};if(k.verbose){let Z=$.storage?$.storage instanceof P8?"memory (custom)":"redis (custom)":k.storage;console.warn(`[ts-rate-limiter] Initialized with:
|
|
45
45
|
- Algorithm: ${this.algorithm}
|
|
46
46
|
- Window: ${this.windowMs}ms
|
|
47
47
|
- Max Requests: ${this.maxRequests}
|
|
48
48
|
- Storage: ${Z}
|
|
49
|
-
- Draft Mode: ${this.draftMode?"enabled":"disabled"}`)}}defaultKeyGenerator($){let Z=$.headers.get("x-forwarded-for");if(Z)return Z.split(",")[0].trim();let Y=$.headers.get("x-client-ip");if(Y)return Y;let X=$.headers.get("x-real-ip");if(X)return X;return $.socket?.remoteAddress||"127.0.0.1"}async check($){try{if(this.skipFn&&await this.skipFn($))return this.createAllowedResult();if(this.maxRequests===0)return{allowed:!1,current:1,limit:0,remaining:this.windowMs,resetTime:Date.now()+this.windowMs};let Z=await this.keyGenerator($);if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow(Z);else if(this.algorithm==="token-bucket")return this.checkTokenBucket(Z);else return this.checkFixedWindow(Z)}catch(Z){if(this.skipFailedRequests)return this.createAllowedResult();throw Z}}async checkFixedWindow($){let{count:Z,resetTime:Y}=await this.storage.increment($,this.windowMs),X=Math.max(0,Y-Date.now());return{allowed:this.draftMode?!0:Z<=this.maxRequests,current:Z,limit:this.maxRequests,remaining:X,resetTime:Y}}async checkSlidingWindow($){if(!this.storage.getSlidingWindowCount)return this.checkFixedWindow($);await this.storage.increment($,this.windowMs);let Z=await this.storage.getSlidingWindowCount($,this.windowMs),X=Date.now()+this.windowMs;return{allowed:this.draftMode?!0:Z<=this.maxRequests,current:Z,limit:this.maxRequests,remaining:this.windowMs,resetTime:X}}async checkTokenBucket($){if(!this.tokenBucketOptions)return this.checkFixedWindow($);let Z=Date.now(),Y=this.tokenBuckets.get($);if(!Y)Y={tokens:this.tokenBucketOptions.capacity,lastRefill:Z},this.tokenBuckets.set($,Y);let J=(Z-Y.lastRefill)*this.tokenBucketOptions.refillRate;if(J>0)Y.tokens=Math.min(Y.tokens+J,this.tokenBucketOptions.capacity),Y.lastRefill=Z;let G=this.draftMode?!0:Y.tokens>=1;if(G&&!this.draftMode)Y.tokens-=1;let W=Y.tokens>=this.tokenBucketOptions.capacity?this.windowMs:Math.ceil(1/this.tokenBucketOptions.refillRate);return{allowed:G,current:this.tokenBucketOptions.capacity-Math.floor(Y.tokens),limit:this.tokenBucketOptions.capacity,remaining:W,resetTime:Z+W}}createAllowedResult(){return{allowed:!0,current:0,limit:this.maxRequests,remaining:this.windowMs,resetTime:Date.now()+this.windowMs}}async consume($){if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow($);else if(this.algorithm==="token-bucket")return this.checkTokenBucket($);else return this.checkFixedWindow($)}async peek($){if(typeof this.storage.getCount!=="function")return null;let Z=await this.storage.getCount($),Y=Date.now();return{allowed:this.draftMode?!0:Z<this.maxRequests,current:Z,limit:this.maxRequests,remaining:this.windowMs,resetTime:Y+this.windowMs}}async enforce($){let Z=await this.consume($);if(!Z.allowed)throw new i1(`Rate limit exceeded for '${$}'`,Z);return Z}async reset($){if(await this.storage.reset($),this.algorithm==="token-bucket")this.tokenBuckets.delete($)}async resetAll(){if(this.algorithm==="token-bucket")this.tokenBuckets.clear();if(this.storage.cleanExpired)this.storage.cleanExpired()}getHeaders($){let Z={};if(this.standardHeaders)Z["RateLimit-Limit"]=this.maxRequests.toString(),Z["RateLimit-Remaining"]=Math.max(0,this.maxRequests-$.current).toString(),Z["RateLimit-Reset"]=Math.ceil($.resetTime/1000).toString();if(this.legacyHeaders){if(Z["X-RateLimit-Limit"]=this.maxRequests.toString(),Z["X-RateLimit-Remaining"]=Math.max(0,this.maxRequests-$.current).toString(),Z["X-RateLimit-Reset"]=Math.ceil($.resetTime/1000).toString(),!$.allowed)Z["Retry-After"]=Math.ceil($.remaining/1000).toString()}return Z}middleware(){return async($)=>{let Z=await this.check($);if(!Z.allowed){if(this.handler)return this.handler($,Z);return new Response("Rate limit exceeded",{status:429,headers:this.getHeaders(Z)})}return null}}dispose(){if(this.storage.dispose)this.storage.dispose();this.tokenBuckets.clear()}}class i1 extends Error{name="RateLimitError";retryAfter;result;constructor($,Z){super($);this.result=Z,this.retryAfter=Math.max(1,Math.ceil(Z.remaining/1000))}toHeaders(){return{"Retry-After":String(this.retryAfter),"RateLimit-Limit":String(this.result.limit),"RateLimit-Remaining":"0","RateLimit-Reset":String(Math.ceil(this.result.resetTime/1000))}}}function g6($){let Z=$,Y=Z._authenticatedUser?.id;if(Y!==void 0)return`user:${String(Y)}`;let X=Z._currentAccessToken?.id;if(X!==void 0)return`token:${String(X)}`;let J=$.headers.get("authorization");if(J?.startsWith("Bearer "))return`bearer:${J.slice(7,39)}`;let G=$.headers.get("x-forwarded-for");if(G)return`ip:${G.split(",")[0]?.trim()??"unknown"}`;let W=$.headers.get("x-real-ip");if(W)return`ip:${W}`;return"anon"}E1();var i9={second:1,minute:60,hour:3600,day:86400},h6=new Map;function E5($,Z){let Y=`${Z}:${$}`,X=h6.get(Y);if(!X)X=new S5({windowMs:Z,maxRequests:$,algorithm:"fixed-window",standardHeaders:!1,legacyHeaders:!1}),h6.set(Y,X);return X}function N5($){if($!==void 0)return $;let Z=S1();return Z?g6(Z):"anon"}function n9($,Z,Y={}){let X=N5(Y.identity),J=`${$}:${X}`,G=async(W)=>{let Q=E5(Z,W);try{await Q.enforce(J)}catch(z){if(z instanceof i1)throw Object.assign(new l9(429,"Too many requests",{key:$,max:Z,retryAfter:z.retryAfter}),{headers:z.toHeaders()});throw z}};return{async per(W){let Q=i9[W];if(!Q)throw Error(`rateLimit().per: unknown period '${W}'`);await G(Q*1000)},async over(W){if(!Number.isFinite(W)||W<=0)throw Error(`rateLimit().over: ttl must be a positive number, got ${W}`);await G(W*1000)}}}async function s9($,Z,Y,X={}){let J=N5(X.identity),G=`${$}:${J}`,Q=await E5(Z,Y*1000).peek(G);if(!Q)return null;return{count:Q.current,limit:Q.limit,remaining:Math.max(0,Q.limit-Q.current)}}async function o9($,Z,Y,X={}){let J=N5(X.identity),G=`${$}:${J}`;await E5(Z,Y*1000).reset(G)}import("@stacksjs/database").then(({setQueryTracker:$})=>{if(typeof $==="function"){let{trackQuery:Z}=(b1(),u6(h5));$(Z)}}).catch(()=>{});export{t6 as withTraceId,T8 as url,v5 as trackQuery,e6 as setCurrentRequest,v8 as serverResponse,y8 as serve,t1 as runWithRequest,M8 as routeParams,t as route,$8 as request,s9 as rateLimitStatus,n9 as rateLimit,d5 as loadRoutes,t5 as listRegisteredRoutes,x8 as installMiddlewareHotReload,o6 as getTraceId,y5 as getQueryShapeCounts,S1 as getCurrentRequest,f5 as createValidationErrorResponse,Z6 as createStacksRouter,g5 as createNotFoundResponse,x1 as createMiddlewareErrorResponse,u as createErrorResponse,R1 as clearTrackedQueries,o9 as clearRateLimit,a5 as clearMiddlewareCache,r6 as cacheRequestQuery,Y6 as Middleware};
|
|
49
|
+
- Draft Mode: ${this.draftMode?"enabled":"disabled"}`)}}defaultKeyGenerator($){let Z=$.headers.get("x-forwarded-for");if(Z)return Z.split(",")[0].trim();let W=$.headers.get("x-client-ip");if(W)return W;let X=$.headers.get("x-real-ip");if(X)return X;return $.socket?.remoteAddress||"127.0.0.1"}async check($){try{if(this.skipFn&&await this.skipFn($))return this.createAllowedResult();if(this.maxRequests===0)return{allowed:!1,current:1,limit:0,remaining:this.windowMs,resetTime:Date.now()+this.windowMs};let Z=await this.keyGenerator($);if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow(Z);else if(this.algorithm==="token-bucket")return this.checkTokenBucket(Z);else return this.checkFixedWindow(Z)}catch(Z){if(this.skipFailedRequests)return this.createAllowedResult();throw Z}}async checkFixedWindow($){let{count:Z,resetTime:W}=await this.storage.increment($,this.windowMs),X=Math.max(0,W-Date.now());return{allowed:this.draftMode?!0:Z<=this.maxRequests,current:Z,limit:this.maxRequests,remaining:X,resetTime:W}}async checkSlidingWindow($){if(!this.storage.getSlidingWindowCount)return this.checkFixedWindow($);await this.storage.increment($,this.windowMs);let Z=await this.storage.getSlidingWindowCount($,this.windowMs),X=Date.now()+this.windowMs;return{allowed:this.draftMode?!0:Z<=this.maxRequests,current:Z,limit:this.maxRequests,remaining:this.windowMs,resetTime:X}}async checkTokenBucket($){if(!this.tokenBucketOptions)return this.checkFixedWindow($);let Z=Date.now(),W=this.tokenBuckets.get($);if(!W)W={tokens:this.tokenBucketOptions.capacity,lastRefill:Z},this.tokenBuckets.set($,W);let Y=(Z-W.lastRefill)*this.tokenBucketOptions.refillRate;if(Y>0)W.tokens=Math.min(W.tokens+Y,this.tokenBucketOptions.capacity),W.lastRefill=Z;let J=this.draftMode?!0:W.tokens>=1;if(J&&!this.draftMode)W.tokens-=1;let G=W.tokens>=this.tokenBucketOptions.capacity?this.windowMs:Math.ceil(1/this.tokenBucketOptions.refillRate);return{allowed:J,current:this.tokenBucketOptions.capacity-Math.floor(W.tokens),limit:this.tokenBucketOptions.capacity,remaining:G,resetTime:Z+G}}createAllowedResult(){return{allowed:!0,current:0,limit:this.maxRequests,remaining:this.windowMs,resetTime:Date.now()+this.windowMs}}async consume($){if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow($);else if(this.algorithm==="token-bucket")return this.checkTokenBucket($);else return this.checkFixedWindow($)}async peek($){if(typeof this.storage.getCount!=="function")return null;let Z=await this.storage.getCount($),W=Date.now();return{allowed:this.draftMode?!0:Z<this.maxRequests,current:Z,limit:this.maxRequests,remaining:this.windowMs,resetTime:W+this.windowMs}}async enforce($){let Z=await this.consume($);if(!Z.allowed)throw new X8(`Rate limit exceeded for '${$}'`,Z);return Z}async reset($){if(await this.storage.reset($),this.algorithm==="token-bucket")this.tokenBuckets.delete($)}async resetAll(){if(this.algorithm==="token-bucket")this.tokenBuckets.clear();if(this.storage.cleanExpired)this.storage.cleanExpired()}getHeaders($){let Z={};if(this.standardHeaders)Z["RateLimit-Limit"]=this.maxRequests.toString(),Z["RateLimit-Remaining"]=Math.max(0,this.maxRequests-$.current).toString(),Z["RateLimit-Reset"]=Math.ceil($.resetTime/1000).toString();if(this.legacyHeaders){if(Z["X-RateLimit-Limit"]=this.maxRequests.toString(),Z["X-RateLimit-Remaining"]=Math.max(0,this.maxRequests-$.current).toString(),Z["X-RateLimit-Reset"]=Math.ceil($.resetTime/1000).toString(),!$.allowed)Z["Retry-After"]=Math.ceil($.remaining/1000).toString()}return Z}middleware(){return async($)=>{let Z=await this.check($);if(!Z.allowed){if(this.handler)return this.handler($,Z);return new Response("Rate limit exceeded",{status:429,headers:this.getHeaders(Z)})}return null}}dispose(){if(this.storage.dispose)this.storage.dispose();this.tokenBuckets.clear()}}function a9($){let Z=$,W=Z._authenticatedUser?.id;if(W!==void 0)return`user:${String(W)}`;let X=Z._currentAccessToken?.id;if(X!==void 0)return`token:${String(X)}`;let Y=$.headers.get("authorization");if(Y?.startsWith("Bearer "))return`bearer:${Y.slice(7,39)}`;let J=$.headers.get("x-forwarded-for");if(J)return`ip:${J.split(",")[0]?.trim()??"unknown"}`;let G=$.headers.get("x-real-ip");if(G)return`ip:${G}`;return"anon"}var CZ,xZ=($)=>$,RZ=($,Z)=>{for(var W in Z)CZ($,W,{get:Z[W],enumerable:!0,configurable:!0,set:EZ.bind(Z,W)})},d=($,Z)=>()=>($&&(Z=$($=0)),Z),qZ,_5,q5,P9,b5,x9,T8,x5,yZ,C,V,fZ,E9,gZ,R9,hZ,mZ,M8,pZ,q9,b9,cZ,S8,dZ,uZ,lZ,nZ,iZ,t5,v9,sZ,oZ,tZ="0.15.9",aZ=()=>{},P,r5,E5,C8,x8,e5,E8,R8,R5,q8,b8,n,A5,g9,c9,f8,d9,u9,l9,v,c,i9,s9,j1,L1=()=>{},o9,t9,F1,k,X8;var r9=u(()=>{CZ=Object.defineProperty;qZ=import.meta.require;b5=d(()=>{_5=new k8,q5=new v8,P9={createKey:bZ,isEquivalent:wZ,estimateMemoryUsage:PZ}});oZ=d(()=>{x9=a5.env.CLARITY_LOG_DIR||zZ(kZ(),"logs"),T8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:x9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},x5={...T8},yZ=(async()=>{try{let{loadConfig:$}=await Promise.resolve().then(()=>(t9(),o9)),Z=await $({name:"clarity",alias:"logging",defaultConfig:T8,cwd:a5.cwd()});if(Z)Object.assign(x5,Z)}catch{}return x5})(),C={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},V=C,fZ=C.red,E9=C.green,gZ=C.yellow,R9=C.blue,hZ=C.magenta,mZ=C.cyan,M8=C.white,pZ=C.gray,q9=C.bgRed,b9=C.bgYellow,cZ=C.bgGray,S8=C.bold,dZ=C.dim,uZ=C.italic,lZ=C.underline,nZ=C.strikethrough,iZ=C.reset,t5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},v9={debug:"\uD83D\uDD0D",info:R9("\u2139"),success:E9("\u2713"),warning:b9(M8(S8(" WARN "))),error:q9(M8(S8(" ERROR ")))},sZ=new $8("stacks")});A5=d(()=>{P=class extends Error{timestamp;context;constructor(Z,W={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=W,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([W,X])=>`${W}: ${X}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},r5=class extends P{code="CONFIG_NOT_FOUND";constructor(Z,W,X){let Y=X===void 0?[]:Array.isArray(X)?X.filter(Boolean):[X],J="";if(Y.length===1)J=` or alias "${Y[0]}"`;else if(Y.length>1)J=` or aliases ${Y.map((G)=>`"${G}"`).join(", ")}`;super(`Configuration "${Z}"${J} not found`,{configName:Z,alias:X,searchPaths:W,searchPathCount:W.length})}},E5=class extends P{code="CONFIG_LOAD_ERROR";constructor(Z,W,X){super(`Failed to load configuration from "${Z}": ${W.message}`,{configPath:Z,configName:X,originalError:W.name,originalMessage:W.message});this.cause=W}},C8=class extends P{code="CONFIG_VALIDATION_ERROR";constructor(Z,W,X){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:X,validationErrors:W,errorCount:W.length})}},x8=class extends P{code="CONFIG_MERGE_ERROR";constructor(Z,W,X,Y){super(`Failed to merge configuration from "${Z}" with "${W}": ${X.message}`,{sourcePath:Z,targetPath:W,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},e5=class extends P{code="ENV_VAR_ERROR";constructor(Z,W,X,Y){super(`Failed to parse environment variable "${Z}" with value "${W}" as ${X}`,{envKey:Z,envValue:W,expectedType:X,configName:Y})}},E8=class extends P{code="FILE_SYSTEM_ERROR";constructor(Z,W,X){super(`File system ${Z} failed for "${W}": ${X.message}`,{operation:Z,path:W,originalError:X.name,originalMessage:X.message});this.cause=X}},R8=class extends P{code="TYPE_GENERATION_ERROR";constructor(Z,W,X){super(`Failed to generate types from "${Z}" to "${W}": ${X.message}`,{configDir:Z,outputPath:W,originalError:X.name,originalMessage:X.message});this.cause=X}},R5=class extends P{code="SCHEMA_VALIDATION_ERROR";constructor(Z,W,X){super(`Schema validation failed${X?` for config "${X}"`:""}`,{schemaPath:Z,configName:X,validationErrors:W,errorCount:W.length})}},q8=class extends P{code="BROWSER_CONFIG_ERROR";constructor(Z,W,X,Y){super(`Failed to fetch configuration from "${Z}": ${W} ${X}`,{endpoint:Z,status:W,statusText:X,configName:Y})}},b8=class extends P{code="PLUGIN_ERROR";constructor(Z,W,X){super(`Plugin "${Z}" failed during ${W}: ${X.message}`,{pluginName:Z,operation:W,originalError:X.name,originalMessage:X.message});this.cause=X}},n={configNotFound($,Z,W){return new r5($,Z,W)},configLoad($,Z,W){return new E5($,Z,W)},configValidation($,Z,W){return new C8($,Z,W)},configMerge($,Z,W,X){return new x8($,Z,W,X)},envVar($,Z,W,X){return new e5($,Z,W,X)},fileSystem($,Z,W){return new E8($,Z,W)},typeGeneration($,Z,W){return new R8($,Z,W)},schemaValidation($,Z,W){return new R5($,Z,W)},browserConfig($,Z,W,X){return new q8($,Z,W,X)},plugin($,Z,W){return new b8($,Z,W)}}});g9=d(()=>{b5(),A5()});f8=d(()=>{c9={replace:"replace",concat:"concat",smart:"smart"}});d9=d(()=>{b5(),A5(),f8()});l9=d(()=>{b5(),A5(),u9=/^https?:\/\//});j1=d(()=>{oZ(),aZ(),b5(),A5(),g9(),d9(),l9(),f8(),v=new $8("bunfig",{showTags:!0}),c=new h8,i9=q(e.cwd(),"config"),s9=q(e.cwd(),"src/generated")});o9={};RZ(o9,{withErrorRecovery:()=>y9,tryLoadConfig:()=>Q1,loadConfigWithResult:()=>G1,loadConfig:()=>n9,isRetryableError:()=>eZ,isConfigNotFoundError:()=>rZ,isBunfigError:()=>f9,globalPerformanceMonitor:()=>q5,globalCache:()=>_5,getEnvOrDefault:()=>$1,generateConfigTypes:()=>B1,defaultGeneratedDir:()=>s9,defaultConfigDir:()=>i9,deepMergeWithArrayStrategy:()=>y8,deepMerge:()=>h9,createLibraryConfig:()=>U1,config:()=>z1,bunfigPlugin:()=>H1,applyEnvVarsToConfig:()=>C5,TypeGenerationError:()=>R8,SchemaValidationError:()=>R5,PluginError:()=>b8,PerformanceMonitor:()=>v8,FileSystemError:()=>E8,ErrorFactory:()=>n,EnvVarError:()=>e5,EnvProcessor:()=>Z8,ConfigValidator:()=>g8,ConfigValidationError:()=>C8,ConfigNotFoundError:()=>r5,ConfigMergeError:()=>x8,ConfigLoader:()=>h8,ConfigLoadError:()=>E5,ConfigFileLoader:()=>W8,ConfigCache:()=>k8,CacheUtils:()=>P9,BunfigError:()=>P,BrowserConfigError:()=>q8,ArrayMergeStrategies:()=>c9});t9=d(()=>{j1(),A5(),b5(),A5(),L1(),g9(),d9(),l9(),f8()});t9();F1={verbose:!1,storage:"memory",algorithm:"fixed-window",windowMs:60000,maxRequests:100,standardHeaders:!0,legacyHeaders:!0,draftMode:!1,redisKeyPrefix:"ratelimit:",memoryStorage:{enableAutoCleanup:!0,cleanupIntervalMs:60000},redis:{url:"redis://localhost:6379",enableSlidingWindow:!1}},k=F1;X8=class X8 extends Error{name="RateLimitError";retryAfter;result;constructor($,Z){super($);this.result=Z,this.retryAfter=Math.max(1,Math.ceil(Z.remaining/1000))}toHeaders(){return{"Retry-After":String(this.retryAfter),"RateLimit-Limit":String(this.result.limit),"RateLimit-Remaining":"0","RateLimit-Reset":String(Math.ceil(this.result.resetTime/1000))}}}});import{HttpError as _1}from"@stacksjs/error-handling";function p8($,Z){let W=`${Z}:${$}`,X=e9.get(W);if(!X)X=new m8({windowMs:Z,maxRequests:$,algorithm:"fixed-window",standardHeaders:!1,legacyHeaders:!1}),e9.set(W,X);return X}function c8($){if($!==void 0)return $;let Z=o();return Z?a9(Z):"anon"}function d8($,Z,W={}){let X=c8(W.identity),Y=`${$}:${X}`,J=async(G)=>{let z=p8(Z,G);try{await z.enforce(Y)}catch(Q){if(Q instanceof X8)throw Object.assign(new _1(429,"Too many requests",{key:$,max:Z,retryAfter:Q.retryAfter}),{headers:Q.toHeaders()});throw Q}};return{async per(G){let z=A1[G];if(!z)throw Error(`rateLimit().per: unknown period '${G}'`);await J(z*1000)},async over(G){if(!Number.isFinite(G)||G<=0)throw Error(`rateLimit().over: ttl must be a positive number, got ${G}`);await J(G*1000)}}}async function V1($,Z,W,X={}){let Y=c8(X.identity),J=`${$}:${Y}`,z=await p8(Z,W*1000).peek(J);if(!z)return null;return{count:z.current,limit:z.limit,remaining:Math.max(0,z.limit-z.current)}}async function I1($,Z,W,X={}){let Y=c8(X.identity),J=`${$}:${Y}`;await p8(Z,W*1000).reset(J)}var A1,e9;var u8=u(()=>{r9();S5();A1={second:1,minute:60,hour:3600,day:86400},e9=new Map});import $5 from"process";function D1(){if(Y8!==void 0)return Y8;return Y8=($5.env.APP_ENV??$5.env.NODE_ENV??"").toLowerCase()==="production",Y8}function O1(){if(J8!==void 0)return J8;return J8=$5.env.STACKS_SECURITY_HEADERS_DISABLE==="true",J8}function K1(){if(V5!==void 0)return V5;let $=$5.env.STACKS_CSP,Z=$5.env.STACKS_CSP_REPORT_ONLY;if($)V5={header:"Content-Security-Policy",value:$};else if(Z)V5={header:"Content-Security-Policy-Report-Only",value:Z};else V5=null;return V5}function $$($){if(O1())return;if(!$.has("X-Content-Type-Options"))$.set("X-Content-Type-Options","nosniff");if(!$.has("X-Frame-Options"))$.set("X-Frame-Options","SAMEORIGIN");if(!$.has("Referrer-Policy"))$.set("Referrer-Policy","strict-origin-when-cross-origin");if(D1()&&!$.has("Strict-Transport-Security"))$.set("Strict-Transport-Security","max-age=31536000; includeSubDomains");let Z=K1();if(Z&&!$.has(Z.header))$.set(Z.header,Z.value)}var Y8,J8,V5;var Z$=()=>{};var Y$={};Y9(Y$,{loadRoutes:()=>X$});import{log as T1}from"@stacksjs/logging";async function X$($){for(let[Z,W]of Object.entries($)){let X=C1(W),Y=X.prefix!==void 0?X.prefix?X.prefix.startsWith("/")?X.prefix:`/${X.prefix}`:void 0:M1.includes(Z)?void 0:`/${Z}`,J=x1(X.middleware);T1.debug(`[route-loader] Loading: ${X.path} prefix=${Y||"/"} middleware=[${J.join(", ")}]`);try{if(Y||J.length>0)await I5.group({prefix:Y,middleware:J.length>0?J:void 0},async()=>{await W$(X.path)});else await W$(X.path)}catch(G){let z=G instanceof Error?G.message:String(G);throw console.error(`[Routes] Failed to load route file '${X.path}': ${z}`),Error(`Route loading failed for '${X.path}': ${z}`)}}await S1()}async function S1(){if(process.env.STACKS_SKIP_DEFAULT_ROUTES==="1")return;try{let{frameworkPath:$}=await import("@stacksjs/path"),Z=$("defaults/bootstrap.ts");if(await Bun.file(Z).exists())await import(Z)}catch($){let Z=$ instanceof Error?$.message:String($);if(!Z.includes("Cannot find module")&&!Z.includes("MODULE_NOT_FOUND"))console.error(`[Routes] Failed to load framework bootstrap: ${Z}`)}}function N1($){if(typeof $!=="string"||$.length===0)throw Error("[route-loader] Invalid route path: empty or non-string");if($.includes("\x00"))throw Error("[route-loader] Invalid route path: null byte");let Z;try{Z=decodeURIComponent($)}catch{throw Error("[route-loader] Invalid route path: malformed URL encoding")}let W=Z.replace(/\.ts$/,"");if(W.startsWith("/")||/^[A-Za-z]:[\\/]/.test(W))throw Error(`[route-loader] Invalid route path: absolute paths not allowed (${W})`);if(W.split(/[/\\]/).some((Y)=>Y===".."))throw Error(`[route-loader] Invalid route path: '..' segment not allowed (${W})`);return W}async function W$($){let Z=N1($),{projectPath:W}=await import("@stacksjs/path");await import(W(`routes/${Z}`))}function C1($){if(typeof $==="string")return{path:$};return $}function x1($){if(!$)return[];if(typeof $==="string")return[$];return $}var M1;var l8=u(()=>{D5();M1=["web"]});import T from"process";import{Buffer as J$}from"buffer";import{timingSafeEqual as E1}from"crypto";import{log as _,report as H$}from"@stacksjs/logging";import{path as M}from"@stacksjs/path";import{UploadedFile as G8}from"@stacksjs/storage";import{applyRequestEnhancements as R1,Router as q1}from"@stacksjs/bun-router";import{isCursorPaginator as b1,isPaginator as w1,isSimplePaginator as P1}from"@stacksjs/orm";function k1($){if(typeof $==="number"){if(!Number.isFinite($)||$<=0)throw Error(`[Router] .rateLimit(): window must be a positive number of seconds, got ${$}`);return Math.floor($)}switch($){case"second":return 1;case"minute":return 60;case"hour":return 3600;case"day":return 86400;default:throw Error(`[Router] .rateLimit(): unknown period '${String($)}'`)}}class a8{max;map=new Map;constructor($){this.max=$}get($){return this.map.get($)}has($){return this.map.has($)}set($,Z){if(this.map.has($))this.map.delete($);if(this.map.set($,Z),this.map.size>this.max){let W=this.map.keys().next().value;if(W!==void 0)this.map.delete(W)}return this}delete($){return this.map.delete($)}clear(){this.map.clear()}get size(){return this.map.size}}function G$($){let Z=T.env.STACKS_EXPOSE_ROUTES??"";if(!Z)return!((T.env.APP_ENV??"").toLowerCase()==="production"||T.env.NODE_ENV==="production");if(Z==="1")return!((T.env.APP_ENV??"").toLowerCase()==="production"||T.env.NODE_ENV==="production");let W=new URL($.url),X=$.headers.get("x-stacks-routes-token")||$.headers.get("X-Stacks-Routes-Token")||W.searchParams.get("token")||"";if(typeof X!=="string"||X.length===0||X.length!==Z.length)return!1;try{return E1(J$.from(X),J$.from(Z))}catch{return!1}}async function z8($,Z){if(!$._corsConfig||!Z)return Z;try{let{applyCorsHeaders:W}=await import(M.storagePath("framework/defaults/app/Middleware/Cors.ts"));return W($,Z,$._corsConfig)}catch(W){return _.warn("[router] CORS header injection failed",{error:W}),Z}}function v1($){let Z=y1($),W=new Map;for(let X of Z)W.set(X,new RegExp(`(^|/):${X}(?=$|/)`,"g"));return{path:$,paramNames:Z,colonRegex:W}}function y1($){let Z=new Set;for(let W of $.matchAll(/\{(\w+)\}/g))if(W[1])Z.add(W[1]);for(let W of $.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(W[1])Z.add(W[1]);return[...Z]}function $9($,Z={}){let W=P5.get($);if(!W)throw Error(`Route '${$}' is not defined. Available routes: ${[...P5.keys()].join(", ")}`);let X=W.paramNames.filter((Q)=>!(Q in Z)||Z[Q]===void 0);if(X.length>0)throw Error(`url('${$}'): missing required path param${X.length>1?"s":""} [${X.join(", ")}] for path '${W.path}'. Pass them as the second argument: url('${$}', { ${W.paramNames.join(", ")} })`);let Y;try{Y=T.env.APP_URL||"https://localhost"}catch{Y="https://localhost"}if(Y=Y.replace(/\/$/,""),!Y.startsWith("http"))Y=`https://${Y}`;let J=W.path,G={};for(let[Q,B]of Object.entries(Z)){let U=`{${Q}}`;if(J.includes(U))J=J.replaceAll(U,encodeURIComponent(String(B)));else{let j=W.colonRegex.get(Q);if(j&&j.test(J))j.lastIndex=0,J=J.replace(j,`$1${encodeURIComponent(String(B))}`);else G[Q]=String(B)}}let z=Object.keys(G).length>0?`?${new URLSearchParams(G).toString()}`:"";return`${Y}${J}${z}`}function f1($){let Z=P5.get($);return Z?[...Z.paramNames]:[]}function _$(){let $=[],Z=new Set;for(let W of Y5.keys()){if(Z.has(W))continue;Z.add(W);let X=W.indexOf(":");if(X===-1)continue;let Y=W.slice(0,X),J=W.slice(X+1),G;for(let[z,Q]of P5.entries())if(Q.path===J){G=z;break}$.push({method:Y,path:J,name:G})}return $.sort((W,X)=>W.path.localeCompare(X.path))}function g1($,Z){let W=`${$}:${String(Z)}`;if(Q$.has(W))return;Q$.add(W),_.warn(`[Router] Middleware '${$}' declared an invalid priority (${String(Z)}). Priorities must be a finite non-negative number; falling back to default ${A$}.`)}function h1($){if($ instanceof f5)return $.toRouterHandler();if($&&typeof $==="object"&&typeof $.handle==="function"&&typeof $!=="function"){let Z=$.handle.bind($);return async(X,Y)=>{try{await Z(X)}catch(J){if(J instanceof Response)return J;throw J}return Y()}}return $}async function m1(){if(w5)return w5;return w5=(async()=>{try{return(await import(M.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(M.storagePath("framework/defaults/app/Middleware.ts"))).default||{}}catch{return{}}}})(),w5}function c1($){if(!$)return $;let Z=B$.get($);if(Z!==void 0)return Z;let W=$.split(p1).filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("");return B$.set($,W),W}async function d1($){let W=(await m1())[$]||c1($);return _.debug(`[middleware] Resolved: ${$} \u2192 ${W}`),W}async function V$($){if(X5.has($))return X5.get($)??null;let Z=await d1($),W;try{let X=M.appPath(`Middleware/${Z}.ts`),J=(await import(X)).default??null;if(!J||typeof J.handle!=="function")return _.error(`[Router] Middleware '${$}' resolved to ${X}, but the file has no default export with a handle() method`),X5.set($,null),null;return X5.set($,J),J}catch(X){W=X}try{let X=M.storagePath(`framework/defaults/app/Middleware/${Z}.ts`),J=(await import(X)).default??null;if(!J||typeof J.handle!=="function")return _.error(`[Router] Middleware '${$}' resolved to ${X}, but the file has no default export with a handle() method`),X5.set($,null),null;return X5.set($,J),J}catch(X){let Y=W instanceof Error?W.message:String(W);return _.error(`[Router] Failed to load middleware '${$}' (resolved to '${Z}'). app/Middleware: ${Y}; defaults:`,X),null}}function I$(){X5.clear(),w5=null,r8.clear(),e8.clear()}function u1(){if(T.env.APP_ENV==="production"||T.env.NODE_ENV==="production")return()=>{};let $=[];return(async()=>{try{let Z=await import("fs"),W=[M.appPath("Middleware"),M.appPath("Middleware.ts")];for(let X of W)try{if(!Z.existsSync(X))continue;let Y=Z.watch(X,{recursive:!0},()=>{_.debug("[middleware] hot-reload: clearing cache"),I$()});$.push(Y)}catch{}}catch{}})(),()=>{for(let Z of $)try{Z.close()}catch{}$=[]}}function O$($){let Z=$.indexOf(":");if(Z===-1)return{name:$};return{name:$.substring(0,Z),params:$.substring(Z+1)}}async function K$(){let $=new Map;for(let[W,X]of Y5)for(let Y of X){let{name:J}=O$(Y),G=$.get(J)??[];G.push(W),$.set(J,G)}if(!$.has("csrf"))$.set("csrf",["(auto-injected on POST/PUT/PATCH/DELETE)"]);let Z=[];for(let[W,X]of $){let Y=await V$(W);if(!Y||typeof Y.handle!=="function")Z.push({alias:W,routes:X})}return Z}async function T$(){let $=await K$();if($.length===0)return;let Z=$.map((W)=>`"${W.alias}" (used by ${W.routes.join(", ")})`).join("; ");throw Error(`[Router] Unresolvable middleware alias(es): ${Z}. Check the alias map in app/Middleware.ts or add app/Middleware/<Class>.ts.`)}function Z5($,Z){let W=r1(Z,!0),X=null;if(typeof Z==="string"){let Y=$.slice(0,$.indexOf(":")).toUpperCase();if(z$.has(Y))X=M$(Z).then(()=>{return}).catch(()=>{return})}return async(Y)=>{try{await N$(Y)}catch(G){let z=G instanceof Error?G:Error(String(G));return U5(z,Y)}let J=S$(Y);if(X)await X;if(D$.has($))Y._forceJson=!0;return _8(J,async()=>{let G=L$.get($);if(G)try{await d8($,G.max).over(G.windowSeconds)}catch(D){return U5(D,Y)}let z=Y5.get($)||[],Q=Y.method.toUpperCase(),B=[...z],U=z.some((D)=>D==="csrf"||D.startsWith("csrf:")),j=s8.has($),H=o8.has($),L=e8.get($),F=L?r8.get(L)===!0:!1;if(z$.has(Q)&&!U&&(H||!j&&!F))B.unshift("csrf");if(B.length>0){let D=(T.env.LOG_LEVEL||"info").toLowerCase();if(D!=="info"&&D!=="warn"&&D!=="error"){let K=Y.url.indexOf("://"),S=K===-1?0:Y.url.indexOf("/",K+3),R=Y.url.indexOf("?",S<0?0:S),E=S<0?"/":Y.url.slice(S,R===-1?void 0:R);_.debug(`[middleware] Executing chain: [${B.join(", ")}] for ${Q} ${E}`)}}let f=[];for(let D of B){let{name:K,params:S}=O$(D);if(S)J._middlewareParams=J._middlewareParams||{},J._middlewareParams[K]=S;let R=await V$(K);if(!R||typeof R.handle!=="function"){_.error(`[Router] Middleware '${K}' on ${$} could not be resolved \u2014 failing closed`);let h=Error(`Middleware '${K}' could not be resolved`),z5=await l(h,J,{status:500});return await z8(J,z5)}let E=R.priority,G5=A$;if(typeof E==="number"&&Number.isFinite(E)&&E>=0)G5=E;else if(E!==void 0)g1(K,E);f.push({name:K,handler:R,priority:G5})}f.sort((D,K)=>D.priority-K.priority);let b=[];for(let{name:D,handler:K}of f){let S=T.hrtime.bigint(),R;try{let G5=new Promise((z5,i)=>{R=setTimeout(()=>i(Error(`Middleware '${D}' exceeded 30000ms`)),30000)});await Promise.race([K.handle(J),G5]);let h=Number(T.hrtime.bigint()-S)/1e6;b.push({name:D,ms:h})}catch(E){let G5=Number(T.hrtime.bigint()-S)/1e6;if(b.push({name:D,ms:G5}),_.debug(`[middleware] Blocked by: ${D}`),E instanceof Response){try{let{_requestId:i,_startNs:O5}=J,K5=O5!=null?Number(T.hrtime.bigint()-O5)/1e6:null,s=K5!=null?[`total;dur=${K5.toFixed(1)}`]:[];for(let T5 of b){let H8=T5.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);s.push(`mw_${H8};dur=${T5.ms.toFixed(1)}`)}if(s.length>0)E.headers.set("Server-Timing",s.join(", "));if(i)E.headers.set("X-Request-ID",i)}catch{}return await z8(J,E)}let h=E instanceof Error?E:Error(String(E)),z5="statusCode"in h||"status"in h?await U5(h,J):await(()=>{return _.error(`[Router] Middleware '${D}' threw an unexpected error:`,h),l(h,J,{status:500})})();try{let{_requestId:i,_startNs:O5}=J,K5=O5!=null?Number(T.hrtime.bigint()-O5)/1e6:null,s=K5!=null?[`total;dur=${K5.toFixed(1)}`]:[];for(let T5 of b){let H8=T5.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);s.push(`mw_${H8};dur=${T5.ms.toFixed(1)}`)}if(s.length>0)z5.headers.set("Server-Timing",s.join(", "));if(i)z5.headers.set("X-Request-ID",i)}catch{}return await z8(J,z5)}finally{clearTimeout(R)}}let O=await W(J);if(d5(),O){if(Y.method==="GET"||Y.method==="HEAD"||Y.method==="OPTIONS")try{let{seedCsrfCookieIfMissing:K}=await import(M.storagePath("framework/defaults/app/Middleware/Csrf.ts"));O=K(J,O)}catch(K){_.warn("[router] CSRF cookie seeding failed",{error:K})}}if(O)O=await z8(J,O);let{_requestId:J5,_startNs:v5}=J,y5=v5!=null?Number(T.hrtime.bigint()-v5)/1e6:null,j8=(D)=>{if(J5)D.set("X-Request-ID",J5);if(y5!=null){let K=[`total;dur=${y5.toFixed(1)}`];for(let S of b){let R=S.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);K.push(`mw_${R};dur=${S.ms.toFixed(1)}`)}D.set("Server-Timing",K.join(", "))}$$(D)};if(O&&typeof O.headers?.set==="function"){if(O.status>=400&&(O.headers.get("content-type")||"").includes("json")&&J5)try{let K=await O.clone().text(),S=JSON.parse(K);if(S&&typeof S==="object"){let R=new Headers(O.headers);return j8(R),new Response(JSON.stringify({...S,request_id:J5}),{status:O.status,statusText:O.statusText,headers:R})}}catch{}try{j8(O.headers)}catch{try{let K=O.clone(),S=new Headers(O.headers);return j8(S),new Response(K.body,{status:O.status,statusText:O.statusText,headers:S})}catch{}}}if(J._compress===!0&&O)try{let{applyCompression:D}=await import(M.storagePath("framework/defaults/app/Middleware/Compress.ts"));return await D(J,O)}catch(D){_.warn(`[router] Compression failed; sending uncompressed response: ${D instanceof Error?D.message:String(D)}`)}return O})}}function W5($){if(!Y5.has($))Y5.set($,[]);let Z=$.includes(":")?$.substring($.indexOf(":")+1):$,W={middleware(X){let Y=Y5.get($);if(Y)Y.push(X);return W},name(X){return P5.set(X,v1(Z)),W},skipCsrf(){return s8.add($),o8.delete($),W},requireCsrf(){return o8.add($),s8.delete($),W},rateLimit(X,Y){if(!Number.isFinite(X)||X<=0)throw Error(`[Router] .rateLimit(): max must be a positive number, got ${String(X)}`);let J=k1(Y);return L$.set($,{max:Math.floor(X),windowSeconds:J}),W}};return W}async function n8($){try{return await Bun.file($).exists()}catch{return!1}}function l1($){if(typeof $!=="string"||$.length===0)throw Error(`[Router] Refusing to resolve handler '${String($)}': empty or non-string`);if($.includes("\x00"))throw Error("[Router] Refusing to resolve handler with null byte");if($.startsWith("/")||/^[A-Za-z]:[\\/]/.test($))throw Error(`[Router] Refusing to resolve absolute handler path '${$}'`);if($.split(/[/\\]/).some((W)=>W===".."))throw Error(`[Router] Refusing to resolve handler path '${$}' (contains '..' segment)`)}function j$($){let Z=U$.get($);if(!Z)Z=import($),U$.set($,Z);return Z}function M$($){let Z=i8.get($);if(!Z)Z=n1($),i8.set($,Z),Z.catch(()=>i8.delete($));return Z}async function n1($){l1($);let Z=$;if(Z=Z.endsWith(".ts")?Z.slice(0,-3):Z,Z.includes("Controller")){let[X,Y="index"]=Z.split("@"),J=M.appPath(`${X}.ts`),G=M.storagePath(`framework/defaults/app/${X}.ts`),z=await n8(J)?J:G;try{let Q=await j$(z);if(!Q.default||typeof Q.default!=="function")throw Error(`Controller ${X} does not export a default class`);let B=new Q.default;if(typeof B[Y]!=="function")throw Error(`Method ${Y} not found in controller ${X}`);return async(U)=>{let j=await B[Y](U);return t8(j,U)}}catch(Q){throw _.error(`[Router] Failed to load controller '${z}':`,Q),Q}}let W;if(Z.includes("storage/framework/orm"))W=Z;else if(Z.includes("OrmAction"))W=M.storagePath(`framework/actions/src/${Z}.ts`);else if(Z.includes("Actions")){let X=M.projectPath(`app/${Z}.ts`),Y=M.storagePath(`framework/defaults/app/${Z}.ts`);W=await n8(X)?X:Y}else{let X=M.appPath(`${Z}.ts`),Y=M.storagePath(`framework/defaults/app/${Z}.ts`);W=await n8(X)?X:Y}try{let Y=(await j$(W)).default;if(!Y)throw Error(`Action '${$}' has no default export`);if(typeof Y.handle!=="function")throw _.error(`[Router] Action '${$}' structure:`,Object.keys(Y)),Error(`Action '${$}' has no handle() method. Got: ${typeof Y.handle}`);let J=Y.skipCsrf===!0||Y.csrf===!1;r8.set($,J);let G=Y.apiResponse===!0;return async(z)=>{if(J)z._skipCsrf=!0;if(G)z._forceJson=!0;try{if(Y.validations){let B=await i1(z,Y.validations);if(!B.valid)return Response.json({error:"Validation failed",errors:B.errors},422)}if(typeof Y.authorize==="function"){let B=await Y.authorize(z);if(B instanceof Response)return B;if(B===!1)return Response.json({error:"Forbidden"},403)}if(typeof Y.before==="function"){let B=await Y.before(z);if(B instanceof Response)return B}let Q=await Y.handle(z);return t8(Q,z)}catch(Q){throw H$(Q,{label:`[Router] action.handle() for '${$}'`}),Q}}}catch(X){throw _.error(`[Router] Failed to import action '${W}':`,X),X}}async function i1($,Z){let W={},X=await s1($,Z);for(let[Y,J]of Object.entries(Z)){let G=X[Y],z;try{z=J.rule.validate(G)}catch{z={valid:!1,errors:[{message:`${Y} validation failed`}]}}if(!z.valid){let Q=[],B=Y.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(j)=>j.toUpperCase()),U=(j)=>j.toLowerCase().startsWith(Y.toLowerCase())||j.includes(B)?j:`${B} ${j}`;if(z.errors&&z.errors.length>0)if(J.message){let j=z.errors[0]?.message??"";Q.push(typeof J.message==="string"?J.message:J.message[Y]||U(j))}else z.errors.forEach((j)=>Q.push(U(j.message)));else Q.push(J.message?typeof J.message==="string"?J.message:`${B} is invalid`:`${B} is invalid`);W[Y]=Q}}return{valid:Object.keys(W).length===0,errors:W}}async function s1($,Z){let W={},X=$.query;if(X)for(let Y in X)W[Y]=X[Y];else new URL($.url).searchParams.forEach((J,G)=>{W[G]=J});if($.params)Object.assign(W,$.params);if($.jsonBody&&typeof $.jsonBody==="object")Object.assign(W,$.jsonBody);else if($.formBody&&typeof $.formBody==="object")Object.assign(W,$.formBody);if(typeof $.allFiles==="function")try{let Y=$.allFiles();for(let J of Object.keys(Y??{}))if(!(J in W))W[J]=Y[J]}catch{}if(!Z)return W;for(let[Y,J]of Object.entries(Z)){let G=W[Y];if(typeof G!=="string")continue;let z=J.rule?.name;if(z==="number"){let Q=Number(G);if(Number.isFinite(Q))W[Y]=Q}else if(z==="boolean"){if(G==="true"||G==="1")W[Y]=!0;else if(G==="false"||G==="0")W[Y]=!1}}return W}function t8($,Z){if($ instanceof Response)return $;if($ instanceof ReadableStream)return new Response($,{headers:{"Content-Type":"application/octet-stream"}});let X=Z._forceJson===!0||t(Z);if($===null||$===void 0)return X?new Response(null,{status:204}):new Response("",{status:200});if(typeof $==="object"){let Y=o1($);if(Y)return Response.json($,{headers:{Link:Y}});return Response.json($)}if(X)return Response.json($);return new Response(String($),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function o1($){if(!w1($)&&!P1($)&&!b1($))return null;let Z=$,W=[];if(Z.prev_page_url)W.push(`<${Z.prev_page_url}>; rel="prev"`);if(Z.next_page_url)W.push(`<${Z.next_page_url}>; rel="next"`);if(Z.first_page_url)W.push(`<${Z.first_page_url}>; rel="first"`);if(Z.last_page_url)W.push(`<${Z.last_page_url}>; rel="last"`);return W.length>0?W.join(", "):null}function t1($,Z={}){let W={};if(Z.type==="sse")W["Content-Type"]="text/event-stream; charset=utf-8",W["Cache-Control"]="no-cache",W.Connection="keep-alive";else if(Z.type==="ndjson")W["Content-Type"]="application/x-ndjson; charset=utf-8";else W["Content-Type"]=Z.contentType??"application/octet-stream";let X=$ instanceof ReadableStream?$:new ReadableStream({async start(J){try{for await(let G of $)J.enqueue(typeof G==="string"?new TextEncoder().encode(G):G);J.close()}catch(G){J.error(G)}}}),Y=new Headers(W);if(Z.headers)new Headers(Z.headers).forEach((G,z)=>Y.set(z,G));return new Response(X,{status:Z.status??200,headers:Y})}function w($){let Z=$._allInputCache;if(Z)return Z;let W={},X=$.query;if(X)for(let Y in X)W[Y]=X[Y];if($.jsonBody&&typeof $.jsonBody==="object")Object.assign(W,$.jsonBody);if($.formBody&&typeof $.formBody==="object")Object.assign(W,$.formBody);if($.params&&typeof $.params==="object")Object.assign(W,$.params);return $._allInputCache=W,W}function S$($){R1($,$.params||{});let Z=$.query;if(!Z){let W=new URL($.url);Z={},W.searchParams.forEach((X,Y)=>{Z[Y]=X}),$.query=Z}return Object.assign($,a1),$}function r1($,Z=!1){if(typeof $==="string"){let X=$;return async(Y)=>{try{if(!Z)await N$(Y),Y=S$(Y);return await(await M$(X))(Y)}catch(J){H$(J,{label:`[Router] ${X}`});let G=J?.statusCode??J?.status,z=typeof G==="number"&&Number.isInteger(G)&&G>=400&&G<600?G:void 0;return await l(J instanceof Error?J:Error(String(J)),Y,{handlerPath:X,status:z})}}}let W=$;return async(X)=>{let Y=await W(X);return t8(Y,X)}}async function N$($){if($._bodyParsed)return;$._bodyParsed=!0;let Z=$.headers.get("content-type")||"";try{if(g5.test(Z)){let X=await $.clone().text();if($._rawBody=X,X.length===0)$.jsonBody={};else try{let Y=JSON.parse(X);$.jsonBody=Y&&typeof Y==="object"?Y:{}}catch(Y){let J=Y instanceof Error?Y.message:"Invalid JSON",{HttpError:G}=await import("@stacksjs/error-handling");throw new G(400,`Invalid JSON body: ${J}`)}}else if(Z.includes("application/x-www-form-urlencoded")){let W=await $.clone().text(),X=new URLSearchParams(W),Y={};X.forEach((J,G)=>{Y[G]=J}),$.formBody=Y}else if(Z.includes("multipart/form-data")){let W=await $.clone().formData(),X={},Y={};W.forEach((J,G)=>{if(J instanceof File)if(Y[G])if(Array.isArray(Y[G]))Y[G].push(J);else Y[G]=[Y[G],J];else Y[G]=J;else X[G]=J}),$.formBody=X,$.files=Y}}catch(W){if(typeof(W?.status??W?.statusCode)==="number")throw W;_.debug("[stacks-router] Body parsing failed:",W)}}function C$($={}){let Z=new q1({verbose:$.verbose??!1}),W="",X=[],Y=!1;function J(z,Q,B){let U=W+Q,j=`${z}:${U}`;if(_.debug(`[router] ${z} ${U} \u2192 ${typeof B==="string"?B:"function"}`),X.length>0)Y5.set(j,[...X]);if(Y)D$.add(j);if(typeof B==="string")e8.set(j,B);return{fullPath:U,routeKey:j}}let G={bunRouter:Z,get routes(){return Z.routes},get(z,Q){let{fullPath:B,routeKey:U}=J("GET",z,Q);return Z.get(B,Z5(U,Q)),W5(U)},post(z,Q){let{fullPath:B,routeKey:U}=J("POST",z,Q);return Z.post(B,Z5(U,Q)),W5(U)},put(z,Q){let{fullPath:B,routeKey:U}=J("PUT",z,Q);return Z.put(B,Z5(U,Q)),W5(U)},patch(z,Q){let{fullPath:B,routeKey:U}=J("PATCH",z,Q);return Z.patch(B,Z5(U,Q)),W5(U)},delete(z,Q){let{fullPath:B,routeKey:U}=J("DELETE",z,Q);return Z.delete(B,Z5(U,Q)),W5(U)},options(z,Q){let{fullPath:B,routeKey:U}=J("OPTIONS",z,Q);return Z.options(B,Z5(U,Q)),W5(U)},group(z,Q){let B=W,U=[...X],j=Y;if(z.prefix)W=B+z.prefix;let H=z.middleware?Array.isArray(z.middleware)?z.middleware:[z.middleware]:void 0;if(H)X=[...X,...H];if(z.apiResponse===!0)Y=!0;_.debug(`[router] Entering group: prefix=${z.prefix||"/"} middleware=[${H?.join(", ")||""}]${Y?" apiResponse=true":""}`);let L=Q();if(L instanceof Promise)return L.then(()=>{return W=B,X=U,Y=j,G}).catch((F)=>{throw W=B,X=U,Y=j,F});return W=B,X=U,Y=j,G},resource(z,Q,B){let U=["index","store","show","update","destroy"],j=B?.only?U.filter((F)=>B.only.includes(F)):B?.except?U.filter((F)=>!B.except.includes(F)):U,H=Q.replace(/Action$/,"");_.debug(`[router] Resource: /${z} \u2192 ${Q} [${j.join(", ")}]`);let L=()=>{for(let F of j)switch(F){case"index":G.get(`/${z}`,`${H}IndexAction`);break;case"store":G.post(`/${z}`,`${H}StoreAction`);break;case"show":G.get(`/${z}/:id`,`${H}ShowAction`);break;case"update":G.put(`/${z}/:id`,`${H}UpdateAction`);break;case"destroy":G.delete(`/${z}/:id`,`${H}DestroyAction`);break}};if(B?.middleware)G.group({middleware:B.middleware},L);else L();return G},match(z,Q,B){_.debug(`[router] Match: [${z.join(", ")}] ${Q} \u2192 ${typeof B==="string"?B:"function"}`);for(let U of z){let j=U.toUpperCase(),{fullPath:H,routeKey:L}=J(j,Q,B),F=Z5(L,B);switch(j){case"GET":Z.get(H,F);break;case"POST":Z.post(H,F);break;case"PUT":Z.put(H,F);break;case"PATCH":Z.patch(H,F);break;case"DELETE":Z.delete(H,F);break;case"OPTIONS":Z.options(H,F);break}}return W5(`${z[0]}:${W}${Q}`)},health(){return Z.get("/api/health",async()=>{let z={},Q=async(j,H)=>{let L=Date.now();try{let F=new AbortController,I=setTimeout(()=>F.abort(),1500);await Promise.race([H(),new Promise((f,b)=>F.signal.addEventListener("abort",()=>b(Error("timeout"))))]),clearTimeout(I),z[j]={ok:!0,ms:Date.now()-L}}catch(F){z[j]={ok:!1,ms:Date.now()-L,message:F instanceof Error?F.message:String(F)}}};await Promise.all([Q("database",async()=>{let{db:j}=await import("@stacksjs/database");await j.unsafe?.("SELECT 1")}),Q("cache",async()=>{let{cache:j}=await import("@stacksjs/cache"),H=`__health__:${Date.now()}`;await j.set(H,1,5),await j.del(H)})]);let B=Object.values(z).every((j)=>j.ok),U={status:B?"healthy":"degraded",checks:z,timestamp:Date.now()};return Response.json(U,B?200:503)}),Z.get("/__routes",(z)=>{if(!G$(z))return Response.json({error:"disabled"},404);return Response.json(_$())}),Z.get("/__storage/:path",async(z)=>{let Q=new URL(z.url),B=Q.searchParams.get("token"),U=z.params,j=U?.path?decodeURIComponent(U.path):decodeURIComponent(Q.pathname.replace(/^\/__storage\//,""));if(!B||typeof j!=="string"||j.length===0)return new Response("Forbidden",{status:403});let{verifySignedStorageToken:H,Storage:L}=await import("@stacksjs/storage");if(!H(B,j).valid)return new Response("Forbidden",{status:403});try{let I=L.disk();if(!await I.fileExists(j))return new Response("Not Found",{status:404});let b=await I.readToBuffer(j),O=await I.mimeType(j).catch(()=>"application/octet-stream");return new Response(b,{status:200,headers:{"Content-Type":O,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(I){return _.error("[storage] signed-url fetch failed:",I),new Response("Internal Error",{status:500})}}),Z.get("/__openapi.json",async(z)=>{if(!G$(z))return Response.json({error:"disabled"},404);try{let{generateOpenApi:Q}=await import("@stacksjs/api"),B=await Q();return Response.json(B)}catch(Q){return Response.json({error:"OpenAPI generation failed",message:Q instanceof Error?Q.message:String(Q)},500)}}),G},use(z){let Q=h1(z);return Z.globalMiddleware.push(Q),G},async serve(z={}){return Z.serve(z)},async handleRequest(z){return Z.handleRequest(z)},getAllowedMethods(z,Q){return Z.getAllowedMethods(z,Q)},async register(z,Q){_.debug(`[router] Register: ${z} prefix=${Q?.prefix||"none"}`);let B=async()=>{await import(z)};if(Q?.prefix||Q?.middleware)await G.group({prefix:Q.prefix,middleware:Q.middleware},B);else await B();return G},async importRoutes(){_.debug("[router] Loading user routes from registry...");try{let{loadRoutes:B}=await Promise.resolve().then(() => (l8(),Y$)),{appPath:U}=await import("@stacksjs/path"),j=(await import(U("Routes.ts"))).default;await B(j)}catch(B){throw _.error("Failed to load route registry:",B),B}_.debug("[router] Loading ORM routes...");let z=[M.frameworkPath("orm/routes.ts"),M.frameworkPath("core/orm/routes.ts")],Q=!1;for(let B of z)try{if(await Bun.file(B).exists()){await import(B),Q=!0;break}}catch(U){_.warn(`[router] ORM routes candidate failed to load, falling back to next: ${B}
|
|
50
|
+
`,U)}if(!Q)_.warn("[router] No ORM routes candidate loaded \u2014 model useApi endpoints are unavailable.");_.debug("[router] Loading discovered package routes...");try{await G.loadDiscoveredRoutes()}catch(B){_.debug("Package route discovery skipped:",B)}await T$()},async loadDiscoveredRoutes(){try{let z=M.storagePath("framework/discovered-packages.json"),Q=Bun.file(z);if(!await Q.exists())return;let U=(await Q.json())?.packages;if(!U)return;let j=M.projectPath("pantry");for(let[H,L]of Object.entries(U)){let F=L?.routes;if(!F)continue;let I=Array.isArray(F)?F:[F],f=`${j}/${H}`;for(let b of I){_.debug(`[router] Discovered route: ${H} \u2192 ${b}`);let O=b.startsWith("/")?b:`${f}/${b}`,J5=L?.routePrefix,v5=L?.routeMiddleware;try{await G.register(O,{prefix:J5,middleware:v5})}catch(y5){_.warn(`Failed to load routes from package '${H}': ${y5}`)}}}}catch{}}};return G}async function e1($,Z){if(!Q8)_.debug("[router] Loading routes for first time..."),Q8=I5.importRoutes().catch((X)=>{throw Q8=null,X});await Q8;let W=await I5.handleRequest($);if(W.status===404&&W.headers.get("content-type")?.includes("json"))try{let X=await W.clone().json();if(X?.message==="Not Found"||X?.error==="Not Found"){let J=new URL($.url),G={...X,path:J.pathname,method:$.method};return new Response(JSON.stringify(G),{status:404,headers:W.headers})}}catch{}return W}async function $6($={}){return I5.serve($)}var s8,o8,L$,F$=5000,r8,e8,z$,P5,A$=10,Q$,X5,w5=null,p1,B$,Y5,D$,U$,i8,a1,I5,Q8=null;var D5=u(()=>{S5();h5();u5();u8();Z$();s8=new Set,o8=new Set,L$=new Map;r8=new a8(F$),e8=new a8(F$),z$=new Set(["POST","PUT","PATCH","DELETE"]),P5=new Map;Q$=new Set;X5=new Map;p1=/[-_\s]+/,B$=new Map;Y5=new Map,D$=new Set;U$=new Map;i8=new Map;a1={get($,Z){let X=w(this)[$];return X!==void 0?X:Z},input($,Z){let X=w(this)[$];return X!==void 0?X:Z},all(){return w(this)},only($){let Z=w(this),W={};for(let X of $)if(X in Z)W[X]=Z[X];return W},except($){let W={...w(this)};for(let X of $)delete W[X];return W},has($){let Z=w(this);if(Array.isArray($))return $.every((W)=>(W in Z)&&Z[W]!==void 0);return $ in Z&&Z[$]!==void 0},hasAny($){let Z=w(this);return $.some((W)=>(W in Z)&&Z[W]!==void 0)},filled($){let Z=w(this),W=(X)=>{let Y=Z[X];return Y!==void 0&&Y!==null&&Y!==""&&!(Array.isArray(Y)&&Y.length===0)};if(Array.isArray($))return $.every(W);return W($)},missing($){let Z=w(this);if(Array.isArray($))return $.every((W)=>!(W in Z)||Z[W]===void 0);return!($ in Z)||Z[$]===void 0},string($,Z=""){let X=w(this)[$];return X!==void 0&&X!==null?String(X):Z},integer($,Z=0){let X=w(this)[$];if(X===void 0||X===null||X==="")return Z;if(typeof X==="number")return Number.isFinite(X)?Math.trunc(X):Z;let Y=String(X).trim();if(!/^-?\d+$/.test(Y))return Z;let J=Number.parseInt(Y,10);return Number.isFinite(J)?J:Z},float($,Z=0){let X=w(this)[$];if(X===void 0||X===null||X==="")return Z;if(typeof X==="number")return Number.isFinite(X)?X:Z;let Y=String(X).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(Y))return Z;let J=Number.parseFloat(Y);return Number.isFinite(J)?J:Z},boolean($,Z=!1){let X=w(this)[$];if(X===void 0||X===null)return Z;if(typeof X==="boolean")return X;if(X==="true"||X==="1"||X===1)return!0;if(X==="false"||X==="0"||X===0)return!1;return Z},array($){let W=w(this)[$];if(Array.isArray(W))return W;return W!==void 0&&W!==null?[W]:[]},file($){let W=(this.files||{})[$];if(!W)return null;let X=Array.isArray(W)?W[0]:W;return X?new G8(X):null},getFiles($){let W=(this.files||{})[$];if(!W)return[];return(Array.isArray(W)?W:[W]).map((Y)=>new G8(Y))},hasFile($){let Z=this.files||{};return $ in Z&&Z[$]!==void 0},allFiles(){let $=this.files||{},Z={};for(let[W,X]of Object.entries($))if(Array.isArray(X))Z[W]=X.map((Y)=>new G8(Y));else Z[W]=new G8(X);return Z},async user(){return this._authenticatedUser},async userToken(){return this._currentAccessToken},async tokenCan($){if(typeof $!=="string"||$.length===0)return!1;let Z=this._currentAccessToken;if(!Z||typeof Z!=="object")return!1;if(!Array.isArray(Z.abilities))return!1;if(Z.abilities.includes("*"))return!0;return Z.abilities.includes($)},async tokenCant($){return!await this.tokenCan($)},async can($,...Z){if(typeof $!=="string"||$.length===0)return!1;let{Gate:W}=await import("@stacksjs/auth"),X=this._authenticatedUser??null;return W.allows($,X,...Z)},async cannot($,...Z){return!await this.can($,...Z)},async authorize($,...Z){let{Gate:W}=await import("@stacksjs/auth"),X=this._authenticatedUser??null;await W.authorize($,X,...Z)}};I5=C$()});D5();S5();l8();u5();D5();h5();u8();export*from"@stacksjs/bun-router";class g extends Error{reason;constructor($,Z,W){let X=W?` in ${W}`:"";super(`[router] Refusing to use ${JSON.stringify(Z)} as a path parameter${X} \u2014 ${$}`);this.name="PathParamError",this.reason=$}}var Z6=/[\u0000-\u001F\u007F]/;function x$($,Z={}){if(typeof $!=="string")throw new g("not-string",$,Z.context);if($.length===0)throw new g("empty",$,Z.context);let W=Z.maxLength??255;if($.length>W)throw new g("too-long",$,Z.context);if($.includes("\x00"))throw new g("null-byte",$,Z.context);if(Z6.test($))throw new g("control-char",$,Z.context);if($.startsWith("/")||/^[A-Z]:[\\/]/i.test($))throw new g("absolute-path",$,Z.context);if(/(^|[\\/])\.\.([\\/]|$)/.test($))throw new g("traversal",$,Z.context);if(!Z.allowSlashes&&/[\\/]/.test($))throw new g("traversal",$,Z.context);return $}function W6($,Z={}){try{return x$($,Z)}catch{return null}}D5();D5();import{timingSafeEqual as X6}from"crypto";import{Buffer as E$}from"buffer";import B8 from"process";var W9="signature",Z9="expires";function q$(){let $=B8.env.APP_KEY||B8.env.STACKS_SIGNED_URL_SECRET;if(!$||$.length<16)throw Error("[router] signed URLs require APP_KEY (\u2265 16 chars) or STACKS_SIGNED_URL_SECRET. "+"Run `./buddy key:generate` or set the env var.");return $}function b$($,Z){return new Bun.CryptoHasher("sha256",Z).update($).digest("hex")}function Y6($,Z){let W=E$.from($.toLowerCase(),"hex"),X=E$.from(Z.toLowerCase(),"hex");if(W.length!==X.length)return!1;return X6(W,X)}function J6($){let Z=new URL($.toString());return Z.searchParams.delete(W9),Z}function w$($){let Z=J6($);return Z.searchParams.sort(),Z.toString()}function P$($,Z={}){let W=q$(),X=$.startsWith("http")?new URL($):new URL($.startsWith("/")?$:`/${$}`,B8.env.APP_URL||"https://localhost");if(Z.ttl!==void 0&&Z.expiresAt!==void 0)G6("dual-expiry","[router] signUrl: both `ttl` and `expiresAt` provided \u2014 using `ttl`.");if(Z.ttl!==void 0)X.searchParams.set(Z9,String(Math.floor(Date.now()/1000)+Z.ttl));else if(Z.expiresAt!==void 0)X.searchParams.set(Z9,String(Math.floor(Z.expiresAt)));let Y=w$(X);return X.searchParams.set(W9,b$(Y,W)),X.toString()}var R$=new Set;function G6($,Z){if(R$.has($))return;R$.add($),console.warn(Z)}function z6($,Z={},W={}){return P$($9($,Z),W)}function k$($){let Z=typeof $==="string"?new URL($,B8.env.APP_URL||"https://localhost"):$,W=Z.searchParams.get(W9);if(!W)return{valid:!1,reason:"missing-signature"};let X=Z.searchParams.get(Z9);if(X!==null){let Y=Number.parseInt(X,10);if(!Number.isFinite(Y)||Date.now()/1000>Y)return{valid:!1,reason:"expired"}}try{let Y=b$(w$(Z),q$());return Y6(W,Y)?{valid:!0}:{valid:!1,reason:"invalid-signature"}}catch{return{valid:!1,reason:"invalid-signature"}}}async function Q6($){let Z=k$($.url);if(Z.valid)return;let W=Z.reason==="expired"?410:401;throw Response.json({error:Z.reason},{status:W})}import{decrypt as B6,encrypt as U6}from"@stacksjs/security";class U8{inner;opts;constructor($,Z={}){this.inner=$;this.opts=Z}async set($,Z,W){let X=await this.wrap($,Z);await this.inner.set($,X,W)}async touch($,Z,W){let X=await this.wrap($,Z);await this.inner.touch($,X,W)}async get($){let Z=await this.inner.get($);if(!Z)return null;return this.unwrap(Z)}destroy($){return this.inner.destroy($)}async all(){let $=await this.inner.all(),Z={};for(let[W,X]of Object.entries($)){let Y=await this.unwrap(X);if(Y)Z[W]=Y}return Z}length(){return this.inner.length()}clear(){return this.inner.clear()}async wrap($,Z){let{id:W,...X}=Z,Y=await U6(JSON.stringify(X),this.opts.appKey);return{_enc:!0,id:W??$,data:Y}}async unwrap($){if(!$||typeof $!=="object")return null;let Z=$;if(Z._enc===!0&&typeof Z.data==="string")try{let W=await B6(Z.data,this.opts.appKey),X=JSON.parse(W);if(Z.id!==void 0)X.id=Z.id;return X}catch{return null}return Z}}import k5 from"process";import{createSessionStore as j6}from"@stacksjs/bun-router";import{DatabaseSessionStore as F6,FileSessionStore as _6,MemorySessionStore as A6,RedisSessionStore as V6,createSessionStore as I6}from"@stacksjs/bun-router";function H6($){let Z=j6($);if(!L6($.encrypt))return Z;let X=$.appKey??k5.env.APP_KEY;if(!X||X.length<16)throw Error("[session] createStacksSessionStore: encryption requested but APP_KEY is missing or too short "+"(need \u226516 chars). Either set APP_KEY in env, pass `appKey` in config, or set `encrypt: false` to opt out.");return new U8(Z,{appKey:X})}function L6($){if($===!0)return!0;if($===!1)return!1;return(k5.env.APP_ENV??k5.env.NODE_ENV??"").toLowerCase()==="production"}import("@stacksjs/database").then(({setQueryTracker:$})=>{if(typeof $==="function"){let{trackQuery:Z}=(u5(),h$(_9));$(Z)}}).catch(()=>{});export{l$ as withTraceId,Q6 as verifySignedUrlMiddleware,k$ as verifySignedUrl,$9 as url,j9 as trackQuery,t1 as stream,z6 as signedUrl,P$ as signUrl,s$ as setCurrentRequest,e1 as serverResponse,$6 as serve,x$ as sanitizePathParam,W6 as safePathParam,_8 as runWithRequest,f1 as routeParams,I5 as route,o$ as request,V1 as rateLimitStatus,d8 as rateLimit,X$ as loadRoutes,_$ as listRegisteredRoutes,t as isApiRequest,u1 as installMiddlewareHotReload,u$ as getTraceId,H9 as getQueryShapeCounts,o as getCurrentRequest,K$ as findUnresolvableRouteMiddleware,L9 as createValidationErrorResponse,H6 as createStacksSessionStore,C$ as createStacksRouter,I6 as createSessionStore,F9 as createNotFoundResponse,U5 as createMiddlewareErrorResponse,l as createErrorResponse,d5 as clearTrackedQueries,I1 as clearRateLimit,I$ as clearMiddlewareCache,i$ as cacheRequestQuery,T$ as assertRouteMiddlewareResolvable,V6 as RedisSessionStore,g as PathParamError,f5 as Middleware,A6 as MemorySessionStore,g5 as JSON_CONTENT_TYPE,_6 as FileSessionStore,U8 as EncryptedSessionStore,F6 as DatabaseSessionStore};
|