@stacksjs/router 0.70.84 → 0.70.85
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 +7 -46
- package/package.json +11 -10
package/dist/index.js
CHANGED
|
@@ -1,53 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var{defineProperty:
|
|
3
|
-
${
|
|
4
|
-
Hint: load related rows with .with('relation') or eager-load via includes() before iterating.`)}).catch(()=>{})}function
|
|
5
|
-
`).slice(0,10),
|
|
2
|
+
var{defineProperty:K,getOwnPropertyNames:R,getOwnPropertyDescriptor:k}=Object,g=Object.prototype.hasOwnProperty;function h($){return this[$]}var E=($)=>{var F=(Y??=new WeakMap).get($),W;if(F)return F;if(F=K({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var V of R($))if(!g.call(F,V))K(F,V,{get:h.bind($,V),enumerable:!(W=k($,V))||W.enumerable})}return Y.set($,F),F},Y;var l=($)=>$;function q($,F){this[$]=l.bind(null,F)}var d=($,F)=>{for(var W in F)K($,W,{get:F[W],enumerable:!0,configurable:!0,set:q.bind(F,W)})};var f=($,F)=>()=>($&&(F=$($=0)),F);var D=import.meta.require;function z($){let F=$.headers,W=F.get("content-type")||"";if(i.test(W))return!0;if(F.get("sec-fetch-dest")==="document")return!1;if((F.get("accept")||"").includes("text/html"))return!1;return!0}var i;var b=f(()=>{i=/^application\/(?:json|.+\+json)(?:;|$)/i});import c from"process";import{AsyncLocalStorage as U}from"async_hooks";import{log as v0}from"@stacksjs/logging";function I(){return n.getStore()}var p,n,u,w0,x0;var H=f(()=>{p=Symbol.for("stacks.router.requestStorage"),n=globalThis[p]??=new U,u=Symbol.for("stacks.router.traceStorage"),w0=globalThis[u]??=new U;x0=new Proxy({},{get($,F){let W=I();if(!W){if(c.env.NODE_ENV!=="production")console.warn(`[RequestContext] Accessing request.${String(F)} outside of request context`);if(F==="bearerToken")return()=>null;if(F==="user"||F==="userToken")return async()=>{return};if(F==="tokenCan"||F==="tokenCant")return async()=>!1;if(F==="headers")return new Headers;if(F==="url")return"";if(F==="method")return"GET";return}let V=W[F];if(typeof V==="function")return V.bind(W);return V}})});var Q={};d(Q,{trackQuery:()=>e,getQueryShapeCounts:()=>$0,createValidationErrorResponse:()=>O0,createNotFoundResponse:()=>L0,createMiddlewareErrorResponse:()=>N0,createErrorResponse:()=>J,clearTrackedQueries:()=>F0});import N from"process";import{log as o}from"@stacksjs/logging";import{createErrorHandler as a,renderProductionErrorPage as A}from"@stacksjs/error-handling";function P($){let F={error:$.error,message:$.message,status:$.status,timestamp:new Date().toISOString()};if($.details)F.details=$.details;return JSON.stringify(F)}function M(){let $=(N.env.APP_ENV??"").toLowerCase();if($==="development")return!0;if(!$&&N.env.NODE_ENV==="development")return!0;return!1}function O(){return{"Content-Type":"application/json"}}function s(){return O()}function v(){return{buffer:Array(X).fill(null),writeIndex:0,count:0,shapeCounts:new Map,n1Warned:new Set}}function m(){let $=I();if(!$)return S;let F=$[w];if(!F)F=v(),$[w]=F;return F}function r($){return $.replace(/'(?:[^']|'')*'/g,"?").replace(/"(?:[^"]|"")*"/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/IN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toUpperCase()}function e($,F,W){let V=m();if(V.buffer[V.writeIndex]={query:$,time:F,connection:W},V.writeIndex=(V.writeIndex+1)%X,V.count<X)V.count++;if(!M())return;let G=r($);if(G.startsWith("INSERT INTO QUERY_LOGS")||G.startsWith("EXPLAIN"))return;let Z=(V.shapeCounts.get(G)??0)+1;if(V.shapeCounts.set(G,Z),Z===t+1&&!V.n1Warned.has(G))V.n1Warned.add(G),import("@stacksjs/logging").then(({log:B})=>{B.warn(`[orm] Possible N+1 \u2014 query shape ran ${Z}\xD7 in this request:
|
|
3
|
+
${G}
|
|
4
|
+
Hint: load related rows with .with('relation') or eager-load via includes() before iterating.`)}).catch(()=>{})}function C(){let $=m();if($.count===0)return[];let F=[],W=$.count<X?0:$.writeIndex;for(let V=0;V<$.count;V++){let G=$.buffer[(W+V)%X];if(G)F.push(G)}return F}function $0(){return new Map(m().shapeCounts)}function F0(){let $=I();if($&&$[w]){$[w]=v();return}S=v()}function V0(){return{appName:"Stacks",theme:"auto",showEnvironment:!0,showQueries:!0,showRequest:!0,enableCopyMarkdown:!0,snippetLines:8,basePaths:[N.cwd()]}}function x($,F=0,W=new WeakSet){if(!$||typeof $!=="object"||F>=Z0)return $;if(W.has($))return G0;if(W.add($),Array.isArray($))return $.map((G)=>x(G,F+1,W));let V={};for(let[G,Z]of Object.entries($)){let B=G.toLowerCase();if(W0.some((L)=>B.includes(L)))V[G]="********";else if(typeof Z==="object"&&Z!==null)V[G]=x(Z,F+1,W);else V[G]=Z}return V}function B0($){let F=$;if(F.jsonBody)return x(F.jsonBody);if(F.formBody)return x(F.formBody);return}async function j0($){let W=$._authenticatedUser;if(W)return{id:W.id,email:W.email,name:W.name||W.username};return}async function J($,F,W){let V=W?.status||500;if(o.debug(`[error] ${V} ${$.message}`),!M()){if(z(F)){let Z=V>=400&&V<500,B=$.details;return new Response(P({error:Z?$.name||"Client Error":"Internal Server Error",message:Z?$.message:"An unexpected error occurred.",status:V,details:Z&&B&&typeof B==="object"?B:void 0}),{status:V,headers:O()})}return new Response(A(V),{status:V,headers:{"Content-Type":"text/html; charset=utf-8"}})}try{let Z=a(V0());Z.setFramework("Stacks","0.70.0");let B=B0(F);if(B){let j=new URL(F.url);Z.setRequest({method:F.method,url:F.url,headers:Object.fromEntries(F.headers.entries()),queryParams:Object.fromEntries(j.searchParams.entries()),body:B})}else Z.setRequest(F);let L=await j0(F);if(L)Z.setUser(L);if(W?.routingContext)Z.setRouting(W.routingContext);else if(W?.handlerPath)Z.setRouting({controller:W.handlerPath});for(let j of C())Z.addQuery(j.query,j.time,j.connection);if(z(F)){let j={handler:W?.handlerPath};if(M())j.stack=$.stack?.split(`
|
|
5
|
+
`).slice(0,10),j.queries=C().slice(-10);return new Response(P({error:$.name||"Error",message:$.message,status:V,details:j}),{status:V,headers:s()})}let T=N.env.APP_URL?N.env.APP_URL.startsWith("http")?N.env.APP_URL:`https://${N.env.APP_URL}`:M()?"*":F.headers.get("origin")??"null",y=await Z.render($,V);return new Response(y,{status:V,headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":T}})}catch(Z){console.error("[Error Handler] Failed to render error page:",Z);let B=(L)=>L.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return new Response(`
|
|
6
6
|
<html>
|
|
7
7
|
<head><title>Error</title></head>
|
|
8
8
|
<body>
|
|
9
9
|
<h1>Error</h1>
|
|
10
|
-
<p>${
|
|
11
|
-
<pre>${
|
|
10
|
+
<p>${B($.message)}</p>
|
|
11
|
+
<pre>${B($.stack||"")}</pre>
|
|
12
12
|
</body>
|
|
13
13
|
</html>
|
|
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 J=$.headers?{...$.headers,...e()}:e();return new Response(U5({error:$.name||"ClientError",message:$.message,status:W}),{status:W,headers:J})}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 I9($,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(H9(404),{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}var x5=50,zZ=5,d5,L9,BZ,UZ=10,jZ="[Circular]";var n5=u(()=>{p5();N5();d5=Symbol.for("stacks.queryTracking"),L9=c5();BZ=["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 D9,statSync as O9}from"fs";import{join as FZ,relative as VZ,resolve as K9}from"path";import e5 from"process";import{Buffer as m}from"buffer";import{createCipheriv as AZ,createDecipheriv as IZ,randomBytes as O8}from"crypto";import{closeSync as K8,createReadStream as M9,createWriteStream as _Z,existsSync as i5,fsyncSync as T9,openSync as S9,writeFileSync as DZ}from"fs";import{access as OZ,constants as N9,mkdir as KZ,readdir as s5,rename as x9,stat as H5,unlink as o5,writeFile as M8}from"fs/promises";import{isAbsolute as MZ,join as L5,resolve as TZ}from"path";import A from"process";import{pipeline as SZ}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 NZ}from"fs";import{existsSync as E8,mkdirSync as xZ,readdirSync as CZ,readFileSync as EZ,writeFileSync as RZ}from"fs";import{homedir as V5}from"os";import{dirname as E9,resolve as R}from"path";import $5 from"process";import{existsSync as qZ,readdirSync as bZ}from"fs";import{extname as S8,resolve as R9}from"path";import wZ from"process";function vZ($,Z){this[$]=kZ.bind(null,Z)}class f8{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 J=this.generateKey($,W),Y=X??this.options.ttl,z=this.estimateSize(Z);this.cache.set(J,{value:Z,timestamp:new Date,ttl:Y,hits:0,size:z}),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(!D9($))return!0;return O9($).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 J=D9(W)?O9(W):null,Y=J?J.mtime:new Date;this.set($,{value:Z,fileTimestamp:Y},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,J)=>X+J.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 g8{metrics=[];maxMetrics=1000;async track($,Z,W={}){let X=performance.now(),J=new Date;try{let Y=await Z(),z=performance.now()-X;return this.recordMetric({operation:$,duration:z,timestamp:J,...W}),Y}catch(Y){let z=performance.now()-X;throw this.recordMetric({operation:`${$}:error`,duration:z,timestamp:J,...W}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let W=Z.map((J)=>J.duration),X=W.reduce((J,Y)=>J+Y,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 gZ($,Z={}){let X=Object.keys(Z).sort().map((J)=>`${J}:${Z[J]}`).join("|");return X?`${$}:${X}`:$}function hZ($,Z){try{return JSON.stringify($)===JSON.stringify(Z)}catch{return $===Z}}function mZ($){return $.getStats().size*2}function pZ($,Z={}){let W=e5.cwd();while(W.includes("storage"))W=K9(W,"..");let X=K9(W,$||"");if(Z?.relative)return VZ(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 cZ(){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 f9{async format($){let Z=await cZ(),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 f9,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 J=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=J,this.keys.set(J,Y),this.encryptionKeys.set(J,{key:Y,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 J,Y=0,z=3,G=1000;while(Y<z)try{try{try{await OZ(this.config.logDirectory,N9.F_OK|N9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await KZ(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 M8(this.currentLogFile,"",{mode:420});if(J=S9(this.currentLogFile,"a",420),DZ(J,Q,{flag:"a"}),T9(J),J!==void 0)K8(J),J=void 0;if((await H5(this.currentLogFile)).size===0){if(await M8(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(Y<z-1){let j=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${z}:`,j);let H=G*2**Y;await new Promise((L)=>setTimeout(L,H)),Y++;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(J!==void 0)try{K8(J)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(Y===z-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}Y++;let B=G*2**(Y-1);await new Promise((U)=>setTimeout(U,B))}})();this.pendingOperations.push(W);let X=this.pendingOperations.length-1;try{await W}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,W=this.generateKeyId(),X=this.generateKey();this.currentKeyId=W,this.keys.set(W,X),this.encryptionKeys.set(W,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,G],[,Q])=>Q.createdAt.getTime()-G.createdAt.getTime()),Y=typeof Z.maxKeys==="number"?Z.maxKeys:1,z=Math.max(1,Y);if(J.length>z)for(let[G]of J.slice(z))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return O8(16).toString("hex")}generateKey(){return O8(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=O8(16),X=AZ("aes-256-gcm",Z,W),J=m.isBuffer($)?$:m.from($,"utf8"),Y=X.update(J),z=X.final(),G=Y.length+z.length,Q=X.getAuthTag(),B=m.allocUnsafe(16+G+16);return W.copy(B,0),Y.copy(B,16),z.copy(B,16+Y.length),Q.copy(B,16+G),{encrypted:B,iv:W}}async compressData($){return new Promise((Z,W)=>{let X=C9(),J=[];X.on("data",(Y)=>J.push(Y)),X.on("end",()=>Z(m.from(m.concat(J)))),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 J=await s5(this.config.logDirectory),Y=J.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}),z=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${W}.${z}`;if(await H5(W).catch(()=>null))try{if(await x9(W,G),Z.compress)try{let Q=`${G}.gz`;await this.compressLogFile(G,Q),await o5(G)}catch(Q){console.error("Error compressing rotated file:",Q)}if(Y.length===0&&!J.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${W}.1`;await M8(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 J=new Date().toISOString().replace(/[:.]/g,"-"),Y=W.replace(/\.log$/,`-${J}.log`);if(await H5(W).catch(()=>null))await x9(W,Y)}if(this.currentLogFile=X,Z.maxFiles){let Y=(await s5(this.config.logDirectory)).filter((z)=>z.startsWith(this.name)).sort((z,G)=>G.localeCompare(z));for(let z of Y.slice(Z.maxFiles))await o5(L5(this.config.logDirectory,z))}}}async compressLogFile($,Z){let W=M9($),X=_Z(Z),J=C9();await SZ(W,J,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 $=S9(this.currentLogFile,"r+");T9($),K8($)}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()?I.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())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:J,level:Y,showTimestamp:z=!0}=$,G=(L)=>L.replace(this.ANSI_PATTERN,"");if(!this.fancy){let L=[];if(z)L.push(Z);if(Y==="warning")L.push("WARN");else if(Y==="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(J),L.join(" ")}let Q=A.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${W} ${J}`;else if(Y==="info"||Y==="success")B=`${W} ${X} ${J}`;else B=`${W} ${X} ${I.cyan(J)}`;if(!z)return B.trim();let U=G(B).trim().length,j=G(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,(Y,z)=>{let G=Number.parseInt(z,10);return G<Z[0].length?String(Z[0][G]):Y});let W=/%([sdijfo%])/g,X=0,J=$.replace(W,(Y,z)=>{if(z==="%")return"%";if(X>=Z.length)return Y;let G=Z[X++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return Y}});if(X<Z.length)J+=` ${Z.slice(X).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(W,X,J)=>{let Y=I.underline(I.blue(X)),z=this.toAbsoluteFilePath(J);if(z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(z)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${G}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),Z=Z.replace(/`([^`]+)`/g,(W,X)=>I.bgGray(X)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(W,X)=>I.bold(X)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(W,X)=>I.italic(X)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(W,X)=>I.italic(X)),Z=Z.replace(/~([^~]+)~/g,(W,X)=>I.strikethrough(X)),Z}supportsHyperlinks(){if(S())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(MZ(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=TZ(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,J=this.formatConsoleTimestamp(X),Y=this.formatFileTimestamp(X),z,G;if(Z instanceof Error)z=Z.message,G=Z.stack;else z=this.formatMessage(Z,W);let{consoleText:Q,fileText:B}=this.buildOutputTexts(z);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":g9[$],H=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",L;switch($){case"debug":L=this.formatConsoleMessage({timestamp:J,icon:j,tag:H,message:I.gray(Q),level:$}),console.error(L);break;case"info":L=this.formatConsoleMessage({timestamp:J,icon:j,tag:H,message:Q,level:$}),console.warn(L);break;case"success":L=this.formatConsoleMessage({timestamp:J,icon:j,tag:H,message:I.green(Q),level:$}),console.error(L);break;case"warning":L=this.formatConsoleMessage({timestamp:J,icon:j,tag:H,message:Q,level:$}),console.warn(L);break;case"error":if(L=this.formatConsoleMessage({timestamp:J,icon:j,tag:H,message:Q,level:$}),console.error(L),G){let F=G.split(`
|
|
15
|
-
`);for(let _ of F)if(_.trim()&&!_.includes(z))console.error(this.formatConsoleMessage({timestamp:J,message:I.gray(` ${_}`),level:$,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${z}`),G)console.error(G)}let U=`${Y} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
16
|
-
`;if(G)U+=`${G}
|
|
17
|
-
`;if(U=U.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(U)}progress($,Z=""){let W={update:(G,Q)=>{},finish:(G)=>{},interrupt:(G,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()&&A.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!S()&&A.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,Q="info")=>{if(!S()&&A.stdout.isTTY)A.stdout.write(`
|
|
18
|
-
`);if(this[Q==="warning"?"warn":Q](G),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&A.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":I.blue("\u25D0"),tag:W,message:`${I.cyan($)}...`}))}return async(W)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-Z),Y=`${$} completed in ${J}ms`,z=new Date,G=this.formatConsoleTimestamp(z),B=`${this.formatFileTimestamp(z)} ${this.environment}.INFO: ${Y}`;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?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":I.green("\u2713"),tag:U,message:`${Y}${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 M9(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"),J=X.subarray(0,16),Y=X.subarray(X.length-16),z=X.subarray(16,X.length-16),G=IZ("aes-256-gcm",W,J);G.setAuthTag(Y);let Q=G.update(z),B=G.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:J,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let G=J.split(`
|
|
20
|
-
`),Q=Math.max(...G.map((H)=>H.length))+2,B=`\u250C${"\u2500".repeat(Q)}\u2510`,U=`\u2514${"\u2500".repeat(Q)}\u2518`,j=G.map((H)=>{return this.formatConsoleMessage({timestamp:W,message:I.cyan(H),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:W,message:I.cyan(B),showTimestamp:!1})),j.forEach((H)=>console.error(H)),console.error(this.formatConsoleMessage({timestamp:W,message:I.cyan(U),showTimestamp:!1}))}else if(!S())console.error(`${X} ${this.environment}.INFO: [BOX] ${Y}`);let z=`${X} ${this.environment}.INFO: [BOX] ${Y}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}async prompt($){if(S())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${I.cyan("?")} ${$} (y/n) `);let W=(X)=>{let J=X.toString().trim().toLowerCase();A.stdin.removeListener("data",W);try{if(typeof A.stdin.setRawMode==="function")A.stdin.setRawMode(!1)}catch{}A.stdin.pause(),console.error(""),Z(J==="y"||J==="yes")};try{if(typeof A.stdin.setRawMode==="function")A.stdin.setRawMode(!0)}catch{}A.stdin.resume(),A.stdin.once("data",W)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let W=$;if(Z&&Z.length>0){let Q=/%([sdijfo%])/g,B=0;if(W=$.replace(Q,(U,j)=>{if(j==="%")return"%";if(B>=Z.length)return U;let H=Z[B++];switch(j){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return U}}),B<Z.length)W+=` ${Z.slice(B).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}let{consoleText:X,fileText:J}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${I.blue("\u25D0")} `;console.error(`${B}${Q} ${I.cyan(X)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
|
|
22
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!A.stdout.isTTY)return;let W=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),X=Math.round($.barLength*W/100),J=$.barLength-X,Y=I.green("\u2501".repeat(X)),z=I.gray("\u2501".repeat(J)),G=`[${Y}${z}]`,Q=`${W}%`.padStart(4),B=$.message?` ${$.message}`:"",U=this.options.showIcons===!1?"":Z||W===100?I.green("\u2713"):I.blue("\u25B6"),j=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",H=`\r${U}${j} ${G} ${Q}${B}`,L=A.stdout.columns||80,F=" ".repeat(Math.max(0,L-H.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${H}${F}`,A.stdout.write($.lastRenderedLine),Z)A.stdout.write(`
|
|
23
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||S()||!A.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(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 Y=L5(this.config.logDirectory,X);if($.before)try{if((await H5(Y)).mtime>=$.before)continue}catch(z){console.error(`Failed to get stats for file ${Y}:`,z);continue}W.push(Y)}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(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function h9($,Z={}){let{maxRetries:W=3,retryDelay:X=1000,isRetryable:J=()=>!0,fallback:Y}=Z,z=Error("Unknown error occurred");for(let G=0;G<=W;G++)try{return await $()}catch(Q){if(z=Q instanceof Error?Q:Error(String(Q)),G===W||!J(z))break;if(X>0)await new Promise((B)=>setTimeout(B,X))}if(Y!==void 0)return Y;throw z instanceof Error?z:Error(`Unknown error: ${String(z)}`)}function m9($){return $ instanceof P}function Y1($){return $ instanceof $8}function z1($){if(m9($))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:J=!0,useBackwardCompatibility:Y=!0,customParsers:z={},verbose:G=!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:J,useBackwardCompatibility:Y,customParsers:z,verbose:G,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[J,Y]of Object.entries($)){let z=[...Z,J],G=z.map((U)=>this.formatEnvKey(U,X.useCamelCase)),Q=`${W}_${G.join("_")}`,B=X.useBackwardCompatibility?`${W}_${z.map((U)=>U.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,z,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{$[J]=this.parseEnvironmentValue(U,typeof Y,Q,X.customParsers,X.configName)}catch(j){if(j instanceof Z8)throw j;throw n.envVar(Q,U,typeof Y,X.configName)}}}}}parseEnvironmentValue($,Z,W,X,J){for(let[Y,z]of Object.entries(X))try{return z($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,Z))try{return Y.parse($)}catch{throw n.envVar(W,$,`${Z} (via ${Y.name} parser)`,J)}return $}getEnvironmentVariables($){let Z={},W=$.toUpperCase();for(let[X,J]of Object.entries(t5.env))if(X.startsWith(W)&&J!==void 0)Z[X]=J;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(J){X.push(`Cannot parse value "${Z}" as ${W}: ${J}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs($,Z,W={}){let{prefix:X,format:J="text"}=W,Y=X||this.generateEnvPrefix($),z=[];switch(this.extractEnvVarInfo(Z,[],Y,z),J){case"markdown":return this.formatAsMarkdown(z,$);case"json":return JSON.stringify(z,null,2);default:return this.formatAsText(z,$)}}extractEnvVarInfo($,Z,W,X){for(let[J,Y]of Object.entries($)){let z=[...Z,J],G=`${W}_${z.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,z,W,X);else X.push({key:G,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${z.join(".")}`,example:this.generateExample(Y)})}}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
|
-
|
|
25
|
-
`;for(let X of $)W+=`${X.key}
|
|
26
|
-
`,W+=` Type: ${X.type}
|
|
27
|
-
`,W+=` Description: ${X.description}
|
|
28
|
-
`,W+=` Example: ${X.example}
|
|
29
|
-
|
|
30
|
-
`;return W}formatAsMarkdown($,Z){let W=`# Environment Variables for ${Z}
|
|
31
|
-
|
|
32
|
-
`;W+=`| Variable | Type | Description | Example |
|
|
33
|
-
`,W+=`|----------|------|-------------|----------|
|
|
34
|
-
`;for(let X of $)W+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
|
|
35
|
-
`;return W}}function G1($,Z){let W=fZ("process");if(typeof W>"u"||!W.env)return Z;let X=W.env[$];return X!==void 0?X:Z}function c9($,Z,W={}){return d9($,Z,W,new WeakMap)}function d9($,Z,W,X){let{arrayMergeMode:J="replace",skipNullish:Y=!1,customMerger:z}=W;if(Z===null||Z===void 0)return Y?$:Z;if(z){let G=z($,Z);if(G!==void 0)return G}if(Array.isArray(Z)||Array.isArray($))return u9($,Z,J,X);if(!y(Z)||!y($))return Z;return j1($,Z,W,X)}function u9($,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 Q1($,Z);case"smart":return B1($,Z,X);default:return Z}return Z}function Q1($,Z){let W=[...Z];for(let X of $)if(!W.some((J)=>v8(J,X)))W.push(X);return W}function B1($,Z,W){if(Z.length===0)return $;if($.length===0)return Z;if(y(Z[0])&&y($[0]))return U1($,Z,W);if(Z.every((X)=>typeof X==="string")&&$.every((X)=>typeof X==="string")){let X=[...Z];for(let J of $)if(!X.includes(J))X.push(J);return X}return Z}function U1($,Z,W){let X=[...Z];for(let J of $){if(!y(J)){X.push(J);continue}let Y=["id","name","key","path","type"],z=!1;for(let G of Y)if(G in J){if(X.find((B)=>y(B)&&(G in B)&&B[G]===J[G])){z=!0;break}}if(!z)X.push(J)}return X}function j1($,Z,W,X){let J=Z;if(y(J)&&X.has(J))return X.get(J);let Y={...$};if(y(J))X.set(J,Y);for(let z in J){if(!Object.prototype.hasOwnProperty.call(J,z))continue;let G=J[z],Q=Y[z];if(W.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){Y[z]=G;continue}if(y(G)&&y(Q))Y[z]=d9(Q,G,W,X);else if(Array.isArray(G)||Array.isArray(Q))Y[z]=u9(Q,G,W.arrayMergeMode||"smart",X);else Y[z]=G}return Y}function h8($,Z,W="replace"){return c9($,Z,{arrayMergeMode:W==="replace"?"replace":"smart",skipNullish:!0})}function v8($,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(!v8($[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 J of W){if(!Object.prototype.hasOwnProperty.call(Z,J))return!1;if(!v8($[J],Z[J]))return!1}return!0}return!1}function y($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class J8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,W={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:Y,trackPerformance:z=!0,verbose:G=!1}=W;if(J){let B=A5.getWithFileCheck("file",$);if(B){if(G)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:h8(Z,j,X),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)A5.setWithFileCheck("file",f,$,Y);return f}catch(B){throw B instanceof Error?n.configLoad($,B):n.configLoad($,Error(String(B)))}};if(z)return b5.track("loadFromPath",Q,{path:$});return Q()}async tryLoadFromPaths($,Z,W={}){for(let X of $)try{let J=await this.loadFromPath(X,Z,W);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(W.verbose)console.warn(`Failed to load config from ${X}:`,J)}return null}generateConfigPaths($,Z,W){let X=this.generateNamePatterns($,W),J=[];for(let Y of X)for(let z of this.extensions)J.push(T8(Z,`${Y}${z}`));return J}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 Y of X){if(!Y)continue;if(W.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)W.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let J=new Set;return W.filter((Y)=>{if(!Y||J.has(Y))return!1;return J.add(Y),!0})}checkFileAccess($){return h9(async()=>{return a5($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,W){let X=[];if(!a5($))return X;if(Z||W){let J=this.generateNamePatterns(Z||"",W);for(let Y of J)for(let z of this.extensions){let G=T8($,`${Y}${z}`);if(await this.checkFileAccess(G))X.push(G)}}else try{let{readdirSync:J}=await import("fs"),Y=J($);for(let z of Y)if(this.looksLikeConfigFile(z)){let G=T8($,z);if(await this.checkFileAccess(G))X.push(G)}}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:J}=await import("fs"),Y=J($,"utf8");JSON.parse(Y)}catch(J){Z.push(`Invalid JSON syntax: ${J}`)}}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 J=await this.loadFromPath(X,{},Z);if(J)W.set(X,J.config)}catch(J){if(Z.verbose)console.warn(`Failed to preload ${X}:`,J)}})),W}}class p8{async validateConfiguration($,Z,W={}){let{stopOnFirstError:X=!1,validateRequired:J=!0,validateTypes:Y=!0,customRules:z=[],trackPerformance:G=!0,verbose:Q=!1}=W,B=async()=>{let U=[],j=[],H={stopOnFirstError:X,validateRequired:J,validateTypes:Y,customRules:z,trackPerformance:G,verbose:Q};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,H);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...z],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(G)return await b5.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,Z,W){try{if(!NZ(Z))throw new q5(Z,[{path:"",message:"Schema file does not exist"}]);let X=await import(Z),J=X.default||X;if(Array.isArray(J))return this.validateWithRules($,J,W);else return this.validateWithJSONSchema($,J,W)}catch(X){throw new q5(Z,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema($,Z,W){let X=[],J=[];return this.validateObjectAgainstSchema($,Z,"",X,J,W),{isValid:X.length===0,errors:X,warnings:J}}validateObjectAgainstSchema($,Z,W,X,J,Y){if(Y.validateTypes&&Z.type){let z=Array.isArray($)?"array":typeof $,G=Array.isArray(Z.type)?Z.type:[Z.type];if(!G.includes(z)){if(X.push({path:W,message:`Expected type ${G.join(" or ")}, got ${z}`,expected:G.join(" or "),actual:z,rule:"type"}),Y.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"}),Y.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 z=0;z<$.length;z++){let G=W?`${W}[${z}]`:`[${z}]`;if(this.validateObjectAgainstSchema($[z],Z.items,G,X,J,Y),Y.stopOnFirstError&&X.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let z=$;if(Y.validateRequired&&Z.required){for(let G of Z.required)if(!(G in z)){if(X.push({path:W?`${W}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(Z.properties){for(let[G,Q]of Object.entries(Z.properties))if(G in z){let B=W?`${W}.${G}`:G;if(this.validateObjectAgainstSchema(z[G],Q,B,X,J,Y),Y.stopOnFirstError&&X.length>0)return}}if(Z.additionalProperties===!1){let G=new Set(Object.keys(Z.properties||{}));for(let Q of Object.keys(z))if(!G.has(Q))J.push({path:W?`${W}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,W){let X=[],J=[];for(let Y of Z)try{let z=this.getValueByPath($,Y.path),G=this.validateWithRule(z,Y,Y.path);if(X.push(...G),W.stopOnFirstError&&X.length>0)break}catch(z){X.push({path:Y.path,message:`Rule validation failed: ${z}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:J}}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 J=Array.isArray($)?"array":typeof $;if(J!==Z.type)X.push({path:W,message:Z.message||`Expected type ${Z.type}, got ${J}`,expected:Z.type,actual:J,rule:"type"})}if(Z.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<Z.min)X.push({path:W,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:J,rule:"min"})}if(Z.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>Z.max)X.push({path:W,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:J,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))X.push({path: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 J=Z.validator($);if(J)X.push({path:W,message:Z.message||J,rule:"custom"})}return X}getValueByPath($,Z){if(!Z)return $;let W=Z.split("."),X=$;for(let J of W)if(X&&typeof X==="object"&&J in X)X=X[J];else return;return X}generateRulesFromInterface($){let Z=[],W=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of W){let[,J,Y,z]=X;Z.push({path:J,required:!Y,type:this.mapTypeScriptType(z)})}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:i9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function H1($){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 c8{fileLoader=new J8;envProcessor=new X8;validator=new p8;async loadConfig($){let Z=Date.now(),{cache:W,performance:X,schema:J,validate:Y,...z}=$;try{if(W?.enabled){let Q=this.checkCache(z.name||"",z);if(Q)return Q}let G;try{G=await this.loadConfigurationStrategies(z,!0,W)}catch(Q){let B=z.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;G={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`No configuration file found for "${z.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))G={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)G={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else G={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(J||Y)await this.validateConfiguration(G.config,J,Y,z.name);if(W?.enabled&&G)this.cacheResult(z.name||"",G,W,z);if(X?.enabled){let Q={operation:"loadConfig",duration:Date.now()-Z,configName:z.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 ${z.name}`);G.metrics=Q}return G}catch(G){let Q=Date.now()-Z;throw v.error(`Configuration loading failed after ${Q}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies($,Z=!1,W){let{name:X="",alias:J,cwd:Y,configDir:z,defaultConfig:G,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:U=!1}=$,j=Y||$5.cwd(),H=[],L=await this.loadLocalConfiguration(X,J,j,z,G,B,U,Q,W);if(L)return H.push(...this.getLocalSearchPaths(X,J,j,z)),this.finalizeResult(L,H,Q,X,U);let F=await this.loadHomeConfiguration(X,J,G,B,U,Q);if(F)return H.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(F,H,Q,X,U);let _=await this.loadPackageJsonConfiguration(X,J,j,G,B,U,Q);if(_)return H.push(R(j,"package.json")),this.finalizeResult(_,H,Q,X,U);if(H.push(...this.getAllSearchPaths(X,J,j,z)),Z)throw n.configNotFound(X,H,J);return{...await this.applyEnvironmentVariables(X,G,Q,U),warnings:[`No configuration file found for "${X}"${H1(J)}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,W,X,J,Y,z,G,Q){let B=G?C5($,J,z):J,U=this.getLocalDirectories(W,X);for(let j of U){if(z)v.info(`Searching for configuration in: ${j}`);let H=this.fileLoader.generateConfigPaths($,j,Z),L=await this.fileLoader.tryLoadFromPaths(H,B,{arrayStrategy:Y,verbose:z,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(L){if(z)v.success(`Configuration loaded from: ${L.source.path}`);return L}}return null}async loadHomeConfiguration($,Z,W,X,J,Y){if(!$)return null;let z=Y?C5($,W,J):W,G=[R(V5(),".config",$),R(V5(),".config"),V5()];for(let Q of G){if(J)v.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths($,Q,Z),U=await this.fileLoader.tryLoadFromPaths(B,z,{arrayStrategy:X,verbose:J});if(U){if(J)v.success(`Configuration loaded from home directory: ${U.source.path}`);return U}}return null}async loadPackageJsonConfiguration($,Z,W,X,J,Y,z){let G=z?C5($,X,Y):X;try{let Q=R(W,"package.json");if(!E8(Q))return null;let B={};try{B=JSON.parse(EZ(Q,"utf8"))}catch(H){if(Y)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(Y)v.success(`Configuration loaded from package.json: ${j}`);return{config:h8(G,U,J),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(Y)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,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,W,X){let J=[];if(W){let Y=W($);if(Y)J.push(...Y)}if(Z){let Y=await this.validator.validateConfiguration($,Z);if(!Y.isValid)J.push(...Y.errors.map((z)=>z.path?`${z.path}: ${z.message}`:z.message))}if(J.length>0)throw n.configValidation(X||"unknown",J,X)}checkCache($,Z){let W=this.generateCacheKey($,Z);return A5.get(W)||null}cacheResult($,Z,W,X){let J=this.generateCacheKey($,X);A5.set(J,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 J=[];return J.push(...this.getLocalSearchPaths($,Z,W,X)),J.push(...this.getHomeSearchPaths($,Z)),J.push(R(W,"package.json")),J}getLocalSearchPaths($,Z,W,X){let J=this.getLocalDirectories(W,X),Y=[];for(let z of J)Y.push(...this.fileLoader.generateConfigPaths($,z,Z));return Y}getHomeSearchPaths($,Z){if(!$)return[];let W=[R(V5(),".config",$),R(V5(),".config"),V5()],X=[];for(let J of W)X.push(...this.fileLoader.generateConfigPaths($,J,Z));return X}async loadConfigWithResult($){return this.loadConfig($)}}function v9($){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 L1($){return c.loadConfig({...$,__strictErrorHandling:!0})}async function o9($){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 J=X instanceof Error?X.name:"UnknownError",Y=X instanceof Error?X.message:String(X);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||Y.includes("config"))&&$.verbose)v.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let G=W?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await c.applyEnvironmentVariables(G.name||"",Z,!0,G.verbose||!1))?.config??Z;return Z}}async function F1($={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"&&v9(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"&&v9(Z)))return(await c.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw Z}}async function V1($,Z,W="replace"){let X=new J8;try{let J=await X.loadFromPath($,Z,{arrayStrategy:W,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function C5($,Z,W=!1){let X=new X8,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(z,G=[]){let Q={...z};for(let[B,U]of Object.entries(z)){let j=[...G,B],H=[`${J}_${j.join("_").toUpperCase()}`,`${J}_${j.map((_)=>_.toUpperCase()).join("")}`,`${J}_${j.map((_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],L,F;for(let _ of H)if(L=$5.env[_],L!==void 0){F=_;break}if(L!==void 0&&F)if(typeof U==="boolean")Q[B]=["true","1","yes"].includes(L.toLowerCase());else if(typeof U==="number"){let _=Number(L);if(!Number.isNaN(_))Q[B]=_}else if(Array.isArray(U))try{Q[B]=JSON.parse(L)}catch{Q[B]=L.split(",").map((_)=>_.trim())}else Q[B]=L;else if(U&&typeof U==="object"&&!Array.isArray(U))Q[B]=Y(U,j)}return Q}return Y(Z)}function A1($){let Z=R($5.cwd(),$.configDir),W=R($5.cwd(),$.generatedDir),X=R(W,"config-types.ts");if(!E8(E9(X)))xZ(E9(X),{recursive:!0,mode:511});let J=E8(Z)?CZ(Z).map((z)=>z.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${X1}
|
|
36
|
-
export type ConfigNames = ${J.length?`'${J.join("' | '")}'`:"string"}
|
|
37
|
-
`;RZ(X,Y,{mode:438})}function I1($){let Z=null,W=null,X=()=>{if(!W)W=o9($).then((Y)=>{return Z=Y,Y},(Y)=>{let z="defaultConfig"in $?$.defaultConfig:{};if(Z=z,"verbose"in $&&$.verbose)v.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return z});return W},J="defaultConfig"in $?$.defaultConfig:{};return Z=J,X(),new Proxy({},{get(Y,z){if(Z)return Z[z];let G=J[z];return X(),G},has(Y,z){return z in(Z||J)},ownKeys(){return Object.keys(Z||J)},getOwnPropertyDescriptor(Y,z){return Object.getOwnPropertyDescriptor(Z||J,z)},set(Y,z,G){if(!Z)Z={...J};return Z[z]=G,!0}})}function D1($){let Z=R9(wZ.cwd(),$?.configDir||"./config");function W(){if(!qZ(Z))return[];let J=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],z=bZ(Z).filter((Q)=>J.has(S8(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),G=new Map;for(let{base:Q,file:B}of z){let U=S8(B).toLowerCase(),j=G.get(Q);if(!j){G.set(Q,B);continue}let H=S8(j).toLowerCase();if(Y.indexOf(U)<Y.indexOf(H))G.set(Q,B)}return Array.from(G.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function X(){let J=W(),Y=J.map((B)=>B.base),z=Y.length?Y.map((B)=>`'${B}'`).join(" | "):"string",G=J.length?`{
|
|
38
|
-
${J.map((B)=>{let U=R9(Z,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${U}').default`}).join(`,
|
|
39
|
-
`)}
|
|
40
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${z}
|
|
41
|
-
export type ConfigByName = ${G}
|
|
42
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
43
|
-
export type ConfigOf = Config
|
|
44
|
-
`}return{name:"bunfig-plugin",setup(J){J.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),J.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:X(),loader:"ts"}})}}}class y8{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 Y={count:1,resetTime:W+Z};return this.records.set($,Y),this.timestamps.set($,[W]),Y}X.count+=1;let J=this.timestamps.get($)||[];return J.push(W),this.timestamps.set($,J),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($)||[],J=Date.now()-Z;return W.filter((Y)=>Y>J).length}async batchIncrement($,Z){let W=new Map;for(let X of $){let J=await this.increment(X,Z);W.set(X,J)}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 J=X.filter((Y)=>Y>Z);if(J.length===0)this.timestamps.delete(W);else if(J.length!==X.length)this.timestamps.set(W,J)}}dispose(){if(this.cleanupTimer)clearInterval(this.cleanupTimer)}startCleanupTimer(){this.cleanupTimer=setInterval(()=>this.cleanExpired(),this.cleanupIntervalMs)}}class d8{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 y8(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 y8?"memory (custom)":"redis (custom)":k.storage;console.warn(`[ts-rate-limiter] Initialized with:
|
|
45
|
-
- Algorithm: ${this.algorithm}
|
|
46
|
-
- Window: ${this.windowMs}ms
|
|
47
|
-
- Max Requests: ${this.maxRequests}
|
|
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 J=(Z-W.lastRefill)*this.tokenBucketOptions.refillRate;if(J>0)W.tokens=Math.min(W.tokens+J,this.tokenBucketOptions.capacity),W.lastRefill=Z;let Y=this.draftMode?!0:W.tokens>=1;if(Y&&!this.draftMode)W.tokens-=1;let z=W.tokens>=this.tokenBucketOptions.capacity?this.windowMs:Math.ceil(1/this.tokenBucketOptions.refillRate);return{allowed:Y,current:this.tokenBucketOptions.capacity-Math.floor(W.tokens),limit:this.tokenBucketOptions.capacity,remaining:z,resetTime:Z+z}}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 Y8(`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 $$($){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 J=$.headers.get("authorization");if(J?.startsWith("Bearer "))return`bearer:${J.slice(7,39)}`;let Y=$.headers.get("x-forwarded-for");if(Y)return`ip:${Y.split(",")[0]?.trim()??"unknown"}`;let z=$.headers.get("x-real-ip");if(z)return`ip:${z}`;return"anon"}var PZ,kZ=($)=>$,yZ=($,Z)=>{for(var W in Z)PZ($,W,{get:Z[W],enumerable:!0,configurable:!0,set:vZ.bind(Z,W)})},d=($,Z)=>()=>($&&(Z=$($=0)),Z),fZ,A5,b5,y9,w5,q9,N8,E5,dZ,N,I,uZ,b9,lZ,w9,nZ,iZ,x8,sZ,P9,k9,oZ,C8,tZ,aZ,rZ,eZ,$1,r5,g9,Z1,W1,X1="0.15.9",J1=()=>{},P,$8,R5,R8,q8,Z8,b8,w8,q5,P8,k8,n,I5,p9,l9,m8,n9,i9,s9,v,c,t9,a9,_1,O1=()=>{},r9,e9,K1,k,Y8;var Z$=u(()=>{PZ=Object.defineProperty;fZ=import.meta.require;w5=d(()=>{A5=new f8,b5=new g8,y9={createKey:gZ,isEquivalent:hZ,estimateMemoryUsage:mZ}});W1=d(()=>{q9=e5.env.CLARITY_LOG_DIR||FZ(pZ(),"logs"),N8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:q9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},E5={...N8},dZ=(async()=>{try{let{loadConfig:$}=await Promise.resolve().then(()=>(e9(),r9)),Z=await $({name:"clarity",alias:"logging",defaultConfig:N8,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"},I=N,uZ=N.red,b9=N.green,lZ=N.yellow,w9=N.blue,nZ=N.magenta,iZ=N.cyan,x8=N.white,sZ=N.gray,P9=N.bgRed,k9=N.bgYellow,oZ=N.bgGray,C8=N.bold,tZ=N.dim,aZ=N.italic,rZ=N.underline,eZ=N.strikethrough,$1=N.reset,r5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},g9={debug:"\uD83D\uDD0D",info:w9("\u2139"),success:b9("\u2713"),warning:k9(x8(C8(" WARN "))),error:P9(x8(C8(" ERROR ")))},Z1=new W8("stacks")});I5=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 J=X===void 0?[]:Array.isArray(X)?X.filter(Boolean):[X],Y="";if(J.length===1)Y=` or alias "${J[0]}"`;else if(J.length>1)Y=` or aliases ${J.map((z)=>`"${z}"`).join(", ")}`;super(`Configuration "${Z}"${Y} 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}},R8=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})}},q8=class extends P{code="CONFIG_MERGE_ERROR";constructor(Z,W,X,J){super(`Failed to merge configuration from "${Z}" with "${W}": ${X.message}`,{sourcePath:Z,targetPath:W,configName:J,originalError:X.name,originalMessage:X.message});this.cause=X}},Z8=class extends P{code="ENV_VAR_ERROR";constructor(Z,W,X,J){super(`Failed to parse environment variable "${Z}" with value "${W}" as ${X}`,{envKey:Z,envValue:W,expectedType:X,configName:J})}},b8=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}},w8=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})}},P8=class extends P{code="BROWSER_CONFIG_ERROR";constructor(Z,W,X,J){super(`Failed to fetch configuration from "${Z}": ${W} ${X}`,{endpoint:Z,status:W,statusText:X,configName:J})}},k8=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 R8($,Z,W)},configMerge($,Z,W,X){return new q8($,Z,W,X)},envVar($,Z,W,X){return new Z8($,Z,W,X)},fileSystem($,Z,W){return new b8($,Z,W)},typeGeneration($,Z,W){return new w8($,Z,W)},schemaValidation($,Z,W){return new q5($,Z,W)},browserConfig($,Z,W,X){return new P8($,Z,W,X)},plugin($,Z,W){return new k8($,Z,W)}}});p9=d(()=>{w5(),I5()});m8=d(()=>{l9={replace:"replace",concat:"concat",smart:"smart"}});n9=d(()=>{w5(),I5(),m8()});s9=d(()=>{w5(),I5(),i9=/^https?:\/\//});_1=d(()=>{W1(),J1(),w5(),I5(),p9(),n9(),s9(),m8(),v=new W8("bunfig",{showTags:!0}),c=new c8,t9=R($5.cwd(),"config"),a9=R($5.cwd(),"src/generated")});r9={};yZ(r9,{withErrorRecovery:()=>h9,tryLoadConfig:()=>V1,loadConfigWithResult:()=>L1,loadConfig:()=>o9,isRetryableError:()=>z1,isConfigNotFoundError:()=>Y1,isBunfigError:()=>m9,globalPerformanceMonitor:()=>b5,globalCache:()=>A5,getEnvOrDefault:()=>G1,generateConfigTypes:()=>A1,defaultGeneratedDir:()=>a9,defaultConfigDir:()=>t9,deepMergeWithArrayStrategy:()=>h8,deepMerge:()=>c9,createLibraryConfig:()=>I1,config:()=>F1,bunfigPlugin:()=>D1,applyEnvVarsToConfig:()=>C5,TypeGenerationError:()=>w8,SchemaValidationError:()=>q5,PluginError:()=>k8,PerformanceMonitor:()=>g8,FileSystemError:()=>b8,ErrorFactory:()=>n,EnvVarError:()=>Z8,EnvProcessor:()=>X8,ConfigValidator:()=>p8,ConfigValidationError:()=>R8,ConfigNotFoundError:()=>$8,ConfigMergeError:()=>q8,ConfigLoader:()=>c8,ConfigLoadError:()=>R5,ConfigFileLoader:()=>J8,ConfigCache:()=>f8,CacheUtils:()=>y9,BunfigError:()=>P,BrowserConfigError:()=>P8,ArrayMergeStrategies:()=>l9});e9=d(()=>{_1(),I5(),w5(),I5(),O1(),p9(),n9(),s9(),m8()});e9();K1={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=K1;Y8=class Y8 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 M1}from"@stacksjs/error-handling";function u8($,Z){let W=`${Z}:${$}`,X=W$.get(W);if(!X)X=new d8({windowMs:Z,maxRequests:$,algorithm:"fixed-window",standardHeaders:!1,legacyHeaders:!1}),W$.set(W,X);return X}function l8($){if($!==void 0)return $;let Z=t();return Z?$$(Z):"anon"}function n8($,Z,W={}){let X=l8(W.identity),J=`${$}:${X}`,Y=async(z)=>{let G=u8(Z,z);try{await G.enforce(J)}catch(Q){if(Q instanceof Y8)throw Object.assign(new M1(429,"Too many requests",{key:$,max:Z,retryAfter:Q.retryAfter}),{headers:Q.toHeaders()});throw Q}};return{async per(z){let G=T1[z];if(!G)throw Error(`rateLimit().per: unknown period '${z}'`);await Y(G*1000)},async over(z){if(!Number.isFinite(z)||z<=0)throw Error(`rateLimit().over: ttl must be a positive number, got ${z}`);await Y(z*1000)}}}async function S1($,Z,W,X={}){let J=l8(X.identity),Y=`${$}:${J}`,G=await u8(Z,W*1000).peek(Y);if(!G)return null;return{count:G.current,limit:G.limit,remaining:Math.max(0,G.limit-G.current)}}async function N1($,Z,W,X={}){let J=l8(X.identity),Y=`${$}:${J}`;await u8(Z,W*1000).reset(Y)}var T1,W$;var i8=u(()=>{Z$();N5();T1={second:1,minute:60,hour:3600,day:86400},W$=new Map});import Z5 from"process";function x1(){if(z8!==void 0)return z8;return z8=(Z5.env.APP_ENV??Z5.env.NODE_ENV??"").toLowerCase()==="production",z8}function C1(){if(G8!==void 0)return G8;return G8=Z5.env.STACKS_SECURITY_HEADERS_DISABLE==="true",G8}function E1(){if(_5!==void 0)return _5;let $=Z5.env.STACKS_CSP,Z=Z5.env.STACKS_CSP_REPORT_ONLY;if($)_5={header:"Content-Security-Policy",value:$};else if(Z)_5={header:"Content-Security-Policy-Report-Only",value:Z};else _5=null;return _5}function X$($){if(C1())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(x1()&&!$.has("Strict-Transport-Security"))$.set("Strict-Transport-Security","max-age=31536000; includeSubDomains");let Z=E1();if(Z&&!$.has(Z.header))$.set(Z.header,Z.value)}var z8,G8,_5;var J$=()=>{};var G$={};G9(G$,{loadRoutes:()=>z$});import{log as R1}from"@stacksjs/logging";async function z$($){for(let[Z,W]of Object.entries($)){let X=P1(W),J=X.prefix!==void 0?X.prefix?X.prefix.startsWith("/")?X.prefix:`/${X.prefix}`:void 0:q1.includes(Z)?void 0:`/${Z}`,Y=k1(X.middleware);R1.debug(`[route-loader] Loading: ${X.path} prefix=${J||"/"} middleware=[${Y.join(", ")}]`);try{if(J||Y.length>0)await D5.group({prefix:J,middleware:Y.length>0?Y:void 0},async()=>{await Y$(X.path)});else await Y$(X.path)}catch(z){let G=z instanceof Error?z.message:String(z);throw console.error(`[Routes] Failed to load route file '${X.path}': ${G}`),Error(`Route loading failed for '${X.path}': ${G}`)}}await b1()}async function b1(){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 w1($){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((J)=>J===".."))throw Error(`[route-loader] Invalid route path: '..' segment not allowed (${W})`);return W}async function Y$($){let Z=w1($),{projectPath:W}=await import("@stacksjs/path");await import(W(`routes/${Z}`))}function P1($){if(typeof $==="string")return{path:$};return $}function k1($){if(!$)return[];if(typeof $==="string")return[$];return $}var q1;var s8=u(()=>{O5();q1=["web"]});import M from"process";import{Buffer as Q$}from"buffer";import{existsSync as v1}from"fs";import{timingSafeEqual as y1}from"crypto";import{log as V,report as A$}from"@stacksjs/logging";import{path as w}from"@stacksjs/path";import{UploadedFile as Q8}from"@stacksjs/storage";import{applyRequestEnhancements as f1,Router as g1}from"@stacksjs/bun-router";import{isCursorPaginator as m1,isPaginator as p1,isSimplePaginator as c1}from"@stacksjs/orm";function I$(){if(j8.size<=1)return!1;let $=globalThis;if(!$[B$]){$[B$]=!0;let Z=[...j8].map((W)=>` - ${W}`).join(`
|
|
50
|
-
`);V.warn(`${j8.size} distinct @stacksjs/router modules loaded in one process; they now share one route table (stacksjs/stacks#1982) so routing still works, but this is a duplicated install worth fixing. It usually means an app vendors storage/framework/core AND installs the published @stacksjs/* dist, and a tsconfig \`paths\` mapping (\`@stacksjs/* -> ./*/src\`) splits module resolution between core files and root files. See stacksjs/stacks#1975.
|
|
51
|
-
Loaded instances:
|
|
52
|
-
${Z}`)}return!0}function i($){let Z=w.storagePath(`framework/defaults/${$}`);if(v1(Z))return Z;if(P5===void 0)try{let W=Bun.resolveSync("@stacksjs/defaults/package.json",M.cwd());P5=W.slice(0,W.lastIndexOf("/"))}catch{P5=null}return P5?`${P5}/${$}`:Z}function d1($){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 $9{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 U$($){let Z=M.env.STACKS_EXPOSE_ROUTES??"";if(!Z)return!((M.env.APP_ENV??"").toLowerCase()==="production"||M.env.NODE_ENV==="production");if(Z==="1")return!((M.env.APP_ENV??"").toLowerCase()==="production"||M.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 y1(Q$.from(X),Q$.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 V.warn("[router] CORS header injection failed",{error:W}),Z}}function u1($){let Z=l1($),W=new Map;for(let X of Z)W.set(X,new RegExp(`(^|/):${X}(?=$|/)`,"g"));return{path:$,paramNames:Z,colonRegex:W}}function l1($){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 X9($,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 J;try{J=M.env.APP_URL||"https://localhost"}catch{J="https://localhost"}if(J=J.replace(/\/$/,""),!J.startsWith("http"))J=`https://${J}`;let Y=W.path,z={};for(let[Q,B]of Object.entries(Z)){let U=`{${Q}}`;if(Y.includes(U))Y=Y.replaceAll(U,encodeURIComponent(String(B)));else{let j=W.colonRegex.get(Q);if(j&&j.test(Y))j.lastIndex=0,Y=Y.replace(j,`$1${encodeURIComponent(String(B))}`);else z[Q]=String(B)}}let G=Object.keys(z).length>0?`?${new URLSearchParams(z).toString()}`:"";return`${J}${Y}${G}`}function n1($){let Z=v5.get($);return Z?[...Z.paramNames]:[]}function O$(){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 J=W.slice(0,X),Y=W.slice(X+1),z;for(let[G,Q]of v5.entries())if(Q.path===Y){z=G;break}$.push({method:J,path:Y,name:z})}return $.sort((W,X)=>W.path.localeCompare(X.path))}function i1($,Z){let W=`${$}:${String(Z)}`;if(H$.has(W))return;H$.add(W),V.warn(`[Router] Middleware '${$}' declared an invalid priority (${String(Z)}). Priorities must be a finite non-negative number; falling back to default ${K$}.`)}function s1($){if($ instanceof h5)return $.toRouterHandler();if($&&typeof $==="object"&&typeof $.handle==="function"&&typeof $!=="function"){let Z=$.handle.bind($);return async(X,J)=>{try{await Z(X)}catch(Y){if(Y instanceof Response)return Y;throw Y}return J()}}return $}async function o1(){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 a1($){if(!$)return $;let Z=L$.get($);if(Z!==void 0)return Z;let W=$.split(t1).filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("");return L$.set($,W),W}async function r1($){let W=(await o1())[$]||a1($);return V.debug(`[middleware] Resolved: ${$} \u2192 ${W}`),W}async function M$($){if(J5.has($))return J5.get($)??null;let Z=await r1($),W;try{let X=w.appPath(`Middleware/${Z}.ts`),Y=(await import(X)).default??null;if(!Y||typeof Y.handle!=="function")return V.error(`[Router] Middleware '${$}' resolved to ${X}, but the file has no default export with a handle() method`),J5.set($,null),null;return J5.set($,Y),Y}catch(X){W=X}try{let X=i(`app/Middleware/${Z}.ts`),Y=(await import(X)).default??null;if(!Y||typeof Y.handle!=="function")return V.error(`[Router] Middleware '${$}' resolved to ${X}, but the file has no default export with a handle() method`),J5.set($,null),null;return J5.set($,Y),Y}catch(X){let J=W instanceof Error?W.message:String(W);return V.error(`[Router] Failed to load middleware '${$}' (resolved to '${Z}'). app/Middleware: ${J}; defaults:`,X),null}}function T$(){J5.clear(),k5=null,Z9.clear(),W9.clear()}function e1(){if(M.env.APP_ENV==="production"||M.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 J=Z.watch(X,{recursive:!0},()=>{V.debug("[middleware] hot-reload: clearing cache"),T$()});$.push(J)}catch{}}catch{}})(),()=>{for(let Z of $)try{Z.close()}catch{}$=[]}}function N$($){let Z=$.indexOf(":");if(Z===-1)return{name:$};return{name:$.substring(0,Z),params:$.substring(Z+1)}}async function x$(){let $=new Map;for(let[W,X]of Y5)for(let J of X){let{name:Y}=N$(J),z=$.get(Y)??[];z.push(W),$.set(Y,z)}if(!$.has("csrf"))$.set("csrf",["(auto-injected on POST/PUT/PATCH/DELETE)"]);let Z=[];for(let[W,X]of $){let J=await M$(W);if(!J||typeof J.handle!=="function")Z.push({alias:W,routes:X})}return Z}async function C$(){let $=await x$();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=G6(Z,!0),X=null;if(typeof Z==="string"){let J=$.slice(0,$.indexOf(":")).toUpperCase();if(j$.has(J))X=E$(Z).then(()=>{return}).catch(()=>{return})}return async(J)=>{try{await q$(J)}catch(z){let G=z instanceof Error?z:Error(String(z));return j5(G,J)}let Y=R$(J);if(X)await X;if(S$.has($))J._forceJson=!0;return _8(Y,async()=>{let z=_$.get($);if(z)try{await n8($,z.max).over(z.windowSeconds)}catch(D){return j5(D,J)}let G=Y5.get($)||[],Q=J.method.toUpperCase(),B=[...G],U=G.some((D)=>D==="csrf"||D.startsWith("csrf:")),j=a8.has($),H=r8.has($),L=W9.get($),F=L?Z9.get(L)===!0:!1;if(j$.has(Q)&&!U&&(H||!j&&!F))B.unshift("csrf");if(B.length>0){let D=(M.env.LOG_LEVEL||"info").toLowerCase();if(D!=="info"&&D!=="warn"&&D!=="error"){let K=J.url.indexOf("://"),T=K===-1?0:J.url.indexOf("/",K+3),E=J.url.indexOf("?",T<0?0:T),C=T<0?"/":J.url.slice(T,E===-1?void 0:E);V.debug(`[middleware] Executing chain: [${B.join(", ")}] for ${Q} ${C}`)}}let f=[];for(let D of B){let{name:K,params:T}=N$(D);if(T)Y._middlewareParams=Y._middlewareParams||{},Y._middlewareParams[K]=T;let E=await M$(K);if(!E||typeof E.handle!=="function"){V.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,Y,{status:500});return await B8(Y,Q5)}let C=E.priority,G5=K$;if(typeof C==="number"&&Number.isFinite(C)&&C>=0)G5=C;else if(C!==void 0)i1(K,C);f.push({name:K,handler:E,priority:G5})}f.sort((D,K)=>D.priority-K.priority);let q=[];for(let{name:D,handler:K}of f){let T=M.hrtime.bigint(),E;try{let G5=new Promise((Q5,s)=>{E=setTimeout(()=>s(Error(`Middleware '${D}' exceeded 30000ms`)),30000)});await Promise.race([K.handle(Y),G5]);let h=Number(M.hrtime.bigint()-T)/1e6;q.push({name:D,ms:h})}catch(C){let G5=Number(M.hrtime.bigint()-T)/1e6;if(q.push({name:D,ms:G5}),V.debug(`[middleware] Blocked by: ${D}`),C instanceof Response){try{let{_requestId:s,_startNs:K5}=Y,M5=K5!=null?Number(M.hrtime.bigint()-K5)/1e6:null,o=M5!=null?[`total;dur=${M5.toFixed(1)}`]:[];for(let T5 of q){let V8=T5.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);o.push(`mw_${V8};dur=${T5.ms.toFixed(1)}`)}if(o.length>0)C.headers.set("Server-Timing",o.join(", "));if(s)C.headers.set("X-Request-ID",s)}catch{}return await B8(Y,C)}let h=C instanceof Error?C:Error(String(C)),Q5="statusCode"in h||"status"in h?await j5(h,Y):await(()=>{return V.error(`[Router] Middleware '${D}' threw an unexpected error:`,h),l(h,Y,{status:500})})();try{let{_requestId:s,_startNs:K5}=Y,M5=K5!=null?Number(M.hrtime.bigint()-K5)/1e6:null,o=M5!=null?[`total;dur=${M5.toFixed(1)}`]:[];for(let T5 of q){let V8=T5.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);o.push(`mw_${V8};dur=${T5.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(Y,Q5)}finally{clearTimeout(E)}}let O=await W(Y);if(l5(),O){if(J.method==="GET"||J.method==="HEAD"||J.method==="OPTIONS")try{let{seedCsrfCookieIfMissing:K}=await import(i("app/Middleware/Csrf.ts"));O=K(Y,O)}catch(K){V.warn("[router] CSRF cookie seeding failed",{error:K})}}if(O)O=await B8(Y,O);let{_requestId:z5,_startNs:f5}=Y,g5=f5!=null?Number(M.hrtime.bigint()-f5)/1e6:null,F8=(D)=>{if(z5)D.set("X-Request-ID",z5);if(g5!=null){let K=[`total;dur=${g5.toFixed(1)}`];for(let T of q){let E=T.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);K.push(`mw_${E};dur=${T.ms.toFixed(1)}`)}D.set("Server-Timing",K.join(", "))}X$(D)};if(O&&typeof O.headers?.set==="function"){if(O.status>=400&&(O.headers.get("content-type")||"").includes("json")&&z5)try{let K=await O.clone().text(),T=JSON.parse(K);if(T&&typeof T==="object"){let E=new Headers(O.headers);return F8(E),new Response(JSON.stringify({...T,request_id:z5}),{status:O.status,statusText:O.statusText,headers:E})}}catch{}try{F8(O.headers)}catch{try{let K=O.clone(),T=new Headers(O.headers);return F8(T),new Response(K.body,{status:O.status,statusText:O.statusText,headers:T})}catch{}}}if(Y._compress===!0&&O)try{let{applyCompression:D}=await import(i("app/Middleware/Compress.ts"));return await D(Y,O)}catch(D){V.warn(`[router] Compression failed; sending uncompressed response: ${D instanceof Error?D.message:String(D)}`)}return O})}}function X5($){if(!Y5.has($))Y5.set($,[]);let Z=$.includes(":")?$.substring($.indexOf(":")+1):$,W={middleware(X){let J=Y5.get($);if(J)J.push(X);return W},name(X){return v5.set(X,u1(Z)),W},skipCsrf(){return a8.add($),r8.delete($),W},requireCsrf(){return r8.add($),a8.delete($),W},rateLimit(X,J){if(!Number.isFinite(X)||X<=0)throw Error(`[Router] .rateLimit(): max must be a positive number, got ${String(X)}`);let Y=d1(J);return _$.set($,{max:Math.floor(X),windowSeconds:Y}),W}};return W}async function o8($){try{return await Bun.file($).exists()}catch{return!1}}function $6($){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 V$($){let Z=F$.get($);if(!Z)Z=import($),F$.set($,Z);return Z}function E$($){let Z=t8.get($);if(!Z)Z=Z6($),t8.set($,Z),Z.catch(()=>t8.delete($));return Z}async function Z6($){$6($);let Z=$;if(Z=Z.endsWith(".ts")?Z.slice(0,-3):Z,Z.includes("Controller")){let[X,J="index"]=Z.split("@"),Y=w.appPath(`${X}.ts`),z=i(`app/${X}.ts`),G=await o8(Y)?Y:z;try{let Q=await V$(G);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[J]!=="function")throw Error(`Method ${J} not found in controller ${X}`);return async(U)=>{let j=await B[J](U);return e8(j,U)}}catch(Q){throw V.error(`[Router] Failed to load controller '${G}':`,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`),J=i(`app/${Z}.ts`);W=await o8(X)?X:J}else{let X=w.appPath(`${Z}.ts`),J=i(`app/${Z}.ts`);W=await o8(X)?X:J}try{let J=(await V$(W)).default;if(!J)throw Error(`Action '${$}' has no default export`);if(typeof J.handle!=="function")throw V.error(`[Router] Action '${$}' structure:`,Object.keys(J)),Error(`Action '${$}' has no handle() method. Got: ${typeof J.handle}`);let Y=J.skipCsrf===!0||J.csrf===!1;Z9.set($,Y);let z=J.apiResponse===!0;return async(G)=>{if(Y)G._skipCsrf=!0;if(z)G._forceJson=!0;try{if(J.validations){let B=await W6(G,J.validations);if(!B.valid)return Response.json({error:"Validation failed",errors:B.errors},{status:422})}if(typeof J.authorize==="function"){let B=await J.authorize(G);if(B instanceof Response)return B;if(B===!1)return Response.json({error:"Forbidden"},{status:403})}if(typeof J.before==="function"){let B=await J.before(G);if(B instanceof Response)return B}let Q=await J.handle(G);return e8(Q,G)}catch(Q){throw A$(Q,{label:`[Router] action.handle() for '${$}'`}),Q}}}catch(X){throw V.error(`[Router] Failed to import action '${W}':`,X),X}}async function W6($,Z){let W={},X=await X6($,Z);for(let[J,Y]of Object.entries(Z)){let z=X[J],G;try{G=Y.rule.validate(z)}catch{G={valid:!1,errors:[{message:`${J} validation failed`}]}}if(!G.valid){let Q=[],B=J.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(j)=>j.toUpperCase()),U=(j)=>j.toLowerCase().startsWith(J.toLowerCase())||j.includes(B)?j:`${B} ${j}`;if(G.errors&&G.errors.length>0)if(Y.message){let j=G.errors[0]?.message??"";Q.push(typeof Y.message==="string"?Y.message:Y.message[J]||U(j))}else G.errors.forEach((j)=>Q.push(U(j.message)));else Q.push(Y.message?typeof Y.message==="string"?Y.message:`${B} is invalid`:`${B} is invalid`);W[J]=Q}}return{valid:Object.keys(W).length===0,errors:W}}async function X6($,Z){let W={},X=$.query;if(X)for(let J in X)W[J]=X[J];else new URL($.url).searchParams.forEach((Y,z)=>{W[z]=Y});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 J=$.allFiles();for(let Y of Object.keys(J??{}))if(!(Y in W))W[Y]=J[Y]}catch{}if(!Z)return W;for(let[J,Y]of Object.entries(Z)){let z=W[J];if(typeof z!=="string")continue;let G=Y.rule?.name;if(G==="number"){let Q=Number(z);if(Number.isFinite(Q))W[J]=Q}else if(G==="boolean"){if(z==="true"||z==="1")W[J]=!0;else if(z==="false"||z==="0")W[J]=!1}}return W}function e8($,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 J=J6($);if(J)return Response.json($,{headers:{Link:J}});return Response.json($)}if(X)return Response.json($);return new Response(String($),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function J6($){if(!p1($)&&!c1($)&&!m1($))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 Y6($,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(Y){try{for await(let z of $)Y.enqueue(typeof z==="string"?new TextEncoder().encode(z):z);Y.close()}catch(z){Y.error(z)}}}),J=new Headers(W);if(Z.headers)new Headers(Z.headers).forEach((z,G)=>J.set(G,z));return new Response(X,{status:Z.status??200,headers:J})}function b($){let Z=$._allInputCache;if(Z)return Z;let W={},X=$.query;if(X)for(let J in X)W[J]=X[J];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 R$($){f1($,$.params||{});let Z=$.query;if(!Z){let W=new URL($.url);Z={},W.searchParams.forEach((X,J)=>{Z[J]=X}),$.query=Z}return Object.assign($,z6),$}function G6($,Z=!1){if(typeof $==="string"){let X=$;return async(J)=>{try{if(!Z)await q$(J),J=R$(J);return await(await E$(X))(J)}catch(Y){A$(Y,{label:`[Router] ${X}`});let z=Y?.statusCode??Y?.status,G=typeof z==="number"&&Number.isInteger(z)&&z>=400&&z<600?z:void 0;return await l(Y instanceof Error?Y:Error(String(Y)),J,{handlerPath:X,status:G})}}}let W=$;return async(X)=>{let J=await W(X);return e8(J,X)}}async function q$($){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 J=JSON.parse(X);$.jsonBody=J&&typeof J==="object"?J:{}}catch(J){let Y=J instanceof Error?J.message:"Invalid JSON",{HttpError:z}=await import("@stacksjs/error-handling");throw new z(400,`Invalid JSON body: ${Y}`)}}else if(Z.includes("application/x-www-form-urlencoded")){let W=await $.clone().text(),X=new URLSearchParams(W),J={};X.forEach((Y,z)=>{J[z]=Y}),$.formBody=J}else if(Z.includes("multipart/form-data")){let W=await $.clone().formData(),X={},J={};W.forEach((Y,z)=>{if(Y instanceof File)if(J[z])if(Array.isArray(J[z]))J[z].push(Y);else J[z]=[J[z],Y];else J[z]=Y;else X[z]=Y}),Reflect.set($,"formBody",X),Reflect.set($,"files",J)}}catch(W){if(typeof(W?.status??W?.statusCode)==="number")throw W;V.debug("[stacks-router] Body parsing failed:",W)}}function b$($={}){let Z=new g1({verbose:$.verbose??!1}),W="",X=[],J=!1;function Y(G,Q,B){let U=W+Q,j=`${G}:${U}`;if(V.debug(`[router] ${G} ${U} \u2192 ${typeof B==="string"?B:"function"}`),X.length>0)Y5.set(j,[...X]);if(J)S$.add(j);if(typeof B==="string")W9.set(j,B);return{fullPath:U,routeKey:j}}let z={bunRouter:Z,get routes(){return Z.routes},get(G,Q){let{fullPath:B,routeKey:U}=Y("GET",G,Q);return Z.get(B,W5(U,Q)),X5(U)},post(G,Q){let{fullPath:B,routeKey:U}=Y("POST",G,Q);return Z.post(B,W5(U,Q)),X5(U)},put(G,Q){let{fullPath:B,routeKey:U}=Y("PUT",G,Q);return Z.put(B,W5(U,Q)),X5(U)},patch(G,Q){let{fullPath:B,routeKey:U}=Y("PATCH",G,Q);return Z.patch(B,W5(U,Q)),X5(U)},delete(G,Q){let{fullPath:B,routeKey:U}=Y("DELETE",G,Q);return Z.delete(B,W5(U,Q)),X5(U)},options(G,Q){let{fullPath:B,routeKey:U}=Y("OPTIONS",G,Q);return Z.options(B,W5(U,Q)),X5(U)},group(G,Q){let B=W,U=[...X],j=J;if(G.prefix)W=B+G.prefix;let H=G.middleware?Array.isArray(G.middleware)?G.middleware:[G.middleware]:void 0;if(H)X=[...X,...H];if(G.apiResponse===!0)J=!0;V.debug(`[router] Entering group: prefix=${G.prefix||"/"} middleware=[${H?.join(", ")||""}]${J?" apiResponse=true":""}`);let L=Q();if(L instanceof Promise)return L.then(()=>{return W=B,X=U,J=j,z}).catch((F)=>{throw W=B,X=U,J=j,F});return W=B,X=U,J=j,z},resource(G,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$/,"");V.debug(`[router] Resource: /${G} \u2192 ${Q} [${j.join(", ")}]`);let L=()=>{for(let F of j)switch(F){case"index":z.get(`/${G}`,`${H}IndexAction`);break;case"store":z.post(`/${G}`,`${H}StoreAction`);break;case"show":z.get(`/${G}/:id`,`${H}ShowAction`);break;case"update":z.put(`/${G}/:id`,`${H}UpdateAction`);break;case"destroy":z.delete(`/${G}/:id`,`${H}DestroyAction`);break}};if(B?.middleware)z.group({middleware:B.middleware},L);else L();return z},match(G,Q,B){V.debug(`[router] Match: [${G.join(", ")}] ${Q} \u2192 ${typeof B==="string"?B:"function"}`);for(let U of G){let j=U.toUpperCase(),{fullPath:H,routeKey:L}=Y(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(`${G[0]}:${W}${Q}`)},health(){return Z.get("/api/health",async()=>{let G={},Q=async(j,H)=>{let L=Date.now();try{let F=new AbortController,_=setTimeout(()=>F.abort(),1500);await Promise.race([H(),new Promise((f,q)=>F.signal.addEventListener("abort",()=>q(Error("timeout"))))]),clearTimeout(_),G[j]={ok:!0,ms:Date.now()-L}}catch(F){G[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(G).every((j)=>j.ok),U={status:B?"healthy":"degraded",checks:G,timestamp:Date.now()};return Response.json(U,{status:B?200:503})}),Z.get("/__routes",(G)=>{if(!U$(G))return Response.json({error:"disabled"},{status:404});return Response.json(O$())}),Z.get("/__storage/:path",async(G)=>{let Q=new URL(G.url),B=Q.searchParams.get("token"),U=G.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 _=L.disk();if(!await _.fileExists(j))return new Response("Not Found",{status:404});let q=await _.readToBuffer(j),O=await _.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(_){return V.error("[storage] signed-url fetch failed:",_),new Response("Internal Error",{status:500})}}),Z.get("/__openapi.json",async(G)=>{if(!U$(G))return Response.json({error:"disabled"},{status: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)},{status:500})}}),z},use(G){let Q=s1(G);return Z.globalMiddleware.push(Q),z},async serve(G={}){return I$(),Z.serve(G)},async handleRequest(G){return Z.handleRequest(G)},getAllowedMethods(G,Q){return Z.getAllowedMethods(G,Q)},async register(G,Q){V.debug(`[router] Register: ${G} prefix=${Q?.prefix||"none"}`);let B=async()=>{await import(G)};if(Q?.prefix||Q?.middleware)await z.group({prefix:Q.prefix,middleware:Q.middleware},B);else await B();return z},async importRoutes(){V.debug("[router] Loading user routes from registry...");try{let{loadRoutes:B}=await Promise.resolve().then(() => (s8(),G$)),{appPath:U}=await import("@stacksjs/path"),j=(await import(U("Routes.ts"))).default;await B(j)}catch(B){throw V.error("Failed to load route registry:",B),B}V.debug("[router] Loading ORM routes...");let G=[w.frameworkPath("orm/routes.ts"),w.frameworkPath("core/orm/routes.ts")],Q=!1;for(let B of G)try{if(await Bun.file(B).exists()){await import(B),Q=!0;break}}catch(U){V.warn(`[router] ORM routes candidate failed to load, falling back to next: ${B}
|
|
53
|
-
`,U)}if(!Q)V.warn("[router] No ORM routes candidate loaded \u2014 model useApi endpoints are unavailable.");V.debug("[router] Loading discovered package routes...");try{await z.loadDiscoveredRoutes()}catch(B){V.debug("Package route discovery skipped:",B)}await C$()},async loadDiscoveredRoutes(){try{let G=w.storagePath("framework/discovered-packages.json"),Q=Bun.file(G);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 _=Array.isArray(F)?F:[F],f=`${j}/${H}`;for(let q of _){V.debug(`[router] Discovered route: ${H} \u2192 ${q}`);let O=q.startsWith("/")?q:`${f}/${q}`,z5=L?.routePrefix,f5=L?.routeMiddleware;try{await z.register(O,{prefix:z5,middleware:f5})}catch(g5){V.warn(`Failed to load routes from package '${H}': ${g5}`)}}}}catch{}}};return z}async function B6($,Z){if(!U8)V.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 Y=new URL($.url),z={...X,path:Y.pathname,method:$.method};return new Response(JSON.stringify(z),{status:404,headers:W.headers})}}catch{}return W}async function U6($={}){return D5.serve($)}var h1,j8,B$,P5,a8,r8,_$,D$=5000,Z9,W9,j$,v5,K$=10,H$,J5,k5=null,t1,L$,Y5,S$,F$,t8,z6,Q6,D5,U8=null;var O5=u(()=>{N5();p5();n5();i8();J$();h1=Symbol.for("@stacksjs/router:loaded-instances"),j8=globalThis[h1]??=new Set;j8.add(import.meta.path);B$=Symbol.for("@stacksjs/router:multi-instance-warned");a8=new Set,r8=new Set,_$=new Map;Z9=new $9(D$),W9=new $9(D$),j$=new Set(["POST","PUT","PATCH","DELETE"]),v5=new Map;H$=new Set;J5=new Map;t1=/[-_\s]+/,L$=new Map;Y5=new Map,S$=new Set;F$=new Map;t8=new Map;z6={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 J=Z[X];return J!==void 0&&J!==null&&J!==""&&!(Array.isArray(J)&&J.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 J=String(X).trim();if(!/^-?\d+$/.test(J))return Z;let Y=Number.parseInt(J,10);return Number.isFinite(Y)?Y: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 J=String(X).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(J))return Z;let Y=Number.parseFloat(J);return Number.isFinite(Y)?Y: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((J)=>new Q8(J))},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((J)=>new Q8(J));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)}};Q6=Symbol.for("@stacksjs/router:route-singleton"),D5=globalThis[Q6]??=b$()});O5();N5();s8();n5();O5();p5();i8();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 j6=/[\u0000-\u001F\u007F]/;function w$($,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(j6.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 H6($,Z={}){try{return w$($,Z)}catch{return null}}O5();O5();import{timingSafeEqual as L6}from"crypto";import{Buffer as P$}from"buffer";import H8 from"process";var Y9="signature",J9="expires";function v$(){let $=H8.env.APP_KEY||H8.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 y$($,Z){return new Bun.CryptoHasher("sha256",Z).update($).digest("hex")}function F6($,Z){let W=P$.from($.toLowerCase(),"hex"),X=P$.from(Z.toLowerCase(),"hex");if(W.length!==X.length)return!1;return L6(W,X)}function V6($){let Z=new URL($.toString());return Z.searchParams.delete(Y9),Z}function f$($){let Z=V6($);return Z.searchParams.sort(),Z.toString()}function g$($,Z={}){let W=v$(),X=$.startsWith("http")?new URL($):new URL($.startsWith("/")?$:`/${$}`,H8.env.APP_URL||"https://localhost");if(Z.ttl!==void 0&&Z.expiresAt!==void 0)A6("dual-expiry","[router] signUrl: both `ttl` and `expiresAt` provided \u2014 using `ttl`.");if(Z.ttl!==void 0)X.searchParams.set(J9,String(Math.floor(Date.now()/1000)+Z.ttl));else if(Z.expiresAt!==void 0)X.searchParams.set(J9,String(Math.floor(Z.expiresAt)));let J=f$(X);return X.searchParams.set(Y9,y$(J,W)),X.toString()}var k$=new Set;function A6($,Z){if(k$.has($))return;k$.add($),console.warn(Z)}function I6($,Z={},W={}){return g$(X9($,Z),W)}function h$($){let Z=typeof $==="string"?new URL($,H8.env.APP_URL||"https://localhost"):$,W=Z.searchParams.get(Y9);if(!W)return{valid:!1,reason:"missing-signature"};let X=Z.searchParams.get(J9);if(X!==null){let J=Number.parseInt(X,10);if(!Number.isFinite(J)||Date.now()/1000>J)return{valid:!1,reason:"expired"}}try{let J=y$(f$(Z),v$());return F6(W,J)?{valid:!0}:{valid:!1,reason:"invalid-signature"}}catch{return{valid:!1,reason:"invalid-signature"}}}async function _6($){let Z=h$($.url);if(Z.valid)return;let W=Z.reason==="expired"?410:401;throw Response.json({error:Z.reason},{status:W})}import{decrypt as D6,encrypt as O6}from"@stacksjs/security";class L8{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);if(this.inner.touch)await this.inner.touch($,X,W);else await this.inner.set($,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 J=await this.unwrap(X);if(J)Z[W]=J}return Z}async length(){if(this.inner.length)return this.inner.length();return Object.keys(await this.all()).length}async clear(){if(this.inner.clear)return this.inner.clear();let $=await this.inner.all?.()??{};await Promise.all(Object.keys($).map((Z)=>this.inner.destroy(Z)))}async wrap($,Z){let{id:W,...X}=Z,J=await O6(JSON.stringify(X),this.opts.appKey);return{_enc:!0,id:W??$,data:J}}async unwrap($){if(!$||typeof $!=="object")return null;let Z=$;if(Z._enc===!0&&typeof Z.data==="string")try{let W=await D6(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 K6}from"@stacksjs/bun-router";import{DatabaseSessionStore as S6,FileSessionStore as N6,MemorySessionStore as x6,RedisSessionStore as C6,createSessionStore as E6}from"@stacksjs/bun-router";function M6($){let Z=K6($);if(!T6($.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 L8(Z,{appKey:X})}function T6($){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(),u$(_9));$(Z)}}).catch(()=>{});export{r$ as withTraceId,I$ as warnOnMultipleRouterInstances,_6 as verifySignedUrlMiddleware,h$ as verifySignedUrl,X9 as url,F9 as trackQuery,Y6 as stream,I6 as signedUrl,g$ as signUrl,ZZ as setCurrentRequest,B6 as serverResponse,U6 as serve,w$ as sanitizePathParam,H6 as safePathParam,_8 as runWithRequest,n1 as routeParams,D5 as route,WZ as request,S1 as rateLimitStatus,n8 as rateLimit,z$ as loadRoutes,O$ as listRegisteredRoutes,a as isApiRequest,e1 as installMiddlewareHotReload,a$ as getTraceId,V9 as getQueryShapeCounts,t as getCurrentRequest,x$ as findUnresolvableRouteMiddleware,A9 as createValidationErrorResponse,M6 as createStacksSessionStore,b$ as createStacksRouter,E6 as createSessionStore,I9 as createNotFoundResponse,j5 as createMiddlewareErrorResponse,l as createErrorResponse,l5 as clearTrackedQueries,N1 as clearRateLimit,T$ as clearMiddlewareCache,$Z as cacheRequestQuery,C$ as assertRouteMiddlewareResolvable,C6 as RedisSessionStore,g as PathParamError,h5 as Middleware,x6 as MemorySessionStore,m5 as JSON_CONTENT_TYPE,N6 as FileSessionStore,L8 as EncryptedSessionStore,S6 as DatabaseSessionStore};
|
|
14
|
+
`,{status:V,headers:{"Content-Type":"text/html; charset=utf-8"}})}}async function N0($,F){let W=$.statusCode??$.status??500,V=M();if(W>=400&&W<500){let G=$.headers?{...$.headers,...O()}:O();return new Response(P({error:$.name||"ClientError",message:$.message,status:W}),{status:W,headers:G})}if(V)return await J($,F,{status:W});return new Response(P({error:"Internal Server Error",message:"An unexpected error occurred.",status:W}),{status:W,headers:O()})}function O0($,F){return new Response(P({error:"ValidationError",message:"Validation failed",status:422,details:{errors:$}}),{status:422,headers:O()})}async function L0($,F){if(M()){let V=Error(`Route not found: ${$}`);return V.name="NotFoundError",await J(V,F,{status:404})}if(z(F))return new Response(P({error:"NotFound",message:`Route not found: ${$}`,status:404}),{status:404,headers:O()});return new Response(A(404),{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}var X=50,t=5,w,S,W0,Z0=10,G0="[Circular]";var _=f(()=>{b();H();w=Symbol.for("stacks.queryTracking"),S=v();W0=["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"]});export*from"@stacksjs/bun-router";import("@stacksjs/database").then(({setQueryTracker:$})=>{if(typeof $==="function"){let{trackQuery:F}=(_(),E(Q));$(F)}}).catch(()=>{});export{p0 as withTraceId,g0 as warnOnMultipleRouterInstances,D1 as verifySignedUrlMiddleware,Y1 as verifySignedUrl,k0 as url,W1 as trackQuery,K1 as stream,m1 as signedUrl,J1 as signUrl,c0 as setCurrentRequest,R0 as serverResponse,y0 as serve,w1 as sanitizePathParam,v1 as safePathParam,i0 as runWithRequest,B1 as routeParams,T0 as route,d0 as request,P1 as rateLimitStatus,M1 as rateLimit,a0 as loadRoutes,G1 as listRegisteredRoutes,N1 as isApiRequest,_0 as installMiddlewareHotReload,q0 as getTraceId,V1 as getQueryShapeCounts,l0 as getCurrentRequest,Q0 as findUnresolvableRouteMiddleware,F1 as createValidationErrorResponse,A1 as createStacksSessionStore,S0 as createStacksRouter,C1 as createSessionStore,$1 as createNotFoundResponse,e0 as createMiddlewareErrorResponse,r0 as createErrorResponse,t0 as clearTrackedQueries,X1 as clearRateLimit,A0 as clearMiddlewareCache,E0 as cacheRequestQuery,C0 as assertRouteMiddlewareResolvable,T1 as RedisSessionStore,I1 as PathParamError,u0 as Middleware,_1 as MemorySessionStore,O1 as JSON_CONTENT_TYPE,Q1 as FileSessionStore,U1 as EncryptedSessionStore,S1 as DatabaseSessionStore};
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/router",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"
|
|
4
|
+
"sideEffects": false,
|
|
5
|
+
"version": "0.70.85",
|
|
5
6
|
"description": "The Stacks framework router.",
|
|
6
7
|
"author": "Chris Breuer",
|
|
7
8
|
"contributors": [
|
|
@@ -56,15 +57,15 @@
|
|
|
56
57
|
"@stacksjs/bun-router": "0.0.17"
|
|
57
58
|
},
|
|
58
59
|
"devDependencies": {
|
|
59
|
-
"@stacksjs/actions": "0.70.
|
|
60
|
-
"@stacksjs/config": "0.70.
|
|
60
|
+
"@stacksjs/actions": "0.70.85",
|
|
61
|
+
"@stacksjs/config": "0.70.85",
|
|
61
62
|
"better-dx": "^0.2.16",
|
|
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.
|
|
63
|
+
"@stacksjs/error-handling": "0.70.85",
|
|
64
|
+
"@stacksjs/logging": "0.70.85",
|
|
65
|
+
"@stacksjs/orm": "0.70.85",
|
|
66
|
+
"@stacksjs/path": "0.70.85",
|
|
67
|
+
"@stacksjs/storage": "0.70.85",
|
|
68
|
+
"@stacksjs/types": "0.70.85",
|
|
69
|
+
"@stacksjs/validation": "0.70.85"
|
|
69
70
|
}
|
|
70
71
|
}
|