@stacksjs/router 0.70.60 → 0.70.62
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/dist/index.js +18 -18
- package/package.json +10 -10
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var{defineProperty:
|
|
2
|
+
var{defineProperty:A8,getOwnPropertyNames:f$,getOwnPropertyDescriptor:g$}=Object,h$=Object.prototype.hasOwnProperty;function m$($){return this[$]}var p$=($)=>{var Z=(J9??=new WeakMap).get($),W;if(Z)return Z;if(Z=A8({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of f$($))if(!h$.call(Z,X))A8(Z,X,{get:m$.bind($,X),enumerable:!(W=g$($,X))||W.enumerable})}return J9.set($,Z),Z},J9;var c$=($)=>$;function d$($,Z){this[$]=c$.bind(null,Z)}var G9=($,Z)=>{for(var W in Z)A8($,W,{get:Z[W],enumerable:!0,configurable:!0,set:d$.bind(Z,W)})};var u=($,Z)=>()=>($&&(Z=$($=0)),Z);var C=import.meta.require;class h5{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 u$ from"process";import{AsyncLocalStorage as Q9}from"async_hooks";import{log as l$}from"@stacksjs/logging";function n$(){let $=B9.getStore();if($)return $;return S5.getStore()?._requestId}function i$($,Z){return B9.run($,Z)}function s$(){let $=S5.getStore();if(!$)return;let Z=$[z9];if(!Z)Z={map:new Map},$[z9]=Z;return Z}async function o$($,Z){let W=s$();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 t$($){l$.debug(`[request] ${$.method} ${new URL($.url).pathname}`),S5.enterWith($)}function _8($,Z){return S5.run($,Z)}function t(){return S5.getStore()}var S5,B9,z9,a$;var N5=u(()=>{S5=new Q9,B9=new Q9;z9=Symbol.for("stacks.requestQueryCache");a$=new Proxy({},{get($,Z){let W=t();if(!W){if(u$.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 a($){let Z=$.headers,W=Z.get("content-type")||"";if(m5.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 m5;var p5=u(()=>{m5=/^application\/(?:json|.+\+json)(?:;|$)/i});var _9={};G9(_9,{trackQuery:()=>L9,getQueryShapeCounts:()=>F9,createValidationErrorResponse:()=>A9,createNotFoundResponse:()=>V9,createMiddlewareErrorResponse:()=>j5,createErrorResponse:()=>l,clearTrackedQueries:()=>l5});import r from"process";import{log as r$}from"@stacksjs/logging";import{createErrorHandler as e$,renderProductionErrorPage as j9}from"@stacksjs/error-handling";function U5($){let Z={error:$.error,message:$.message,status:$.status,timestamp:new Date().toISOString()};if($.details)Z.details=$.details;return JSON.stringify(Z)}function B5(){let $=(r.env.APP_ENV??"").toLowerCase();if($==="development")return!0;if(!$&&r.env.NODE_ENV==="development")return!0;return!1}function e(){return{"Content-Type":"application/json"}}function $Z(){return e()}function c5(){return{buffer:Array(C5).fill(null),writeIndex:0,count:0,shapeCounts:new Map,n1Warned:new Set}}function I8(){let $=t();if(!$)return H9;let Z=$[d5];if(!Z)Z=c5(),$[d5]=Z;return Z}function WZ($){return $.replace(/'(?:[^']|'')*'/g,"?").replace(/"(?:[^"]|"")*"/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/IN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toUpperCase()}function L9($,Z,W){let X=I8();if(X.buffer[X.writeIndex]={query:$,time:Z,connection:W},X.writeIndex=(X.writeIndex+1)%C5,X.count<C5)X.count++;if(!B5())return;let Y=WZ($);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===ZZ+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
3
|
${Y}
|
|
4
|
-
Hint: load related rows with .with('relation') or eager-load via includes() before iterating.`)}).catch(()=>{})}function
|
|
5
|
-
`).slice(0,10),U.queries=
|
|
4
|
+
Hint: load related rows with .with('relation') or eager-load via includes() before iterating.`)}).catch(()=>{})}function U9(){let $=I8();if($.count===0)return[];let Z=[],W=$.count<C5?0:$.writeIndex;for(let X=0;X<$.count;X++){let Y=$.buffer[(W+X)%C5];if(Y)Z.push(Y)}return Z}function F9(){return new Map(I8().shapeCounts)}function l5(){let $=t();if($&&$[d5]){$[d5]=c5();return}H9=c5()}function XZ(){return{appName:"Stacks",theme:"auto",showEnvironment:!0,showQueries:!0,showRequest:!0,enableCopyMarkdown:!0,snippetLines:8,basePaths:[r.cwd()]}}function u5($,Z=0,W=new WeakSet){if(!$||typeof $!=="object"||Z>=JZ)return $;if(W.has($))return GZ;if(W.add($),Array.isArray($))return $.map((Y)=>u5(Y,Z+1,W));let X={};for(let[Y,J]of Object.entries($)){let G=Y.toLowerCase();if(YZ.some((z)=>G.includes(z)))X[Y]="********";else if(typeof J==="object"&&J!==null)X[Y]=u5(J,Z+1,W);else X[Y]=J}return X}function zZ($){let Z=$;if(Z.jsonBody)return u5(Z.jsonBody);if(Z.formBody)return u5(Z.formBody);return}async function QZ($){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(r$.debug(`[error] ${X} ${$.message}`),!B5()){if(a(Z)){let J=X>=400&&X<500,G=$.details;return new Response(U5({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:e()})}return new Response(j9(X),{status:X,headers:{"Content-Type":"text/html; charset=utf-8"}})}try{let J=e$(XZ());J.setFramework("Stacks","0.70.0");let G=zZ(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 QZ(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 U9())J.addQuery(U.query,U.time,U.connection);if(a(Z)){let U={handler:W?.handlerPath};if(B5())U.stack=$.stack?.split(`
|
|
5
|
+
`).slice(0,10),U.queries=U9().slice(-10);return new Response(U5({error:$.name||"Error",message:$.message,status:X,details:U}),{status:X,headers:$Z()})}let Q=r.env.APP_URL?r.env.APP_URL.startsWith("http")?r.env.APP_URL:`https://${r.env.APP_URL}`:B5()?"*":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>
|
|
@@ -11,16 +11,16 @@ var{defineProperty:L8,getOwnPropertyNames:v$,getOwnPropertyDescriptor:y$}=Object
|
|
|
11
11
|
<pre>${G($.stack||"")}</pre>
|
|
12
12
|
</body>
|
|
13
13
|
</html>
|
|
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:
|
|
14
|
+
`,{status:X,headers:{"Content-Type":"text/html; charset=utf-8"}})}}async function j5($,Z){let W=$.statusCode??$.status??500,X=B5();if(W>=400&&W<500){let Y=$.headers?{...$.headers,...e()}:e();return new Response(U5({error:$.name||"ClientError",message:$.message,status:W}),{status:W,headers:Y})}if(X)return await l($,Z,{status:W});return new Response(U5({error:"Internal Server Error",message:"An unexpected error occurred.",status:W}),{status:W,headers:e()})}function A9($,Z){return new Response(U5({error:"ValidationError",message:"Validation failed",status:422,details:{errors:$}}),{status:422,headers:e()})}async function V9($,Z){if(B5()){let X=Error(`Route not found: ${$}`);return X.name="NotFoundError",await l(X,Z,{status:404})}if(a(Z))return new Response(U5({error:"NotFound",message:`Route not found: ${$}`,status:404}),{status:404,headers:e()});return new Response(j9(404),{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}var C5=50,ZZ=5,d5,H9,YZ,JZ=10,GZ="[Circular]";var n5=u(()=>{p5();N5();d5=Symbol.for("stacks.queryTracking"),H9=c5();YZ=["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 I9,statSync as D9}from"fs";import{join as BZ,relative as UZ,resolve as O9}from"path";import e5 from"process";import{Buffer as m}from"buffer";import{createCipheriv as jZ,createDecipheriv as HZ,randomBytes as D8}from"crypto";import{closeSync as O8,createReadStream as K9,createWriteStream as LZ,existsSync as i5,fsyncSync as T9,openSync as M9,writeFileSync as FZ}from"fs";import{access as AZ,constants as S9,mkdir as VZ,readdir as s5,rename as N9,stat as H5,unlink as o5,writeFile as K8}from"fs/promises";import{isAbsolute as _Z,join as L5,resolve as IZ}from"path";import V from"process";import{pipeline as DZ}from"stream/promises";import{createGzip as C9}from"zlib";import F5 from"process";import p from"process";import t5 from"process";import{existsSync as a5}from"fs";import{resolve as T8}from"path";import{existsSync as OZ}from"fs";import{existsSync as x8,mkdirSync as KZ,readdirSync as TZ,readFileSync as MZ,writeFileSync as SZ}from"fs";import{homedir as A5}from"os";import{dirname as x9,resolve as R}from"path";import $5 from"process";import{existsSync as NZ,readdirSync as CZ}from"fs";import{extname as M8,resolve as E9}from"path";import xZ from"process";function qZ($,Z){this[$]=RZ.bind(null,Z)}class y8{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(!I9($))return!0;return D9($).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=I9(W)?D9(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 f8{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 PZ($,Z={}){let X=Object.keys(Z).sort().map((Y)=>`${Y}:${Z[Y]}`).join("|");return X?`${$}:${X}`:$}function kZ($,Z){try{return JSON.stringify($)===JSON.stringify(Z)}catch{return $===Z}}function vZ($){return $.getStats().size*2}function yZ($,Z={}){let W=e5.cwd();while(W.includes("storage"))W=O9(W,"..");let X=O9(W,$||"");if(Z?.relative)return UZ(e5.cwd(),X);return X}function S(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fZ(){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 y9{async format($){let Z=await fZ(),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:F5.pid,hostname:Z(),environment:F5.env.NODE_ENV||"development",platform:F5.platform,version:F5.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:F5.env.NODE_ENV||F5.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class W8{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={...E5},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new y9,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??V.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{...r5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...r5};return{...r5,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:E5.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!S()&&this.config.writeToFile===!0}async writeToFile($){let W=(async()=>{let Y,J=0,G=3,z=1000;while(J<G)try{try{try{await AZ(this.config.logDirectory,S9.F_OK|S9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await VZ(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(!i5(this.currentLogFile))await K8(this.currentLogFile,"",{mode:420});if(Y=M9(this.currentLogFile,"a",420),FZ(Y,Q,{flag:"a"}),T9(Y),Y!==void 0)O8(Y),Y=void 0;if((await H5(this.currentLogFile)).size===0){if(await K8(this.currentLogFile,Q,{flag:"w",mode:420}),(await H5(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{O8(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 L5(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 L5(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return L5(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(S())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 D8(16).toString("hex")}generateKey(){return D8(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=D8(16),X=jZ("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=C9(),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(S())return;if(!this.shouldWriteToFile())return;let $=await H5(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 s5(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 H5(W).catch(()=>null))try{if(await N9(W,z),Z.compress)try{let Q=`${z}.gz`;await this.compressLogFile(z,Q),await o5(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 K8(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 H5(W).catch(()=>null))await N9(W,J)}if(this.currentLogFile=X,Z.maxFiles){let J=(await s5(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,z)=>z.localeCompare(G));for(let G of J.slice(Z.maxFiles))await o5(L5(this.config.logDirectory,G))}}}async compressLogFile($,Z){let W=K9($),X=LZ(Z),Y=C9();await DZ(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()})),i5(this.currentLogFile))try{let $=M9(this.currentLogFile,"r+");T9($),O8($)}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(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await s5(this.config.logDirectory)).filter((W)=>(W.includes("temp")||W.includes(".tmp"))&&W.includes(this.name));for(let W of Z)try{await o5(L5(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()?_.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())return!1;let $=typeof V.env.NO_COLOR<"u",Z=V.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof V.stderr<"u"&&V.stderr.isTTY||typeof V.stdout<"u"&&V.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=V.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} ${_.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=_.underline(_.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)=>_.bgGray(X)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(W,X)=>_.bold(X)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(W,X)=>_.italic(X)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(W,X)=>_.italic(X)),Z=Z.replace(/~([^~]+)~/g,(W,X)=>_.strikethrough(X)),Z}supportsHyperlinks(){if(S())return!1;let $=V.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=V.env.HOME||"";if(W)Z=Z.replace(/^~(?=$|\/)/,W)}if(_Z(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=IZ(Z);else return null;return i5(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?"":f9[$],H=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",L;switch($){case"debug":L=this.formatConsoleMessage({timestamp:Y,icon:j,tag:H,message:_.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:_.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:_.gray(` ${I}`),level:$,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${G}`),z)console.error(z)}let U=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
16
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()&&!
|
|
18
|
-
`);if(this[Q==="warning"?"warn":Q](z),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
19
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?
|
|
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:
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt($){if(
|
|
22
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
23
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||
|
|
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()&&!S()&&V.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()&&!S()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,Q="info")=>{if(!S()&&V.stdout.isTTY)V.stdout.write(`
|
|
18
|
+
`);if(this[Q==="warning"?"warn":Q](z),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":_.blue("\u25D0"),tag:W,message:`${_.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?_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:this.options.showIcons===!1?"":_.green("\u2713"),tag:U,message:`${J}${W?` ${JSON.stringify(W)}`:""}`}))}else if(!S())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 W8(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(S())throw Error("createReadStream is not supported in browser environments");if(!i5(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return K9(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=HZ("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 S()}isServerMode(){return!S()}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:_.cyan(H),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:W,message:_.cyan(B),showTimestamp:!1})),j.forEach((H)=>console.error(H)),console.error(this.formatConsoleMessage({timestamp:W,message:_.cyan(U),showTimestamp:!1}))}else if(!S())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(S())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${_.cyan("?")} ${$} (y/n) `);let W=(X)=>{let Y=X.toString().trim().toLowerCase();V.stdin.removeListener("data",W);try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!1)}catch{}V.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!0)}catch{}V.stdin.resume(),V.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?_.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${_.blue("\u25D0")} `;console.error(`${B}${Q} ${_.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()||!V.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=_.green("\u2501".repeat(X)),G=_.gray("\u2501".repeat(Y)),z=`[${J}${G}]`,Q=`${W}%`.padStart(4),B=$.message?` ${$.message}`:"",U=this.options.showIcons===!1?"":Z||W===100?_.green("\u2713"):_.blue("\u25B6"),j=this.options.showTags!==!1&&this.name?` ${_.gray(this.formatTag(this.name))}`:"",H=`\r${U}${j} ${z} ${Q}${B}`,L=V.stdout.columns||80,F=" ".repeat(Math.max(0,L-H.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${H}${F}`,V.stdout.write($.lastRenderedLine),Z)V.stdout.write(`
|
|
23
|
+
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||S()||!V.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await s5(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=L5(this.config.logDirectory,X);if($.before)try{if((await H5(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 o5(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 g9($,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 h9($){return $ instanceof P}function $1($){return $ instanceof $8}function Z1($){if(h9($))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 X8{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 b5.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=t5.env[Q]||(B?t5.env[B]:void 0);if(U!==void 0){if(X.verbose){let j=t5.env[Q]?Q:B}try{$[Y]=this.parseEnvironmentValue(U,typeof J,Q,X.customParsers,X.configName)}catch(j){if(j instanceof Z8)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(t5.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
25
|
`;for(let X of $)W+=`${X.key}
|
|
26
26
|
`,W+=` Type: ${X.type}
|
|
@@ -32,19 +32,19 @@ var{defineProperty:L8,getOwnPropertyNames:v$,getOwnPropertyDescriptor:y$}=Object
|
|
|
32
32
|
`;W+=`| Variable | Type | Description | Example |
|
|
33
33
|
`,W+=`|----------|------|-------------|----------|
|
|
34
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}
|
|
35
|
+
`;return W}}function W1($,Z){let W=wZ("process");if(typeof W>"u"||!W.env)return Z;let X=W.env[$];return X!==void 0?X:Z}function p9($,Z,W={}){return c9($,Z,W,new WeakMap)}function c9($,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 d9($,Z,Y,X);if(!y(Z)||!y($))return Z;return G1($,Z,W,X)}function d9($,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 X1($,Z);case"smart":return Y1($,Z,X);default:return Z}return Z}function X1($,Z){let W=[...Z];for(let X of $)if(!W.some((Y)=>k8(Y,X)))W.push(X);return W}function Y1($,Z,W){if(Z.length===0)return $;if($.length===0)return Z;if(y(Z[0])&&y($[0]))return J1($,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 J1($,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 G1($,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]=c9(Q,z,W,X);else if(Array.isArray(z)||Array.isArray(Q))J[G]=d9(Q,z,W.arrayMergeMode||"smart",X);else J[G]=z}return J}function g8($,Z,W="replace"){return p9($,Z,{arrayMergeMode:W==="replace"?"replace":"smart",skipNullish:!0})}function k8($,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(!k8($[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(!k8($[Y],Z[Y]))return!1}return!0}return!1}function y($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Y8{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=V5.getWithFileCheck("file",$);if(B){if(z)console.log(`Configuration loaded from cache: ${$}`);return B}}let Q=async()=>{if(!a5($))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 R5($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new R5($,Error("Configuration must export a valid object"),"unknown");let f={config:g8(Z,j,X),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)V5.setWithFileCheck("file",f,$,J);return f}catch(B){throw B instanceof Error?n.configLoad($,B):n.configLoad($,Error(String(B)))}};if(G)return b5.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(T8(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 g9(async()=>{return a5($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,W){let X=[];if(!a5($))return X;if(Z||W){let Y=this.generateNamePatterns(Z||"",W);for(let J of Y)for(let G of this.extensions){let z=T8($,`${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=T8($,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(!a5($))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 m8{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 b5.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,Z,W){try{if(!OZ(Z))throw new q5(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 q5(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:n9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function z1($){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 p8{fileLoader=new Y8;envProcessor=new X8;validator=new m8;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||$5.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(R(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}"${z1(Y)}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,W,X,Y,J,G,z,Q){let B=z?x5($,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?x5($,W,Y):W,z=[R(A5(),".config",$),R(A5(),".config"),A5()];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?x5($,X,J):X;try{let Q=R(W,"package.json");if(!x8(Q))return null;let B={};try{B=JSON.parse(MZ(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:g8(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:x5($,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 V5.get(W)||null}cacheResult($,Z,W,X){let Y=this.generateCacheKey($,X);V5.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([$,R($,"config"),R($,".config"),Z?R($,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(R(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=[R(A5(),".config",$),R(A5(),".config"),A5()],X=[];for(let Y of W)X.push(...this.fileLoader.generateConfigPaths($,Y,Z));return X}async loadConfigWithResult($){return this.loadConfig($)}}function k9($){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 Q1($){return c.loadConfig({...$,__strictErrorHandling:!0})}async function s9($){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 B1($={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"&&k9(W)))return(await c.applyEnvironmentVariables($,{},!0,!1)).config;throw W}}try{return(await c.loadConfig({...$,cwd:$.cwd||$5.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&k9(Z)))return(await c.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw Z}}async function U1($,Z,W="replace"){let X=new Y8;try{let Y=await X.loadFromPath($,Z,{arrayStrategy:W,useCache:!1,trackPerformance:!1});return Y?Y.config:null}catch{return null}}function x5($,Z,W=!1){let X=new X8,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=$5.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 j1($){let Z=R($5.cwd(),$.configDir),W=R($5.cwd(),$.generatedDir),X=R(W,"config-types.ts");if(!x8(x9(X)))KZ(x9(X),{recursive:!0,mode:511});let Y=x8(Z)?TZ(Z).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${rZ}
|
|
36
36
|
export type ConfigNames = ${Y.length?`'${Y.join("' | '")}'`:"string"}
|
|
37
|
-
`;
|
|
38
|
-
${Y.map((B)=>{let U=
|
|
37
|
+
`;SZ(X,J,{mode:438})}function H1($){let Z=null,W=null,X=()=>{if(!W)W=s9($).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 F1($){let Z=E9(xZ.cwd(),$?.configDir||"./config");function W(){if(!NZ(Z))return[];let Y=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=CZ(Z).filter((Q)=>Y.has(M8(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=M8(B).toLowerCase(),j=z.get(Q);if(!j){z.set(Q,B);continue}let H=M8(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=E9(Z,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${U}').default`}).join(`,
|
|
39
39
|
`)}
|
|
40
40
|
}`:"Record<string, any>";return`export type ConfigNames = ${G}
|
|
41
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(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
|
|
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 v8{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 c8{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 v8(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 v8?"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 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};
|
|
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 J8(`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 e9($){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 EZ,RZ=($)=>$,bZ=($,Z)=>{for(var W in Z)EZ($,W,{get:Z[W],enumerable:!0,configurable:!0,set:qZ.bind(Z,W)})},d=($,Z)=>()=>($&&(Z=$($=0)),Z),wZ,V5,b5,v9,w5,R9,S8,E5,gZ,N,_,hZ,q9,mZ,b9,pZ,cZ,N8,dZ,w9,P9,uZ,C8,lZ,nZ,iZ,sZ,oZ,r5,f9,tZ,aZ,rZ="0.15.9",eZ=()=>{},P,$8,R5,E8,R8,Z8,q8,b8,q5,w8,P8,n,_5,m9,u9,h8,l9,n9,i9,v,c,o9,t9,L1,A1=()=>{},a9,r9,V1,k,J8;var $$=u(()=>{EZ=Object.defineProperty;wZ=import.meta.require;w5=d(()=>{V5=new y8,b5=new f8,v9={createKey:PZ,isEquivalent:kZ,estimateMemoryUsage:vZ}});aZ=d(()=>{R9=e5.env.CLARITY_LOG_DIR||BZ(yZ(),"logs"),S8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:R9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},E5={...S8},gZ=(async()=>{try{let{loadConfig:$}=await Promise.resolve().then(()=>(r9(),a9)),Z=await $({name:"clarity",alias:"logging",defaultConfig:S8,cwd:e5.cwd()});if(Z)Object.assign(E5,Z)}catch{}return E5})(),N={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"},_=N,hZ=N.red,q9=N.green,mZ=N.yellow,b9=N.blue,pZ=N.magenta,cZ=N.cyan,N8=N.white,dZ=N.gray,w9=N.bgRed,P9=N.bgYellow,uZ=N.bgGray,C8=N.bold,lZ=N.dim,nZ=N.italic,iZ=N.underline,sZ=N.strikethrough,oZ=N.reset,r5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f9={debug:"\uD83D\uDD0D",info:b9("\u2139"),success:q9("\u2713"),warning:P9(N8(C8(" WARN "))),error:w9(N8(C8(" ERROR ")))},tZ=new W8("stacks")});_5=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}`}},$8=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})}},R5=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}},E8=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})}},R8=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}},Z8=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})}},q8=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}},b8=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}},q5=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})}},w8=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})}},P8=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 $8($,Z,W)},configLoad($,Z,W){return new R5($,Z,W)},configValidation($,Z,W){return new E8($,Z,W)},configMerge($,Z,W,X){return new R8($,Z,W,X)},envVar($,Z,W,X){return new Z8($,Z,W,X)},fileSystem($,Z,W){return new q8($,Z,W)},typeGeneration($,Z,W){return new b8($,Z,W)},schemaValidation($,Z,W){return new q5($,Z,W)},browserConfig($,Z,W,X){return new w8($,Z,W,X)},plugin($,Z,W){return new P8($,Z,W)}}});m9=d(()=>{w5(),_5()});h8=d(()=>{u9={replace:"replace",concat:"concat",smart:"smart"}});l9=d(()=>{w5(),_5(),h8()});i9=d(()=>{w5(),_5(),n9=/^https?:\/\//});L1=d(()=>{aZ(),eZ(),w5(),_5(),m9(),l9(),i9(),h8(),v=new W8("bunfig",{showTags:!0}),c=new p8,o9=R($5.cwd(),"config"),t9=R($5.cwd(),"src/generated")});a9={};bZ(a9,{withErrorRecovery:()=>g9,tryLoadConfig:()=>U1,loadConfigWithResult:()=>Q1,loadConfig:()=>s9,isRetryableError:()=>Z1,isConfigNotFoundError:()=>$1,isBunfigError:()=>h9,globalPerformanceMonitor:()=>b5,globalCache:()=>V5,getEnvOrDefault:()=>W1,generateConfigTypes:()=>j1,defaultGeneratedDir:()=>t9,defaultConfigDir:()=>o9,deepMergeWithArrayStrategy:()=>g8,deepMerge:()=>p9,createLibraryConfig:()=>H1,config:()=>B1,bunfigPlugin:()=>F1,applyEnvVarsToConfig:()=>x5,TypeGenerationError:()=>b8,SchemaValidationError:()=>q5,PluginError:()=>P8,PerformanceMonitor:()=>f8,FileSystemError:()=>q8,ErrorFactory:()=>n,EnvVarError:()=>Z8,EnvProcessor:()=>X8,ConfigValidator:()=>m8,ConfigValidationError:()=>E8,ConfigNotFoundError:()=>$8,ConfigMergeError:()=>R8,ConfigLoader:()=>p8,ConfigLoadError:()=>R5,ConfigFileLoader:()=>Y8,ConfigCache:()=>y8,CacheUtils:()=>v9,BunfigError:()=>P,BrowserConfigError:()=>w8,ArrayMergeStrategies:()=>u9});r9=d(()=>{L1(),_5(),w5(),_5(),A1(),m9(),l9(),i9(),h8()});r9();V1={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=V1;J8=class J8 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 d8($,Z){let W=`${Z}:${$}`,X=Z$.get(W);if(!X)X=new c8({windowMs:Z,maxRequests:$,algorithm:"fixed-window",standardHeaders:!1,legacyHeaders:!1}),Z$.set(W,X);return X}function u8($){if($!==void 0)return $;let Z=t();return Z?e9(Z):"anon"}function l8($,Z,W={}){let X=u8(W.identity),Y=`${$}:${X}`,J=async(G)=>{let z=d8(Z,G);try{await z.enforce(Y)}catch(Q){if(Q instanceof J8)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=I1[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 D1($,Z,W,X={}){let Y=u8(X.identity),J=`${$}:${Y}`,z=await d8(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 O1($,Z,W,X={}){let Y=u8(X.identity),J=`${$}:${Y}`;await d8(Z,W*1000).reset(J)}var I1,Z$;var n8=u(()=>{$$();N5();I1={second:1,minute:60,hour:3600,day:86400},Z$=new Map});import Z5 from"process";function K1(){if(G8!==void 0)return G8;return G8=(Z5.env.APP_ENV??Z5.env.NODE_ENV??"").toLowerCase()==="production",G8}function T1(){if(z8!==void 0)return z8;return z8=Z5.env.STACKS_SECURITY_HEADERS_DISABLE==="true",z8}function M1(){if(I5!==void 0)return I5;let $=Z5.env.STACKS_CSP,Z=Z5.env.STACKS_CSP_REPORT_ONLY;if($)I5={header:"Content-Security-Policy",value:$};else if(Z)I5={header:"Content-Security-Policy-Report-Only",value:Z};else I5=null;return I5}function W$($){if(T1())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(K1()&&!$.has("Strict-Transport-Security"))$.set("Strict-Transport-Security","max-age=31536000; includeSubDomains");let Z=M1();if(Z&&!$.has(Z.header))$.set(Z.header,Z.value)}var G8,z8,I5;var X$=()=>{};var G$={};G9(G$,{loadRoutes:()=>J$});import{log as S1}from"@stacksjs/logging";async function J$($){for(let[Z,W]of Object.entries($)){let X=E1(W),Y=X.prefix!==void 0?X.prefix?X.prefix.startsWith("/")?X.prefix:`/${X.prefix}`:void 0:N1.includes(Z)?void 0:`/${Z}`,J=R1(X.middleware);S1.debug(`[route-loader] Loading: ${X.path} prefix=${Y||"/"} middleware=[${J.join(", ")}]`);try{if(Y||J.length>0)await D5.group({prefix:Y,middleware:J.length>0?J:void 0},async()=>{await Y$(X.path)});else await Y$(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 C1()}async function C1(){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 x1($){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 Y$($){let Z=x1($),{projectPath:W}=await import("@stacksjs/path");await import(W(`routes/${Z}`))}function E1($){if(typeof $==="string")return{path:$};return $}function R1($){if(!$)return[];if(typeof $==="string")return[$];return $}var N1;var i8=u(()=>{O5();N1=["web"]});import T from"process";import{Buffer as z$}from"buffer";import{existsSync as q1}from"fs";import{timingSafeEqual as b1}from"crypto";import{log as A,report as F$}from"@stacksjs/logging";import{path as w}from"@stacksjs/path";import{UploadedFile as Q8}from"@stacksjs/storage";import{applyRequestEnhancements as w1,Router as P1}from"@stacksjs/bun-router";import{isCursorPaginator as k1,isPaginator as v1,isSimplePaginator as y1}from"@stacksjs/orm";function i($){let Z=w.storagePath(`framework/defaults/${$}`);if(q1(Z))return Z;if(P5===void 0)try{let W=Bun.resolveSync("@stacksjs/defaults/package.json",T.cwd());P5=W.slice(0,W.lastIndexOf("/"))}catch{P5=null}return P5?`${P5}/${$}`:Z}function f1($){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 e8{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 Q$($){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 b1(z$.from(X),z$.from(Z))}catch{return!1}}async function B8($,Z){if(!$._corsConfig||!Z)return Z;try{let{applyCorsHeaders:W}=await import(i("app/Middleware/Cors.ts"));return W($,Z,$._corsConfig)}catch(W){return A.warn("[router] CORS header injection failed",{error:W}),Z}}function g1($){let Z=h1($),W=new Map;for(let X of Z)W.set(X,new RegExp(`(^|/):${X}(?=$|/)`,"g"));return{path:$,paramNames:Z,colonRegex:W}}function h1($){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 W9($,Z={}){let W=v5.get($);if(!W)throw Error(`Route '${$}' is not defined. Available routes: ${[...v5.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 m1($){let Z=v5.get($);return Z?[...Z.paramNames]:[]}function _$(){let $=[],Z=new Set;for(let W of J5.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 v5.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 p1($,Z){let W=`${$}:${String(Z)}`;if(U$.has(W))return;U$.add(W),A.warn(`[Router] Middleware '${$}' declared an invalid priority (${String(Z)}). Priorities must be a finite non-negative number; falling back to default ${I$}.`)}function c1($){if($ instanceof h5)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 d1(){if(k5)return k5;return k5=(async()=>{try{return(await import(w.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(i("app/Middleware.ts"))).default||{}}catch{return{}}}})(),k5}function l1($){if(!$)return $;let Z=j$.get($);if(Z!==void 0)return Z;let W=$.split(u1).filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("");return j$.set($,W),W}async function n1($){let W=(await d1())[$]||l1($);return A.debug(`[middleware] Resolved: ${$} \u2192 ${W}`),W}async function D$($){if(Y5.has($))return Y5.get($)??null;let Z=await n1($),W;try{let X=w.appPath(`Middleware/${Z}.ts`),J=(await import(X)).default??null;if(!J||typeof J.handle!=="function")return A.error(`[Router] Middleware '${$}' resolved to ${X}, but the file has no default export with a handle() method`),Y5.set($,null),null;return Y5.set($,J),J}catch(X){W=X}try{let X=i(`app/Middleware/${Z}.ts`),J=(await import(X)).default??null;if(!J||typeof J.handle!=="function")return A.error(`[Router] Middleware '${$}' resolved to ${X}, but the file has no default export with a handle() method`),Y5.set($,null),null;return Y5.set($,J),J}catch(X){let Y=W instanceof Error?W.message:String(W);return A.error(`[Router] Failed to load middleware '${$}' (resolved to '${Z}'). app/Middleware: ${Y}; defaults:`,X),null}}function O$(){Y5.clear(),k5=null,$9.clear(),Z9.clear()}function i1(){if(T.env.APP_ENV==="production"||T.env.NODE_ENV==="production")return()=>{};let $=[];return(async()=>{try{let Z=await import("fs"),W=[w.appPath("Middleware"),w.appPath("Middleware.ts")];for(let X of W)try{if(!Z.existsSync(X))continue;let Y=Z.watch(X,{recursive:!0},()=>{A.debug("[middleware] hot-reload: clearing cache"),O$()});$.push(Y)}catch{}}catch{}})(),()=>{for(let Z of $)try{Z.close()}catch{}$=[]}}function T$($){let Z=$.indexOf(":");if(Z===-1)return{name:$};return{name:$.substring(0,Z),params:$.substring(Z+1)}}async function M$(){let $=new Map;for(let[W,X]of J5)for(let Y of X){let{name:J}=T$(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 D$(W);if(!Y||typeof Y.handle!=="function")Z.push({alias:W,routes:X})}return Z}async function S$(){let $=await M$();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 W5($,Z){let W=Z6(Z,!0),X=null;if(typeof Z==="string"){let Y=$.slice(0,$.indexOf(":")).toUpperCase();if(B$.has(Y))X=N$(Z).then(()=>{return}).catch(()=>{return})}return async(Y)=>{try{await x$(Y)}catch(G){let z=G instanceof Error?G:Error(String(G));return j5(z,Y)}let J=C$(Y);if(X)await X;if(K$.has($))Y._forceJson=!0;return _8(J,async()=>{let G=A$.get($);if(G)try{await l8($,G.max).over(G.windowSeconds)}catch(D){return j5(D,Y)}let z=J5.get($)||[],Q=Y.method.toUpperCase(),B=[...z],U=z.some((D)=>D==="csrf"||D.startsWith("csrf:")),j=t8.has($),H=a8.has($),L=Z9.get($),F=L?$9.get(L)===!0:!1;if(B$.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("://"),M=K===-1?0:Y.url.indexOf("/",K+3),E=Y.url.indexOf("?",M<0?0:M),x=M<0?"/":Y.url.slice(M,E===-1?void 0:E);A.debug(`[middleware] Executing chain: [${B.join(", ")}] for ${Q} ${x}`)}}let f=[];for(let D of B){let{name:K,params:M}=T$(D);if(M)J._middlewareParams=J._middlewareParams||{},J._middlewareParams[K]=M;let E=await D$(K);if(!E||typeof E.handle!=="function"){A.error(`[Router] Middleware '${K}' on ${$} could not be resolved \u2014 failing closed`);let h=Error(`Middleware '${K}' could not be resolved`),Q5=await l(h,J,{status:500});return await B8(J,Q5)}let x=E.priority,z5=I$;if(typeof x==="number"&&Number.isFinite(x)&&x>=0)z5=x;else if(x!==void 0)p1(K,x);f.push({name:K,handler:E,priority:z5})}f.sort((D,K)=>D.priority-K.priority);let q=[];for(let{name:D,handler:K}of f){let M=T.hrtime.bigint(),E;try{let z5=new Promise((Q5,s)=>{E=setTimeout(()=>s(Error(`Middleware '${D}' exceeded 30000ms`)),30000)});await Promise.race([K.handle(J),z5]);let h=Number(T.hrtime.bigint()-M)/1e6;q.push({name:D,ms:h})}catch(x){let z5=Number(T.hrtime.bigint()-M)/1e6;if(q.push({name:D,ms:z5}),A.debug(`[middleware] Blocked by: ${D}`),x instanceof Response){try{let{_requestId:s,_startNs:K5}=J,T5=K5!=null?Number(T.hrtime.bigint()-K5)/1e6:null,o=T5!=null?[`total;dur=${T5.toFixed(1)}`]:[];for(let M5 of q){let F8=M5.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);o.push(`mw_${F8};dur=${M5.ms.toFixed(1)}`)}if(o.length>0)x.headers.set("Server-Timing",o.join(", "));if(s)x.headers.set("X-Request-ID",s)}catch{}return await B8(J,x)}let h=x instanceof Error?x:Error(String(x)),Q5="statusCode"in h||"status"in h?await j5(h,J):await(()=>{return A.error(`[Router] Middleware '${D}' threw an unexpected error:`,h),l(h,J,{status:500})})();try{let{_requestId:s,_startNs:K5}=J,T5=K5!=null?Number(T.hrtime.bigint()-K5)/1e6:null,o=T5!=null?[`total;dur=${T5.toFixed(1)}`]:[];for(let M5 of q){let F8=M5.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);o.push(`mw_${F8};dur=${M5.ms.toFixed(1)}`)}if(o.length>0)Q5.headers.set("Server-Timing",o.join(", "));if(s)Q5.headers.set("X-Request-ID",s)}catch{}return await B8(J,Q5)}finally{clearTimeout(E)}}let O=await W(J);if(l5(),O){if(Y.method==="GET"||Y.method==="HEAD"||Y.method==="OPTIONS")try{let{seedCsrfCookieIfMissing:K}=await import(i("app/Middleware/Csrf.ts"));O=K(J,O)}catch(K){A.warn("[router] CSRF cookie seeding failed",{error:K})}}if(O)O=await B8(J,O);let{_requestId:G5,_startNs:f5}=J,g5=f5!=null?Number(T.hrtime.bigint()-f5)/1e6:null,L8=(D)=>{if(G5)D.set("X-Request-ID",G5);if(g5!=null){let K=[`total;dur=${g5.toFixed(1)}`];for(let M of q){let E=M.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);K.push(`mw_${E};dur=${M.ms.toFixed(1)}`)}D.set("Server-Timing",K.join(", "))}W$(D)};if(O&&typeof O.headers?.set==="function"){if(O.status>=400&&(O.headers.get("content-type")||"").includes("json")&&G5)try{let K=await O.clone().text(),M=JSON.parse(K);if(M&&typeof M==="object"){let E=new Headers(O.headers);return L8(E),new Response(JSON.stringify({...M,request_id:G5}),{status:O.status,statusText:O.statusText,headers:E})}}catch{}try{L8(O.headers)}catch{try{let K=O.clone(),M=new Headers(O.headers);return L8(M),new Response(K.body,{status:O.status,statusText:O.statusText,headers:M})}catch{}}}if(J._compress===!0&&O)try{let{applyCompression:D}=await import(i("app/Middleware/Compress.ts"));return await D(J,O)}catch(D){A.warn(`[router] Compression failed; sending uncompressed response: ${D instanceof Error?D.message:String(D)}`)}return O})}}function X5($){if(!J5.has($))J5.set($,[]);let Z=$.includes(":")?$.substring($.indexOf(":")+1):$,W={middleware(X){let Y=J5.get($);if(Y)Y.push(X);return W},name(X){return v5.set(X,g1(Z)),W},skipCsrf(){return t8.add($),a8.delete($),W},requireCsrf(){return a8.add($),t8.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=f1(Y);return A$.set($,{max:Math.floor(X),windowSeconds:J}),W}};return W}async function s8($){try{return await Bun.file($).exists()}catch{return!1}}function s1($){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 L$($){let Z=H$.get($);if(!Z)Z=import($),H$.set($,Z);return Z}function N$($){let Z=o8.get($);if(!Z)Z=o1($),o8.set($,Z),Z.catch(()=>o8.delete($));return Z}async function o1($){s1($);let Z=$;if(Z=Z.endsWith(".ts")?Z.slice(0,-3):Z,Z.includes("Controller")){let[X,Y="index"]=Z.split("@"),J=w.appPath(`${X}.ts`),G=i(`app/${X}.ts`),z=await s8(J)?J:G;try{let Q=await L$(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 r8(j,U)}}catch(Q){throw A.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=w.storagePath(`framework/actions/src/${Z}.ts`);else if(Z.includes("Actions")){let X=w.projectPath(`app/${Z}.ts`),Y=i(`app/${Z}.ts`);W=await s8(X)?X:Y}else{let X=w.appPath(`${Z}.ts`),Y=i(`app/${Z}.ts`);W=await s8(X)?X:Y}try{let Y=(await L$(W)).default;if(!Y)throw Error(`Action '${$}' has no default export`);if(typeof Y.handle!=="function")throw A.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;$9.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 t1(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 r8(Q,z)}catch(Q){throw F$(Q,{label:`[Router] action.handle() for '${$}'`}),Q}}}catch(X){throw A.error(`[Router] Failed to import action '${W}':`,X),X}}async function t1($,Z){let W={},X=await a1($,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 a1($,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 r8($,Z){if($ instanceof Response)return $;if($ instanceof ReadableStream)return new Response($,{headers:{"Content-Type":"application/octet-stream"}});let X=Z._forceJson===!0||a(Z);if($===null||$===void 0)return X?new Response(null,{status:204}):new Response("",{status:200});if(typeof $==="object"){let Y=r1($);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 r1($){if(!v1($)&&!y1($)&&!k1($))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 e1($,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 b($){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 C$($){w1($,$.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($,$6),$}function Z6($,Z=!1){if(typeof $==="string"){let X=$;return async(Y)=>{try{if(!Z)await x$(Y),Y=C$(Y);return await(await N$(X))(Y)}catch(J){F$(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 r8(Y,X)}}async function x$($){if($._bodyParsed)return;$._bodyParsed=!0;let Z=$.headers.get("content-type")||"";try{if(m5.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;A.debug("[stacks-router] Body parsing failed:",W)}}function E$($={}){let Z=new P1({verbose:$.verbose??!1}),W="",X=[],Y=!1;function J(z,Q,B){let U=W+Q,j=`${z}:${U}`;if(A.debug(`[router] ${z} ${U} \u2192 ${typeof B==="string"?B:"function"}`),X.length>0)J5.set(j,[...X]);if(Y)K$.add(j);if(typeof B==="string")Z9.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,W5(U,Q)),X5(U)},post(z,Q){let{fullPath:B,routeKey:U}=J("POST",z,Q);return Z.post(B,W5(U,Q)),X5(U)},put(z,Q){let{fullPath:B,routeKey:U}=J("PUT",z,Q);return Z.put(B,W5(U,Q)),X5(U)},patch(z,Q){let{fullPath:B,routeKey:U}=J("PATCH",z,Q);return Z.patch(B,W5(U,Q)),X5(U)},delete(z,Q){let{fullPath:B,routeKey:U}=J("DELETE",z,Q);return Z.delete(B,W5(U,Q)),X5(U)},options(z,Q){let{fullPath:B,routeKey:U}=J("OPTIONS",z,Q);return Z.options(B,W5(U,Q)),X5(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;A.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$/,"");A.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){A.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=W5(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 X5(`${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,q)=>F.signal.addEventListener("abort",()=>q(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(!Q$(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 q=await I.readToBuffer(j),O=await I.mimeType(j).catch(()=>"application/octet-stream");return new Response(q,{status:200,headers:{"Content-Type":O,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(I){return A.error("[storage] signed-url fetch failed:",I),new Response("Internal Error",{status:500})}}),Z.get("/__openapi.json",async(z)=>{if(!Q$(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=c1(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){A.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(){A.debug("[router] Loading user routes from registry...");try{let{loadRoutes:B}=await Promise.resolve().then(() => (i8(),G$)),{appPath:U}=await import("@stacksjs/path"),j=(await import(U("Routes.ts"))).default;await B(j)}catch(B){throw A.error("Failed to load route registry:",B),B}A.debug("[router] Loading ORM routes...");let z=[w.frameworkPath("orm/routes.ts"),w.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){A.warn(`[router] ORM routes candidate failed to load, falling back to next: ${B}
|
|
50
|
+
`,U)}if(!Q)A.warn("[router] No ORM routes candidate loaded \u2014 model useApi endpoints are unavailable.");A.debug("[router] Loading discovered package routes...");try{await G.loadDiscoveredRoutes()}catch(B){A.debug("Package route discovery skipped:",B)}await S$()},async loadDiscoveredRoutes(){try{let z=w.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=w.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 q of I){A.debug(`[router] Discovered route: ${H} \u2192 ${q}`);let O=q.startsWith("/")?q:`${f}/${q}`,G5=L?.routePrefix,f5=L?.routeMiddleware;try{await G.register(O,{prefix:G5,middleware:f5})}catch(g5){A.warn(`Failed to load routes from package '${H}': ${g5}`)}}}}catch{}}};return G}async function W6($,Z){if(!U8)A.debug("[router] Loading routes for first time..."),U8=D5.importRoutes().catch((X)=>{throw U8=null,X});await U8;let W=await D5.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 X6($={}){return D5.serve($)}var P5,t8,a8,A$,V$=5000,$9,Z9,B$,v5,I$=10,U$,Y5,k5=null,u1,j$,J5,K$,H$,o8,$6,D5,U8=null;var O5=u(()=>{N5();p5();n5();n8();X$();t8=new Set,a8=new Set,A$=new Map;$9=new e8(V$),Z9=new e8(V$),B$=new Set(["POST","PUT","PATCH","DELETE"]),v5=new Map;U$=new Set;Y5=new Map;u1=/[-_\s]+/,j$=new Map;J5=new Map,K$=new Set;H$=new Map;o8=new Map;$6={get($,Z){let X=b(this)[$];return X!==void 0?X:Z},input($,Z){let X=b(this)[$];return X!==void 0?X:Z},all(){return b(this)},only($){let Z=b(this),W={};for(let X of $)if(X in Z)W[X]=Z[X];return W},except($){let W={...b(this)};for(let X of $)delete W[X];return W},has($){let Z=b(this);if(Array.isArray($))return $.every((W)=>(W in Z)&&Z[W]!==void 0);return $ in Z&&Z[$]!==void 0},hasAny($){let Z=b(this);return $.some((W)=>(W in Z)&&Z[W]!==void 0)},filled($){let Z=b(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=b(this);if(Array.isArray($))return $.every((W)=>!(W in Z)||Z[W]===void 0);return!($ in Z)||Z[$]===void 0},string($,Z=""){let X=b(this)[$];return X!==void 0&&X!==null?String(X):Z},integer($,Z=0){let X=b(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=b(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=b(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=b(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 Q8(X):null},getFiles($){let W=(this.files||{})[$];if(!W)return[];return(Array.isArray(W)?W:[W]).map((Y)=>new Q8(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 Q8(Y));else Z[W]=new Q8(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)}};D5=E$()});O5();N5();i8();n5();O5();p5();n8();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 Y6=/[\u0000-\u001F\u007F]/;function R$($,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(Y6.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 J6($,Z={}){try{return R$($,Z)}catch{return null}}O5();O5();import{timingSafeEqual as G6}from"crypto";import{Buffer as q$}from"buffer";import j8 from"process";var Y9="signature",X9="expires";function w$(){let $=j8.env.APP_KEY||j8.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 P$($,Z){return new Bun.CryptoHasher("sha256",Z).update($).digest("hex")}function z6($,Z){let W=q$.from($.toLowerCase(),"hex"),X=q$.from(Z.toLowerCase(),"hex");if(W.length!==X.length)return!1;return G6(W,X)}function Q6($){let Z=new URL($.toString());return Z.searchParams.delete(Y9),Z}function k$($){let Z=Q6($);return Z.searchParams.sort(),Z.toString()}function v$($,Z={}){let W=w$(),X=$.startsWith("http")?new URL($):new URL($.startsWith("/")?$:`/${$}`,j8.env.APP_URL||"https://localhost");if(Z.ttl!==void 0&&Z.expiresAt!==void 0)B6("dual-expiry","[router] signUrl: both `ttl` and `expiresAt` provided \u2014 using `ttl`.");if(Z.ttl!==void 0)X.searchParams.set(X9,String(Math.floor(Date.now()/1000)+Z.ttl));else if(Z.expiresAt!==void 0)X.searchParams.set(X9,String(Math.floor(Z.expiresAt)));let Y=k$(X);return X.searchParams.set(Y9,P$(Y,W)),X.toString()}var b$=new Set;function B6($,Z){if(b$.has($))return;b$.add($),console.warn(Z)}function U6($,Z={},W={}){return v$(W9($,Z),W)}function y$($){let Z=typeof $==="string"?new URL($,j8.env.APP_URL||"https://localhost"):$,W=Z.searchParams.get(Y9);if(!W)return{valid:!1,reason:"missing-signature"};let X=Z.searchParams.get(X9);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=P$(k$(Z),w$());return z6(W,Y)?{valid:!0}:{valid:!1,reason:"invalid-signature"}}catch{return{valid:!1,reason:"invalid-signature"}}}async function j6($){let Z=y$($.url);if(Z.valid)return;let W=Z.reason==="expired"?410:401;throw Response.json({error:Z.reason},{status:W})}import{decrypt as H6,encrypt as L6}from"@stacksjs/security";class H8{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 L6(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 H6(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 y5 from"process";import{createSessionStore as F6}from"@stacksjs/bun-router";import{DatabaseSessionStore as _6,FileSessionStore as I6,MemorySessionStore as D6,RedisSessionStore as O6,createSessionStore as K6}from"@stacksjs/bun-router";function A6($){let Z=F6($);if(!V6($.encrypt))return Z;let X=$.appKey??y5.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 H8(Z,{appKey:X})}function V6($){if($===!0)return!0;if($===!1)return!1;return(y5.env.APP_ENV??y5.env.NODE_ENV??"").toLowerCase()==="production"}import("@stacksjs/database").then(({setQueryTracker:$})=>{if(typeof $==="function"){let{trackQuery:Z}=(n5(),p$(_9));$(Z)}}).catch(()=>{});export{i$ as withTraceId,j6 as verifySignedUrlMiddleware,y$ as verifySignedUrl,W9 as url,L9 as trackQuery,e1 as stream,U6 as signedUrl,v$ as signUrl,t$ as setCurrentRequest,W6 as serverResponse,X6 as serve,R$ as sanitizePathParam,J6 as safePathParam,_8 as runWithRequest,m1 as routeParams,D5 as route,a$ as request,D1 as rateLimitStatus,l8 as rateLimit,J$ as loadRoutes,_$ as listRegisteredRoutes,a as isApiRequest,i1 as installMiddlewareHotReload,n$ as getTraceId,F9 as getQueryShapeCounts,t as getCurrentRequest,M$ as findUnresolvableRouteMiddleware,A9 as createValidationErrorResponse,A6 as createStacksSessionStore,E$ as createStacksRouter,K6 as createSessionStore,V9 as createNotFoundResponse,j5 as createMiddlewareErrorResponse,l as createErrorResponse,l5 as clearTrackedQueries,O1 as clearRateLimit,O$ as clearMiddlewareCache,o$ as cacheRequestQuery,S$ as assertRouteMiddlewareResolvable,O6 as RedisSessionStore,g as PathParamError,h5 as Middleware,D6 as MemorySessionStore,m5 as JSON_CONTENT_TYPE,I6 as FileSessionStore,H8 as EncryptedSessionStore,_6 as DatabaseSessionStore};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/router",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.70.
|
|
4
|
+
"version": "0.70.62",
|
|
5
5
|
"description": "The Stacks framework router.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -56,15 +56,15 @@
|
|
|
56
56
|
"@stacksjs/bun-router": "0.0.17"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@stacksjs/actions": "0.70.
|
|
60
|
-
"@stacksjs/config": "0.70.
|
|
59
|
+
"@stacksjs/actions": "0.70.62",
|
|
60
|
+
"@stacksjs/config": "0.70.62",
|
|
61
61
|
"better-dx": "^0.2.12",
|
|
62
|
-
"@stacksjs/error-handling": "0.70.
|
|
63
|
-
"@stacksjs/logging": "0.70.
|
|
64
|
-
"@stacksjs/orm": "0.70.
|
|
65
|
-
"@stacksjs/path": "0.70.
|
|
66
|
-
"@stacksjs/storage": "0.70.
|
|
67
|
-
"@stacksjs/types": "0.70.
|
|
68
|
-
"@stacksjs/validation": "0.70.
|
|
62
|
+
"@stacksjs/error-handling": "0.70.62",
|
|
63
|
+
"@stacksjs/logging": "0.70.62",
|
|
64
|
+
"@stacksjs/orm": "0.70.62",
|
|
65
|
+
"@stacksjs/path": "0.70.62",
|
|
66
|
+
"@stacksjs/storage": "0.70.62",
|
|
67
|
+
"@stacksjs/types": "0.70.62",
|
|
68
|
+
"@stacksjs/validation": "0.70.62"
|
|
69
69
|
}
|
|
70
70
|
}
|