@stacksjs/actions 0.70.44 → 0.70.45
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/{chunk-6x1m5rkr.js → chunk-4fz2qb8b.js} +1 -1
- package/dist/{chunk-wv5yb5wb.js → chunk-4p0rjazd.js} +2 -2
- package/dist/{chunk-tc935b45.js → chunk-77pta9ww.js} +1 -1
- package/dist/{chunk-aw6d8zr3.js → chunk-cqedfbaf.js} +1 -1
- package/dist/{chunk-h93n2j40.js → chunk-d5yxdz7e.js} +1 -1
- package/dist/{chunk-60qjz7zb.js → chunk-h0hfqr1p.js} +1 -1
- package/dist/{chunk-67y94dzt.js → chunk-h5rff0v9.js} +1 -1
- package/dist/chunk-jbvvb45k.js +3 -0
- package/dist/chunk-kr2k0h74.js +16 -0
- package/dist/chunk-s03z9zn3.js +920 -0
- package/dist/{chunk-n1y0gpv6.js → chunk-sxp97zys.js} +1 -1
- package/dist/{chunk-7bpdkc40.js → chunk-tzx3h4r8.js} +1 -1
- package/dist/{chunk-n2x7v39b.js → chunk-vek18p55.js} +1 -1
- package/dist/{chunk-wnrgcx3d.js → chunk-yh15ydty.js} +1 -1
- package/dist/{chunk-x471rxrn.js → chunk-yvva7qsg.js} +1 -1
- package/dist/{chunk-rdajkt2s.js → chunk-zaw01rqz.js} +1 -1
- package/dist/{chunk-schcaf73.js → chunk-zbhjh5sz.js} +1 -1
- package/dist/src/action.js +1 -1
- package/dist/src/actions.js +1 -1
- package/dist/src/add.js +1 -1
- package/dist/src/ai/request-model-access.js +1 -1
- package/dist/src/build.js +1 -1
- package/dist/src/commit.js +1 -1
- package/dist/src/deploy/index.js +2 -2
- package/dist/src/dev/api.js +1 -1
- package/dist/src/dev/dashboard-globals.js +1 -1
- package/dist/src/dev/dashboard-utils.js +1 -1
- package/dist/src/dev/dashboard.js +4 -4
- package/dist/src/dev/index.js +1 -1
- package/dist/src/dev/views.js +1 -1
- package/dist/src/discover-packages.js +1 -1
- package/dist/src/examples.js +1 -1
- package/dist/src/generate/component-meta.js +1 -1
- package/dist/src/generate/env-files.js +1 -1
- package/dist/src/generate/ide-helpers.js +1 -1
- package/dist/src/generate/index.js +1 -1
- package/dist/src/generate/lib-entries.js +1 -1
- package/dist/src/generate/vscode-custom-data.js +1 -1
- package/dist/src/helpers/component-meta.js +1 -1
- package/dist/src/helpers/index.js +1 -1
- package/dist/src/helpers/lib-entries.js +1 -1
- package/dist/src/helpers/package-json.js +1 -1
- package/dist/src/helpers/utils.js +1 -1
- package/dist/src/helpers/vscode-custom-data.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/make-command.js +1 -1
- package/dist/src/make-job.js +1 -1
- package/dist/src/make-policy.js +1 -1
- package/dist/src/make-resource.js +1 -1
- package/dist/src/make.js +1 -1
- package/dist/src/orm/base.js +1 -1
- package/dist/src/release.js +1 -1
- package/dist/src/run-action.js +1 -1
- package/dist/src/scaffold-crud.js +1 -1
- package/dist/src/setup/index.js +1 -1
- package/dist/src/setup/ssl.js +1 -1
- package/dist/src/stacks.js +1 -1
- package/dist/src/templates.js +1 -1
- package/dist/src/types.js +1 -1
- package/dist/src/upgrade/dependencies.js +1 -1
- package/dist/src/upgrade/framework-utils.js +1 -1
- package/dist/src/upgrade/framework.js +1 -1
- package/dist/src/upgrade/index.js +1 -1
- package/dist/src/upgrade.js +1 -1
- package/package.json +16 -16
- package/dist/chunk-96b7fcmd.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{aa as R}from"./chunk-3086k7zk.js";import{Ya as L}from"./chunk-
|
|
2
|
+
import{aa as R}from"./chunk-3086k7zk.js";import{Ya as L}from"./chunk-sxp97zys.js";import{ib as b}from"./chunk-jbvvb45k.js";import J from"process";import{italic as X,runCommand as V}from"@stacksjs/cli";import{ExitCode as Y}from"@stacksjs/types";import{localUrl as j}from"@stacksjs/config";import{Action as P}from"@stacksjs/enums";import{handleError as W}from"@stacksjs/error-handling";import{log as B}from"@stacksjs/logging";import{frameworkPath as D,path as Z,resolve as U}from"@stacksjs/path";import{createFolder as _,doesFolderExist as K,writeTextFile as w}from"@stacksjs/storage";import{template as f}from"@stacksjs/strings";var M=!1;function Iq(z){M=Boolean(z)}function Jq(){return M}function x(z,...q){return f(R[z],...q)}async function A(z,q){if(M){let G=q.split(`
|
|
3
3
|
`),H=G.slice(0,60).map((I)=>` ${I}`).join(`
|
|
4
4
|
`),Q=G.length>60?`
|
|
5
5
|
${X(`\u2026 ${G.length-60} more lines elided`)}`:"";B.info(`[dry-run] would write ${z} (${G.length} lines)`),J.stdout.write(`${H}${Q}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./chunk-xg9xscqz.js";import{gb as $Q}from"./chunk-96b7fcmd.js";import{watch as V0}from"fs";import CQ from"fs/promises";import wQ from"path";import AQ from"process";import{existsSync as pY,statSync as mY}from"fs";import{existsSync as E0,mkdirSync as c9,readdirSync as l9,readFileSync as O0,writeFileSync as n9}from"fs";import{homedir as bQ}from"os";import{dirname as o9,resolve as zQ}from"path";import fX from"process";import{existsSync as gY,statSync as uY}from"fs";import{existsSync as BY,mkdirSync as D0,readdirSync as T0,writeFileSync as S0}from"fs";import{homedir as yQ}from"os";import{dirname as cY,resolve as ZQ}from"path";import kQ from"process";import{join as N0,relative as C0,resolve as lY}from"path";import OX from"process";import{existsSync as SZ,mkdirSync as _$,readdirSync as G$,writeFileSync as J$}from"fs";import{homedir as iX}from"os";import{dirname as W$,resolve as YQ}from"path";import aQ from"process";import{join as k0,relative as x0,resolve as nY}from"path";import DX from"process";import{existsSync as NZ,mkdirSync as L$,readdirSync as K$,writeFileSync as j$}from"fs";import{dirname as R$,resolve as TX}from"path";import qY from"process";import{Buffer as SQ}from"buffer";import{createCipheriv as P0,createDecipheriv as b0,randomBytes as sX}from"crypto";import{closeSync as oX,createReadStream as iY,createWriteStream as y0,existsSync as rX,fsyncSync as sY,openSync as oY,writeFileSync as v0}from"fs";import{access as d0,constants as rY,mkdir as h0,readdir as GX,rename as tY,stat as vQ,unlink as JX,writeFile as tX}from"fs/promises";import{join as dQ}from"path";import a from"process";import{pipeline as f0}from"stream/promises";import{createGzip as aY}from"zlib";import hQ from"process";import MQ from"process";import{Buffer as IQ}from"buffer";import{createCipheriv as p0,createDecipheriv as m0,randomBytes as aX}from"crypto";import{closeSync as eX,createReadStream as eY,createWriteStream as g0,existsSync as UX,fsyncSync as QZ,openSync as XZ,writeFileSync as u0}from"fs";import{access as c0,constants as YZ,mkdir as l0,readdir as HX,rename as ZZ,stat as fQ,unlink as WX,writeFile as QY}from"fs/promises";import{isAbsolute as n0,join as pQ,resolve as i0}from"path";import k from"process";import{pipeline as s0}from"stream/promises";import{createGzip as $Z}from"zlib";import mQ from"process";import VQ from"process";import AX from"process";import{existsSync as zX}from"fs";import{resolve as XY}from"path";import{existsSync as o0}from"fs";import{existsSync as r0,readdirSync as t0}from"fs";import{extname as YY,resolve as _Z}from"path";import a0 from"process";import{join as e0,relative as Q8,resolve as GZ}from"path";import SX from"process";import{Buffer as FQ}from"buffer";import{createCipheriv as X8,createDecipheriv as Y8,randomBytes as ZY}from"crypto";import{closeSync as $Y,createReadStream as JZ,createWriteStream as Z8,existsSync as BX,fsyncSync as UZ,openSync as HZ,writeFileSync as $8}from"fs";import{access as _8,constants as WZ,mkdir as G8,readdir as qX,rename as AZ,stat as gQ,unlink as LX,writeFile as _Y}from"fs/promises";import{isAbsolute as J8,join as uQ,resolve as U8}from"path";import x from"process";import{pipeline as H8}from"stream/promises";import{createGzip as zZ}from"zlib";import cQ from"process";import EQ from"process";import KX from"process";import{existsSync as jX}from"fs";import{resolve as GY}from"path";import{existsSync as W8}from"fs";var{serve:M0,Glob:fY}=globalThis.Bun;class CZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),_=Z??this.options.ttl,G=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:_,hits:0,size:G}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!pY(Q))return!0;return mY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=pY(Y)?mY(Y):null,_=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:_},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class kZ{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let _=await X(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...Y}),_}catch(_){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...Y}),_}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,_)=>$+_,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var NX=new CZ,OY=new kZ,A8=Object.defineProperty,z8=(Q)=>Q;function B8(Q,X){this[Q]=z8.bind(null,X)}var q8=(Q,X)=>{for(var Y in X)A8(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:B8.bind(X,Y)})},L8=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),xZ={};q8(xZ,{withErrorRecovery:()=>yZ,tryLoadConfig:()=>h8,loadConfigWithResult:()=>v8,loadConfig:()=>pZ,isRetryableError:()=>C8,isConfigNotFoundError:()=>N8,isBunfigError:()=>vZ,globalPerformanceMonitor:()=>XX,globalCache:()=>nQ,getEnvOrDefault:()=>k8,generateConfigTypes:()=>f8,defaultGeneratedDir:()=>sZ,defaultConfigDir:()=>iZ,deepMergeWithArrayStrategy:()=>CY,deepMerge:()=>dZ,createLibraryConfig:()=>p8,config:()=>d8,bunfigPlugin:()=>m8,applyEnvVarsToConfig:()=>tQ,TypeGenerationError:()=>FY,SchemaValidationError:()=>QX,PluginError:()=>VY,PerformanceMonitor:()=>TY,FileSystemError:()=>IY,ErrorFactory:()=>NQ,EnvVarError:()=>yX,EnvProcessor:()=>pX,ConfigValidator:()=>kY,ConfigValidationError:()=>wY,ConfigNotFoundError:()=>bX,ConfigMergeError:()=>RY,ConfigLoader:()=>xY,ConfigLoadError:()=>eQ,ConfigFileLoader:()=>mX,ConfigCache:()=>DY,CacheUtils:()=>gZ,BunfigError:()=>JQ,BrowserConfigError:()=>MY,ArrayMergeStrategies:()=>lZ});class DY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),_=Z??this.options.ttl,G=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:_,hits:0,size:G}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!gY(Q))return!0;return uY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=gY(Y)?uY(Y):null,_=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:_},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class TY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let _=await X(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...Y}),_}catch(_){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...Y}),_}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,_)=>$+_,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K8(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j8(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function w8(Q){return Q.getStats().size*2}function SY(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&f(X[0])&&"id"in X[0]&&X[0].id===3&&f(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(f(X)&&f(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(f(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&f(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&f(X[0])&&f(Q[0])){let Z=[...X];for(let $ of Q)if(f($)&&"name"in $){if(!Z.find((G)=>f(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(f($)&&"path"in $){if(!Z.find((G)=>f(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((_)=>CX(_,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!f(X)||!f(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(f($)&&f(Y[Z]))Y[Z]=SY(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&f($[0])&&f(Y[Z][0])){let _=[...$];for(let G of Y[Z])if(f(G)&&"name"in G){if(!_.find((J)=>f(J)&&("name"in J)&&J.name===G.name))_.push(G)}else if(f(G)&&"path"in G){if(!_.find((J)=>f(J)&&("path"in J)&&J.path===G.path))_.push(G)}else if(!_.some((U)=>CX(U,G)))_.push(G);Y[Z]=_}else if($.every((_)=>typeof _==="string")&&Y[Z].every((_)=>typeof _==="string")){let _=[...$];for(let G of Y[Z])if(!_.includes(G))_.push(G);Y[Z]=_}else Y[Z]=$;else Y[Z]=$}return Y}function CX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!CX(Q[Y],X[Y]))return!1;return!0}if(f(Q)&&f(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!CX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function R8(Q,X){if(!NZ(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return SY(X,Z)}catch{return null}}catch{return null}}async function I8({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||qY.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],_=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of _)for(let U of $){let J=TX(Z,`${G}${U}`),H=await R8(J,Y);if(H!==null)return H}try{let G=TX(Z,"package.json");if(NZ(G)){let J=(await import(G))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return SY(Y,J)}catch{}}}catch{}return Y}function F8(Q,X={}){let Y=DX.cwd();while(Y.includes("storage"))Y=nY(Y,"..");let Z=nY(Y,Q||"");if(X?.relative)return x0(DX.cwd(),Z);return Z}async function M8(){try{let Q=await I8({name:"clarity",defaultConfig:FX,cwd:DX.cwd(),endpoint:"",headers:{}});return{...FX,...Q}}catch{return FX}}function g(){if(MQ.env.NODE_ENV==="test"||MQ.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V8(){if(MQ.env.NODE_ENV==="test"||MQ.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof MQ<"u"){let Q=MQ.type;if(Q==="renderer"||Q==="worker")return!1;return!!(MQ.versions&&(MQ.versions.node||MQ.versions.bun))}return!1}class PZ{async format(Q){let X=await V8(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:hQ.pid,hostname:X(),environment:hQ.env.NODE_ENV||"development",platform:hQ.platform,version:hQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hQ.env.NODE_ENV||hQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...KY},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new PZ,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??a.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),_=this.generateKey();this.currentKeyId=$,this.keys.set($,_),this.encryptionKeys.set($,{key:_,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...MX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...MX};return{...MX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:KY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,_=0,G=3,U=1000;while(_<G)try{try{try{await d0(this.config.logDirectory,rY.F_OK|rY.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await h0(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:SQ.from(Q);try{if(!rX(this.currentLogFile))await tX(this.currentLogFile,"",{mode:420});if($=oY(this.currentLogFile,"a",420),v0($,J,{flag:"a"}),sY($),$!==void 0)oX($),$=void 0;if((await vQ(this.currentLogFile)).size===0){if(await tX(this.currentLogFile,J,{flag:"w",mode:420}),(await vQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let W=H;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(_<G-1){let A=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${G}:`,A);let B=U*2**_;await new Promise((z)=>setTimeout(z,B)),_++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if($!==void 0)try{oX($)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(J){if(_===G-1){let W=J,A=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}_++;let H=U*2**(_-1);await new Promise((W)=>setTimeout(W,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 dQ(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 dQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return dQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(g())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,U],[,J])=>J.createdAt.getTime()-U.createdAt.getTime()),_=typeof X.maxKeys==="number"?X.maxKeys:1,G=Math.max(1,_);if($.length>G)for(let[U]of $.slice(G))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return sX(16).toString("hex")}generateKey(){return sX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=sX(16),Z=P0("aes-256-gcm",X,Y),$=SQ.concat([Z.update(Q,"utf8"),Z.final()]),_=Z.getAuthTag();return{encrypted:SQ.concat([Y,$,_]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=aY(),$=[];Z.on("data",(_)=>$.push(_)),Z.on("end",()=>X(SQ.from(SQ.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(g())return;let Q=await vQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await GX(this.config.logDirectory),_=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,H)=>{let W=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),G=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,U=`${Y}.${G}`;if(await vQ(Y).catch(()=>null))try{if(await tY(Y,U),X.compress)try{let J=`${U}.gz`;await this.compressLogFile(U,J),await JX(U)}catch(J){console.error("Error compressing rotated file:",J)}if(_.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await tX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),_=Y.replace(/\.log$/,`-${$}.log`);if(await vQ(Y).catch(()=>null))await tY(Y,_)}if(this.currentLogFile=Z,X.maxFiles){let _=(await GX(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,U)=>U.localeCompare(G));for(let G of _.slice(X.maxFiles))await JX(dQ(this.config.logDirectory,G))}}}async compressLogFile(Q,X){let Y=iY(Q),Z=y0(X),$=aY();await f0(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),rX(this.currentLogFile))try{let Q=oY(this.currentLogFile,"r+");sY(Q),oX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await GX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await JX(dQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?h.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:_,showTimestamp:G=!0}=Q,U=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(G)z.push(X);if(_==="warning")z.push("WARN");else if(_==="error")z.push("ERROR");else if(Y)z.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)z.push(Z.replace(/[[\]]/g,""));return z.push($),z.join(" ")}let J=a.stdout.columns||120,H="";if(_==="warning"||_==="error")H=`${Y} ${$}`;else if(_==="info"||_==="success")H=`${Y} ${Z} ${$}`;else H=`${Y} ${Z} ${h.cyan($)}`;if(!G)return H.trim();let W=U(H).trim().length,A=U(X).length,B=Math.max(1,J-2-W-A);return`${H.trim()}${" ".repeat(B)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(_,G)=>{let U=Number.parseInt(G,10);return U<X[0].length?String(X[0][U]):_});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(_,G)=>{if(G==="%")return"%";if(Z>=X.length)return _;let U=X[Z++];switch(G){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return _}});if(Z<X.length)$+=` ${X.slice(Z).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),G,U;if(X instanceof Error)G=X.message,U=X.stack;else G=this.formatMessage(X,Y);if(this.fancy&&!g()){let H=uZ[Q],W=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:h.gray(G),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:G,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:h.green(G),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:G,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:G,level:Q}),console.error(A),U){let B=U.split(`
|
|
3
|
+
import"./chunk-xg9xscqz.js";import{ib as $Q}from"./chunk-jbvvb45k.js";import{watch as V0}from"fs";import CQ from"fs/promises";import wQ from"path";import AQ from"process";import{existsSync as pY,statSync as mY}from"fs";import{existsSync as E0,mkdirSync as c9,readdirSync as l9,readFileSync as O0,writeFileSync as n9}from"fs";import{homedir as bQ}from"os";import{dirname as o9,resolve as zQ}from"path";import fX from"process";import{existsSync as gY,statSync as uY}from"fs";import{existsSync as BY,mkdirSync as D0,readdirSync as T0,writeFileSync as S0}from"fs";import{homedir as yQ}from"os";import{dirname as cY,resolve as ZQ}from"path";import kQ from"process";import{join as N0,relative as C0,resolve as lY}from"path";import OX from"process";import{existsSync as SZ,mkdirSync as _$,readdirSync as G$,writeFileSync as J$}from"fs";import{homedir as iX}from"os";import{dirname as W$,resolve as YQ}from"path";import aQ from"process";import{join as k0,relative as x0,resolve as nY}from"path";import DX from"process";import{existsSync as NZ,mkdirSync as L$,readdirSync as K$,writeFileSync as j$}from"fs";import{dirname as R$,resolve as TX}from"path";import qY from"process";import{Buffer as SQ}from"buffer";import{createCipheriv as P0,createDecipheriv as b0,randomBytes as sX}from"crypto";import{closeSync as oX,createReadStream as iY,createWriteStream as y0,existsSync as rX,fsyncSync as sY,openSync as oY,writeFileSync as v0}from"fs";import{access as d0,constants as rY,mkdir as h0,readdir as GX,rename as tY,stat as vQ,unlink as JX,writeFile as tX}from"fs/promises";import{join as dQ}from"path";import a from"process";import{pipeline as f0}from"stream/promises";import{createGzip as aY}from"zlib";import hQ from"process";import MQ from"process";import{Buffer as IQ}from"buffer";import{createCipheriv as p0,createDecipheriv as m0,randomBytes as aX}from"crypto";import{closeSync as eX,createReadStream as eY,createWriteStream as g0,existsSync as UX,fsyncSync as QZ,openSync as XZ,writeFileSync as u0}from"fs";import{access as c0,constants as YZ,mkdir as l0,readdir as HX,rename as ZZ,stat as fQ,unlink as WX,writeFile as QY}from"fs/promises";import{isAbsolute as n0,join as pQ,resolve as i0}from"path";import k from"process";import{pipeline as s0}from"stream/promises";import{createGzip as $Z}from"zlib";import mQ from"process";import VQ from"process";import AX from"process";import{existsSync as zX}from"fs";import{resolve as XY}from"path";import{existsSync as o0}from"fs";import{existsSync as r0,readdirSync as t0}from"fs";import{extname as YY,resolve as _Z}from"path";import a0 from"process";import{join as e0,relative as Q8,resolve as GZ}from"path";import SX from"process";import{Buffer as FQ}from"buffer";import{createCipheriv as X8,createDecipheriv as Y8,randomBytes as ZY}from"crypto";import{closeSync as $Y,createReadStream as JZ,createWriteStream as Z8,existsSync as BX,fsyncSync as UZ,openSync as HZ,writeFileSync as $8}from"fs";import{access as _8,constants as WZ,mkdir as G8,readdir as qX,rename as AZ,stat as gQ,unlink as LX,writeFile as _Y}from"fs/promises";import{isAbsolute as J8,join as uQ,resolve as U8}from"path";import x from"process";import{pipeline as H8}from"stream/promises";import{createGzip as zZ}from"zlib";import cQ from"process";import EQ from"process";import KX from"process";import{existsSync as jX}from"fs";import{resolve as GY}from"path";import{existsSync as W8}from"fs";var{serve:M0,Glob:fY}=globalThis.Bun;class CZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),_=Z??this.options.ttl,G=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:_,hits:0,size:G}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!pY(Q))return!0;return mY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=pY(Y)?mY(Y):null,_=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:_},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class kZ{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let _=await X(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...Y}),_}catch(_){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...Y}),_}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,_)=>$+_,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var NX=new CZ,OY=new kZ,A8=Object.defineProperty,z8=(Q)=>Q;function B8(Q,X){this[Q]=z8.bind(null,X)}var q8=(Q,X)=>{for(var Y in X)A8(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:B8.bind(X,Y)})},L8=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),xZ={};q8(xZ,{withErrorRecovery:()=>yZ,tryLoadConfig:()=>h8,loadConfigWithResult:()=>v8,loadConfig:()=>pZ,isRetryableError:()=>C8,isConfigNotFoundError:()=>N8,isBunfigError:()=>vZ,globalPerformanceMonitor:()=>XX,globalCache:()=>nQ,getEnvOrDefault:()=>k8,generateConfigTypes:()=>f8,defaultGeneratedDir:()=>sZ,defaultConfigDir:()=>iZ,deepMergeWithArrayStrategy:()=>CY,deepMerge:()=>dZ,createLibraryConfig:()=>p8,config:()=>d8,bunfigPlugin:()=>m8,applyEnvVarsToConfig:()=>tQ,TypeGenerationError:()=>FY,SchemaValidationError:()=>QX,PluginError:()=>VY,PerformanceMonitor:()=>TY,FileSystemError:()=>IY,ErrorFactory:()=>NQ,EnvVarError:()=>yX,EnvProcessor:()=>pX,ConfigValidator:()=>kY,ConfigValidationError:()=>wY,ConfigNotFoundError:()=>bX,ConfigMergeError:()=>RY,ConfigLoader:()=>xY,ConfigLoadError:()=>eQ,ConfigFileLoader:()=>mX,ConfigCache:()=>DY,CacheUtils:()=>gZ,BunfigError:()=>JQ,BrowserConfigError:()=>MY,ArrayMergeStrategies:()=>lZ});class DY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),_=Z??this.options.ttl,G=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:_,hits:0,size:G}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!gY(Q))return!0;return uY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=gY(Y)?uY(Y):null,_=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:_},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class TY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let _=await X(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...Y}),_}catch(_){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...Y}),_}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,_)=>$+_,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K8(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j8(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function w8(Q){return Q.getStats().size*2}function SY(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&f(X[0])&&"id"in X[0]&&X[0].id===3&&f(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(f(X)&&f(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(f(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&f(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&f(X[0])&&f(Q[0])){let Z=[...X];for(let $ of Q)if(f($)&&"name"in $){if(!Z.find((G)=>f(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(f($)&&"path"in $){if(!Z.find((G)=>f(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((_)=>CX(_,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!f(X)||!f(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(f($)&&f(Y[Z]))Y[Z]=SY(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&f($[0])&&f(Y[Z][0])){let _=[...$];for(let G of Y[Z])if(f(G)&&"name"in G){if(!_.find((J)=>f(J)&&("name"in J)&&J.name===G.name))_.push(G)}else if(f(G)&&"path"in G){if(!_.find((J)=>f(J)&&("path"in J)&&J.path===G.path))_.push(G)}else if(!_.some((U)=>CX(U,G)))_.push(G);Y[Z]=_}else if($.every((_)=>typeof _==="string")&&Y[Z].every((_)=>typeof _==="string")){let _=[...$];for(let G of Y[Z])if(!_.includes(G))_.push(G);Y[Z]=_}else Y[Z]=$;else Y[Z]=$}return Y}function CX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!CX(Q[Y],X[Y]))return!1;return!0}if(f(Q)&&f(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!CX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function R8(Q,X){if(!NZ(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return SY(X,Z)}catch{return null}}catch{return null}}async function I8({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||qY.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],_=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of _)for(let U of $){let J=TX(Z,`${G}${U}`),H=await R8(J,Y);if(H!==null)return H}try{let G=TX(Z,"package.json");if(NZ(G)){let J=(await import(G))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return SY(Y,J)}catch{}}}catch{}return Y}function F8(Q,X={}){let Y=DX.cwd();while(Y.includes("storage"))Y=nY(Y,"..");let Z=nY(Y,Q||"");if(X?.relative)return x0(DX.cwd(),Z);return Z}async function M8(){try{let Q=await I8({name:"clarity",defaultConfig:FX,cwd:DX.cwd(),endpoint:"",headers:{}});return{...FX,...Q}}catch{return FX}}function g(){if(MQ.env.NODE_ENV==="test"||MQ.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V8(){if(MQ.env.NODE_ENV==="test"||MQ.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof MQ<"u"){let Q=MQ.type;if(Q==="renderer"||Q==="worker")return!1;return!!(MQ.versions&&(MQ.versions.node||MQ.versions.bun))}return!1}class PZ{async format(Q){let X=await V8(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:hQ.pid,hostname:X(),environment:hQ.env.NODE_ENV||"development",platform:hQ.platform,version:hQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hQ.env.NODE_ENV||hQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...KY},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new PZ,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??a.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),_=this.generateKey();this.currentKeyId=$,this.keys.set($,_),this.encryptionKeys.set($,{key:_,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...MX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...MX};return{...MX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:KY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,_=0,G=3,U=1000;while(_<G)try{try{try{await d0(this.config.logDirectory,rY.F_OK|rY.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await h0(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:SQ.from(Q);try{if(!rX(this.currentLogFile))await tX(this.currentLogFile,"",{mode:420});if($=oY(this.currentLogFile,"a",420),v0($,J,{flag:"a"}),sY($),$!==void 0)oX($),$=void 0;if((await vQ(this.currentLogFile)).size===0){if(await tX(this.currentLogFile,J,{flag:"w",mode:420}),(await vQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let W=H;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(_<G-1){let A=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${G}:`,A);let B=U*2**_;await new Promise((z)=>setTimeout(z,B)),_++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if($!==void 0)try{oX($)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(J){if(_===G-1){let W=J,A=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}_++;let H=U*2**(_-1);await new Promise((W)=>setTimeout(W,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 dQ(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 dQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return dQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(g())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,U],[,J])=>J.createdAt.getTime()-U.createdAt.getTime()),_=typeof X.maxKeys==="number"?X.maxKeys:1,G=Math.max(1,_);if($.length>G)for(let[U]of $.slice(G))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return sX(16).toString("hex")}generateKey(){return sX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=sX(16),Z=P0("aes-256-gcm",X,Y),$=SQ.concat([Z.update(Q,"utf8"),Z.final()]),_=Z.getAuthTag();return{encrypted:SQ.concat([Y,$,_]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=aY(),$=[];Z.on("data",(_)=>$.push(_)),Z.on("end",()=>X(SQ.from(SQ.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(g())return;let Q=await vQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await GX(this.config.logDirectory),_=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,H)=>{let W=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),G=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,U=`${Y}.${G}`;if(await vQ(Y).catch(()=>null))try{if(await tY(Y,U),X.compress)try{let J=`${U}.gz`;await this.compressLogFile(U,J),await JX(U)}catch(J){console.error("Error compressing rotated file:",J)}if(_.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await tX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),_=Y.replace(/\.log$/,`-${$}.log`);if(await vQ(Y).catch(()=>null))await tY(Y,_)}if(this.currentLogFile=Z,X.maxFiles){let _=(await GX(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,U)=>U.localeCompare(G));for(let G of _.slice(X.maxFiles))await JX(dQ(this.config.logDirectory,G))}}}async compressLogFile(Q,X){let Y=iY(Q),Z=y0(X),$=aY();await f0(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),rX(this.currentLogFile))try{let Q=oY(this.currentLogFile,"r+");sY(Q),oX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await GX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await JX(dQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?h.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:_,showTimestamp:G=!0}=Q,U=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(G)z.push(X);if(_==="warning")z.push("WARN");else if(_==="error")z.push("ERROR");else if(Y)z.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)z.push(Z.replace(/[[\]]/g,""));return z.push($),z.join(" ")}let J=a.stdout.columns||120,H="";if(_==="warning"||_==="error")H=`${Y} ${$}`;else if(_==="info"||_==="success")H=`${Y} ${Z} ${$}`;else H=`${Y} ${Z} ${h.cyan($)}`;if(!G)return H.trim();let W=U(H).trim().length,A=U(X).length,B=Math.max(1,J-2-W-A);return`${H.trim()}${" ".repeat(B)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(_,G)=>{let U=Number.parseInt(G,10);return U<X[0].length?String(X[0][U]):_});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(_,G)=>{if(G==="%")return"%";if(Z>=X.length)return _;let U=X[Z++];switch(G){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return _}});if(Z<X.length)$+=` ${X.slice(Z).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),G,U;if(X instanceof Error)G=X.message,U=X.stack;else G=this.formatMessage(X,Y);if(this.fancy&&!g()){let H=uZ[Q],W=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:h.gray(G),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:G,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:h.green(G),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:G,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:H,tag:W,message:G,level:Q}),console.error(A),U){let B=U.split(`
|
|
4
4
|
`);for(let z of B)if(z.trim()&&!z.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:h.gray(` ${z}`),level:Q,showTimestamp:!1}))}break}}else if(!g()){if(console.error(`${_} ${this.environment}.${Q.toUpperCase()}: ${G}`),U)console.error(U)}if(!this.shouldLog(Q))return;let J=`${_} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
5
5
|
`;if(U)J+=`${U}
|
|
6
6
|
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!g()){let Y=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:h.blue("\u25D0"),tag:Y,message:`${h.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),_=`${Q} completed in ${$}ms`,G=new Date,U=this.formatConsoleTimestamp(G),H=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${_}`;if(Y)H+=` ${JSON.stringify(Y)}`;if(H+=`
|
|
@@ -61,7 +61,7 @@ export type ConfigOf = Config
|
|
|
61
61
|
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
62
62
|
`;return Y}}function O9(Q,X,Y={}){return $0(Q,X,Y,new WeakMap)}function $0(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:_=!1,customMerger:G}=Y;if(X===null||X===void 0)return _?Q:X;if(G){let U=G(Q,X);if(U!==void 0)return U}if(Array.isArray(X)||Array.isArray(Q))return _0(Q,X,$,Z);if(!qQ(X)||!qQ(Q))return X;return N9(Q,X,Y,Z)}function _0(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return D9(Q,X);case"smart":return T9(Q,X,Z);default:return X}return X}function D9(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>EY($,Z)))Y.push(Z);return Y}function T9(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(qQ(X[0])&&qQ(Q[0]))return S9(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function S9(Q,X,Y){let Z=[...X];for(let $ of Q){if(!qQ($)){Z.push($);continue}let _=["id","name","key","path","type"],G=!1;for(let U of _)if(U in $){if(Z.find((H)=>qQ(H)&&(U in H)&&H[U]===$[U])){G=!0;break}}if(!G)Z.push($)}return Z}function N9(Q,X,Y,Z){let $=X;if(qQ($)&&Z.has($))return Z.get($);let _={...Q};if(qQ($))Z.set($,_);for(let G in $){if(!Object.prototype.hasOwnProperty.call($,G))continue;let U=$[G],J=_[G];if(Y.skipNullish&&(U===null||U===void 0))continue;if(U===null||U===void 0){_[G]=U;continue}if(qQ(U)&&qQ(J))_[G]=$0(J,U,Y,Z);else if(Array.isArray(U)||Array.isArray(J))_[G]=_0(J,U,Y.arrayMergeMode||"smart",Z);else _[G]=U}return _}function G0(Q,X,Y="replace"){return O9(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function EY(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!EY(Q[Y],X[Y]))return!1;return!0}if(qQ(Q)&&qQ(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!EY(Q[$],X[$]))return!1}return!0}return!1}function qQ(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class J0{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:_,trackPerformance:G=!0,verbose:U=!1}=Y;if($){let H=NX.getWithFileCheck("file",Q);if(H){if(U)console.log(`Configuration loaded from cache: ${Q}`);return H}}let J=async()=>{if(!jX(Q))return null;try{let H=`?t=${Date.now()}`,W=await import(Q+H),A=W.default||W,B="default"in W,z=Object.keys(W).length>0;if(!B&&!z)throw new dX(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new dX(Q,Error("Configuration must export a valid object"),"unknown");let C={config:G0(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)NX.setWithFileCheck("file",C,Q,_);return C}catch(H){throw H instanceof Error?iQ.configLoad(Q,H):iQ.configLoad(Q,Error(String(H)))}};if(G)return OY.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let _ of Z)for(let G of this.extensions)$.push(GY(X,`${_}${G}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);let Z=X===void 0?[]:Array.isArray(X)?X:[X];for(let _ of Z){if(!_)continue;if(Y.push(_,`.${_}.config`,`${_}.config`,`.${_}`),Q)Y.push(`${Q}.${_}.config`,`.${Q}.${_}.config`)}let $=new Set;return Y.filter((_)=>{if(!_||$.has(_))return!1;return $.add(_),!0})}checkFileAccess(Q){return E9(async()=>{return jX(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!jX(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let _ of $)for(let G of this.extensions){let U=GY(Q,`${_}${G}`);if(await this.checkFileAccess(U))Z.push(U)}}else try{let{readdirSync:$}=await import("fs"),_=$(Q);for(let G of _)if(this.looksLikeConfigFile(G)){let U=GY(Q,G);if(await this.checkFileAccess(U))Z.push(U)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!jX(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),_=$(Q,"utf8");JSON.parse(_)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var C9=/^https?:\/\//;class U0{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:_=!0,customRules:G=[],trackPerformance:U=!0,verbose:J=!1}=Y,H=async()=>{let W=[],A=[],B={stopOnFirstError:Z,validateRequired:$,validateTypes:_,customRules:G,trackPerformance:U,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,B);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...G],B);else return this.validateWithJSONSchema(Q,X,B)}catch(z){return W.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:W,warnings:A}}};if(U)return await OY.track("validateConfiguration",H);return H()}async validateWithSchemaFile(Q,X,Y){try{if(!W8(X))throw new hX(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new hX(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,_){if(_.validateTypes&&X.type){let G=Array.isArray(Q)?"array":typeof Q,U=Array.isArray(X.type)?X.type:[X.type];if(!U.includes(G)){if(Z.push({path:Y,message:`Expected type ${U.join(" or ")}, got ${G}`,expected:U.join(" or "),actual:G,rule:"type"}),_.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),_.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let G=0;G<Q.length;G++){let U=Y?`${Y}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],X.items,U,Z,$,_),_.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(_.validateRequired&&X.required){for(let U of X.required)if(!(U in G)){if(Z.push({path:Y?`${Y}.${U}`:U,message:`Missing required property '${U}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if(X.properties){for(let[U,J]of Object.entries(X.properties))if(U in G){let H=Y?`${Y}.${U}`:U;if(this.validateObjectAgainstSchema(G[U],J,H,Z,$,_),_.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let U=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(G))if(!U.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let _ of X)try{let G=this.getValueByPath(Q,_.path),U=this.validateWithRule(G,_,_.path);if(Z.push(...U),Y.stopOnFirstError&&Z.length>0)break}catch(G){Z.push({path:_.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,_,G]=Z;X.push({path:$,required:!_,type:this.mapTypeScriptType(G)})}return X}mapTypeScriptType(Q){switch(Q.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:C9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var RQ=new gX("bunfig",{showTags:!0});function k9(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class H0{fileLoader=new J0;envProcessor=new bY;validator=new U0;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:_,...G}=Q;try{if(Y?.enabled){let J=this.checkCache(G.name||"",G);if(J)return J}let U;try{U=await this.loadConfigurationStrategies(G,!0,Y)}catch(J){let H=G.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(H)throw J;U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let W=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!W&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),B=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(H&&(B||W))throw J;if(A&&(!H||!B))U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!H)U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||_)await this.validateConfiguration(U.config,$,_,G.name);if(Y?.enabled&&U)this.cacheResult(G.name||"",U,Y,G);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:G.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)RQ.warn(`Slow configuration loading detected: ${J.duration}ms for ${G.name}`);U.metrics=J}return U}catch(U){if(U instanceof Error&&U.name==="ConfigNotFoundError")throw U;let J=Date.now()-X;throw RQ.error(`Configuration loading failed after ${J}ms:`,[U instanceof Error?U:Error(String(U))]),U}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:_,configDir:G,defaultConfig:U,checkEnv:J=!0,arrayStrategy:H="replace",verbose:W=!1}=Q,A=_||fX.cwd(),B=[],z=await this.loadLocalConfiguration(Z,$,A,G,U,H,W,J,Y);if(z)return B.push(...this.getLocalSearchPaths(Z,$,A,G)),this.finalizeResult(z,B,J,Z,W);let S=await this.loadHomeConfiguration(Z,$,U,H,W,J);if(S)return B.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(S,B,J,Z,W);let R=await this.loadPackageJsonConfiguration(Z,$,A,U,H,W,J);if(R)return B.push(zQ(A,"package.json")),this.finalizeResult(R,B,J,Z,W);if(B.push(...this.getAllSearchPaths(Z,$,A,G)),X)throw iQ.configNotFound(Z,B,$);return{...await this.applyEnvironmentVariables(Z,U,J,W),warnings:[`No configuration file found for "${Z}"${k9($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,_,G,U,J){let H=U?RX(Q,$,G):$,W=this.getLocalDirectories(Y,Z);for(let A of W){if(G)RQ.info(`Searching for configuration in: ${A}`);let B=this.fileLoader.generateConfigPaths(Q,A,X),z=await this.fileLoader.tryLoadFromPaths(B,H,{arrayStrategy:_,verbose:G,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(z){if(G)RQ.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,_){if(!Q)return null;let G=_?RX(Q,Y,$):Y,U=[zQ(bQ(),".config",Q),zQ(bQ(),".config"),bQ()];for(let J of U){if($)RQ.info(`Checking home directory: ${J}`);let H=this.fileLoader.generateConfigPaths(Q,J,X),W=await this.fileLoader.tryLoadFromPaths(H,G,{arrayStrategy:Z,verbose:$});if(W){if($)RQ.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,_,G){let U=G?RX(Q,Z,_):Z;try{let J=zQ(Y,"package.json");if(!E0(J))return null;let H={};try{H=JSON.parse(O0(J,"utf8"))}catch(B){if(_)RQ.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let W=H[Q],A=Q;if(!W&&X){let B=Array.isArray(X)?X:[X];for(let z of B){if(!z)continue;if(H[z]){W=H[z],A=z;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(_)RQ.success(`Configuration loaded from package.json: ${A}`);return{config:G0(U,W,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(_)RQ.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:RX(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let _=Y(Q);if(_)$.push(..._)}if(X){let _=await this.validator.validateConfiguration(Q,X);if(!_.isValid)$.push(..._.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if($.length>0)throw iQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return NX.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);NX.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,zQ(Q,"config"),zQ(Q,".config"),X?zQ(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(zQ(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),_=[];for(let G of $)_.push(...this.fileLoader.generateConfigPaths(Q,G,X));return _}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[zQ(bQ(),".config",Q),zQ(bQ(),".config"),bQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var zY=new H0;async function DZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await zY.loadConfig(Q);else Z=await zY.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",_=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||_.includes("config"))&&Q.verbose)RQ.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let U=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await zY.applyEnvironmentVariables(U.name||"",X,!0,U.verbose||!1))?.config??X;return X}}function RX(Q,X,Y=!1){let Z=new bY,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(G,U=[]){let J={...G};for(let[H,W]of Object.entries(G)){let A=[...U,H],B=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((R)=>R.toUpperCase()).join("")}`,`${$}_${A.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,S;for(let R of B)if(z=fX.env[R],z!==void 0){S=R;break}if(z!==void 0&&S)if(typeof W==="boolean")J[H]=["true","1","yes"].includes(z.toLowerCase());else if(typeof W==="number"){let R=Number(z);if(!Number.isNaN(R))J[H]=R}else if(Array.isArray(W))try{J[H]=JSON.parse(z)}catch{J[H]=z.split(",").map((R)=>R.trim())}else J[H]=z;else if(W&&typeof W==="object"&&!Array.isArray(W))J[H]=_(W,A)}return J}return _(X)}var V_=zQ(fX.cwd(),"config"),E_=zQ(fX.cwd(),"src/generated"),x9=import("@stacksjs/stx"),lQ={partialsDir:"partials",componentsDir:"components",layoutsDir:"layouts",publicDir:"public",ssr:!0,defaultTitle:"stx App"},TZ={css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",html:"text/html; charset=utf-8",txt:"text/plain",xml:"application/xml",pdf:"application/pdf",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp",mp4:"video/mp4",webm:"video/webm",ogg:"audio/ogg",mp3:"audio/mpeg",wav:"audio/wav",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject"};async function O_(Q){let X=await DZ({name:"stx",cwd:AQ.cwd(),defaultConfig:lQ}),Y=Q.componentsDir??X.componentsDir??lQ.componentsDir,Z=Q.layoutsDir??X.layoutsDir??lQ.layoutsDir,$=Q.partialsDir??X.partialsDir??lQ.partialsDir,_=Q.publicDir??X.publicDir??"public",G=Q.stxModule?Promise.resolve(Q.stxModule):x9,{patterns:U,port:J=3456}=Q;if(U.length===0)throw console.error("Usage: serve <files...> [--port 3000]"),console.error(`
|
|
63
63
|
Examples:`),console.error(" serve pages/*.stx"),console.error(" serve pages/*.md"),console.error(" serve pages/*.html"),console.error(" serve pages/ --port 3000"),console.error(" serve index.stx about.md page.html"),console.error(`
|
|
64
|
-
After installing: bun add bun-plugin-stx`),Error("No file patterns provided");let H=new Map,W=null,A=!1,B=new Set,z=(L)=>{if(B.has(L))return;try{V0(L,{recursive:!0},(q,j)=>{if(!j)return;let M=String(j);if(!M.endsWith(".stx")&&!M.endsWith(".md")&&!M.endsWith(".html"))return;W=null,H.clear()}).on("error",()=>{}),B.add(L)}catch{}},S=new Map,R=[];function C(L){let K=[],q=L.split("/").map((j)=>{if(!j)return"";let M=j.match(/^\[\.\.\.(.+)\]$/);if(M)return K.push(M[1]),"(.+)";let I=j.match(/^\[(.+)\]$/);if(I)return K.push(I[1]),"([^/]+)";return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{re:new RegExp(`^${q}/?$`),names:K}}function s(L){let K=L;for(let q of U){let j=q.replace(/\/$/,"");if(K.startsWith(`${j}/`)){K=K.slice(j.length+1);break}}if(K=K.replace(/\.(stx|md|html)$/,""),K==="index"||K.endsWith("/index"))K=K.replace(/\/?index$/,"");return K.startsWith("/")?K:`/${K}`}async function o(L){try{let q=(await CQ.readFile(L,"utf-8")).match(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/);if(!q)return;let j=q[0].match(/middleware\s*:\s*(\[[^\]]*\]|['"][^'"]+['"])/);if(!j)return;let M=j[1].startsWith("[")?Array.from(j[1].matchAll(/['"]([^'"]+)['"]/g)).map((V)=>V[1]):[j[1].replace(/['"]/g,"")];if(M.length===0)return;let I=s(L);if(I.includes("[")){let{re:V,names:T}=C(I);R.push({re:V,names:T,middleware:M})}else S.set(I,M)}catch{}}function LQ(L){let K=S.get(L);if(K)return{names:K,params:{}};let q=L.replace(/\/$/,"");if(q!==L){let j=S.get(q);if(j)return{names:j,params:{}}}for(let j of R){let M=j.re.exec(L);if(M){let I={};return j.names.forEach((V,T)=>{I[V]=decodeURIComponent(M[T+1]??"")}),{names:j.middleware,params:I}}}return{names:[],params:{}}}function UQ(L){let K={},q=L.headers.get("cookie")||"";if(!q)return K;for(let j of q.split(/;\s*/)){let M=j.indexOf("=");if(M===-1)continue;let I=j.slice(0,M);if(!I)continue;try{K[I]=decodeURIComponent(j.slice(M+1))}catch{K[I]=j.slice(M+1)}}return K}function HQ(L,K,q=""){let j=L.includes("?")?"&":"?",M=encodeURIComponent(K+q);return Response.redirect(`${L}${j}next=${M}`,302)}let DQ=Q.auth===!1?null:Q.auth??{},yY=DQ?.cookieName??"auth-token",W0=DQ?.redirectTo??"/login",A0=DQ?.home??"/",z0=DQ?.protectedPaths??[],B0={...DQ===null?{}:{auth:(L,K)=>{if(!K.cookies[yY])return K.redirect(W0);return null},guest:(L,K)=>{if(K.cookies[yY])return Response.redirect(A0,302);return null}},...Q.middleware??{}};function q0(L){let K=[],q=Q.middlewareGroups??{},j=new Set,M=(I)=>{if(j.has(I))return;j.add(I);let V=q[I];if(V)V.forEach(M);else K.push(I)};return L.forEach(M),K}let L0=Q.globalMiddleware??[];async function uX(){if(W!==null)return W;let L=[],K=[".stx",".md",".html"];for(let q of U)try{if((await CQ.stat(q).catch(()=>null))?.isDirectory()){z(q);let M=["layouts","components","partials"];if(Z)M.push(Z.replace(/^.*\//,""));if(Y)M.push(Y.replace(/^.*\//,""));if($)M.push($.replace(/^.*\//,""));for(let I of[".stx",".md",".html"]){let V=new fY(`**/*${I}`),T=await Array.fromAsync(V.scan({cwd:q,followSymlinks:!0}));L.push(...T.filter((y)=>!M.some((u)=>y.startsWith(`${u}/`))).map((y)=>`${q}/${y}`.replace(/\/+/g,"/")))}}else if(q.includes("*")){let M=new fY(q),I=q.split("*")[0].replace(/\/$/,""),V=await Array.fromAsync(M.scan({cwd:I||".",followSymlinks:!0}));L.push(...V.map((T)=>I?`${I}/${T}`:T))}else if(K.some((M)=>q.endsWith(M)))L.push(q)}catch(j){console.error(`Error processing pattern "${q}":`,j)}W=L,S.clear(),R.length=0,await Promise.all(L.map((q)=>o(q)));try{let{Router:q}=await import("./chunk-
|
|
64
|
+
After installing: bun add bun-plugin-stx`),Error("No file patterns provided");let H=new Map,W=null,A=!1,B=new Set,z=(L)=>{if(B.has(L))return;try{V0(L,{recursive:!0},(q,j)=>{if(!j)return;let M=String(j);if(!M.endsWith(".stx")&&!M.endsWith(".md")&&!M.endsWith(".html"))return;W=null,H.clear()}).on("error",()=>{}),B.add(L)}catch{}},S=new Map,R=[];function C(L){let K=[],q=L.split("/").map((j)=>{if(!j)return"";let M=j.match(/^\[\.\.\.(.+)\]$/);if(M)return K.push(M[1]),"(.+)";let I=j.match(/^\[(.+)\]$/);if(I)return K.push(I[1]),"([^/]+)";return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{re:new RegExp(`^${q}/?$`),names:K}}function s(L){let K=L;for(let q of U){let j=q.replace(/\/$/,"");if(K.startsWith(`${j}/`)){K=K.slice(j.length+1);break}}if(K=K.replace(/\.(stx|md|html)$/,""),K==="index"||K.endsWith("/index"))K=K.replace(/\/?index$/,"");return K.startsWith("/")?K:`/${K}`}async function o(L){try{let q=(await CQ.readFile(L,"utf-8")).match(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/);if(!q)return;let j=q[0].match(/middleware\s*:\s*(\[[^\]]*\]|['"][^'"]+['"])/);if(!j)return;let M=j[1].startsWith("[")?Array.from(j[1].matchAll(/['"]([^'"]+)['"]/g)).map((V)=>V[1]):[j[1].replace(/['"]/g,"")];if(M.length===0)return;let I=s(L);if(I.includes("[")){let{re:V,names:T}=C(I);R.push({re:V,names:T,middleware:M})}else S.set(I,M)}catch{}}function LQ(L){let K=S.get(L);if(K)return{names:K,params:{}};let q=L.replace(/\/$/,"");if(q!==L){let j=S.get(q);if(j)return{names:j,params:{}}}for(let j of R){let M=j.re.exec(L);if(M){let I={};return j.names.forEach((V,T)=>{I[V]=decodeURIComponent(M[T+1]??"")}),{names:j.middleware,params:I}}}return{names:[],params:{}}}function UQ(L){let K={},q=L.headers.get("cookie")||"";if(!q)return K;for(let j of q.split(/;\s*/)){let M=j.indexOf("=");if(M===-1)continue;let I=j.slice(0,M);if(!I)continue;try{K[I]=decodeURIComponent(j.slice(M+1))}catch{K[I]=j.slice(M+1)}}return K}function HQ(L,K,q=""){let j=L.includes("?")?"&":"?",M=encodeURIComponent(K+q);return Response.redirect(`${L}${j}next=${M}`,302)}let DQ=Q.auth===!1?null:Q.auth??{},yY=DQ?.cookieName??"auth-token",W0=DQ?.redirectTo??"/login",A0=DQ?.home??"/",z0=DQ?.protectedPaths??[],B0={...DQ===null?{}:{auth:(L,K)=>{if(!K.cookies[yY])return K.redirect(W0);return null},guest:(L,K)=>{if(K.cookies[yY])return Response.redirect(A0,302);return null}},...Q.middleware??{}};function q0(L){let K=[],q=Q.middlewareGroups??{},j=new Set,M=(I)=>{if(j.has(I))return;j.add(I);let V=q[I];if(V)V.forEach(M);else K.push(I)};return L.forEach(M),K}let L0=Q.globalMiddleware??[];async function uX(){if(W!==null)return W;let L=[],K=[".stx",".md",".html"];for(let q of U)try{if((await CQ.stat(q).catch(()=>null))?.isDirectory()){z(q);let M=["layouts","components","partials"];if(Z)M.push(Z.replace(/^.*\//,""));if(Y)M.push(Y.replace(/^.*\//,""));if($)M.push($.replace(/^.*\//,""));for(let I of[".stx",".md",".html"]){let V=new fY(`**/*${I}`),T=await Array.fromAsync(V.scan({cwd:q,followSymlinks:!0}));L.push(...T.filter((y)=>!M.some((u)=>y.startsWith(`${u}/`))).map((y)=>`${q}/${y}`.replace(/\/+/g,"/")))}}else if(q.includes("*")){let M=new fY(q),I=q.split("*")[0].replace(/\/$/,""),V=await Array.fromAsync(M.scan({cwd:I||".",followSymlinks:!0}));L.push(...V.map((T)=>I?`${I}/${T}`:T))}else if(K.some((M)=>q.endsWith(M)))L.push(q)}catch(j){console.error(`Error processing pattern "${q}":`,j)}W=L,S.clear(),R.length=0,await Promise.all(L.map((q)=>o(q)));try{let{Router:q}=await import("./chunk-tzx3h4r8.js"),j=U[0]?.replace(/\/$/,"")||"pages",M=new q(AQ.cwd(),{pagesDir:j});console.log(`[stx] Generated ${M.routes.length} routes \u2192 .stx/routes.ts`)}catch(q){}return L}async function K0(){if(A)return;A=!0;let L="./resources/assets",K="./.stx/assets";try{if(await CQ.stat(L).then(()=>!0).catch(()=>!1))await CQ.rm(K,{recursive:!0,force:!0}),await CQ.cp(L,K,{recursive:!0})}catch{}}let vY=new Map;async function j0(L){for(let[K,q]of L){let j=await CQ.stat(K).catch(()=>null);if(!j||j.mtimeMs!==q)return!1}return!0}async function w0(L,K){let q=new Map,j=[L,...K],M=await Promise.all(j.map((I)=>CQ.stat(I).catch(()=>null)));for(let I=0;I<j.length;I++){let V=M[I];if(V)q.set(j[I],V.mtimeMs)}return q}let sQ=null,dY=!1,cX=null,hY=new Map;async function R0(){if(dY)return sQ;dY=!0;try{let L=await import("./chunk-h5rff0v9.js");return sQ={CSSGenerator:L.CSSGenerator,config:L.config},sQ}catch{try{let K=await import(wQ.join(AQ.env.HOME||"","Code/Tools/crosswind/packages/crosswind/src/index.ts"));return sQ={CSSGenerator:K.CSSGenerator,config:K.config},sQ}catch{return null}}}async function b9(L){try{let K=await R0();if(!K)return"";let q=/class\s*=\s*["']([^"']+)["']/gi,j=new Set,M=q.exec(L);while(M!==null){for(let w of M[1].split(/\s+/))if(w.trim())j.add(w.trim());M=q.exec(L)}let I=/(?:x-class|:class)\s*=\s*"([^"]+)"/gi,V=I.exec(L);while(V!==null){let w=V[1].match(/'([^']+)'/g);if(w)for(let p of w){let m=p.slice(1,-1);for(let O of m.split(/\s+/))if(O.trim())j.add(O.trim())}V=I.exec(L)}if(j.size===0)return"";if(!cX)cX=DZ({name:"crosswind",cwd:AQ.cwd(),defaultConfig:{}});let T=await cX;if(T.safelist)for(let w of T.safelist)j.add(w);let y=[...j].sort().join(" "),u=hY.get(y);if(u!==void 0)return u;let c={...K.config,preflight:!0,minify:!1};if(T.shortcuts)c.shortcuts={...c.shortcuts||{},...T.shortcuts};if(T.theme)c.theme={...c.theme||{},...T.theme};let F=new K.CSSGenerator(c);for(let w of j)F.generate(w);let E="",P=c.shortcuts||{};for(let[w,p]of Object.entries(P)){if(!j.has(w))continue;let m=p.split(/\s+/).filter(Boolean);for(let O of m)F.generate(O)}let N=F.toCSS(!0,!1);for(let[w,p]of Object.entries(P)){if(!j.has(w))continue;let m=p.split(/\s+/).filter(Boolean),O=[],_Q=[];for(let XQ of m){let xQ=XQ.startsWith("dark:"),oQ=(xQ?XQ.slice(5):XQ).replace(/[/:.[\]%()]/g,(TQ)=>`\\${TQ}`),r=new RegExp(`\\.${oQ}\\s*\\{([^}]+)\\}`),GQ=N.match(r);if(GQ)if(xQ)_Q.push(GQ[1].trim());else O.push(GQ[1].trim())}if(O.length)E+=`.${w} { ${O.join(" ")} }
|
|
65
65
|
`;if(_Q.length)E+=`@media (prefers-color-scheme: dark) { .dark .${w} { ${_Q.join(" ")} } }
|
|
66
66
|
`}let D=N+E;return hY.set(y,D),D}catch(K){return console.warn("Failed to generate Crosswind CSS:",K),""}}async function lX(L){let K=vY.get(L);if(K&&await j0(K.signature))return K.html;let q=await Bun.file(L).text(),j=/<script\b([^>]*)\bserver\b[^>]*>([\s\S]*?)<\/script>/gi,M=[],I;while((I=j.exec(q))!==null)M.push(I[2]);let V=q.replace(/<script\b[^>]*\bserver\b[^>]*>[\s\S]*?<\/script>/gi,""),T={__filename:L,__dirname:wQ.dirname(L)},{processDirectives:y,extractVariables:u,defaultConfig:c,generateSpaShell:F,injectRouterScript:E,resetHead:P}=await G;P();for(let O of M)await u(O,T,L);T.__stx_head_preset=!0;let N={...c,...Y&&{componentsDir:Y},...Z&&{layoutsDir:Z},...$&&{partialsDir:$},autoShell:!0,ssr:X.ssr??lQ.ssr??!0,app:X.app||{},..."strict"in X&&{strict:X.strict},..."router"in X&&{router:X.router},..."skipDefaultSeoTags"in X&&{skipDefaultSeoTags:X.skipDefaultSeoTags},..."defaultTitle"in X&&{defaultTitle:X.defaultTitle},..."defaultDescription"in X&&{defaultDescription:X.defaultDescription},..."defaultImage"in X&&{defaultImage:X.defaultImage},..."seo"in X&&{seo:X.seo}};if(N.ssr===!1||X.ssr===!1)return F({template:V,context:T,title:X.defaultTitle??"stx App"});let D=V,w=new Set;D=await y(D,T,L,N,w),D=await E(D);let p=/@for|:for|@if|:if|x-for|x-if/;if(/<template\s[^>]*(?:@for|:for|@if|:if|x-for|x-if)/.test(D))D=D.replace(/<template(?:\s[^>]*)?>|<\/template>/gi,(O)=>{if(p.test(O))return O;if(O==="</template>")return O;return""});else D=D.replace(/<template[^>]*>/gi,"").replace(/<\/template>/gi,"");if(!T.__stx_skip_cache){let O=await w0(L,w);vY.set(L,{html:D,signature:O})}return D}async function YX(L){let K=await uX(),q=L.startsWith("/")?L.slice(1):L,j=[];for(let I of[".stx",".md",".html",""]){let V=q.endsWith(I)?q:`${q}${I}`;j.push(V)}if(q==="")j.push("index.stx"),j.push("index.md"),j.push("index.html");else j.push(`${q}/index.stx`),j.push(`${q}/index.md`),j.push(`${q}/index.html`);let M=wQ.basename(q,wQ.extname(q));if(M&&!q.includes("/"))j.push(`${M}.stx`),j.push(`${M}.md`),j.push(`${M}.html`);for(let I of j)for(let V of K){let T=V.replace(/^\.\//,"").replace(/\\/g,"/"),y=T;for(let u of U){let c=u.replace(/\\/g,"/").replace(/\/$/,"");if(T.startsWith(`${c}/`)){y=T.slice(c.length+1);break}}if(T===I||y===I)return await lX(V)}for(let I of K){let V=I.replace(/^\.\//,"").replace(/\\/g,"/"),T=V;for(let F of U){let E=F.replace(/\\/g,"/").replace(/\/$/,"");if(V.startsWith(`${E}/`)){T=V.slice(E.length+1);break}}let y=T.replace(/\.(stx|md|html)$/,""),u=y==="index"||y.endsWith("/index"),c=L==="/"||q==="";if(`/${y}`===L||y===q||`/${y}.stx`===L||`/${y}.md`===L||`/${y}.html`===L||u&&c){let F=await lX(I);return H.set(L,F),F}if(y.startsWith("pages/")){let F=y.slice(6);if(`/${F}`===L||F===q){let E=await lX(I);return H.set(L,E),E}}}for(let I of K){let V=I.replace(/^\.\//,"").replace(/\\/g,"/");if(!V.includes("["))continue;let T=V;for(let F of U){let E=F.replace(/\\/g,"/").replace(/\/$/,"");if(V.startsWith(`${E}/`)){T=V.slice(E.length+1);break}}let y=T.replace(/\.(stx|md|html)$/,""),u=y.replace(/\[([^\]]+)\]/g,"([^/]+)").replace(/\//g,"\\/"),c=[new RegExp(`^${u}$`)];if(y.startsWith("pages/")){let F=y.slice(6).replace(/\[([^\]]+)\]/g,"([^/]+)").replace(/\//g,"\\/");c.push(new RegExp(`^${F}$`))}for(let F of c){let E=q.match(F);if(E){let P=[...y.matchAll(/\[([^\]]+)\]/g)].map((w)=>w[1]),N=E.slice(1),D=await I0(I,P,N,q);return H.set(L,D),D}}}return null}async function I0(L,K,q,j){let M=await Bun.file(L).text(),I=/<script\b([^>]*)\bserver\b[^>]*>([\s\S]*?)<\/script>/gi,V=[],T;while((T=I.exec(M))!==null)V.push(T[2]);let y=M.replace(/<script\b[^>]*\bserver\b[^>]*>[\s\S]*?<\/script>/gi,""),u={__filename:L,__dirname:wQ.dirname(L),__route:j};for(let O=0;O<K.length;O++)u[K[O]]=q[O];let{processDirectives:c,extractVariables:F,defaultConfig:E,injectRouterScript:P,resetHead:N}=await G;N();for(let O of V)await F(O,u,L);u.__stx_head_preset=!0;let D={...E,...Y&&{componentsDir:Y},...Z&&{layoutsDir:Z},...$&&{partialsDir:$},autoShell:!0,ssr:X.ssr??lQ.ssr??!0,app:X.app||{},..."strict"in X&&{strict:X.strict},..."router"in X&&{router:X.router},..."skipDefaultSeoTags"in X&&{skipDefaultSeoTags:X.skipDefaultSeoTags},..."defaultTitle"in X&&{defaultTitle:X.defaultTitle},..."defaultDescription"in X&&{defaultDescription:X.defaultDescription},..."defaultImage"in X&&{defaultImage:X.defaultImage},..."seo"in X&&{seo:X.seo}},w=y;if(w=await c(w,u,L,D,new Set),K.length>0){let O={};for(let XQ=0;XQ<K.length;XQ++)O[K[XQ]]=q[XQ];let _Q=`<script>if(window.stx)window.stx._rp=${JSON.stringify(O)};else window.__stx_rp=${JSON.stringify(O)};</script>`;if(w.includes("</head>"))w=w.replace("</head>",`${_Q}
|
|
67
67
|
</head>`);else w=`${_Q}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ib as L}from"./chunk-jbvvb45k.js";import C from"process";import{log as D}from"@stacksjs/cli";async function S(){try{return(await import("./chunk-vek18p55.js")).tsCloud||null}catch{return null}}async function N(){let G=await S();return{name:G?.project?.name||"stacks",region:G?.project?.region||"us-east-1"}}async function b(G){try{let{AWSClient:Q}=await import("@stacksjs/ts-cloud"),J=new Q,_=new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}),K=await J.request({service:"sts",region:G,method:"POST",path:"/",body:_.toString()}),j=String(K).match(/<Account>(\d+)<\/Account>/);if(j&&j[1])return j[1];return C.env.AWS_ACCOUNT_ID||""}catch(Q){return C.env.AWS_ACCOUNT_ID||""}}async function f(G){let{environment:Q}=G,J=await S();if(!J)throw Error("Cloud configuration not found. Ensure config/cloud.ts exports tsCloud.");let{InfrastructureGenerator:_}=await import("@stacksjs/ts-cloud"),j=new _({config:J,environment:Q}).generate().getBuilder().build();return JSON.stringify(j)}function v(G){let Q={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m"};if(G.includes("COMPLETE")&&!G.includes("ROLLBACK"))return`${Q.green}${G}${Q.reset}`;if(G.includes("IN_PROGRESS"))return`${Q.yellow}${G}${Q.reset}`;if(G.includes("FAILED")||G.includes("ROLLBACK"))return`${Q.red}${G}${Q.reset}`;if(G.includes("DELETE"))return`${Q.gray}${G}${Q.reset}`;return G}async function p(G){let{region:Q,domain:J,sslDomains:_,hostedZoneId:K,albDnsName:j,stackName:Y}=G;console.log(""),console.log("Setting up SSL certificate...");try{let{Route53Client:$,ACMClient:w,AWSClient:F}=await import("@stacksjs/ts-cloud"),M=new $(Q),V=new w(Q),W=new F;console.log(` Requesting SSL certificate for ${J}...`);let P=await V.requestCertificate({DomainName:_[0]??J,SubjectAlternativeNames:_.length>1?_.slice(1):void 0,ValidationMethod:"DNS"});console.log(` Certificate ARN: ${P.CertificateArn}`),await new Promise((R)=>setTimeout(R,5000));let U=await V.describeCertificate({CertificateArn:P.CertificateArn});console.log(" Adding DNS validation records...");for(let R of U.DomainValidationOptions||[])if(R.ResourceRecord)await M.changeResourceRecordSets({HostedZoneId:K,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:R.ResourceRecord.Name,Type:"CNAME",TTL:300,ResourceRecords:[{Value:R.ResourceRecord.Value}]}}]}});console.log("\u2713 Validation records added"),console.log(" Waiting for certificate validation (this may take 1-5 minutes)...");for(let R=0;R<30;R++){let Z=await V.describeCertificate({CertificateArn:P.CertificateArn});if(Z.Status==="ISSUED"){console.log("\u2713 Certificate issued!");let{AWSCloudFormationClient:A}=await import("@stacksjs/ts-cloud"),B=await new A(Q).listStackResources(Y),I=B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="ApplicationLoadBalancer")?.PhysicalResourceId,X=B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="ECSTargetGroup")?.PhysicalResourceId||B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="WebTargetGroup")?.PhysicalResourceId;if(I&&X){console.log(" Creating HTTPS listener...");let O=new URLSearchParams({Action:"CreateListener",LoadBalancerArn:I,Protocol:"HTTPS",Port:"443","Certificates.member.1.CertificateArn":P.CertificateArn,"DefaultActions.member.1.Type":"forward","DefaultActions.member.1.TargetGroupArn":X,Version:"2015-12-01"});await W.request({service:"elasticloadbalancing",region:Q,method:"POST",path:"/",body:O.toString()}),console.log("\u2713 HTTPS listener created!"),console.log(" Configuring HTTP to HTTPS redirect...");let h=new URLSearchParams({Action:"DescribeListeners",LoadBalancerArn:I,Version:"2015-12-01"}),H=await W.request({service:"elasticloadbalancing",region:Q,method:"POST",path:"/",body:h.toString()}),x=H?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member||H?.DescribeListenersResult?.Listeners?.member,T=(Array.isArray(x)?x:x?[x]:[]).find((y)=>y.Port==="80"||y.Port===80);if(T){let y=new URLSearchParams({Action:"ModifyListener",ListenerArn:T.ListenerArn,"DefaultActions.member.1.Type":"redirect","DefaultActions.member.1.RedirectConfig.Protocol":"HTTPS","DefaultActions.member.1.RedirectConfig.Port":"443","DefaultActions.member.1.RedirectConfig.StatusCode":"HTTP_301",Version:"2015-12-01"});await W.request({service:"elasticloadbalancing",region:Q,method:"POST",path:"/",body:y.toString()}),console.log("\u2713 HTTP to HTTPS redirect configured!")}}let z=B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="CloudFrontDistribution")?.PhysicalResourceId;if(z){console.log(" Updating CloudFront distribution with SSL certificate...");let O=await W.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${z}/config`}),h=O._headers?.etag||O._headers?.ETag,H=O.DistributionConfig;if(H&&h){H.Aliases={Quantity:_.length,Items:_},H.ViewerCertificate={ACMCertificateArn:P.CertificateArn,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CloudFrontDefaultCertificate:!1};let x=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
4
4
|
<CallerReference>${H.CallerReference}</CallerReference>
|
|
5
5
|
<Aliases>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ib as U}from"./chunk-jbvvb45k.js";import{frameworkPath as E,join as W,path as R,projectPath as L}from"@stacksjs/path";import{existsSync as T,globSync as j,mkdirSync as I,writeFileSync as F}from"@stacksjs/storage";import{readFileSync as v}from"fs";var $=null;async function P(){if($)return $;try{$=(await import("@stacksjs/ts-md")).parseMarkdown}catch{$=(q)=>q}return $}function M(q){if(!q)return"";return $?$(q):q}async function p(){await P();let q=j(["components/*.stx","components/**/*.stx","resources/components/**/*.stx","storage/framework/defaults/resources/components/**/*.stx"],{cwd:L(),absolute:!0}),G=E("component-meta");if(!T(G))I(G,{recursive:!0});for(let X of q){let Q=R.parse(X).name,H=B(X),z=W(G,`${Q}.json`);F(z,JSON.stringify(H,null,2))}}function B(q){let G=v(q,"utf8"),X=b(G),Q=x(G),H=X?D(X):[],z=X?f(X):[],Z=h(Q);return{props:H,events:z,slots:Z}}function b(q){let G=/<script\b[^>]*\bserver\b[^>]*>([\s\S]*?)<\/script>/i.exec(q);if(G?.[1])return G[1];return/<script\b[^>]*>([\s\S]*?)<\/script>/i.exec(q)?.[1]??null}function x(q){let G=/<template\b[^>]*>([\s\S]*?)<\/template>/i.exec(q);if(G?.[1])return G[1];return q.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"")}function D(q){let G=w(q),X=S(q,G);if(!X)return[];let Q=k(X,G),H=g(q);return Q.map((z)=>{return{name:z.required?z.name:`${z.name}?`,description:M(z.description),type:z.type,default:H[z.name]??z.default??"unknown",required:z.required}})}function w(q){let G=new Map,X=/(?:export\s+)?interface\s+([A-Z][\w$]*)\s*(?:extends\s+[\w$,\s]+)?\s*\{/g,Q;while((Q=X.exec(q))!==null){let z=Q[1];if(!z)continue;let Z=Q.index+Q[0].length,Y=K(q,Z-1,"{","}");if(Y!==null)G.set(z,Y)}let H=/(?:export\s+)?type\s+([A-Z][\w$]*)\s*=\s*\{/g;while((Q=H.exec(q))!==null){let z=Q[1];if(!z)continue;let Z=Q.index+Q[0].length,Y=K(q,Z-1,"{","}");if(Y!==null)G.set(z,Y)}return G}function S(q,G){let Q=/defineProps\s*<\s*([\s\S]+?)\s*>\s*\(/.exec(q),H=Q?.[1]?.trim();if(!Q||!H)return null;if(H.startsWith("{")){let Z=q.indexOf("{",Q.index);return K(q,Z,"{","}")}let z=H.replace(/[<>(].*$/,"").split("&")[0]?.trim();if(!z)return null;return G.get(z)??null}function k(q,G){let X=[],Q=N(q,[";",`
|
|
3
3
|
`]),H="";for(let z of Q){let Z=z.trim();if(!Z)continue;let Y=/^\/\*\*([\s\S]*?)\*\/\s*([\s\S]*)$/.exec(Z);if(Y){H=(Y[1]??"").split(`
|
|
4
4
|
`).map((A)=>A.replace(/^\s*\*\s?/,"")).join(`
|
|
5
5
|
`).trim();let C=(Y[2]??"").trim();if(!C)continue;let J=V(C,H,G);if(J)X.push(J);H="";continue}if(Z.startsWith("//")){H=Z.replace(/^\/\/\s?/,"");continue}let _=V(Z,H,G);if(_)X.push(_);H=""}return X}function V(q,G,X){if(/^[a-zA-Z_$][\w$]*\s*\(/.test(q.trimStart()))return null;let Q=/^([a-zA-Z_$][\w$]*)\s*(\??)\s*:\s*([\s\S]+?)\s*[;,]?\s*$/.exec(q);if(!Q)return null;let H=Q[1],z=Q[2]??"",Z=Q[3];if(!H||!Z)return null;return{name:H,type:O(Z),required:z!=="?",description:G}}function g(q){let G={},X=/const\s*\{\s*([\s\S]*?)\s*\}\s*=\s*(?:withDefaults\s*\(\s*)?defineProps/g,Q;while((Q=X.exec(q))!==null)if(Q[1])y(Q[1],G);let H=q.indexOf("withDefaults(");if(H>=0){let z=q.indexOf("defineProps",H);if(z>0){let Z=q.indexOf(">",z),Y=q.indexOf(")",Z>=0?Z:z);if(Y>0){let _=q.indexOf(",",Y),C=_>=0?q.indexOf("{",_):-1;if(C>0){let J=K(q,C,"{","}");if(J)u(J,G)}}}}return G}function y(q,G){for(let X of N(q,[","])){let Q=/^\s*([a-zA-Z_$][\w$]*)\s*=\s*([\s\S]+?)\s*$/.exec(X),H=Q?.[1],z=Q?.[2];if(H&&z)G[H]=O(z)}}function u(q,G){for(let X of N(q,[","])){let Q=/^\s*([a-zA-Z_$][\w$]*)\s*:\s*([\s\S]+?)\s*$/.exec(X.trim()),H=Q?.[1],z=Q?.[2];if(H&&z)G[H]=O(z)}}function f(q){let G=/defineEmits\s*<\s*\{([\s\S]*?)\}\s*>\s*\(/.exec(q);if(!G?.[1])return[];let X=[];for(let Q of N(G[1],[";",`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ib as O}from"./chunk-jbvvb45k.js";import{log as B}from"@stacksjs/logging";import*as J from"@stacksjs/path";import{doesExist as Q,get as R,writeFile as L}from"@stacksjs/storage";async function X(q){let b=q.name;if(!b)return B.error("Policy name is required"),!1;let z=b.endsWith("Policy")?b:`${b}Policy`,v=q.model||z.replace("Policy",""),I=T(z,v),H=J.appPath(`Policies/${z}.ts`);try{let G=J.appPath("Policies");if(!Q(G)){let{mkdirSync:K}=await import("@stacksjs/storage");K(G,{recursive:!0})}if(await L(H,I),B.success(`Created policy: ${H}`),q.register!==!1)await U(v,z);return!0}catch(G){return B.error(`Failed to create policy: ${G.message}`),!1}}function T(q,b){return`import type _User from '../models/User'
|
|
3
3
|
import { BasePolicy } from '@stacksjs/auth'
|
|
4
4
|
|
|
5
5
|
type UserModel = _User
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ya as o}from"./chunk-
|
|
2
|
+
import{Ya as o}from"./chunk-sxp97zys.js";import{Action as r}from"@stacksjs/enums";async function v(e){await o(r.Dev,e)}async function s(e){await o(r.Dev,e)}async function a(e){await n(e)}async function n(e){await o(r.DevApi,e)}async function D(e){await o(r.DevComponents,e)}async function p(e){await o(r.DevDashboard,e)}async function c(e){await o(r.DevSystemTray,e)}async function m(e){await o(r.DevDesktop,e)}async function u(e){await o(r.DevDocs,e)}
|
|
3
3
|
export{v as ia,s as ja,a as ka,n as la,D as ma,p as na,c as oa,m as pa,u as qa};
|