@stacksjs/query-builder 0.70.92 → 0.70.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +91 -91
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var p0=import.meta.require;import{existsSync as M5,statSync as H5}from"fs";import{existsSync as Q2,mkdirSync as nj,readdirSync as ij,readFileSync as z2,writeFileSync as lj}from"fs";import{homedir as zX}from"os";import{dirname as rj,resolve as L9}from"path";import N8 from"process";import{existsSync as C5,statSync as w5}from"fs";import{existsSync as G1,mkdirSync as L2,readdirSync as j2,writeFileSync as E2}from"fs";import{homedir as LX}from"os";import{dirname as q5,resolve as i0}from"path";import t9 from"process";import{join as G2,relative as F2,resolve as P5}from"path";import S8 from"process";import{existsSync as A6,mkdirSync as QE,readdirSync as zE,writeFileSync as LE}from"fs";import{homedir as GZ}from"os";import{dirname as GE,resolve as u0}from"path";import P$ from"process";import{join as O2,relative as J2,resolve as T5}from"path";import A8 from"process";import{existsSync as k6,mkdirSync as VE,readdirSync as IE,writeFileSync as KE}from"fs";import{dirname as DE,resolve as k8}from"path";import F1 from"process";import{Buffer as h9}from"buffer";import{createCipheriv as W2,createDecipheriv as V2,randomBytes as FZ}from"crypto";import{closeSync as OZ,createReadStream as N5,createWriteStream as I2,existsSync as JZ,fsyncSync as S5,openSync as A5,writeFileSync as K2}from"fs";import{access as R2,constants as k5,mkdir as D2,readdir as f$,rename as x5,stat as jX,unlink as g$,writeFile as WZ}from"fs/promises";import{join as EX}from"path";import b0 from"process";import{pipeline as M2}from"stream/promises";import{createGzip as B5}from"zlib";import GX from"process";import P9 from"process";import{Buffer as R9}from"buffer";import{createCipheriv as H2,createDecipheriv as C2,randomBytes as VZ}from"crypto";import{closeSync as IZ,createReadStream as y5,createWriteStream as w2,existsSync as d$,fsyncSync as h5,openSync as v5,writeFileSync as q2}from"fs";import{access as P2,constants as b5,mkdir as T2,readdir as p$,rename as f5,stat as FX,unlink as c$,writeFile as KZ}from"fs/promises";import{isAbsolute as N2,join as OX,resolve as S2}from"path";import z0 from"process";import{pipeline as A2}from"stream/promises";import{createGzip as g5}from"zlib";import JX from"process";import T9 from"process";import m$ from"process";import{existsSync as u$}from"fs";import{resolve as RZ}from"path";import{existsSync as k2}from"fs";import{existsSync as x2,readdirSync as B2}from"fs";import{extname as DZ,resolve as d5}from"path";import y2 from"process";import{join as h2,relative as v2,resolve as p5}from"path";import x8 from"process";import{Buffer as D9}from"buffer";import{createCipheriv as b2,createDecipheriv as f2,randomBytes as MZ}from"crypto";import{closeSync as HZ,createReadStream as c5,createWriteStream as g2,existsSync as n$,fsyncSync as m5,openSync as u5,writeFileSync as d2}from"fs";import{access as p2,constants as n5,mkdir as c2,readdir as i$,rename as i5,stat as WX,unlink as l$,writeFile as CZ}from"fs/promises";import{isAbsolute as m2,join as VX,resolve as u2}from"path";import L0 from"process";import{pipeline as n2}from"stream/promises";import{createGzip as l5}from"zlib";import IX from"process";import N9 from"process";import s$ from"process";import{existsSync as o$}from"fs";import{resolve as wZ}from"path";import{existsSync as i2}from"fs";import{Database as w_}from"bun:sqlite";import{mkdirSync as q_}from"fs";import{dirname as P_}from"path";import t$ from"process";import $8 from"process";import{createInterface as n_}from"readline";import{existsSync as s_,readFileSync as o_,writeFileSync as rX}from"fs";import NY from"process";import SY from"process";import{existsSync as P1,mkdirSync as IQ,writeFileSync as KQ}from"fs";import{dirname as AY,join as T1}from"path";import GU from"process";import{existsSync as g9,mkdirSync as IU,mkdtempSync as MQ,readdirSync as KU,readFileSync as RU,rmSync as HQ,unlinkSync as H8,writeFileSync as DU}from"fs";import{tmpdir as CQ}from"os";import{join as m0}from"path";import B$ from"process";import{existsSync as N1,readFileSync as yQ,unlinkSync as hQ}from"fs";import{dirname as xY,join as _5}from"path";import qU from"process";import{existsSync as PU,readdirSync as pQ}from"fs";import{dirname as BY,join as TU}from"path";import NU from"process";import{readdirSync as iQ}from"fs";import{extname as dZ,join as yY}from"path";import lQ from"process";import{readdirSync as rQ,readFileSync as hY,statSync as aQ}from"fs";import{extname as vY,join as tQ}from"path";import{writeFileSync as Xz}from"fs";import{join as $z}from"path";import Zz from"process";import{existsSync as p8,mkdirSync as Qz,readdirSync as zz,writeFileSync as Lz}from"fs";import{dirname as bY,join as c9}from"path";import y$ from"process";import{existsSync as Oz}from"fs";import{dirname as fY,join as AU}from"path";import kU from"process";import{existsSync as Rz}from"fs";import{join as Dz}from"path";import Mz from"process";import{existsSync as gY,statSync as dY}from"fs";import{join as Hz,relative as Cz,resolve as pY}from"path";import c8 from"process";import{Buffer as M9}from"buffer";import{createCipheriv as wz,createDecipheriv as qz,randomBytes as pZ}from"crypto";import{closeSync as cZ,createReadStream as cY,createWriteStream as Pz,existsSync as Z8,fsyncSync as mY,openSync as uY,writeFileSync as Tz}from"fs";import{access as Nz,constants as nY,mkdir as Sz,readdir as Y8,rename as iY,stat as RX,unlink as U8,writeFile as mZ}from"fs/promises";import{isAbsolute as Az,join as DX,resolve as kz}from"path";import F0 from"process";import{pipeline as xz}from"stream/promises";import{createGzip as lY}from"zlib";import MX from"process";import S9 from"process";import _8 from"process";import{existsSync as Q8}from"fs";import{resolve as uZ}from"path";import{existsSync as Bz}from"fs";import{existsSync as S1,mkdirSync as yz,readdirSync as hz,readFileSync as vz,writeFileSync as bz}from"fs";import{homedir as HX}from"os";import{dirname as sY,resolve as l0}from"path";import XX from"process";import{existsSync as fz,readdirSync as gz}from"fs";import{extname as nZ,resolve as oY}from"path";import dz from"process";import{spawnSync as pz}from"child_process";import{existsSync as TX,readFileSync as cz}from"fs";import{join as NX}from"path";import xU from"process";import{Database as b1}from"bun:sqlite";import{readdirSync as Xj,statSync as $j}from"fs";import{basename as Zj,extname as Yj}from"path";import Uj from"process";import{existsSync as D7,mkdirSync as Lj,writeFileSync as jj}from"fs";import{dirname as O6,join as O5}from"path";import M7 from"process";var{defineProperty:E1,getOwnPropertyNames:b7,getOwnPropertyDescriptor:f7}=Object,g7=Object.prototype.hasOwnProperty;function d7(X){return this[X]}var p7=(X)=>{var $=(K5??=new WeakMap).get(X),Z;if($)return $;if($=E1({},"__esModule",{value:!0}),X&&typeof X==="object"||typeof X==="function"){for(var Y of b7(X))if(!g7.call($,Y))E1($,Y,{get:d7.bind(X,Y),enumerable:!(Z=f7(X,Y))||Z.enumerable})}return K5.set(X,$),$},K5,c7=(X)=>X;function m7(X,$){this[X]=c7.bind(null,$)}var n1=(X,$)=>{for(var Z in $)E1(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:m7.bind($,Z)})},e=(X,$)=>()=>(X&&($=X(X=0)),$),u7=import.meta.require;function hj(X){_0={..._0,...X}}function vj(){return _0}function bj(){return typeof window<"u"&&typeof document<"u"}async function E8(){if(_0.getToken){let X=_0.getToken();return X instanceof Promise?X:X}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function c0(){let X={"Content-Type":"application/json",Accept:"application/json",..._0.headers},$=await E8();if($)X.Authorization=`Bearer ${$}`;return X}async function E9(X){if(X.status===401)throw _0.onUnauthorized?.(),new B9("Unauthorized",401);if(!X.ok){let Z=await X.json().catch(()=>({message:"Request failed"}));throw new B9(Z.message||`HTTP ${X.status}`,X.status)}let $=await X.json();if(_0.transformResponse)return _0.transformResponse($);return $}class R6{state;constructor(X){this.state={table:X,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...X){return this.state.selectColumns=X,this}where(X,$,Z){if(Z===void 0)this.state.wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this.state.wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this.state.wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this.state.wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}andWhere(X,$,Z){return this.where(X,$,Z)}whereNull(X){return this.where(X,"is",null)}whereNotNull(X){return this.where(X,"is not",null)}whereIn(X,$){return this.where(X,"in",$)}whereNotIn(X,$){return this.where(X,"not in",$)}orderBy(X,$="asc"){return this.state.orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}latest(X="created_at"){return this.orderBy(X,"desc")}oldest(X="created_at"){return this.orderBy(X,"asc")}limit(X){return this.state.limitValue=X,this}offset(X){return this.state.offsetValue=X,this}skip(X){return this.offset(X)}take(X){return this.limit(X)}with(...X){return this.state.withRelations.push(...X),this}buildQueryParams(){let X=new URLSearchParams;for(let $ of this.state.wheres)if($.operator==="=")X.append($.column,String($.value));else if($.operator==="in"&&Array.isArray($.value))X.append(`${$.column}[]`,$.value.join(","));else if($.operator==="is"&&$.value===null)X.append(`filter[${$.column}][is]`,"null");else if($.operator==="is not"&&$.value===null)X.append(`filter[${$.column}][is_not]`,"null");else X.append(`filter[${$.column}][${$.operator}]`,String($.value));if(this.state.orderBy.length>0){let $=this.state.orderBy.map((Z)=>`${Z.direction==="desc"?"-":""}${Z.column}`).join(",");X.append("sort",$)}if(this.state.limitValue!==void 0)X.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)X.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))X.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)X.append("include",this.state.withRelations.join(","));return X}buildUrl(X){let $=`${_0.baseUrl}/${this.state.table}`;if(X!==void 0)return`${$}/${X}`;let Y=this.buildQueryParams().toString();return Y?`${$}?${Y}`:$}async get(){let X=this.buildUrl(),$=await fetch(X,{method:"GET",headers:await c0()}),Z=await E9($);return Array.isArray(Z)?Z:Z.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let X=await this.first();if(!X)throw new B9(`No ${this.state.table} found`,404);return X}async find(X){let $=this.buildUrl(X);try{let Z=await fetch($,{method:"GET",headers:await c0()});if(Z.status===404)return null;let Y=await E9(Z);return"data"in Y&&!Array.isArray(Y.data)?Y.data:Y}catch{return null}}async findOrFail(X){let $=await this.find(X);if(!$)throw new B9(`${this.state.table} with id ${X} not found`,404);return $}async count(){let X=this.buildQueryParams();X.append("count","true");let $=`${_0.baseUrl}/${this.state.table}?${X.toString()}`,Z=await fetch($,{method:"GET",headers:await c0()});return(await E9(Z)).count}async exists(){return await this.count()>0}async create(X){let $=`${_0.baseUrl}/${this.state.table}`,Z=_0.transformRequest?_0.transformRequest(X):X,Y=await fetch($,{method:"POST",headers:await c0(),body:JSON.stringify(Z)}),U=await E9(Y);return"data"in U&&!Array.isArray(U.data)?U.data:U}async insert(X){return this.create(X)}async update(X,$){let Z=`${_0.baseUrl}/${this.state.table}/${X}`,Y=_0.transformRequest?_0.transformRequest($):$,U=await fetch(Z,{method:"PATCH",headers:await c0(),body:JSON.stringify(Y)}),_=await E9(U);return"data"in _&&!Array.isArray(_.data)?_.data:_}async delete(X){let $=`${_0.baseUrl}/${this.state.table}/${X}`;return(await fetch($,{method:"DELETE",headers:await c0()})).ok}async destroy(X){return this.delete(X)}async paginate(X=1,$=15){this.limit($).offset((X-1)*$);let Z=this.buildQueryParams();Z.append("paginate","true");let Y=`${_0.baseUrl}/${this.state.table}?${Z.toString()}`,U=await fetch(Y,{method:"GET",headers:await c0()});return E9(U)}toState(){return{...this.state}}}function D6(X){return new R6(X)}function fj(){return new Proxy({},{get:(X,$)=>{return()=>D6($)}})}class kX{_attributes;_definition;constructor(X,$={}){this._definition=X,this._attributes={...$}}get(X){return this._attributes[X]}set(X,$){this._attributes[X]=$}get attributes(){return{...this._attributes}}get id(){let X=this._definition.primaryKey||"id";return this._attributes[X]}toJSON(){let X=new Set;for(let[Z,Y]of Object.entries(this._definition.attributes))if(Y.hidden)X.add(Z);let $={};for(let[Z,Y]of Object.entries(this._attributes))if(!X.has(Z))$[Z]=Y;return $}}class V0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(X){this._definition=X}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}whereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"and"}),this}whereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"and"}),this}whereNull(X){return this._wheres.push({column:X,operator:"is",value:null,boolean:"and"}),this}whereNotNull(X){return this._wheres.push({column:X,operator:"is not",value:null,boolean:"and"}),this}whereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"and"}),this}orderBy(X,$="asc"){return this._orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}orderByAsc(X){return this.orderBy(X,"asc")}limit(X){return this._limit=X,this}take(X){return this.limit(X)}offset(X){return this._offset=X,this}skip(X){return this.offset(X)}select(...X){return this._select=X,this}with(...X){return this._withRelations.push(...X),this}latest(X="created_at"){return this.orderByDesc(X)}oldest(X="created_at"){return this.orderByAsc(X)}buildQueryParams(){let X=new URLSearchParams;for(let $ of this._wheres)if($.operator==="=")X.append($.column,String($.value));else if(($.operator==="in"||$.operator==="not in")&&Array.isArray($.value))X.append(`${$.column}[]`,$.value.join(","));else if($.operator==="is"&&$.value===null)X.append(`filter[${$.column}][is]`,"null");else if($.operator==="is not"&&$.value===null)X.append(`filter[${$.column}][is_not]`,"null");else X.append(`filter[${$.column}][${$.operator}]`,String($.value));if(this._orderBy.length>0){let $=this._orderBy.map((Z)=>`${Z.direction==="desc"?"-":""}${Z.column}`).join(",");X.append("sort",$)}if(this._limit!==void 0)X.append("limit",String(this._limit));if(this._offset!==void 0)X.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))X.append("fields",this._select.join(","));if(this._withRelations.length>0)X.append("include",this._withRelations.join(","));return X}buildUrl(X){let $=`${_0.baseUrl}/${this.getTablePath()}`;if(X!==void 0)return`${$}/${X}`;let Y=this.buildQueryParams().toString();return Y?`${$}?${Y}`:$}async get(){let X=this.buildUrl(),$=await fetch(X,{method:"GET",headers:await c0()}),Z=await E9($);return(Array.isArray(Z)?Z:Z.data).map((U)=>new kX(this._definition,U))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let X=await this.first();if(!X)throw new B9(`No ${this._definition.name} found`,404);return X}async find(X){let $=this.buildUrl(X);try{let Z=await fetch($,{method:"GET",headers:await c0()});if(Z.status===404)return null;let Y=await E9(Z),U="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new kX(this._definition,U)}catch{return null}}async findOrFail(X){let $=await this.find(X);if(!$)throw new B9(`${this._definition.name} with id ${X} not found`,404);return $}async count(){let X=this.buildQueryParams();X.append("count","true");let $=`${_0.baseUrl}/${this.getTablePath()}?${X.toString()}`,Z=await fetch($,{method:"GET",headers:await c0()});return(await E9(Z)).count}async exists(){return await this.count()>0}async pluck(X){return this._select=[X],(await this.get()).map((Z)=>Z.get(X))}async paginate(X=1,$=15){this._limit=$,this._offset=(X-1)*$;let Z=this.buildQueryParams();Z.append("paginate","true");let Y=`${_0.baseUrl}/${this.getTablePath()}?${Z.toString()}`,U=await fetch(Y,{method:"GET",headers:await c0()}),_=await E9(U);return{..._,data:_.data.map((Q)=>new kX(this._definition,Q))}}}function n7(X){return new Proxy({query:()=>new V0(X),where(Z,Y,U){return new V0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new V0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new V0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new V0(X).whereNotIn(Z,Y)},whereNull(Z){return new V0(X).whereNull(Z)},whereNotNull(Z){return new V0(X).whereNotNull(Z)},whereLike(Z,Y){return new V0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new V0(X).orderBy(Z,Y)},orderByDesc(Z){return new V0(X).orderByDesc(Z)},select(...Z){return new V0(X).select(...Z)},limit:(Z)=>new V0(X).limit(Z),take:(Z)=>new V0(X).take(Z),skip:(Z)=>new V0(X).skip(Z),latest:(Z="created_at")=>new V0(X).latest(Z),oldest:(Z="created_at")=>new V0(X).oldest(Z),async find(Z){return new V0(X).find(Z)},async findOrFail(Z){return new V0(X).findOrFail(Z)},async all(){return new V0(X).get()},async first(){return new V0(X).first()},async firstOrFail(){return new V0(X).firstOrFail()},async count(){return new V0(X).count()},async exists(){return new V0(X).exists()},async paginate(Z,Y){return new V0(X).paginate(Z,Y)},async pluck(Z){return new V0(X).pluck(Z)},async create(Z){let Y=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,U=`${_0.baseUrl}/${Y}`,_=_0.transformRequest?_0.transformRequest(Z):Z,Q=await fetch(U,{method:"POST",headers:await c0(),body:JSON.stringify(_)}),L=await E9(Q),z="data"in L&&!Array.isArray(L.data)?L.data:L;return new kX(X,z)},async update(Z,Y){let U=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,_=`${_0.baseUrl}/${U}/${Z}`,Q=_0.transformRequest?_0.transformRequest(Y):Y,L=await fetch(_,{method:"PATCH",headers:await c0(),body:JSON.stringify(Q)}),z=await E9(L),j="data"in z&&!Array.isArray(z.data)?z.data:z;return new kX(X,j)},async delete(Z){let Y=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,U=`${_0.baseUrl}/${Y}/${Z}`;return(await fetch(U,{method:"DELETE",headers:await c0()})).ok},async destroy(Z){return this.delete(Z)},getDefinition:()=>X,getTable:()=>X.table},{get(Z,Y){if(typeof Y==="string"&&Y.startsWith("where")&&Y.length>5){let U=Y.slice(5),_=U.charAt(0).toLowerCase()+U.slice(1);if(_ in X.attributes||_==="id"||_===X.primaryKey)return(Q)=>new V0(X).where(_,Q)}return Reflect.get(Z,Y)}})}var _0,B9,i7,l7,M6=e(()=>{_0={baseUrl:""},B9=class extends Error{status;constructor($,Z){super($);this.name="BrowserQueryError",this.status=Z}},i7={async login(X){let $=await fetch(`${_0.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",..._0.headers},body:JSON.stringify(X)});if(!$.ok){let U=await $.json().catch(()=>({message:"Login failed"}));throw new B9(U.message||"Login failed",$.status)}let Z=await $.json(),Y=Z.data||Z;if(typeof localStorage<"u"&&Y.token)localStorage.setItem("auth_token",Y.token);return Y},async register(X){let $=await fetch(`${_0.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",..._0.headers},body:JSON.stringify(X)});if(!$.ok){let U=await $.json().catch(()=>({message:"Registration failed"}));throw new B9(U.message||"Registration failed",$.status)}let Z=await $.json(),Y=Z.data||Z;if(typeof localStorage<"u"&&Y.token)localStorage.setItem("auth_token",Y.token);return Y},async logout(){if(await E8())try{await fetch(`${_0.baseUrl}/logout`,{method:"POST",headers:await c0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await E8())return null;try{let $=await fetch(`${_0.baseUrl}/user`,{method:"GET",headers:await c0()});if($.status===401)return _0.onUnauthorized?.(),null;if(!$.ok)return null;let Z=await $.json();return Z.user||Z}catch{return null}},async check(){return await this.user()!==null},getToken:E8},l7=D6});class H6{config;entityMappings=new Map;constructor(X){if(this.config=X,X.entityMappings)for(let $ of X.entityMappings)this.registerEntity($)}createTable(X){return{...X,billingMode:X.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(X){return{tableName:X}}registerEntity(X){this.entityMappings.set(X.entityType,X)}getEntityMapping(X){return this.entityMappings.get(X)}buildPrimaryKey(X,$){let Z=this.entityMappings.get(X);if(!Z)throw Error(`No entity mapping found for type: ${X}`);let Y=this.interpolatePattern(Z.pkPattern,$),U=this.interpolatePattern(Z.skPattern,$);return{pk:Y,sk:U}}parseEntityFromItem(X){let $=X.pk||X.PK;if(!$)return null;for(let[Z,Y]of this.entityMappings){let U=Y.pkPattern.split("${")[0];if($.startsWith(U))return{entityType:Z,data:this.unmarshall(X)}}return null}buildQueryParams(X){return{tableName:X.tableName??this.config.tableName??"",keyConditions:X.keyConditions??[],...X}}buildScanParams(X){return{tableName:X.tableName??this.config.tableName??"",...X}}buildGetItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},...X}}buildPutItemParams(X){return{tableName:X.tableName??this.config.tableName??"",item:X.item??{},...X}}buildUpdateItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},updateExpressions:X.updateExpressions??{},...X}}buildDeleteItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},...X}}buildBatchGetItemParams(X){return{requestItems:X.requestItems??{}}}buildBatchWriteItemParams(X){return{requestItems:X.requestItems??{}}}buildTransactWriteParams(X){return{transactItems:X.transactItems??[],...X}}buildKeyConditionExpression(X){return this.buildExpression(X,"AND")}buildFilterExpression(X){return this.buildExpression(X,"AND")}buildUpdateExpression(X){let $={},Z={},Y=[],U=0;if(X.set&&Object.keys(X.set).length>0){let _=[];for(let[Q,L]of Object.entries(X.set)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} = ${j}`),U++}Y.push(`SET ${_.join(", ")}`)}if(X.remove&&X.remove.length>0){let _=[];for(let Q of X.remove){let L=`#attr${U}`;$[L]=Q,_.push(L),U++}Y.push(`REMOVE ${_.join(", ")}`)}if(X.add&&Object.keys(X.add).length>0){let _=[];for(let[Q,L]of Object.entries(X.add)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} ${j}`),U++}Y.push(`ADD ${_.join(", ")}`)}if(X.delete&&Object.keys(X.delete).length>0){let _=[];for(let[Q,L]of Object.entries(X.delete)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} ${j}`),U++}Y.push(`DELETE ${_.join(", ")}`)}return{expression:Y.join(" "),expressionAttributeNames:$,expressionAttributeValues:Z}}buildProjectionExpression(X){let $={},Z=[];return X.forEach((Y,U)=>{let _=`#proj${U}`;$[_]=Y,Z.push(_)}),{expression:Z.join(", "),expressionAttributeNames:$}}marshall(X){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.marshallValue(Y);return $}unmarshall(X){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.unmarshallValue(Y);return $}interpolatePattern(X,$){return X.replace(/\$\{(\w+)\}/g,(Z,Y)=>{if(!(Y in $))throw Error(`Missing value for pattern key: ${Y}`);return String($[Y])})}buildExpression(X,$){let Z={},Y={},U=[];return X.forEach((_,Q)=>{let L=`#attr${Q}`;Z[L]=_.attribute;let z;switch(_.operator){case"=":case"<":case"<=":case">":case">=":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`${L} ${_.operator} ${j}`;break}case"BETWEEN":{let j=`:val${Q}a`,E=`:val${Q}b`;Y[j]=this.marshallValue(_.values?.[0]),Y[E]=this.marshallValue(_.values?.[1]),z=`${L} BETWEEN ${j} AND ${E}`;break}case"begins_with":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`begins_with(${L}, ${j})`;break}case"contains":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`contains(${L}, ${j})`;break}case"attribute_exists":z=`attribute_exists(${L})`;break;case"attribute_not_exists":z=`attribute_not_exists(${L})`;break;case"attribute_type":{let j=`:val${Q}`;Y[j]={S:_.value},z=`attribute_type(${L}, ${j})`;break}case"IN":{let j=(_.values??[]).map((E,V)=>`:val${Q}_${V}`);_.values?.forEach((E,V)=>{Y[`:val${Q}_${V}`]=this.marshallValue(E)}),z=`${L} IN (${j.join(", ")})`;break}default:throw Error(`Unknown operator: ${_.operator}`)}U.push(z)}),{expression:U.join(` ${$} `),expressionAttributeNames:Z,expressionAttributeValues:Y}}marshallValue(X){if(X===null||X===void 0)return{NULL:!0};if(typeof X==="string")return{S:X};if(typeof X==="number")return{N:String(X)};if(typeof X==="boolean")return{BOOL:X};if(X instanceof Uint8Array||Buffer.isBuffer(X))return{B:X};if(Array.isArray(X)){if(X.length===0)return{L:[]};let $=typeof X[0],Z=X.every((U)=>typeof U==="string"),Y=X.every((U)=>typeof U==="number");if(Z)return{SS:X};if(Y)return{NS:X.map(String)};return{L:X.map((U)=>this.marshallValue(U))}}if(typeof X==="object"){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.marshallValue(Y);return{M:$}}return{S:String(X)}}unmarshallValue(X){if(!X||typeof X!=="object")return X;if("S"in X)return X.S;if("N"in X)return Number(X.N);if("BOOL"in X)return X.BOOL;if("NULL"in X)return null;if("B"in X)return X.B;if("SS"in X)return X.SS;if("NS"in X)return X.NS.map(Number);if("BS"in X)return X.BS;if("L"in X)return X.L.map(($)=>this.unmarshallValue($));if("M"in X){let $={};for(let[Z,Y]of Object.entries(X.M))$[Z]=this.unmarshallValue(Y);return $}return X}}function bX(X){return new H6(X)}async function iX(X,$){let Z=X instanceof ArrayBuffer?X:X.buffer.slice(X.byteOffset,X.byteOffset+X.byteLength),Y=await crypto.subtle.importKey("raw",Z,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",Y,new TextEncoder().encode($))}async function R5(X){let $=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(X));return Array.from(new Uint8Array($)).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}async function s7(X,$,Z,Y){let U=await iX(new TextEncoder().encode(`AWS4${X}`),$),_=await iX(U,Z),Q=await iX(_,Y);return iX(Q,"aws4_request")}async function o7(X,$,Z,Y,U,_,Q){let z=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),j=z.slice(0,8),E=$.pathname,V=$.search.slice(1),G={...Z,host:$.host,"x-amz-date":z};if(U.sessionToken)G["x-amz-security-token"]=U.sessionToken;let J=Object.keys(G).sort(),W=J.map((y)=>`${y.toLowerCase()}:${G[y].trim()}`).join(`
|
|
2
|
+
var p0=import.meta.require;import{existsSync as H5,statSync as C5}from"fs";import{existsSync as z2,mkdirSync as lj,readdirSync as sj,readFileSync as L2,writeFileSync as oj}from"fs";import{homedir as zX}from"os";import{dirname as tj,resolve as L9}from"path";import N8 from"process";import{existsSync as w5,statSync as q5}from"fs";import{existsSync as G1,mkdirSync as j2,readdirSync as E2,writeFileSync as G2}from"fs";import{homedir as LX}from"os";import{dirname as P5,resolve as l0}from"path";import t9 from"process";import{join as F2,relative as O2,resolve as T5}from"path";import S8 from"process";import{existsSync as k6,mkdirSync as LE,readdirSync as jE,writeFileSync as EE}from"fs";import{homedir as GZ}from"os";import{dirname as OE,resolve as n0}from"path";import P$ from"process";import{join as J2,relative as W2,resolve as N5}from"path";import A8 from"process";import{existsSync as x6,mkdirSync as KE,readdirSync as RE,writeFileSync as DE}from"fs";import{dirname as HE,resolve as k8}from"path";import F1 from"process";import{Buffer as v9}from"buffer";import{createCipheriv as V2,createDecipheriv as I2,randomBytes as FZ}from"crypto";import{closeSync as OZ,createReadStream as S5,createWriteStream as K2,existsSync as JZ,fsyncSync as A5,openSync as k5,writeFileSync as R2}from"fs";import{access as D2,constants as x5,mkdir as M2,readdir as f$,rename as B5,stat as jX,unlink as g$,writeFile as WZ}from"fs/promises";import{join as EX}from"path";import b0 from"process";import{pipeline as H2}from"stream/promises";import{createGzip as y5}from"zlib";import GX from"process";import T9 from"process";import{Buffer as D9}from"buffer";import{createCipheriv as C2,createDecipheriv as w2,randomBytes as VZ}from"crypto";import{closeSync as IZ,createReadStream as h5,createWriteStream as q2,existsSync as d$,fsyncSync as v5,openSync as b5,writeFileSync as P2}from"fs";import{access as T2,constants as f5,mkdir as N2,readdir as p$,rename as g5,stat as FX,unlink as c$,writeFile as KZ}from"fs/promises";import{isAbsolute as S2,join as OX,resolve as A2}from"path";import L0 from"process";import{pipeline as k2}from"stream/promises";import{createGzip as d5}from"zlib";import JX from"process";import N9 from"process";import m$ from"process";import{existsSync as u$}from"fs";import{resolve as RZ}from"path";import{existsSync as x2}from"fs";import{existsSync as B2,readdirSync as y2}from"fs";import{extname as DZ,resolve as p5}from"path";import h2 from"process";import{join as v2,relative as b2,resolve as c5}from"path";import x8 from"process";import{Buffer as M9}from"buffer";import{createCipheriv as f2,createDecipheriv as g2,randomBytes as MZ}from"crypto";import{closeSync as HZ,createReadStream as m5,createWriteStream as d2,existsSync as n$,fsyncSync as u5,openSync as n5,writeFileSync as p2}from"fs";import{access as c2,constants as i5,mkdir as m2,readdir as i$,rename as l5,stat as WX,unlink as l$,writeFile as CZ}from"fs/promises";import{isAbsolute as u2,join as VX,resolve as n2}from"path";import j0 from"process";import{pipeline as i2}from"stream/promises";import{createGzip as s5}from"zlib";import IX from"process";import S9 from"process";import s$ from"process";import{existsSync as o$}from"fs";import{resolve as wZ}from"path";import{existsSync as l2}from"fs";import{Database as q_}from"bun:sqlite";import{mkdirSync as P_}from"fs";import{dirname as T_}from"path";import t$ from"process";import $8 from"process";import{createInterface as i_}from"readline";import{existsSync as o_,readFileSync as r_,writeFileSync as rX}from"fs";import SY from"process";import AY from"process";import{existsSync as P1,mkdirSync as KQ,writeFileSync as RQ}from"fs";import{dirname as kY,join as T1}from"path";import FU from"process";import{existsSync as d9,mkdirSync as KU,mkdtempSync as HQ,readdirSync as RU,readFileSync as DU,rmSync as CQ,unlinkSync as H8,writeFileSync as MU}from"fs";import{tmpdir as wQ}from"os";import{join as m0}from"path";import B$ from"process";import{existsSync as N1,readFileSync as hQ,unlinkSync as vQ}from"fs";import{dirname as BY,join as Q5}from"path";import PU from"process";import{existsSync as TU,readdirSync as cQ}from"fs";import{dirname as yY,join as NU}from"path";import SU from"process";import{readdirSync as lQ}from"fs";import{extname as dZ,join as hY}from"path";import sQ from"process";import{readdirSync as aQ,readFileSync as vY,statSync as tQ}from"fs";import{extname as bY,join as eQ}from"path";import{writeFileSync as $z}from"fs";import{join as Zz}from"path";import Yz from"process";import{existsSync as p8,mkdirSync as zz,readdirSync as Lz,writeFileSync as jz}from"fs";import{dirname as fY,join as m9}from"path";import y$ from"process";import{existsSync as Jz}from"fs";import{dirname as gY,join as kU}from"path";import xU from"process";import{existsSync as Dz}from"fs";import{join as Mz}from"path";import Hz from"process";import{existsSync as dY,statSync as pY}from"fs";import{join as Cz,relative as wz,resolve as cY}from"path";import c8 from"process";import{Buffer as H9}from"buffer";import{createCipheriv as qz,createDecipheriv as Pz,randomBytes as pZ}from"crypto";import{closeSync as cZ,createReadStream as mY,createWriteStream as Tz,existsSync as Z8,fsyncSync as uY,openSync as nY,writeFileSync as Nz}from"fs";import{access as Sz,constants as iY,mkdir as Az,readdir as Y8,rename as lY,stat as RX,unlink as U8,writeFile as mZ}from"fs/promises";import{isAbsolute as kz,join as DX,resolve as xz}from"path";import O0 from"process";import{pipeline as Bz}from"stream/promises";import{createGzip as sY}from"zlib";import MX from"process";import A9 from"process";import _8 from"process";import{existsSync as Q8}from"fs";import{resolve as uZ}from"path";import{existsSync as yz}from"fs";import{existsSync as S1,mkdirSync as hz,readdirSync as vz,readFileSync as bz,writeFileSync as fz}from"fs";import{homedir as HX}from"os";import{dirname as oY,resolve as s0}from"path";import XX from"process";import{existsSync as gz,readdirSync as dz}from"fs";import{extname as nZ,resolve as rY}from"path";import pz from"process";import{spawnSync as cz}from"child_process";import{existsSync as TX,readFileSync as mz}from"fs";import{join as NX}from"path";import BU from"process";import{Database as b1}from"bun:sqlite";import{readdirSync as $j,statSync as Zj}from"fs";import{basename as Yj,extname as Uj}from"path";import _j from"process";import{existsSync as M7,mkdirSync as jj,writeFileSync as Ej}from"fs";import{dirname as J6,join as J5}from"path";import H7 from"process";var{defineProperty:E1,getOwnPropertyNames:f7,getOwnPropertyDescriptor:g7}=Object,d7=Object.prototype.hasOwnProperty;function p7(X){return this[X]}var c7=(X)=>{var $=(R5??=new WeakMap).get(X),Z;if($)return $;if($=E1({},"__esModule",{value:!0}),X&&typeof X==="object"||typeof X==="function"){for(var Y of f7(X))if(!d7.call($,Y))E1($,Y,{get:p7.bind(X,Y),enumerable:!(Z=g7(X,Y))||Z.enumerable})}return R5.set(X,$),$},R5,m7=(X)=>X;function u7(X,$){this[X]=m7.bind(null,$)}var i1=(X,$)=>{for(var Z in $)E1(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:u7.bind($,Z)})},t=(X,$)=>()=>(X&&($=X(X=0)),$),n7=import.meta.require;function bj(X){Q0={...Q0,...X}}function fj(){return Q0}function gj(){return typeof window<"u"&&typeof document<"u"}async function E8(){if(Q0.getToken){let X=Q0.getToken();return X instanceof Promise?X:X}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function c0(){let X={"Content-Type":"application/json",Accept:"application/json",...Q0.headers},$=await E8();if($)X.Authorization=`Bearer ${$}`;return X}async function E9(X){if(X.status===401)throw Q0.onUnauthorized?.(),new y9("Unauthorized",401);if(!X.ok){let Z=await X.json().catch(()=>({message:"Request failed"}));throw new y9(Z.message||`HTTP ${X.status}`,X.status)}let $=await X.json();if(Q0.transformResponse)return Q0.transformResponse($);return $}class D6{state;constructor(X){this.state={table:X,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...X){return this.state.selectColumns=X,this}where(X,$,Z){if(Z===void 0)this.state.wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this.state.wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this.state.wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this.state.wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}andWhere(X,$,Z){return this.where(X,$,Z)}whereNull(X){return this.where(X,"is",null)}whereNotNull(X){return this.where(X,"is not",null)}whereIn(X,$){return this.where(X,"in",$)}whereNotIn(X,$){return this.where(X,"not in",$)}orderBy(X,$="asc"){return this.state.orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}latest(X="created_at"){return this.orderBy(X,"desc")}oldest(X="created_at"){return this.orderBy(X,"asc")}limit(X){return this.state.limitValue=X,this}offset(X){return this.state.offsetValue=X,this}skip(X){return this.offset(X)}take(X){return this.limit(X)}with(...X){return this.state.withRelations.push(...X),this}buildQueryParams(){let X=new URLSearchParams;for(let $ of this.state.wheres)if($.operator==="=")X.append($.column,String($.value));else if($.operator==="in"&&Array.isArray($.value))X.append(`${$.column}[]`,$.value.join(","));else if($.operator==="is"&&$.value===null)X.append(`filter[${$.column}][is]`,"null");else if($.operator==="is not"&&$.value===null)X.append(`filter[${$.column}][is_not]`,"null");else X.append(`filter[${$.column}][${$.operator}]`,String($.value));if(this.state.orderBy.length>0){let $=this.state.orderBy.map((Z)=>`${Z.direction==="desc"?"-":""}${Z.column}`).join(",");X.append("sort",$)}if(this.state.limitValue!==void 0)X.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)X.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))X.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)X.append("include",this.state.withRelations.join(","));return X}buildUrl(X){let $=`${Q0.baseUrl}/${this.state.table}`;if(X!==void 0)return`${$}/${X}`;let Y=this.buildQueryParams().toString();return Y?`${$}?${Y}`:$}async get(){let X=this.buildUrl(),$=await fetch(X,{method:"GET",headers:await c0()}),Z=await E9($);return Array.isArray(Z)?Z:Z.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let X=await this.first();if(!X)throw new y9(`No ${this.state.table} found`,404);return X}async find(X){let $=this.buildUrl(X);try{let Z=await fetch($,{method:"GET",headers:await c0()});if(Z.status===404)return null;let Y=await E9(Z);return"data"in Y&&!Array.isArray(Y.data)?Y.data:Y}catch{return null}}async findOrFail(X){let $=await this.find(X);if(!$)throw new y9(`${this.state.table} with id ${X} not found`,404);return $}async count(){let X=this.buildQueryParams();X.append("count","true");let $=`${Q0.baseUrl}/${this.state.table}?${X.toString()}`,Z=await fetch($,{method:"GET",headers:await c0()});return(await E9(Z)).count}async exists(){return await this.count()>0}async create(X){let $=`${Q0.baseUrl}/${this.state.table}`,Z=Q0.transformRequest?Q0.transformRequest(X):X,Y=await fetch($,{method:"POST",headers:await c0(),body:JSON.stringify(Z)}),U=await E9(Y);return"data"in U&&!Array.isArray(U.data)?U.data:U}async insert(X){return this.create(X)}async update(X,$){let Z=`${Q0.baseUrl}/${this.state.table}/${X}`,Y=Q0.transformRequest?Q0.transformRequest($):$,U=await fetch(Z,{method:"PATCH",headers:await c0(),body:JSON.stringify(Y)}),_=await E9(U);return"data"in _&&!Array.isArray(_.data)?_.data:_}async delete(X){let $=`${Q0.baseUrl}/${this.state.table}/${X}`;return(await fetch($,{method:"DELETE",headers:await c0()})).ok}async destroy(X){return this.delete(X)}async paginate(X=1,$=15){this.limit($).offset((X-1)*$);let Z=this.buildQueryParams();Z.append("paginate","true");let Y=`${Q0.baseUrl}/${this.state.table}?${Z.toString()}`,U=await fetch(Y,{method:"GET",headers:await c0()});return E9(U)}toState(){return{...this.state}}}function M6(X){return new D6(X)}function dj(){return new Proxy({},{get:(X,$)=>{return()=>M6($)}})}class kX{_attributes;_definition;constructor(X,$={}){this._definition=X,this._attributes={...$}}get(X){return this._attributes[X]}set(X,$){this._attributes[X]=$}get attributes(){return{...this._attributes}}get id(){let X=this._definition.primaryKey||"id";return this._attributes[X]}toJSON(){let X=new Set;for(let[Z,Y]of Object.entries(this._definition.attributes))if(Y.hidden)X.add(Z);let $={};for(let[Z,Y]of Object.entries(this._attributes))if(!X.has(Z))$[Z]=Y;return $}}class I0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(X){this._definition=X}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}whereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"and"}),this}whereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"and"}),this}whereNull(X){return this._wheres.push({column:X,operator:"is",value:null,boolean:"and"}),this}whereNotNull(X){return this._wheres.push({column:X,operator:"is not",value:null,boolean:"and"}),this}whereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"and"}),this}orderBy(X,$="asc"){return this._orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}orderByAsc(X){return this.orderBy(X,"asc")}limit(X){return this._limit=X,this}take(X){return this.limit(X)}offset(X){return this._offset=X,this}skip(X){return this.offset(X)}select(...X){return this._select=X,this}with(...X){return this._withRelations.push(...X),this}latest(X="created_at"){return this.orderByDesc(X)}oldest(X="created_at"){return this.orderByAsc(X)}buildQueryParams(){let X=new URLSearchParams;for(let $ of this._wheres)if($.operator==="=")X.append($.column,String($.value));else if(($.operator==="in"||$.operator==="not in")&&Array.isArray($.value))X.append(`${$.column}[]`,$.value.join(","));else if($.operator==="is"&&$.value===null)X.append(`filter[${$.column}][is]`,"null");else if($.operator==="is not"&&$.value===null)X.append(`filter[${$.column}][is_not]`,"null");else X.append(`filter[${$.column}][${$.operator}]`,String($.value));if(this._orderBy.length>0){let $=this._orderBy.map((Z)=>`${Z.direction==="desc"?"-":""}${Z.column}`).join(",");X.append("sort",$)}if(this._limit!==void 0)X.append("limit",String(this._limit));if(this._offset!==void 0)X.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))X.append("fields",this._select.join(","));if(this._withRelations.length>0)X.append("include",this._withRelations.join(","));return X}buildUrl(X){let $=`${Q0.baseUrl}/${this.getTablePath()}`;if(X!==void 0)return`${$}/${X}`;let Y=this.buildQueryParams().toString();return Y?`${$}?${Y}`:$}async get(){let X=this.buildUrl(),$=await fetch(X,{method:"GET",headers:await c0()}),Z=await E9($);return(Array.isArray(Z)?Z:Z.data).map((U)=>new kX(this._definition,U))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let X=await this.first();if(!X)throw new y9(`No ${this._definition.name} found`,404);return X}async find(X){let $=this.buildUrl(X);try{let Z=await fetch($,{method:"GET",headers:await c0()});if(Z.status===404)return null;let Y=await E9(Z),U="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new kX(this._definition,U)}catch{return null}}async findOrFail(X){let $=await this.find(X);if(!$)throw new y9(`${this._definition.name} with id ${X} not found`,404);return $}async count(){let X=this.buildQueryParams();X.append("count","true");let $=`${Q0.baseUrl}/${this.getTablePath()}?${X.toString()}`,Z=await fetch($,{method:"GET",headers:await c0()});return(await E9(Z)).count}async exists(){return await this.count()>0}async pluck(X){return this._select=[X],(await this.get()).map((Z)=>Z.get(X))}async paginate(X=1,$=15){this._limit=$,this._offset=(X-1)*$;let Z=this.buildQueryParams();Z.append("paginate","true");let Y=`${Q0.baseUrl}/${this.getTablePath()}?${Z.toString()}`,U=await fetch(Y,{method:"GET",headers:await c0()}),_=await E9(U);return{..._,data:_.data.map((Q)=>new kX(this._definition,Q))}}}function i7(X){return new Proxy({query:()=>new I0(X),where(Z,Y,U){return new I0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new I0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new I0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new I0(X).whereNotIn(Z,Y)},whereNull(Z){return new I0(X).whereNull(Z)},whereNotNull(Z){return new I0(X).whereNotNull(Z)},whereLike(Z,Y){return new I0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new I0(X).orderBy(Z,Y)},orderByDesc(Z){return new I0(X).orderByDesc(Z)},select(...Z){return new I0(X).select(...Z)},limit:(Z)=>new I0(X).limit(Z),take:(Z)=>new I0(X).take(Z),skip:(Z)=>new I0(X).skip(Z),latest:(Z="created_at")=>new I0(X).latest(Z),oldest:(Z="created_at")=>new I0(X).oldest(Z),async find(Z){return new I0(X).find(Z)},async findOrFail(Z){return new I0(X).findOrFail(Z)},async all(){return new I0(X).get()},async first(){return new I0(X).first()},async firstOrFail(){return new I0(X).firstOrFail()},async count(){return new I0(X).count()},async exists(){return new I0(X).exists()},async paginate(Z,Y){return new I0(X).paginate(Z,Y)},async pluck(Z){return new I0(X).pluck(Z)},async create(Z){let Y=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,U=`${Q0.baseUrl}/${Y}`,_=Q0.transformRequest?Q0.transformRequest(Z):Z,Q=await fetch(U,{method:"POST",headers:await c0(),body:JSON.stringify(_)}),L=await E9(Q),z="data"in L&&!Array.isArray(L.data)?L.data:L;return new kX(X,z)},async update(Z,Y){let U=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,_=`${Q0.baseUrl}/${U}/${Z}`,Q=Q0.transformRequest?Q0.transformRequest(Y):Y,L=await fetch(_,{method:"PATCH",headers:await c0(),body:JSON.stringify(Q)}),z=await E9(L),j="data"in z&&!Array.isArray(z.data)?z.data:z;return new kX(X,j)},async delete(Z){let Y=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,U=`${Q0.baseUrl}/${Y}/${Z}`;return(await fetch(U,{method:"DELETE",headers:await c0()})).ok},async destroy(Z){return this.delete(Z)},getDefinition:()=>X,getTable:()=>X.table},{get(Z,Y){if(typeof Y==="string"&&Y.startsWith("where")&&Y.length>5){let U=Y.slice(5),_=U.charAt(0).toLowerCase()+U.slice(1);if(_ in X.attributes||_==="id"||_===X.primaryKey)return(Q)=>new I0(X).where(_,Q)}return Reflect.get(Z,Y)}})}var Q0,y9,l7,s7,H6=t(()=>{Q0={baseUrl:""},y9=class extends Error{status;constructor($,Z){super($);this.name="BrowserQueryError",this.status=Z}},l7={async login(X){let $=await fetch(`${Q0.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...Q0.headers},body:JSON.stringify(X)});if(!$.ok){let U=await $.json().catch(()=>({message:"Login failed"}));throw new y9(U.message||"Login failed",$.status)}let Z=await $.json(),Y=Z.data||Z;if(typeof localStorage<"u"&&Y.token)localStorage.setItem("auth_token",Y.token);return Y},async register(X){let $=await fetch(`${Q0.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...Q0.headers},body:JSON.stringify(X)});if(!$.ok){let U=await $.json().catch(()=>({message:"Registration failed"}));throw new y9(U.message||"Registration failed",$.status)}let Z=await $.json(),Y=Z.data||Z;if(typeof localStorage<"u"&&Y.token)localStorage.setItem("auth_token",Y.token);return Y},async logout(){if(await E8())try{await fetch(`${Q0.baseUrl}/logout`,{method:"POST",headers:await c0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await E8())return null;try{let $=await fetch(`${Q0.baseUrl}/user`,{method:"GET",headers:await c0()});if($.status===401)return Q0.onUnauthorized?.(),null;if(!$.ok)return null;let Z=await $.json();return Z.user||Z}catch{return null}},async check(){return await this.user()!==null},getToken:E8},s7=M6});class C6{config;entityMappings=new Map;constructor(X){if(this.config=X,X.entityMappings)for(let $ of X.entityMappings)this.registerEntity($)}createTable(X){return{...X,billingMode:X.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(X){return{tableName:X}}registerEntity(X){this.entityMappings.set(X.entityType,X)}getEntityMapping(X){return this.entityMappings.get(X)}buildPrimaryKey(X,$){let Z=this.entityMappings.get(X);if(!Z)throw Error(`No entity mapping found for type: ${X}`);let Y=this.interpolatePattern(Z.pkPattern,$),U=this.interpolatePattern(Z.skPattern,$);return{pk:Y,sk:U}}parseEntityFromItem(X){let $=X.pk||X.PK;if(!$)return null;for(let[Z,Y]of this.entityMappings){let U=Y.pkPattern.split("${")[0];if($.startsWith(U))return{entityType:Z,data:this.unmarshall(X)}}return null}buildQueryParams(X){return{tableName:X.tableName??this.config.tableName??"",keyConditions:X.keyConditions??[],...X}}buildScanParams(X){return{tableName:X.tableName??this.config.tableName??"",...X}}buildGetItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},...X}}buildPutItemParams(X){return{tableName:X.tableName??this.config.tableName??"",item:X.item??{},...X}}buildUpdateItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},updateExpressions:X.updateExpressions??{},...X}}buildDeleteItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},...X}}buildBatchGetItemParams(X){return{requestItems:X.requestItems??{}}}buildBatchWriteItemParams(X){return{requestItems:X.requestItems??{}}}buildTransactWriteParams(X){return{transactItems:X.transactItems??[],...X}}buildKeyConditionExpression(X){return this.buildExpression(X,"AND")}buildFilterExpression(X){return this.buildExpression(X,"AND")}buildUpdateExpression(X){let $={},Z={},Y=[],U=0;if(X.set&&Object.keys(X.set).length>0){let _=[];for(let[Q,L]of Object.entries(X.set)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} = ${j}`),U++}Y.push(`SET ${_.join(", ")}`)}if(X.remove&&X.remove.length>0){let _=[];for(let Q of X.remove){let L=`#attr${U}`;$[L]=Q,_.push(L),U++}Y.push(`REMOVE ${_.join(", ")}`)}if(X.add&&Object.keys(X.add).length>0){let _=[];for(let[Q,L]of Object.entries(X.add)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} ${j}`),U++}Y.push(`ADD ${_.join(", ")}`)}if(X.delete&&Object.keys(X.delete).length>0){let _=[];for(let[Q,L]of Object.entries(X.delete)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} ${j}`),U++}Y.push(`DELETE ${_.join(", ")}`)}return{expression:Y.join(" "),expressionAttributeNames:$,expressionAttributeValues:Z}}buildProjectionExpression(X){let $={},Z=[];return X.forEach((Y,U)=>{let _=`#proj${U}`;$[_]=Y,Z.push(_)}),{expression:Z.join(", "),expressionAttributeNames:$}}marshall(X){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.marshallValue(Y);return $}unmarshall(X){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.unmarshallValue(Y);return $}interpolatePattern(X,$){return X.replace(/\$\{(\w+)\}/g,(Z,Y)=>{if(!(Y in $))throw Error(`Missing value for pattern key: ${Y}`);return String($[Y])})}buildExpression(X,$){let Z={},Y={},U=[];return X.forEach((_,Q)=>{let L=`#attr${Q}`;Z[L]=_.attribute;let z;switch(_.operator){case"=":case"<":case"<=":case">":case">=":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`${L} ${_.operator} ${j}`;break}case"BETWEEN":{let j=`:val${Q}a`,E=`:val${Q}b`;Y[j]=this.marshallValue(_.values?.[0]),Y[E]=this.marshallValue(_.values?.[1]),z=`${L} BETWEEN ${j} AND ${E}`;break}case"begins_with":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`begins_with(${L}, ${j})`;break}case"contains":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`contains(${L}, ${j})`;break}case"attribute_exists":z=`attribute_exists(${L})`;break;case"attribute_not_exists":z=`attribute_not_exists(${L})`;break;case"attribute_type":{let j=`:val${Q}`;Y[j]={S:_.value},z=`attribute_type(${L}, ${j})`;break}case"IN":{let j=(_.values??[]).map((E,V)=>`:val${Q}_${V}`);_.values?.forEach((E,V)=>{Y[`:val${Q}_${V}`]=this.marshallValue(E)}),z=`${L} IN (${j.join(", ")})`;break}default:throw Error(`Unknown operator: ${_.operator}`)}U.push(z)}),{expression:U.join(` ${$} `),expressionAttributeNames:Z,expressionAttributeValues:Y}}marshallValue(X){if(X===null||X===void 0)return{NULL:!0};if(typeof X==="string")return{S:X};if(typeof X==="number")return{N:String(X)};if(typeof X==="boolean")return{BOOL:X};if(X instanceof Uint8Array||Buffer.isBuffer(X))return{B:X};if(Array.isArray(X)){if(X.length===0)return{L:[]};let $=typeof X[0],Z=X.every((U)=>typeof U==="string"),Y=X.every((U)=>typeof U==="number");if(Z)return{SS:X};if(Y)return{NS:X.map(String)};return{L:X.map((U)=>this.marshallValue(U))}}if(typeof X==="object"){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.marshallValue(Y);return{M:$}}return{S:String(X)}}unmarshallValue(X){if(!X||typeof X!=="object")return X;if("S"in X)return X.S;if("N"in X)return Number(X.N);if("BOOL"in X)return X.BOOL;if("NULL"in X)return null;if("B"in X)return X.B;if("SS"in X)return X.SS;if("NS"in X)return X.NS.map(Number);if("BS"in X)return X.BS;if("L"in X)return X.L.map(($)=>this.unmarshallValue($));if("M"in X){let $={};for(let[Z,Y]of Object.entries(X.M))$[Z]=this.unmarshallValue(Y);return $}return X}}function bX(X){return new C6(X)}async function iX(X,$){let Z=X instanceof ArrayBuffer?X:X.buffer.slice(X.byteOffset,X.byteOffset+X.byteLength),Y=await crypto.subtle.importKey("raw",Z,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",Y,new TextEncoder().encode($))}async function D5(X){let $=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(X));return Array.from(new Uint8Array($)).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}async function o7(X,$,Z,Y){let U=await iX(new TextEncoder().encode(`AWS4${X}`),$),_=await iX(U,Z),Q=await iX(_,Y);return iX(Q,"aws4_request")}async function r7(X,$,Z,Y,U,_,Q){let z=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),j=z.slice(0,8),E=$.pathname,V=$.search.slice(1),G={...Z,host:$.host,"x-amz-date":z};if(U.sessionToken)G["x-amz-security-token"]=U.sessionToken;let J=Object.keys(G).sort(),W=J.map((d)=>`${d.toLowerCase()}:${G[d].trim()}`).join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`,F=J.map((
|
|
5
|
-
`),w=await
|
|
6
|
-
`),H=await s7(U.secretAccessKey,j,_,Q),x=await iX(H,q),h=Array.from(new Uint8Array(x)).map((y)=>y.toString(16).padStart(2,"0")).join(""),c=`${T} Credential=${U.accessKeyId}/${N}, SignedHeaders=${F}, Signature=${h}`;return{...G,authorization:c}}class C6{config;endpoint;credentials;constructor(X){if(this.config=X,this.endpoint=X.endpoint??`https://dynamodb.${X.region}.amazonaws.com`,this.credentials=X.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(X,$){let Z=new URL(this.endpoint),Y=JSON.stringify($),U={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${X}`},_=await o7("POST",Z,U,Y,this.credentials,this.config.region,"dynamodb"),Q=await fetch(Z.toString(),{method:"POST",headers:_,body:Y});if(!Q.ok){let L=await Q.text(),z;try{let j=JSON.parse(L);z=j.message??j.Message??L}catch{z=L}throw Error(`DynamoDB ${X} failed: ${Q.status} - ${z}`)}return Q.json()}async query(X){return this.execute("Query",X)}async scan(X){return this.execute("Scan",X)}async getItem(X){return this.execute("GetItem",X)}async putItem(X){return this.execute("PutItem",X)}async updateItem(X){return this.execute("UpdateItem",X)}async deleteItem(X){return this.execute("DeleteItem",X)}async batchGetItem(X){return this.execute("BatchGetItem",X)}async batchWriteItem(X){return this.execute("BatchWriteItem",X)}async transactWriteItems(X){return this.execute("TransactWriteItems",X)}async describeTable(X){return this.execute("DescribeTable",{TableName:X})}async createTable(X){return this.execute("CreateTable",X)}async deleteTable(X){return this.execute("DeleteTable",{TableName:X})}async listTables(X){return this.execute("ListTables",X??{})}async updateTable(X){return this.execute("UpdateTable",X)}async updateTimeToLive(X){return this.execute("UpdateTimeToLive",X)}async describeTimeToLive(X){return this.execute("DescribeTimeToLive",{TableName:X})}}function w6(X){return new C6(X)}function gj(X){y9={...y9,...X},G8=null,F8=null}function l9(){if(!G8)G8=w6({region:y9.region??"us-east-1",endpoint:y9.endpoint,credentials:y9.credentials});return G8}function s9(){if(!F8)F8=bX({region:y9.region??"us-east-1",endpoint:y9.endpoint,credentials:y9.credentials});return F8}class r7{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(X={}){this._attributes={...X},this._original={...X};for(let[$,Z]of Object.entries(X))this[$]=Z}static query(){return new q6(this)}static async find(X){let $=this,Z=l9(),Y=s9(),U=`${$.pkPrefix}${$.keyDelimiter}${X}`,_=$.skPrefix;try{let Q=await Z.getItem({TableName:$.tableName,Key:Y.marshall({[$.pkAttribute]:U,[$.skAttribute]:_})});if(!Q.Item)return null;let L=Y.unmarshall(Q.Item),z=new $(L);return z._exists=!0,z}catch(Q){return console.error("Find error:",Q),null}}static async findOrFail(X){let $=await this.find(X);if(!$)throw Error(`${this.name} not found with id: ${X}`);return $}static async all(){return this.query().get()}static async create(X){let $=this,Z=l9(),Y=s9(),U=X[$.primaryKey];if(!U)throw Error(`${$.primaryKey} is required`);let _=`${$.pkPrefix}${$.keyDelimiter}${U}`,Q=$.skPrefix,L=new Date().toISOString(),z={...X,[$.pkAttribute]:_,[$.skAttribute]:Q,[$.entityTypeAttribute]:$.name};if($.timestamps)z[$.createdAtField]=L,z[$.updatedAtField]=L;await Z.putItem({TableName:$.tableName,Item:Y.marshall(z),ConditionExpression:`attribute_not_exists(${$.pkAttribute})`});let j=new $(z);return j._exists=!0,j}static async updateOrCreate(X,$){let Z=this,Y=X[Z.primaryKey],U=await Z.find(Y);if(U)return await U.update($),U;return Z.create({...X,...$})}static where(X,$,Z){return this.query().where(X,$,Z)}static wherePk(X){return this.query().wherePk(X)}getKey(){let X=this.constructor;return this[X.primaryKey]}getAttribute(X){return this._attributes[X]}setAttribute(X,$){return this._attributes[X]=$,this[X]=$,this}getAttributes(){return{...this._attributes}}isDirty(X){if(X)return this._attributes[X]!==this._original[X];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let X={};for(let[$,Z]of Object.entries(this._attributes))if(Z!==this._original[$])X[$]=Z;return X}async save(){if(this._exists){let X=this.getDirty();if(Object.keys(X).length>0)await this.update(X)}else{let $=await this.constructor.create(this._attributes);this._attributes=$._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(X){let $=this.constructor,Z=l9(),Y=s9(),U=this.getKey(),_=`${$.pkPrefix}${$.keyDelimiter}${U}`,Q=$.skPrefix,L=new Date().toISOString(),z={...X};if($.timestamps)z[$.updatedAtField]=L;let j=[],E={},V={},G=0;for(let[J,W]of Object.entries(z)){let F=`#attr${G}`,K=`:val${G}`;E[F]=J,V[K]=Y.marshall({v:W}).v,j.push(`${F} = ${K}`),G++}await Z.updateItem({TableName:$.tableName,Key:Y.marshall({[$.pkAttribute]:_,[$.skAttribute]:Q}),UpdateExpression:`SET ${j.join(", ")}`,ExpressionAttributeNames:E,ExpressionAttributeValues:V});for(let[J,W]of Object.entries(z))this._attributes[J]=W,this[J]=W;return this._original={...this._attributes},this}async delete(){let X=this.constructor,$=l9(),Z=s9(),Y=this.getKey(),U=`${X.pkPrefix}${X.keyDelimiter}${Y}`,_=X.skPrefix;return await $.deleteItem({TableName:X.tableName,Key:Z.marshall({[X.pkAttribute]:U,[X.skAttribute]:_})}),this._exists=!1,!0}async refresh(){let $=await this.constructor.find(this.getKey());if($){this._attributes=$._attributes,this._original={...this._attributes};for(let[Z,Y]of Object.entries(this._attributes))this[Z]=Y}return this}toObject(){let X=this.constructor,$={...this._attributes};return delete $[X.pkAttribute],delete $[X.skAttribute],delete $[X.entityTypeAttribute],$}toJSON(){return this.toObject()}}class q6{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(X){this.ModelClass=X}wherePk(X){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${X}`,this}where(X,$,Z){if(Z===void 0)this._filterConditions.push({attribute:X,operator:"=",value:$});else this._filterConditions.push({attribute:X,operator:$,value:Z});return this}whereIn(X,$){return this._filterConditions.push({attribute:X,operator:"IN",values:$}),this}whereBetween(X,$,Z){return this._filterConditions.push({attribute:X,operator:"BETWEEN",value:$,values:[$,Z]}),this}whereBeginsWith(X,$){return this._filterConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereExists(X){return this._filterConditions.push({attribute:X,operator:"attribute_exists"}),this}whereNotExists(X){return this._filterConditions.push({attribute:X,operator:"attribute_not_exists"}),this}orderBy(X){return this._scanForward=X==="asc",this}limit(X){return this._limitValue=X,this}select(...X){return this._projectionAttrs.push(...X),this}index(X){return this._indexName=X,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(X){return this._startKey=X,this}buildRequest(){let X=s9(),$={TableName:this.ModelClass.tableName};if(this._indexName)$.IndexName=this._indexName;let Z={},Y={},U=0,_=[];if(this._pkValue){let Q=`#pk${U}`,L=`:pk${U}`;Z[Q]=this.ModelClass.pkAttribute,Y[L]={S:this._pkValue},_.push(`${Q} = ${L}`),U++}if(this._skCondition){let Q=`#sk${U}`;switch(Z[Q]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let L=`:sk${U}`;Y[L]={S:this._skCondition.value},_.push(`${Q} = ${L}`);break}case"begins_with":{let L=`:sk${U}`;Y[L]={S:this._skCondition.value},_.push(`begins_with(${Q}, ${L})`);break}}U++}if(_.length>0)$.KeyConditionExpression=_.join(" AND ");if(this._filterConditions.length>0){let Q=[];for(let L of this._filterConditions){let z=`#flt${U}`;if(Z[z]=L.attribute,L.operator==="attribute_exists")Q.push(`attribute_exists(${z})`);else if(L.operator==="attribute_not_exists")Q.push(`attribute_not_exists(${z})`);else if(L.operator==="IN"&&L.values){let j=L.values.map((E,V)=>`:flt${U}_${V}`);L.values.forEach((E,V)=>{Y[`:flt${U}_${V}`]=X.marshall({v:E}).v}),Q.push(`${z} IN (${j.join(", ")})`)}else if(L.operator==="BETWEEN"&&L.values){let j=`:flt${U}a`,E=`:flt${U}b`;Y[j]=X.marshall({v:L.values[0]}).v,Y[E]=X.marshall({v:L.values[1]}).v,Q.push(`${z} BETWEEN ${j} AND ${E}`)}else if(L.operator==="begins_with"){let j=`:flt${U}`;Y[j]=X.marshall({v:L.value}).v,Q.push(`begins_with(${z}, ${j})`)}else{let j=`:flt${U}`;Y[j]=X.marshall({v:L.value}).v,Q.push(`${z} ${L.operator} ${j}`)}U++}$.FilterExpression=Q.join(" AND ")}if(this._projectionAttrs.length>0){let Q=[];for(let L of this._projectionAttrs){let z=`#proj${U}`;Z[z]=L,Q.push(z),U++}$.ProjectionExpression=Q.join(", ")}if(Object.keys(Z).length>0)$.ExpressionAttributeNames=Z;if(Object.keys(Y).length>0)$.ExpressionAttributeValues=Y;if(this._limitValue!==void 0)$.Limit=this._limitValue;if($.ScanIndexForward=this._scanForward,this._consistentReadValue)$.ConsistentRead=!0;if(this._startKey)$.ExclusiveStartKey=X.marshall(this._startKey);return $}async get(){let X=l9(),$=s9(),Z=this.buildRequest();return((this._pkValue!==void 0?await X.query(Z):await X.scan(Z)).Items??[]).map((Q)=>{let L=$.unmarshall(Q),z=new this.ModelClass(L);return z._exists=!0,z})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let X=l9(),$=this.buildRequest();return $.Select="COUNT",(this._pkValue!==void 0?await X.query($):await X.scan($)).Count??0}async paginate(X,$){let Z=s9();if($)this._startKey=$;this._limitValue=X;let Y=l9(),U=this.buildRequest(),Q=this._pkValue!==void 0?await Y.query(U):await Y.scan(U);return{items:(Q.Items??[]).map((z)=>{let j=Z.unmarshall(z),E=new this.ModelClass(j);return E._exists=!0,E}),lastKey:Q.LastEvaluatedKey?Z.unmarshall(Q.LastEvaluatedKey):void 0}}}var y9,G8=null,F8=null,a7=e(()=>{y9={region:process.env.AWS_REGION??"us-east-1"}});function T8(X){let $=JSON.stringify({tableName:X.tableName,keySchema:X.keySchema,attributeDefinitions:[...X.attributeDefinitions||[]].sort((Y,U)=>Y.name.localeCompare(U.name)),globalSecondaryIndexes:[...X.globalSecondaryIndexes||[]].sort((Y,U)=>Y.indexName.localeCompare(U.indexName)),localSecondaryIndexes:[...X.localSecondaryIndexes||[]].sort((Y,U)=>Y.indexName.localeCompare(U.indexName)),billingMode:X.billingMode,ttlAttribute:X.ttlAttribute,streamSpecification:X.streamSpecification}),Z=0;for(let Y=0;Y<$.length;Y++){let U=$.charCodeAt(Y);Z=(Z<<5)-Z+U,Z=Z&Z}return Math.abs(Z).toString(16).padStart(8,"0")}function t7(X){let $=e7(X);return X2($)}function e7(X){return{tableName:X.tableName||"",pkAttribute:X.pkAttribute||"pk",skAttribute:X.skAttribute||"sk",pkPrefix:X.pkPrefix||"",skPrefix:X.skPrefix||"METADATA",entityTypeAttribute:X.entityTypeAttribute||"_et",timestamps:X.timestamps!==!1,ttlAttribute:X.ttlAttribute,gsis:X.gsis,lsis:X.lsis,billingMode:X.billingMode||"PAY_PER_REQUEST",provisionedThroughput:X.provisionedThroughput,streamEnabled:X.streamEnabled,streamViewType:X.streamViewType}}function X2(X){let $=[{name:X.pkAttribute,type:"S"},{name:X.skAttribute,type:"S"}],Z=[];if(X.gsis)for(let Y of X.gsis){if(!$.some((U)=>U.name===Y.pkAttribute))$.push({name:Y.pkAttribute,type:"S"});if(Y.skAttribute&&!$.some((U)=>U.name===Y.skAttribute))$.push({name:Y.skAttribute,type:"S"});Z.push({indexName:Y.indexName,keySchema:{partitionKey:Y.pkAttribute,sortKey:Y.skAttribute},projection:{type:Array.isArray(Y.projection)?"INCLUDE":Y.projection||"ALL",nonKeyAttributes:Array.isArray(Y.projection)?Y.projection:void 0},provisionedThroughput:Y.provisionedThroughput})}return{tableName:X.tableName,keySchema:{partitionKey:X.pkAttribute,sortKey:X.skAttribute},attributeDefinitions:$,globalSecondaryIndexes:Z.length>0?Z:void 0,billingMode:X.billingMode,provisionedThroughput:X.provisionedThroughput,ttlAttribute:X.ttlAttribute,streamSpecification:X.streamEnabled?{enabled:!0,viewType:X.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function $2(X,$){let Z=[],Y=$.tableName;if(!X)Z.push({type:"CREATE_TABLE",tableName:Y,details:{definition:$}});else{let U=X.keySchema.partitionKey!==$.keySchema.partitionKey,_=X.keySchema.sortKey!==$.keySchema.sortKey;if(U||_)console.warn(`[Migration] Table ${Y}: Key schema changes require table recreation. Current: pk=${X.keySchema.partitionKey}, sk=${X.keySchema.sortKey}. Target: pk=${$.keySchema.partitionKey}, sk=${$.keySchema.sortKey}. This operation is not supported automatically.`);let Q=X.globalSecondaryIndexes||[],L=$.globalSecondaryIndexes||[],z=new Set(Q.map((G)=>G.indexName)),j=new Set(L.map((G)=>G.indexName));for(let G of L)if(!z.has(G.indexName))Z.push({type:"ADD_GSI",tableName:Y,details:{gsi:G}});for(let G of Q)if(!j.has(G.indexName))Z.push({type:"DELETE_GSI",tableName:Y,details:{indexName:G.indexName}});if(X.billingMode!==$.billingMode&&$.billingMode)Z.push({type:"UPDATE_BILLING_MODE",tableName:Y,details:{billingMode:$.billingMode,provisionedThroughput:$.provisionedThroughput}});if(X.ttlAttribute!==$.ttlAttribute)Z.push({type:"UPDATE_TTL",tableName:Y,details:{ttlAttribute:$.ttlAttribute||null,enabled:!!$.ttlAttribute}});let E=X.streamSpecification?.enabled,V=$.streamSpecification?.enabled;if(E!==V)if(V)Z.push({type:"ENABLE_STREAM",tableName:Y,details:{viewType:$.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else Z.push({type:"DISABLE_STREAM",tableName:Y,details:{}})}return{tableName:Y,operations:Z,timestamp:new Date().toISOString(),hash:T8($)}}function dj(X,$){return T8(X)===T8($)}class P6{client;initialized=!1;constructor(X){this.client=X}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(K9),this.initialized=!0}catch(X){if(X.message?.includes("ResourceNotFoundException")||X.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${K9}`),await this.client.createTable({TableName:K9,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(K9),this.initialized=!0;else throw X}}async waitForTableActive(X,$=30){for(let Z=0;Z<$;Z++){try{if((await this.client.describeTable(X)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((Y)=>setTimeout(Y,1000))}throw Error(`Table ${X} did not become active within ${$} seconds`)}async getLatestState(X){await this.ensureMigrationsTable();let $=`${cX}#${X}`,Z=await this.client.query({TableName:K9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:$}},ScanIndexForward:!1,Limit:1});if(!Z.Items||Z.Items.length===0)return null;return this.unmarshallState(Z.Items[0])}async getHistory(X){await this.ensureMigrationsTable();let $=`${cX}#${X}`,Z=await this.client.query({TableName:K9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:$}},ScanIndexForward:!1});if(!Z.Items)return[];return Z.Items.map((Y)=>this.unmarshallState(Y))}async recordMigration(X,$,Z){await this.ensureMigrationsTable();let Y=await this.getLatestState(X),U=Z??(Y?Y.version+1:1),_=`${cX}#${X}`,Q=`${D5}#${String(U).padStart(6,"0")}`,L={tableName:X,hash:T8($),definition:$,appliedAt:new Date().toISOString(),version:U};return await this.client.putItem({TableName:K9,Item:this.marshallState(L,_,Q)}),console.log(`[Migration] Recorded migration for ${X} (version ${U})`),L}async listTrackedTables(){await this.ensureMigrationsTable();let X=await this.client.scan({TableName:K9,ProjectionExpression:"pk"});if(!X.Items)return[];let $=new Set;for(let Z of X.Items){let U=(Z.pk?.S||"").replace(`${cX}#`,"");if(U)$.add(U)}return Array.from($)}async hasMigrations(X){return await this.getLatestState(X)!==null}async deleteMigrationHistory(X){await this.ensureMigrationsTable();let $=await this.getHistory(X),Z=`${cX}#${X}`;for(let Y of $){let U=`${D5}#${String(Y.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:K9,Key:{pk:{S:Z},sk:{S:U}}})}console.log(`[Migration] Deleted migration history for ${X}`)}marshallState(X,$,Z){return{pk:{S:$},sk:{S:Z},tableName:{S:X.tableName},hash:{S:X.hash},definition:{S:JSON.stringify(X.definition)},appliedAt:{S:X.appliedAt},version:{N:String(X.version)}}}unmarshallState(X){return{tableName:X.tableName?.S||"",hash:X.hash?.S||"",definition:JSON.parse(X.definition?.S||"{}"),appliedAt:X.appliedAt?.S||"",version:Number(X.version?.N||0)}}}var K9="_qb_migrations",cX="MIGRATION",D5="VERSION",T6=()=>{};class N6{client;tracker;config;constructor(X){this.config=X,this.client=w6({region:X.region,endpoint:X.endpoint,credentials:X.credentials}),this.tracker=new P6(this.client)}async execute(X){let $={tableName:X.tableName,success:!0,operations:[]};if(X.operations.length===0)return this.log(`[Migration] No changes needed for ${X.tableName}`),$;this.log(`[Migration] Executing ${X.operations.length} operations for ${X.tableName}`);try{for(let Z of X.operations)await this.executeOperation(Z),$.operations.push(Z.type);this.log(`[Migration] Successfully applied ${$.operations.length} operations to ${X.tableName}`)}catch(Z){$.success=!1,$.error=Z.message,console.error(`[Migration] Failed to execute migration for ${X.tableName}:`,Z)}return $}async executeOperation(X){if(this.log(`[Migration] Executing ${X.type} on ${X.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${X.type}`,X.details);return}switch(X.type){case"CREATE_TABLE":await this.createTable(X.details.definition);break;case"DELETE_TABLE":await this.deleteTable(X.tableName);break;case"ADD_GSI":await this.addGSI(X.tableName,X.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(X.tableName,X.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(X.tableName,X.details.ttlAttribute,X.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(X.tableName,X.details.billingMode,X.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(X.tableName,X.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(X.tableName);break;default:throw Error(`Unknown migration operation type: ${X.type}`)}}async createTable(X){let $={TableName:X.tableName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:X.attributeDefinitions.map((Z)=>({AttributeName:Z.name,AttributeType:Z.type})),BillingMode:X.billingMode||"PAY_PER_REQUEST"};if(X.keySchema.sortKey)$.KeySchema.push({AttributeName:X.keySchema.sortKey,KeyType:"RANGE"});if(X.billingMode==="PROVISIONED"&&X.provisionedThroughput)$.ProvisionedThroughput={ReadCapacityUnits:X.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:X.provisionedThroughput.writeCapacityUnits};if(X.globalSecondaryIndexes&&X.globalSecondaryIndexes.length>0)$.GlobalSecondaryIndexes=X.globalSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:Z.keySchema.partitionKey,KeyType:"HASH"},...Z.keySchema.sortKey?[{AttributeName:Z.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}},...Z.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:Z.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:Z.provisionedThroughput.writeCapacityUnits}}:{}}));if(X.localSecondaryIndexes&&X.localSecondaryIndexes.length>0)$.LocalSecondaryIndexes=X.localSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:Z.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}}}));if(X.streamSpecification?.enabled)$.StreamSpecification={StreamEnabled:!0,StreamViewType:X.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${X.tableName}`),await this.client.createTable($),await this.waitForTableActive(X.tableName),X.ttlAttribute)await this.updateTTL(X.tableName,X.ttlAttribute,!0);this.log(`[Migration] Table created: ${X.tableName}`)}async deleteTable(X){this.log(`[Migration] Deleting table: ${X}`),await this.client.deleteTable(X),this.log(`[Migration] Table deleted: ${X}`)}async addGSI(X,$){this.log(`[Migration] Adding GSI ${$.indexName} to ${X}`);let Z=await this.client.describeTable(X),Y=new Set(Z.Table?.AttributeDefinitions?.map((Q)=>Q.AttributeName)||[]),U=[];if(!Y.has($.keySchema.partitionKey))U.push({AttributeName:$.keySchema.partitionKey,AttributeType:"S"});if($.keySchema.sortKey&&!Y.has($.keySchema.sortKey))U.push({AttributeName:$.keySchema.sortKey,AttributeType:"S"});let _={TableName:X,AttributeDefinitions:U.length>0?U:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:$.indexName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"},...$.keySchema.sortKey?[{AttributeName:$.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:$.projection.type,...$.projection.nonKeyAttributes?{NonKeyAttributes:$.projection.nonKeyAttributes}:{}},...$.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:$.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:$.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(_),await this.waitForGSIActive(X,$.indexName),this.log(`[Migration] GSI ${$.indexName} added to ${X}`)}async deleteGSI(X,$){this.log(`[Migration] Deleting GSI ${$} from ${X}`);let Z={TableName:X,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:$}}]};await this.executeUpdateTable(Z),this.log(`[Migration] GSI ${$} deleted from ${X}`)}async updateTTL(X,$,Z){this.log(`[Migration] Updating TTL on ${X}: ${Z?$:"disabled"}`);let Y={TableName:X,TimeToLiveSpecification:{Enabled:Z,AttributeName:$||"ttl"}};await this.executeUpdateTimeToLive(Y),this.log(`[Migration] TTL updated on ${X}`)}async updateBillingMode(X,$,Z){this.log(`[Migration] Updating billing mode on ${X} to ${$}`);let Y={TableName:X,BillingMode:$};if($==="PROVISIONED"&&Z)Y.ProvisionedThroughput={ReadCapacityUnits:Z.readCapacityUnits,WriteCapacityUnits:Z.writeCapacityUnits};await this.executeUpdateTable(Y),await this.waitForTableActive(X),this.log(`[Migration] Billing mode updated on ${X}`)}async enableStream(X,$){this.log(`[Migration] Enabling stream on ${X} with view type ${$}`);let Z={TableName:X,StreamSpecification:{StreamEnabled:!0,StreamViewType:$}};await this.executeUpdateTable(Z),await this.waitForTableActive(X),this.log(`[Migration] Stream enabled on ${X}`)}async disableStream(X){this.log(`[Migration] Disabling stream on ${X}`);let $={TableName:X,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable($),await this.waitForTableActive(X),this.log(`[Migration] Stream disabled on ${X}`)}async executeUpdateTable(X){await this.client.updateTable(X)}async executeUpdateTimeToLive(X){await this.client.updateTimeToLive(X)}async waitForTableActive(X,$=60){this.log(`[Migration] Waiting for table ${X} to become active...`);for(let Z=0;Z<$;Z++){try{let U=(await this.client.describeTable(X)).Table?.TableStatus;if(U==="ACTIVE")return;this.log(`[Migration] Table status: ${U}, waiting...`)}catch{}await new Promise((Y)=>setTimeout(Y,2000))}throw Error(`Table ${X} did not become active within ${$*2} seconds`)}async waitForGSIActive(X,$,Z=120){this.log(`[Migration] Waiting for GSI ${$} to become active...`);for(let Y=0;Y<Z;Y++){try{let _=(await this.client.describeTable(X)).Table?.GlobalSecondaryIndexes?.find((L)=>L.IndexName===$);if(_?.IndexStatus==="ACTIVE")return;let Q=_?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${Q}, waiting...`)}catch{}await new Promise((U)=>setTimeout(U,5000))}throw Error(`GSI ${$} did not become active within ${Z*5} seconds`)}async migrateModel(X){let $=t7(X),Z=null;try{let _=await this.client.describeTable($.tableName);if(_.Table)Z=this.tableInfoToDefinition(_.Table)}catch(_){if(!_.message?.includes("ResourceNotFoundException")&&!_.message?.includes("not found"))throw _}let Y=$2(Z,$),U=await this.execute(Y);if(U.success&&!this.config.dryRun)U.state=await this.tracker.recordMigration($.tableName,$);return U}async migrateModels(X){let $=[];for(let Z of X)try{let Y=await this.migrateModel(Z);$.push(Y)}catch(Y){$.push({tableName:Z.tableName||"unknown",success:!1,operations:[],error:Y.message})}return $}async getStatus(){let X=new Map,$=await this.tracker.listTrackedTables();for(let Z of $){let Y=await this.tracker.getLatestState(Z);X.set(Z,Y)}return X}tableInfoToDefinition(X){let $={partitionKey:"",sortKey:void 0};for(let U of X.KeySchema||[])if(U.KeyType==="HASH")$.partitionKey=U.AttributeName;else if(U.KeyType==="RANGE")$.sortKey=U.AttributeName;let Z=(X.AttributeDefinitions||[]).map((U)=>({name:U.AttributeName,type:U.AttributeType})),Y=(X.GlobalSecondaryIndexes||[]).map((U)=>{let _={partitionKey:"",sortKey:void 0};for(let Q of U.KeySchema||[])if(Q.KeyType==="HASH")_.partitionKey=Q.AttributeName;else if(Q.KeyType==="RANGE")_.sortKey=Q.AttributeName;return{indexName:U.IndexName,keySchema:_,projection:{type:U.Projection?.ProjectionType||"ALL",nonKeyAttributes:U.Projection?.NonKeyAttributes},provisionedThroughput:U.ProvisionedThroughput?{readCapacityUnits:U.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:U.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:X.TableName,keySchema:$,attributeDefinitions:Z,globalSecondaryIndexes:Y.length>0?Y:void 0,billingMode:X.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:X.ProvisionedThroughput?{readCapacityUnits:X.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:X.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:X.TimeToLiveDescription?.AttributeName,streamSpecification:X.StreamSpecification?{enabled:X.StreamSpecification.StreamEnabled,viewType:X.StreamSpecification.StreamViewType}:void 0}}log(...X){if(this.config.verbose||this.config.dryRun)console.log(...X)}}function Z2(X){return new N6(X)}async function pj(X,$){return Z2($).migrateModels(X)}var Y2=e(()=>{T6()});class S6{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(X,$,Z,Y){this.driver=X,this.client=$,this.tableName=Z,this.pkAttribute=Y.pkAttribute,this.skAttribute=Y.skAttribute,this.entityTypeAttr=Y.entityTypeAttribute,this.delimiter=Y.keyDelimiter}entity(X){return this._entityType=X,this}pk(X){return this._pkValue=X,this}get sk(){let X=this;return{equals($){return X._skCondition={type:"eq",value:$},X},beginsWith($){return X._skCondition={type:"begins_with",value:$},X},between($,Z){return X._skCondition={type:"between",value:$,value2:Z},X},lt($){return X._skCondition={type:"lt",value:$},X},lte($){return X._skCondition={type:"lte",value:$},X},gt($){return X._skCondition={type:"gt",value:$},X},gte($){return X._skCondition={type:"gte",value:$},X}}}index(X){return this._indexName=X,this}project(...X){return this._projectionAttrs.push(...X),this}filter(X,$,Z){return this._filterConditions.push({attribute:X,operator:$,value:Z}),this}where(X,$){return this.filter(X,"=",$)}whereIn(X,$){return this._filterConditions.push({attribute:X,operator:"IN",values:$}),this}limit(X){return this._limitValue=X,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(X){return this._startKey=X,this}toRequest(){let X={TableName:this.tableName};if(this._indexName)X.IndexName=this._indexName;let $=[],Z={},Y={},U=0;if(this._pkValue){let _=`#pk${U}`,Q=`:pk${U}`;Z[_]=this.pkAttribute,Y[Q]={S:this._pkValue},$.push(`${_} = ${Q}`),U++}if(this._skCondition){let _=`#sk${U}`;switch(Z[_]=this.skAttribute,this._skCondition.type){case"eq":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} = ${Q}`);break}case"begins_with":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`begins_with(${_}, ${Q})`);break}case"between":{let Q=`:sk${U}a`,L=`:sk${U}b`;Y[Q]={S:this._skCondition.value},Y[L]={S:this._skCondition.value2},$.push(`${_} BETWEEN ${Q} AND ${L}`);break}case"lt":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} < ${Q}`);break}case"lte":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} <= ${Q}`);break}case"gt":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} > ${Q}`);break}case"gte":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} >= ${Q}`);break}}U++}if($.length>0)X.KeyConditionExpression=$.join(" AND ");if(this._filterConditions.length>0){let _=[];for(let Q of this._filterConditions){let L=`#flt${U}`;if(Z[L]=Q.attribute,Q.operator==="IN"&&Q.values){let z=Q.values.map((j,E)=>`:flt${U}_${E}`);Q.values.forEach((j,E)=>{Y[`:flt${U}_${E}`]=this.driver.marshall({v:j}).v}),_.push(`${L} IN (${z.join(", ")})`)}else{let z=`:flt${U}`;Y[z]=this.driver.marshall({v:Q.value}).v,_.push(`${L} ${Q.operator} ${z}`)}U++}X.FilterExpression=_.join(" AND ")}if(this._projectionAttrs.length>0){let _=[];for(let Q of this._projectionAttrs){let L=`#proj${U}`;Z[L]=Q,_.push(L),U++}X.ProjectionExpression=_.join(", ")}if(Object.keys(Z).length>0)X.ExpressionAttributeNames=Z;if(Object.keys(Y).length>0)X.ExpressionAttributeValues=Y;if(this._limitValue!==void 0)X.Limit=this._limitValue;if(X.ScanIndexForward=this._scanForward,this._consistentRead)X.ConsistentRead=!0;if(this._startKey)X.ExclusiveStartKey=this.driver.marshall(this._startKey);return X}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let X=this.toRequest();return((this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X)).Items??[]).map((Y)=>this.driver.unmarshall(Y))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let X=[],$;do{if($)this._startKey=$;let Z=this.toRequest(),U=this._pkValue!==void 0?await this.client.query(Z):await this.client.scan(Z),_=(U.Items??[]).map((Q)=>this.driver.unmarshall(Q));X.push(..._),$=U.LastEvaluatedKey?this.driver.unmarshall(U.LastEvaluatedKey):void 0}while($);return X}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let X=this.toRequest();return X.Select="COUNT",(this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X)).Count??0}}class i1{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(X){let $={region:X.region,tableName:X.table,endpoint:X.endpoint,credentials:X.credentials};return this.driver=bX($),this.tableName=X.table,this.pkAttribute=X.pkAttribute??"pk",this.skAttribute=X.skAttribute??"sk",this.entityTypeAttr=X.entityTypeAttribute??"_et",this.delimiter=X.keyDelimiter??"#",this}setClient(X){return this.client=X,this}registerEntity(X){if(this.entityMappings.set(X.entityType,X),this.driver)this.driver.registerEntity(X);return this}entity(X){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new S6(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(X)}async batchWrite(X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let $=[];for(let Z of X)if(Z.put){let Y={...Z.put.item,[this.entityTypeAttr]:Z.put.entity};$.push({PutRequest:{Item:this.driver.marshall(Y)}})}else if(Z.delete)$.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}});if($.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:$}})}async transactWrite(X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let $=[];for(let Z of X)if(Z.put){let Y={...Z.put.item,[this.entityTypeAttr]:Z.put.entity},U={Put:{TableName:this.tableName,Item:this.driver.marshall(Y)}};if(Z.put.condition)U.Put.ConditionExpression=Z.put.condition;$.push(U)}else if(Z.update){let Y={[this.pkAttribute]:Z.update.pk};if(Z.update.sk)Y[this.skAttribute]=Z.update.sk;let U=[],_={},Q={},L=0;if(Z.update.set){let z=[];for(let[j,E]of Object.entries(Z.update.set)){let V=`#set${L}`,G=`:set${L}`;_[V]=j,Q[G]=this.driver.marshall({v:E}).v,z.push(`${V} = ${G}`),L++}if(z.length>0)U.push(`SET ${z.join(", ")}`)}if(Z.update.add){let z=[];for(let[j,E]of Object.entries(Z.update.add)){let V=`#add${L}`,G=`:add${L}`;_[V]=j,Q[G]={N:String(E)},z.push(`${V} ${G}`),L++}if(z.length>0)U.push(`ADD ${z.join(", ")}`)}if(Z.update.remove&&Z.update.remove.length>0){let z=[];for(let j of Z.update.remove){let E=`#rem${L}`;_[E]=j,z.push(E),L++}U.push(`REMOVE ${z.join(", ")}`)}$.push({Update:{TableName:this.tableName,Key:this.driver.marshall(Y),UpdateExpression:U.join(" "),ExpressionAttributeNames:_,ExpressionAttributeValues:Q}})}else if(Z.delete){let Y={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}};if(Z.delete.condition)Y.Delete.ConditionExpression=Z.delete.condition;$.push(Y)}else if(Z.conditionCheck)$.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.conditionCheck.pk,[this.skAttribute]:Z.conditionCheck.sk}),ConditionExpression:Z.conditionCheck.condition}});if($.length>0)await this.client.transactWriteItems({TransactItems:$})}getDriver(){return this.driver}}function cj(){return new i1}var U2,_2=e(()=>{a7(),Y2(),T6(),U2=new i1});class x6{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!M5(X))return!0;return H5(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=M5(Z)?H5(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.timestamp).sort();return{size:$,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class B6{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function l2(X,$){this[X]=A4.bind(null,$)}class O1{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!C5(X))return!0;return w5(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=C5(Z)?w5(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.timestamp).sort();return{size:$,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class J1{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function s2(X,$={}){let Y=Object.keys($).sort().map((U)=>`${U}:${$[U]}`).join("|");return Y?`${X}:${Y}`:X}function o2(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function r2(X){return X.getStats().size*2}function l1(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&C0($[0])&&"id"in $[0]&&$[0].id===3&&C0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(C0($)&&C0(X)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return X;if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray($)&&Array.isArray(X)){if(C0(X)&&"arr"in X&&Array.isArray(X.arr)&&C0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&C0($[0])&&C0(X[0])){let Y=[...$];for(let U of X)if(C0(U)&&"name"in U){if(!Y.find((Q)=>C0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(C0(U)&&"path"in U){if(!Y.find((Q)=>C0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>B8(_,U)))Y.push(U);return Y}if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}if(!C0($)||!C0(X))return $;let Z={...X};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let U=$[Y];if(U===null||U===void 0)continue;else if(C0(U)&&C0(Z[Y]))Z[Y]=l1(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&C0(U[0])&&C0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(C0(Q)&&"name"in Q){if(!_.find((z)=>C0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(C0(Q)&&"path"in Q){if(!_.find((z)=>C0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>B8(L,Q)))_.push(Q);Z[Y]=_}else if(U.every((_)=>typeof _==="string")&&Z[Y].every((_)=>typeof _==="string")){let _=[...U];for(let Q of Z[Y])if(!_.includes(Q))_.push(Q);Z[Y]=_}else Z[Y]=U;else Z[Y]=U}return Z}function B8(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!B8(X[Z],$[Z]))return!1;return!0}if(C0(X)&&C0($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!B8(X[U],$[U]))return!1}return!0}return!1}function C0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function a2(X,$){if(!k6(X))return null;try{let Z=await import(X),Y=Z.default||Z;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return l1($,Y)}catch{return null}}catch{return null}}async function t2({name:X="",cwd:$,defaultConfig:Z}){let Y=$||F1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],_=[`${X}.config`,`.${X}.config`,X,`.${X}`];for(let Q of _)for(let L of U){let z=k8(Y,`${Q}${L}`),j=await a2(z,Z);if(j!==null)return j}try{let Q=k8(Y,"package.json");if(k6(Q)){let z=(await import(Q))[X];if(z&&typeof z==="object"&&!Array.isArray(z))try{return l1(Z,z)}catch{}}}catch{}return Z}function e2(X,$={}){let Z=A8.cwd();while(Z.includes("storage"))Z=T5(Z,"..");let Y=T5(Z,X||"");if($?.relative)return J2(A8.cwd(),Y);return Y}async function X4(){try{let X=await t2({name:"clarity",defaultConfig:J8,cwd:A8.cwd(),endpoint:"",headers:{}});return{...J8,...X}}catch{return J8}}function P0(){if(P9.env.NODE_ENV==="test"||P9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $4(){if(P9.env.NODE_ENV==="test"||P9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P9<"u"){let X=P9.type;if(X==="renderer"||X==="worker")return!1;return!!(P9.versions&&(P9.versions.node||P9.versions.bun))}return!1}class y6{async format(X){let $=await $4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:GX.pid,hostname:$(),environment:GX.env.NODE_ENV||"development",platform:GX.platform,version:GX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:GX.env.NODE_ENV||GX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class y8{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(X,$={}){this.name=X,this.config={...K1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new y6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??b0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...W8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...W8};return{...W8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:K1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await R2(this.config.logDirectory,k5.F_OK|k5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await D2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:h9.from(X);try{if(!JZ(this.currentLogFile))await WZ(this.currentLogFile,"",{mode:420});if(U=A5(this.currentLogFile,"a",420),K2(U,z,{flag:"a"}),S5(U),U!==void 0)OZ(U),U=void 0;if((await jX(this.currentLogFile)).size===0){if(await WZ(this.currentLogFile,z,{flag:"w",mode:420}),(await jX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{OZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 EX(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 EX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return EX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(P0())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return FZ(16).toString("hex")}generateKey(){return FZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=FZ(16),Y=W2("aes-256-gcm",$,Z),U=h9.concat([Y.update(X,"utf8"),Y.final()]),_=Y.getAuthTag();return{encrypted:h9.concat([Z,U,_]),iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=B5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(h9.from(h9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(P0())return;let X=await jX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await f$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await jX(Z).catch(()=>null))try{if(await x5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await g$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await WZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await jX(Z).catch(()=>null))await x5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await f$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await g$(EX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=N5(X),Y=I2($),U=B5();await M2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Z={timestamp:new Date,level:X,message:$,name:this.name};this.logBuffer.push(Z)}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(X)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(X){return{debug:0,info:1,success:2,warning:3,error:4}[X]}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),JZ(this.currentLogFile))try{let X=A5(this.currentLogFile,"r+");S5(X),OZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!P0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await f$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await g$(EX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.fancy?R0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=b0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${R0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}async log(X,$,...Z){let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);if(this.fancy&&!P0()){let j=a6[X],E=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",V;switch(X){case"debug":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:R0.gray(Q),level:X}),console.error(V);break;case"info":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.error(V);break;case"success":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:R0.green(Q),level:X}),console.error(V);break;case"warning":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.warn(V);break;case"error":if(V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.error(V),L){let G=L.split(`
|
|
7
|
-
`);for(let J of G)if(J.trim()&&!J.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:
|
|
4
|
+
`,F=J.map((d)=>d.toLowerCase()).join(";"),K=await D5(Y),D=[X,E,V,W,F,K].join(`
|
|
5
|
+
`),w=await D5(D),T="AWS4-HMAC-SHA256",N=`${j}/${_}/${Q}/aws4_request`,q=[T,z,N,w].join(`
|
|
6
|
+
`),H=await o7(U.secretAccessKey,j,_,Q),S=await iX(H,q),h=Array.from(new Uint8Array(S)).map((d)=>d.toString(16).padStart(2,"0")).join(""),p=`${T} Credential=${U.accessKeyId}/${N}, SignedHeaders=${F}, Signature=${h}`;return{...G,authorization:p}}class w6{config;endpoint;credentials;constructor(X){if(this.config=X,this.endpoint=X.endpoint??`https://dynamodb.${X.region}.amazonaws.com`,this.credentials=X.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(X,$){let Z=new URL(this.endpoint),Y=JSON.stringify($),U={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${X}`},_=await r7("POST",Z,U,Y,this.credentials,this.config.region,"dynamodb"),Q=await fetch(Z.toString(),{method:"POST",headers:_,body:Y});if(!Q.ok){let L=await Q.text(),z;try{let j=JSON.parse(L);z=j.message??j.Message??L}catch{z=L}throw Error(`DynamoDB ${X} failed: ${Q.status} - ${z}`)}return Q.json()}async query(X){return this.execute("Query",X)}async scan(X){return this.execute("Scan",X)}async getItem(X){return this.execute("GetItem",X)}async putItem(X){return this.execute("PutItem",X)}async updateItem(X){return this.execute("UpdateItem",X)}async deleteItem(X){return this.execute("DeleteItem",X)}async batchGetItem(X){return this.execute("BatchGetItem",X)}async batchWriteItem(X){return this.execute("BatchWriteItem",X)}async transactWriteItems(X){return this.execute("TransactWriteItems",X)}async describeTable(X){return this.execute("DescribeTable",{TableName:X})}async createTable(X){return this.execute("CreateTable",X)}async deleteTable(X){return this.execute("DeleteTable",{TableName:X})}async listTables(X){return this.execute("ListTables",X??{})}async updateTable(X){return this.execute("UpdateTable",X)}async updateTimeToLive(X){return this.execute("UpdateTimeToLive",X)}async describeTimeToLive(X){return this.execute("DescribeTimeToLive",{TableName:X})}}function q6(X){return new w6(X)}function pj(X){h9={...h9,...X},G8=null,F8=null}function l9(){if(!G8)G8=q6({region:h9.region??"us-east-1",endpoint:h9.endpoint,credentials:h9.credentials});return G8}function s9(){if(!F8)F8=bX({region:h9.region??"us-east-1",endpoint:h9.endpoint,credentials:h9.credentials});return F8}class a7{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(X={}){this._attributes={...X},this._original={...X};for(let[$,Z]of Object.entries(X))this[$]=Z}static query(){return new P6(this)}static async find(X){let $=this,Z=l9(),Y=s9(),U=`${$.pkPrefix}${$.keyDelimiter}${X}`,_=$.skPrefix;try{let Q=await Z.getItem({TableName:$.tableName,Key:Y.marshall({[$.pkAttribute]:U,[$.skAttribute]:_})});if(!Q.Item)return null;let L=Y.unmarshall(Q.Item),z=new $(L);return z._exists=!0,z}catch(Q){return console.error("Find error:",Q),null}}static async findOrFail(X){let $=await this.find(X);if(!$)throw Error(`${this.name} not found with id: ${X}`);return $}static async all(){return this.query().get()}static async create(X){let $=this,Z=l9(),Y=s9(),U=X[$.primaryKey];if(!U)throw Error(`${$.primaryKey} is required`);let _=`${$.pkPrefix}${$.keyDelimiter}${U}`,Q=$.skPrefix,L=new Date().toISOString(),z={...X,[$.pkAttribute]:_,[$.skAttribute]:Q,[$.entityTypeAttribute]:$.name};if($.timestamps)z[$.createdAtField]=L,z[$.updatedAtField]=L;await Z.putItem({TableName:$.tableName,Item:Y.marshall(z),ConditionExpression:`attribute_not_exists(${$.pkAttribute})`});let j=new $(z);return j._exists=!0,j}static async updateOrCreate(X,$){let Z=this,Y=X[Z.primaryKey],U=await Z.find(Y);if(U)return await U.update($),U;return Z.create({...X,...$})}static where(X,$,Z){return this.query().where(X,$,Z)}static wherePk(X){return this.query().wherePk(X)}getKey(){let X=this.constructor;return this[X.primaryKey]}getAttribute(X){return this._attributes[X]}setAttribute(X,$){return this._attributes[X]=$,this[X]=$,this}getAttributes(){return{...this._attributes}}isDirty(X){if(X)return this._attributes[X]!==this._original[X];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let X={};for(let[$,Z]of Object.entries(this._attributes))if(Z!==this._original[$])X[$]=Z;return X}async save(){if(this._exists){let X=this.getDirty();if(Object.keys(X).length>0)await this.update(X)}else{let $=await this.constructor.create(this._attributes);this._attributes=$._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(X){let $=this.constructor,Z=l9(),Y=s9(),U=this.getKey(),_=`${$.pkPrefix}${$.keyDelimiter}${U}`,Q=$.skPrefix,L=new Date().toISOString(),z={...X};if($.timestamps)z[$.updatedAtField]=L;let j=[],E={},V={},G=0;for(let[J,W]of Object.entries(z)){let F=`#attr${G}`,K=`:val${G}`;E[F]=J,V[K]=Y.marshall({v:W}).v,j.push(`${F} = ${K}`),G++}await Z.updateItem({TableName:$.tableName,Key:Y.marshall({[$.pkAttribute]:_,[$.skAttribute]:Q}),UpdateExpression:`SET ${j.join(", ")}`,ExpressionAttributeNames:E,ExpressionAttributeValues:V});for(let[J,W]of Object.entries(z))this._attributes[J]=W,this[J]=W;return this._original={...this._attributes},this}async delete(){let X=this.constructor,$=l9(),Z=s9(),Y=this.getKey(),U=`${X.pkPrefix}${X.keyDelimiter}${Y}`,_=X.skPrefix;return await $.deleteItem({TableName:X.tableName,Key:Z.marshall({[X.pkAttribute]:U,[X.skAttribute]:_})}),this._exists=!1,!0}async refresh(){let $=await this.constructor.find(this.getKey());if($){this._attributes=$._attributes,this._original={...this._attributes};for(let[Z,Y]of Object.entries(this._attributes))this[Z]=Y}return this}toObject(){let X=this.constructor,$={...this._attributes};return delete $[X.pkAttribute],delete $[X.skAttribute],delete $[X.entityTypeAttribute],$}toJSON(){return this.toObject()}}class P6{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(X){this.ModelClass=X}wherePk(X){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${X}`,this}where(X,$,Z){if(Z===void 0)this._filterConditions.push({attribute:X,operator:"=",value:$});else this._filterConditions.push({attribute:X,operator:$,value:Z});return this}whereIn(X,$){return this._filterConditions.push({attribute:X,operator:"IN",values:$}),this}whereBetween(X,$,Z){return this._filterConditions.push({attribute:X,operator:"BETWEEN",value:$,values:[$,Z]}),this}whereBeginsWith(X,$){return this._filterConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereExists(X){return this._filterConditions.push({attribute:X,operator:"attribute_exists"}),this}whereNotExists(X){return this._filterConditions.push({attribute:X,operator:"attribute_not_exists"}),this}orderBy(X){return this._scanForward=X==="asc",this}limit(X){return this._limitValue=X,this}select(...X){return this._projectionAttrs.push(...X),this}index(X){return this._indexName=X,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(X){return this._startKey=X,this}buildRequest(){let X=s9(),$={TableName:this.ModelClass.tableName};if(this._indexName)$.IndexName=this._indexName;let Z={},Y={},U=0,_=[];if(this._pkValue){let Q=`#pk${U}`,L=`:pk${U}`;Z[Q]=this.ModelClass.pkAttribute,Y[L]={S:this._pkValue},_.push(`${Q} = ${L}`),U++}if(this._skCondition){let Q=`#sk${U}`;switch(Z[Q]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let L=`:sk${U}`;Y[L]={S:this._skCondition.value},_.push(`${Q} = ${L}`);break}case"begins_with":{let L=`:sk${U}`;Y[L]={S:this._skCondition.value},_.push(`begins_with(${Q}, ${L})`);break}}U++}if(_.length>0)$.KeyConditionExpression=_.join(" AND ");if(this._filterConditions.length>0){let Q=[];for(let L of this._filterConditions){let z=`#flt${U}`;if(Z[z]=L.attribute,L.operator==="attribute_exists")Q.push(`attribute_exists(${z})`);else if(L.operator==="attribute_not_exists")Q.push(`attribute_not_exists(${z})`);else if(L.operator==="IN"&&L.values){let j=L.values.map((E,V)=>`:flt${U}_${V}`);L.values.forEach((E,V)=>{Y[`:flt${U}_${V}`]=X.marshall({v:E}).v}),Q.push(`${z} IN (${j.join(", ")})`)}else if(L.operator==="BETWEEN"&&L.values){let j=`:flt${U}a`,E=`:flt${U}b`;Y[j]=X.marshall({v:L.values[0]}).v,Y[E]=X.marshall({v:L.values[1]}).v,Q.push(`${z} BETWEEN ${j} AND ${E}`)}else if(L.operator==="begins_with"){let j=`:flt${U}`;Y[j]=X.marshall({v:L.value}).v,Q.push(`begins_with(${z}, ${j})`)}else{let j=`:flt${U}`;Y[j]=X.marshall({v:L.value}).v,Q.push(`${z} ${L.operator} ${j}`)}U++}$.FilterExpression=Q.join(" AND ")}if(this._projectionAttrs.length>0){let Q=[];for(let L of this._projectionAttrs){let z=`#proj${U}`;Z[z]=L,Q.push(z),U++}$.ProjectionExpression=Q.join(", ")}if(Object.keys(Z).length>0)$.ExpressionAttributeNames=Z;if(Object.keys(Y).length>0)$.ExpressionAttributeValues=Y;if(this._limitValue!==void 0)$.Limit=this._limitValue;if($.ScanIndexForward=this._scanForward,this._consistentReadValue)$.ConsistentRead=!0;if(this._startKey)$.ExclusiveStartKey=X.marshall(this._startKey);return $}async get(){let X=l9(),$=s9(),Z=this.buildRequest();return((this._pkValue!==void 0?await X.query(Z):await X.scan(Z)).Items??[]).map((Q)=>{let L=$.unmarshall(Q),z=new this.ModelClass(L);return z._exists=!0,z})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let X=l9(),$=this.buildRequest();return $.Select="COUNT",(this._pkValue!==void 0?await X.query($):await X.scan($)).Count??0}async paginate(X,$){let Z=s9();if($)this._startKey=$;this._limitValue=X;let Y=l9(),U=this.buildRequest(),Q=this._pkValue!==void 0?await Y.query(U):await Y.scan(U);return{items:(Q.Items??[]).map((z)=>{let j=Z.unmarshall(z),E=new this.ModelClass(j);return E._exists=!0,E}),lastKey:Q.LastEvaluatedKey?Z.unmarshall(Q.LastEvaluatedKey):void 0}}}var h9,G8=null,F8=null,t7=t(()=>{h9={region:process.env.AWS_REGION??"us-east-1"}});function T8(X){let $=JSON.stringify({tableName:X.tableName,keySchema:X.keySchema,attributeDefinitions:[...X.attributeDefinitions||[]].sort((Y,U)=>Y.name.localeCompare(U.name)),globalSecondaryIndexes:[...X.globalSecondaryIndexes||[]].sort((Y,U)=>Y.indexName.localeCompare(U.indexName)),localSecondaryIndexes:[...X.localSecondaryIndexes||[]].sort((Y,U)=>Y.indexName.localeCompare(U.indexName)),billingMode:X.billingMode,ttlAttribute:X.ttlAttribute,streamSpecification:X.streamSpecification}),Z=0;for(let Y=0;Y<$.length;Y++){let U=$.charCodeAt(Y);Z=(Z<<5)-Z+U,Z=Z&Z}return Math.abs(Z).toString(16).padStart(8,"0")}function e7(X){let $=X2(X);return $2($)}function X2(X){return{tableName:X.tableName||"",pkAttribute:X.pkAttribute||"pk",skAttribute:X.skAttribute||"sk",pkPrefix:X.pkPrefix||"",skPrefix:X.skPrefix||"METADATA",entityTypeAttribute:X.entityTypeAttribute||"_et",timestamps:X.timestamps!==!1,ttlAttribute:X.ttlAttribute,gsis:X.gsis,lsis:X.lsis,billingMode:X.billingMode||"PAY_PER_REQUEST",provisionedThroughput:X.provisionedThroughput,streamEnabled:X.streamEnabled,streamViewType:X.streamViewType}}function $2(X){let $=[{name:X.pkAttribute,type:"S"},{name:X.skAttribute,type:"S"}],Z=[];if(X.gsis)for(let Y of X.gsis){if(!$.some((U)=>U.name===Y.pkAttribute))$.push({name:Y.pkAttribute,type:"S"});if(Y.skAttribute&&!$.some((U)=>U.name===Y.skAttribute))$.push({name:Y.skAttribute,type:"S"});Z.push({indexName:Y.indexName,keySchema:{partitionKey:Y.pkAttribute,sortKey:Y.skAttribute},projection:{type:Array.isArray(Y.projection)?"INCLUDE":Y.projection||"ALL",nonKeyAttributes:Array.isArray(Y.projection)?Y.projection:void 0},provisionedThroughput:Y.provisionedThroughput})}return{tableName:X.tableName,keySchema:{partitionKey:X.pkAttribute,sortKey:X.skAttribute},attributeDefinitions:$,globalSecondaryIndexes:Z.length>0?Z:void 0,billingMode:X.billingMode,provisionedThroughput:X.provisionedThroughput,ttlAttribute:X.ttlAttribute,streamSpecification:X.streamEnabled?{enabled:!0,viewType:X.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Z2(X,$){let Z=[],Y=$.tableName;if(!X)Z.push({type:"CREATE_TABLE",tableName:Y,details:{definition:$}});else{let U=X.keySchema.partitionKey!==$.keySchema.partitionKey,_=X.keySchema.sortKey!==$.keySchema.sortKey;if(U||_)console.warn(`[Migration] Table ${Y}: Key schema changes require table recreation. Current: pk=${X.keySchema.partitionKey}, sk=${X.keySchema.sortKey}. Target: pk=${$.keySchema.partitionKey}, sk=${$.keySchema.sortKey}. This operation is not supported automatically.`);let Q=X.globalSecondaryIndexes||[],L=$.globalSecondaryIndexes||[],z=new Set(Q.map((G)=>G.indexName)),j=new Set(L.map((G)=>G.indexName));for(let G of L)if(!z.has(G.indexName))Z.push({type:"ADD_GSI",tableName:Y,details:{gsi:G}});for(let G of Q)if(!j.has(G.indexName))Z.push({type:"DELETE_GSI",tableName:Y,details:{indexName:G.indexName}});if(X.billingMode!==$.billingMode&&$.billingMode)Z.push({type:"UPDATE_BILLING_MODE",tableName:Y,details:{billingMode:$.billingMode,provisionedThroughput:$.provisionedThroughput}});if(X.ttlAttribute!==$.ttlAttribute)Z.push({type:"UPDATE_TTL",tableName:Y,details:{ttlAttribute:$.ttlAttribute||null,enabled:!!$.ttlAttribute}});let E=X.streamSpecification?.enabled,V=$.streamSpecification?.enabled;if(E!==V)if(V)Z.push({type:"ENABLE_STREAM",tableName:Y,details:{viewType:$.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else Z.push({type:"DISABLE_STREAM",tableName:Y,details:{}})}return{tableName:Y,operations:Z,timestamp:new Date().toISOString(),hash:T8($)}}function cj(X,$){return T8(X)===T8($)}class T6{client;initialized=!1;constructor(X){this.client=X}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(R9),this.initialized=!0}catch(X){if(X.message?.includes("ResourceNotFoundException")||X.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${R9}`),await this.client.createTable({TableName:R9,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(R9),this.initialized=!0;else throw X}}async waitForTableActive(X,$=30){for(let Z=0;Z<$;Z++){try{if((await this.client.describeTable(X)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((Y)=>setTimeout(Y,1000))}throw Error(`Table ${X} did not become active within ${$} seconds`)}async getLatestState(X){await this.ensureMigrationsTable();let $=`${cX}#${X}`,Z=await this.client.query({TableName:R9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:$}},ScanIndexForward:!1,Limit:1});if(!Z.Items||Z.Items.length===0)return null;return this.unmarshallState(Z.Items[0])}async getHistory(X){await this.ensureMigrationsTable();let $=`${cX}#${X}`,Z=await this.client.query({TableName:R9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:$}},ScanIndexForward:!1});if(!Z.Items)return[];return Z.Items.map((Y)=>this.unmarshallState(Y))}async recordMigration(X,$,Z){await this.ensureMigrationsTable();let Y=await this.getLatestState(X),U=Z??(Y?Y.version+1:1),_=`${cX}#${X}`,Q=`${M5}#${String(U).padStart(6,"0")}`,L={tableName:X,hash:T8($),definition:$,appliedAt:new Date().toISOString(),version:U};return await this.client.putItem({TableName:R9,Item:this.marshallState(L,_,Q)}),console.log(`[Migration] Recorded migration for ${X} (version ${U})`),L}async listTrackedTables(){await this.ensureMigrationsTable();let X=await this.client.scan({TableName:R9,ProjectionExpression:"pk"});if(!X.Items)return[];let $=new Set;for(let Z of X.Items){let U=(Z.pk?.S||"").replace(`${cX}#`,"");if(U)$.add(U)}return Array.from($)}async hasMigrations(X){return await this.getLatestState(X)!==null}async deleteMigrationHistory(X){await this.ensureMigrationsTable();let $=await this.getHistory(X),Z=`${cX}#${X}`;for(let Y of $){let U=`${M5}#${String(Y.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:R9,Key:{pk:{S:Z},sk:{S:U}}})}console.log(`[Migration] Deleted migration history for ${X}`)}marshallState(X,$,Z){return{pk:{S:$},sk:{S:Z},tableName:{S:X.tableName},hash:{S:X.hash},definition:{S:JSON.stringify(X.definition)},appliedAt:{S:X.appliedAt},version:{N:String(X.version)}}}unmarshallState(X){return{tableName:X.tableName?.S||"",hash:X.hash?.S||"",definition:JSON.parse(X.definition?.S||"{}"),appliedAt:X.appliedAt?.S||"",version:Number(X.version?.N||0)}}}var R9="_qb_migrations",cX="MIGRATION",M5="VERSION",N6=()=>{};class S6{client;tracker;config;constructor(X){this.config=X,this.client=q6({region:X.region,endpoint:X.endpoint,credentials:X.credentials}),this.tracker=new T6(this.client)}async execute(X){let $={tableName:X.tableName,success:!0,operations:[]};if(X.operations.length===0)return this.log(`[Migration] No changes needed for ${X.tableName}`),$;this.log(`[Migration] Executing ${X.operations.length} operations for ${X.tableName}`);try{for(let Z of X.operations)await this.executeOperation(Z),$.operations.push(Z.type);this.log(`[Migration] Successfully applied ${$.operations.length} operations to ${X.tableName}`)}catch(Z){$.success=!1,$.error=Z.message,console.error(`[Migration] Failed to execute migration for ${X.tableName}:`,Z)}return $}async executeOperation(X){if(this.log(`[Migration] Executing ${X.type} on ${X.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${X.type}`,X.details);return}switch(X.type){case"CREATE_TABLE":await this.createTable(X.details.definition);break;case"DELETE_TABLE":await this.deleteTable(X.tableName);break;case"ADD_GSI":await this.addGSI(X.tableName,X.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(X.tableName,X.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(X.tableName,X.details.ttlAttribute,X.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(X.tableName,X.details.billingMode,X.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(X.tableName,X.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(X.tableName);break;default:throw Error(`Unknown migration operation type: ${X.type}`)}}async createTable(X){let $={TableName:X.tableName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:X.attributeDefinitions.map((Z)=>({AttributeName:Z.name,AttributeType:Z.type})),BillingMode:X.billingMode||"PAY_PER_REQUEST"};if(X.keySchema.sortKey)$.KeySchema.push({AttributeName:X.keySchema.sortKey,KeyType:"RANGE"});if(X.billingMode==="PROVISIONED"&&X.provisionedThroughput)$.ProvisionedThroughput={ReadCapacityUnits:X.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:X.provisionedThroughput.writeCapacityUnits};if(X.globalSecondaryIndexes&&X.globalSecondaryIndexes.length>0)$.GlobalSecondaryIndexes=X.globalSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:Z.keySchema.partitionKey,KeyType:"HASH"},...Z.keySchema.sortKey?[{AttributeName:Z.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}},...Z.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:Z.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:Z.provisionedThroughput.writeCapacityUnits}}:{}}));if(X.localSecondaryIndexes&&X.localSecondaryIndexes.length>0)$.LocalSecondaryIndexes=X.localSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:Z.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}}}));if(X.streamSpecification?.enabled)$.StreamSpecification={StreamEnabled:!0,StreamViewType:X.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${X.tableName}`),await this.client.createTable($),await this.waitForTableActive(X.tableName),X.ttlAttribute)await this.updateTTL(X.tableName,X.ttlAttribute,!0);this.log(`[Migration] Table created: ${X.tableName}`)}async deleteTable(X){this.log(`[Migration] Deleting table: ${X}`),await this.client.deleteTable(X),this.log(`[Migration] Table deleted: ${X}`)}async addGSI(X,$){this.log(`[Migration] Adding GSI ${$.indexName} to ${X}`);let Z=await this.client.describeTable(X),Y=new Set(Z.Table?.AttributeDefinitions?.map((Q)=>Q.AttributeName)||[]),U=[];if(!Y.has($.keySchema.partitionKey))U.push({AttributeName:$.keySchema.partitionKey,AttributeType:"S"});if($.keySchema.sortKey&&!Y.has($.keySchema.sortKey))U.push({AttributeName:$.keySchema.sortKey,AttributeType:"S"});let _={TableName:X,AttributeDefinitions:U.length>0?U:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:$.indexName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"},...$.keySchema.sortKey?[{AttributeName:$.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:$.projection.type,...$.projection.nonKeyAttributes?{NonKeyAttributes:$.projection.nonKeyAttributes}:{}},...$.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:$.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:$.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(_),await this.waitForGSIActive(X,$.indexName),this.log(`[Migration] GSI ${$.indexName} added to ${X}`)}async deleteGSI(X,$){this.log(`[Migration] Deleting GSI ${$} from ${X}`);let Z={TableName:X,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:$}}]};await this.executeUpdateTable(Z),this.log(`[Migration] GSI ${$} deleted from ${X}`)}async updateTTL(X,$,Z){this.log(`[Migration] Updating TTL on ${X}: ${Z?$:"disabled"}`);let Y={TableName:X,TimeToLiveSpecification:{Enabled:Z,AttributeName:$||"ttl"}};await this.executeUpdateTimeToLive(Y),this.log(`[Migration] TTL updated on ${X}`)}async updateBillingMode(X,$,Z){this.log(`[Migration] Updating billing mode on ${X} to ${$}`);let Y={TableName:X,BillingMode:$};if($==="PROVISIONED"&&Z)Y.ProvisionedThroughput={ReadCapacityUnits:Z.readCapacityUnits,WriteCapacityUnits:Z.writeCapacityUnits};await this.executeUpdateTable(Y),await this.waitForTableActive(X),this.log(`[Migration] Billing mode updated on ${X}`)}async enableStream(X,$){this.log(`[Migration] Enabling stream on ${X} with view type ${$}`);let Z={TableName:X,StreamSpecification:{StreamEnabled:!0,StreamViewType:$}};await this.executeUpdateTable(Z),await this.waitForTableActive(X),this.log(`[Migration] Stream enabled on ${X}`)}async disableStream(X){this.log(`[Migration] Disabling stream on ${X}`);let $={TableName:X,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable($),await this.waitForTableActive(X),this.log(`[Migration] Stream disabled on ${X}`)}async executeUpdateTable(X){await this.client.updateTable(X)}async executeUpdateTimeToLive(X){await this.client.updateTimeToLive(X)}async waitForTableActive(X,$=60){this.log(`[Migration] Waiting for table ${X} to become active...`);for(let Z=0;Z<$;Z++){try{let U=(await this.client.describeTable(X)).Table?.TableStatus;if(U==="ACTIVE")return;this.log(`[Migration] Table status: ${U}, waiting...`)}catch{}await new Promise((Y)=>setTimeout(Y,2000))}throw Error(`Table ${X} did not become active within ${$*2} seconds`)}async waitForGSIActive(X,$,Z=120){this.log(`[Migration] Waiting for GSI ${$} to become active...`);for(let Y=0;Y<Z;Y++){try{let _=(await this.client.describeTable(X)).Table?.GlobalSecondaryIndexes?.find((L)=>L.IndexName===$);if(_?.IndexStatus==="ACTIVE")return;let Q=_?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${Q}, waiting...`)}catch{}await new Promise((U)=>setTimeout(U,5000))}throw Error(`GSI ${$} did not become active within ${Z*5} seconds`)}async migrateModel(X){let $=e7(X),Z=null;try{let _=await this.client.describeTable($.tableName);if(_.Table)Z=this.tableInfoToDefinition(_.Table)}catch(_){if(!_.message?.includes("ResourceNotFoundException")&&!_.message?.includes("not found"))throw _}let Y=Z2(Z,$),U=await this.execute(Y);if(U.success&&!this.config.dryRun)U.state=await this.tracker.recordMigration($.tableName,$);return U}async migrateModels(X){let $=[];for(let Z of X)try{let Y=await this.migrateModel(Z);$.push(Y)}catch(Y){$.push({tableName:Z.tableName||"unknown",success:!1,operations:[],error:Y.message})}return $}async getStatus(){let X=new Map,$=await this.tracker.listTrackedTables();for(let Z of $){let Y=await this.tracker.getLatestState(Z);X.set(Z,Y)}return X}tableInfoToDefinition(X){let $={partitionKey:"",sortKey:void 0};for(let U of X.KeySchema||[])if(U.KeyType==="HASH")$.partitionKey=U.AttributeName;else if(U.KeyType==="RANGE")$.sortKey=U.AttributeName;let Z=(X.AttributeDefinitions||[]).map((U)=>({name:U.AttributeName,type:U.AttributeType})),Y=(X.GlobalSecondaryIndexes||[]).map((U)=>{let _={partitionKey:"",sortKey:void 0};for(let Q of U.KeySchema||[])if(Q.KeyType==="HASH")_.partitionKey=Q.AttributeName;else if(Q.KeyType==="RANGE")_.sortKey=Q.AttributeName;return{indexName:U.IndexName,keySchema:_,projection:{type:U.Projection?.ProjectionType||"ALL",nonKeyAttributes:U.Projection?.NonKeyAttributes},provisionedThroughput:U.ProvisionedThroughput?{readCapacityUnits:U.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:U.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:X.TableName,keySchema:$,attributeDefinitions:Z,globalSecondaryIndexes:Y.length>0?Y:void 0,billingMode:X.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:X.ProvisionedThroughput?{readCapacityUnits:X.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:X.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:X.TimeToLiveDescription?.AttributeName,streamSpecification:X.StreamSpecification?{enabled:X.StreamSpecification.StreamEnabled,viewType:X.StreamSpecification.StreamViewType}:void 0}}log(...X){if(this.config.verbose||this.config.dryRun)console.log(...X)}}function Y2(X){return new S6(X)}async function mj(X,$){return Y2($).migrateModels(X)}var U2=t(()=>{N6()});class A6{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(X,$,Z,Y){this.driver=X,this.client=$,this.tableName=Z,this.pkAttribute=Y.pkAttribute,this.skAttribute=Y.skAttribute,this.entityTypeAttr=Y.entityTypeAttribute,this.delimiter=Y.keyDelimiter}entity(X){return this._entityType=X,this}pk(X){return this._pkValue=X,this}get sk(){let X=this;return{equals($){return X._skCondition={type:"eq",value:$},X},beginsWith($){return X._skCondition={type:"begins_with",value:$},X},between($,Z){return X._skCondition={type:"between",value:$,value2:Z},X},lt($){return X._skCondition={type:"lt",value:$},X},lte($){return X._skCondition={type:"lte",value:$},X},gt($){return X._skCondition={type:"gt",value:$},X},gte($){return X._skCondition={type:"gte",value:$},X}}}index(X){return this._indexName=X,this}project(...X){return this._projectionAttrs.push(...X),this}filter(X,$,Z){return this._filterConditions.push({attribute:X,operator:$,value:Z}),this}where(X,$){return this.filter(X,"=",$)}whereIn(X,$){return this._filterConditions.push({attribute:X,operator:"IN",values:$}),this}limit(X){return this._limitValue=X,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(X){return this._startKey=X,this}toRequest(){let X={TableName:this.tableName};if(this._indexName)X.IndexName=this._indexName;let $=[],Z={},Y={},U=0;if(this._pkValue){let _=`#pk${U}`,Q=`:pk${U}`;Z[_]=this.pkAttribute,Y[Q]={S:this._pkValue},$.push(`${_} = ${Q}`),U++}if(this._skCondition){let _=`#sk${U}`;switch(Z[_]=this.skAttribute,this._skCondition.type){case"eq":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} = ${Q}`);break}case"begins_with":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`begins_with(${_}, ${Q})`);break}case"between":{let Q=`:sk${U}a`,L=`:sk${U}b`;Y[Q]={S:this._skCondition.value},Y[L]={S:this._skCondition.value2},$.push(`${_} BETWEEN ${Q} AND ${L}`);break}case"lt":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} < ${Q}`);break}case"lte":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} <= ${Q}`);break}case"gt":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} > ${Q}`);break}case"gte":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} >= ${Q}`);break}}U++}if($.length>0)X.KeyConditionExpression=$.join(" AND ");if(this._filterConditions.length>0){let _=[];for(let Q of this._filterConditions){let L=`#flt${U}`;if(Z[L]=Q.attribute,Q.operator==="IN"&&Q.values){let z=Q.values.map((j,E)=>`:flt${U}_${E}`);Q.values.forEach((j,E)=>{Y[`:flt${U}_${E}`]=this.driver.marshall({v:j}).v}),_.push(`${L} IN (${z.join(", ")})`)}else{let z=`:flt${U}`;Y[z]=this.driver.marshall({v:Q.value}).v,_.push(`${L} ${Q.operator} ${z}`)}U++}X.FilterExpression=_.join(" AND ")}if(this._projectionAttrs.length>0){let _=[];for(let Q of this._projectionAttrs){let L=`#proj${U}`;Z[L]=Q,_.push(L),U++}X.ProjectionExpression=_.join(", ")}if(Object.keys(Z).length>0)X.ExpressionAttributeNames=Z;if(Object.keys(Y).length>0)X.ExpressionAttributeValues=Y;if(this._limitValue!==void 0)X.Limit=this._limitValue;if(X.ScanIndexForward=this._scanForward,this._consistentRead)X.ConsistentRead=!0;if(this._startKey)X.ExclusiveStartKey=this.driver.marshall(this._startKey);return X}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let X=this.toRequest();return((this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X)).Items??[]).map((Y)=>this.driver.unmarshall(Y))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let X=[],$;do{if($)this._startKey=$;let Z=this.toRequest(),U=this._pkValue!==void 0?await this.client.query(Z):await this.client.scan(Z),_=(U.Items??[]).map((Q)=>this.driver.unmarshall(Q));X.push(..._),$=U.LastEvaluatedKey?this.driver.unmarshall(U.LastEvaluatedKey):void 0}while($);return X}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let X=this.toRequest();return X.Select="COUNT",(this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X)).Count??0}}class l1{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(X){let $={region:X.region,tableName:X.table,endpoint:X.endpoint,credentials:X.credentials};return this.driver=bX($),this.tableName=X.table,this.pkAttribute=X.pkAttribute??"pk",this.skAttribute=X.skAttribute??"sk",this.entityTypeAttr=X.entityTypeAttribute??"_et",this.delimiter=X.keyDelimiter??"#",this}setClient(X){return this.client=X,this}registerEntity(X){if(this.entityMappings.set(X.entityType,X),this.driver)this.driver.registerEntity(X);return this}entity(X){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new A6(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(X)}async batchWrite(X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let $=[];for(let Z of X)if(Z.put){let Y={...Z.put.item,[this.entityTypeAttr]:Z.put.entity};$.push({PutRequest:{Item:this.driver.marshall(Y)}})}else if(Z.delete)$.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}});if($.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:$}})}async transactWrite(X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let $=[];for(let Z of X)if(Z.put){let Y={...Z.put.item,[this.entityTypeAttr]:Z.put.entity},U={Put:{TableName:this.tableName,Item:this.driver.marshall(Y)}};if(Z.put.condition)U.Put.ConditionExpression=Z.put.condition;$.push(U)}else if(Z.update){let Y={[this.pkAttribute]:Z.update.pk};if(Z.update.sk)Y[this.skAttribute]=Z.update.sk;let U=[],_={},Q={},L=0;if(Z.update.set){let z=[];for(let[j,E]of Object.entries(Z.update.set)){let V=`#set${L}`,G=`:set${L}`;_[V]=j,Q[G]=this.driver.marshall({v:E}).v,z.push(`${V} = ${G}`),L++}if(z.length>0)U.push(`SET ${z.join(", ")}`)}if(Z.update.add){let z=[];for(let[j,E]of Object.entries(Z.update.add)){let V=`#add${L}`,G=`:add${L}`;_[V]=j,Q[G]={N:String(E)},z.push(`${V} ${G}`),L++}if(z.length>0)U.push(`ADD ${z.join(", ")}`)}if(Z.update.remove&&Z.update.remove.length>0){let z=[];for(let j of Z.update.remove){let E=`#rem${L}`;_[E]=j,z.push(E),L++}U.push(`REMOVE ${z.join(", ")}`)}$.push({Update:{TableName:this.tableName,Key:this.driver.marshall(Y),UpdateExpression:U.join(" "),ExpressionAttributeNames:_,ExpressionAttributeValues:Q}})}else if(Z.delete){let Y={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}};if(Z.delete.condition)Y.Delete.ConditionExpression=Z.delete.condition;$.push(Y)}else if(Z.conditionCheck)$.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.conditionCheck.pk,[this.skAttribute]:Z.conditionCheck.sk}),ConditionExpression:Z.conditionCheck.condition}});if($.length>0)await this.client.transactWriteItems({TransactItems:$})}getDriver(){return this.driver}}function uj(){return new l1}var _2,Q2=t(()=>{t7(),U2(),N6(),_2=new l1});class B6{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!H5(X))return!0;return C5(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=H5(Z)?C5(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.timestamp).sort();return{size:$,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class y6{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function s2(X,$){this[X]=k4.bind(null,$)}class O1{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!w5(X))return!0;return q5(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=w5(Z)?q5(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.timestamp).sort();return{size:$,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class J1{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function o2(X,$={}){let Y=Object.keys($).sort().map((U)=>`${U}:${$[U]}`).join("|");return Y?`${X}:${Y}`:X}function r2(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function a2(X){return X.getStats().size*2}function s1(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&H0($[0])&&"id"in $[0]&&$[0].id===3&&H0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(H0($)&&H0(X)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return X;if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray($)&&Array.isArray(X)){if(H0(X)&&"arr"in X&&Array.isArray(X.arr)&&H0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&H0($[0])&&H0(X[0])){let Y=[...$];for(let U of X)if(H0(U)&&"name"in U){if(!Y.find((Q)=>H0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(H0(U)&&"path"in U){if(!Y.find((Q)=>H0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>B8(_,U)))Y.push(U);return Y}if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}if(!H0($)||!H0(X))return $;let Z={...X};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let U=$[Y];if(U===null||U===void 0)continue;else if(H0(U)&&H0(Z[Y]))Z[Y]=s1(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&H0(U[0])&&H0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(H0(Q)&&"name"in Q){if(!_.find((z)=>H0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(H0(Q)&&"path"in Q){if(!_.find((z)=>H0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>B8(L,Q)))_.push(Q);Z[Y]=_}else if(U.every((_)=>typeof _==="string")&&Z[Y].every((_)=>typeof _==="string")){let _=[...U];for(let Q of Z[Y])if(!_.includes(Q))_.push(Q);Z[Y]=_}else Z[Y]=U;else Z[Y]=U}return Z}function B8(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!B8(X[Z],$[Z]))return!1;return!0}if(H0(X)&&H0($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!B8(X[U],$[U]))return!1}return!0}return!1}function H0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function t2(X,$){if(!x6(X))return null;try{let Z=await import(X),Y=Z.default||Z;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return s1($,Y)}catch{return null}}catch{return null}}async function e2({name:X="",cwd:$,defaultConfig:Z}){let Y=$||F1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],_=[`${X}.config`,`.${X}.config`,X,`.${X}`];for(let Q of _)for(let L of U){let z=k8(Y,`${Q}${L}`),j=await t2(z,Z);if(j!==null)return j}try{let Q=k8(Y,"package.json");if(x6(Q)){let z=(await import(Q))[X];if(z&&typeof z==="object"&&!Array.isArray(z))try{return s1(Z,z)}catch{}}}catch{}return Z}function X4(X,$={}){let Z=A8.cwd();while(Z.includes("storage"))Z=N5(Z,"..");let Y=N5(Z,X||"");if($?.relative)return W2(A8.cwd(),Y);return Y}async function $4(){try{let X=await e2({name:"clarity",defaultConfig:J8,cwd:A8.cwd(),endpoint:"",headers:{}});return{...J8,...X}}catch{return J8}}function P0(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Z4(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T9<"u"){let X=T9.type;if(X==="renderer"||X==="worker")return!1;return!!(T9.versions&&(T9.versions.node||T9.versions.bun))}return!1}class h6{async format(X){let $=await Z4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:GX.pid,hostname:$(),environment:GX.env.NODE_ENV||"development",platform:GX.platform,version:GX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:GX.env.NODE_ENV||GX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class y8{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(X,$={}){this.name=X,this.config={...K1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new h6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??b0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...W8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...W8};return{...W8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:K1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await D2(this.config.logDirectory,x5.F_OK|x5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await M2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:v9.from(X);try{if(!JZ(this.currentLogFile))await WZ(this.currentLogFile,"",{mode:420});if(U=k5(this.currentLogFile,"a",420),R2(U,z,{flag:"a"}),A5(U),U!==void 0)OZ(U),U=void 0;if((await jX(this.currentLogFile)).size===0){if(await WZ(this.currentLogFile,z,{flag:"w",mode:420}),(await jX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{OZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 EX(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 EX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return EX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(P0())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return FZ(16).toString("hex")}generateKey(){return FZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=FZ(16),Y=V2("aes-256-gcm",$,Z),U=v9.concat([Y.update(X,"utf8"),Y.final()]),_=Y.getAuthTag();return{encrypted:v9.concat([Z,U,_]),iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=y5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(v9.from(v9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(P0())return;let X=await jX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await f$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await jX(Z).catch(()=>null))try{if(await B5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await g$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await WZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await jX(Z).catch(()=>null))await B5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await f$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await g$(EX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=S5(X),Y=K2($),U=y5();await H2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Z={timestamp:new Date,level:X,message:$,name:this.name};this.logBuffer.push(Z)}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(X)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(X){return{debug:0,info:1,success:2,warning:3,error:4}[X]}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),JZ(this.currentLogFile))try{let X=k5(this.currentLogFile,"r+");A5(X),OZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!P0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await f$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await g$(EX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.fancy?D0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=b0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${D0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}async log(X,$,...Z){let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);if(this.fancy&&!P0()){let j=t6[X],E=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"",V;switch(X){case"debug":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:D0.gray(Q),level:X}),console.error(V);break;case"info":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.error(V);break;case"success":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:D0.green(Q),level:X}),console.error(V);break;case"warning":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.warn(V);break;case"error":if(V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.error(V),L){let G=L.split(`
|
|
7
|
+
`);for(let J of G)if(J.trim()&&!J.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:D0.gray(` ${J}`),level:X,showTimestamp:!1}))}break}}else if(!P0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}if(!this.shouldLog(X))return;let z=`${_} ${this.environment}.${X.toUpperCase()}: ${Q}
|
|
8
8
|
`;if(L)z+=`${L}
|
|
9
|
-
`;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(X){let $=performance.now();if(this.fancy&&!P0()){let Z=this.options.showTags!==!1&&this.name?
|
|
10
|
-
`,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!P0()){let E=this.options.showTags!==!1&&this.name?
|
|
11
|
-
`),Q=Math.max(..._.map((E)=>E.length))+2,L=`\u250C${"\u2500".repeat(Q)}\u2510`,z=`\u2514${"\u2500".repeat(Q)}\u2518`,j=_.map((E)=>{let V=" ".repeat(Q-E.length-2);return`\u2502 ${E}${V} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Z,message:
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt(X){if(P0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${
|
|
13
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress(X,$=""){if(!this.enabled||!this.fancy||P0()||X<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Z=20;return this.activeProgressBar={total:X,current:0,message:$,barLength:Z,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Q,L)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(X,Q)),L!==void 0)this.activeProgressBar.message=L;let z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,z)},finish:(Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Q!==void 0)this.activeProgressBar.message=Q;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Q,L="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;b0.stdout.write(`${"\r".padEnd(b0.stdout.columns||80)}\r`),this.log(L,Q),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(X,$=!1){if(!this.enabled||!this.fancy||P0()||!b0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=
|
|
14
|
-
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||P0()||!b0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(P0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await f$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=EX(this.config.logDirectory,Y);if(X.before)try{if((await jX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await g$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function O8(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&O0($[0])&&"id"in $[0]&&$[0].id===3&&O0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(O0($)&&O0(X)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return X;if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray($)&&Array.isArray(X)){if(O0(X)&&"arr"in X&&Array.isArray(X.arr)&&O0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&O0($[0])&&O0(X[0])){let Y=[...$];for(let U of X)if(O0(U)&&"name"in U){if(!Y.find((Q)=>O0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(O0(U)&&"path"in U){if(!Y.find((Q)=>O0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>h8(_,U)))Y.push(U);return Y}if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}if(!O0($)||!O0(X))return $;let Z={...X};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let U=$[Y];if(U===null||U===void 0)continue;else if(O0(U)&&O0(Z[Y]))Z[Y]=O8(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&O0(U[0])&&O0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(O0(Q)&&"name"in Q){if(!_.find((z)=>O0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(O0(Q)&&"path"in Q){if(!_.find((z)=>O0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>h8(L,Q)))_.push(Q);Z[Y]=_}else if(U.every((_)=>typeof _==="string")&&Z[Y].every((_)=>typeof _==="string")){let _=[...U];for(let Q of Z[Y])if(!_.includes(Q))_.push(Q);Z[Y]=_}else Z[Y]=U;else Z[Y]=U}return Z}function s1(X,$,Z="replace"){if($===null||$===void 0)return X;if(Array.isArray($))return Z==="replace"?$:O8(X,$);if(Array.isArray(X))return Z==="replace"?$:O8(X,$);if(!O0($)||!O0(X))return $;let Y={...X};for(let U of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],Q=Y[U];if(_===null||_===void 0)continue;if(Array.isArray(_)||Array.isArray(Q))if(Z==="replace")Y[U]=_;else Y[U]=O8(Q,_);else if(O0(_)&&O0(Q))Y[U]=s1(Q,_,Z);else Y[U]=_}return Y}function h8(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!h8(X[Z],$[Z]))return!1;return!0}if(O0(X)&&O0($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!h8(X[U],$[U]))return!1}return!0}return!1}function O0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function r$(X,$,Z="replace"){if(!A6(X))return null;try{let Y=await import(X),U=Y.default||Y;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return s1($,U,Z)}catch{return null}}catch{return null}}function Z4(X,$,Z=!1){if(!X)return $;let Y=X.toUpperCase().replace(/-/g,"_"),U={...$};function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),J=`${Y}_${V.map(G).join("_")}`,W=`${Y}_${V.map((F)=>F.toUpperCase()).join("_")}`;if(Z)g0.info(`Checking environment variable ${J} for config ${X}.${V.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))z[j]=_(E,V);else{let F=P$.env[J]||P$.env[W];if(F!==void 0){if(Z)g0.info(`Using environment variable ${F?J:W} for config ${X}.${V.join(".")}`);if(typeof E==="number")z[j]=Number(F);else if(typeof E==="boolean")z[j]=F.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(F);if(Array.isArray(K))z[j]=K;else z[j]=F.split(",").map((D)=>D.trim())}catch{z[j]=F.split(",").map((K)=>K.trim())}else z[j]=F}}}return z}return _(U)}async function Y4({name:X="",alias:$,cwd:Z,configDir:Y,defaultConfig:U,verbose:_=!1,checkEnv:Q=!0,arrayStrategy:L="replace"}){let z=Q&&typeof U==="object"&&U!==null&&!Array.isArray(U)?Z4(X,U,_):U,j=Z||P$.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(_)g0.info(`Loading configuration for "${X}"${$?` (alias: "${$}")`:""} from ${j}`);let V=[X,`.${X}`].filter(Boolean),G=[`${X}.config`,`.${X}.config`].filter(Boolean),J=$?[$,`.${$}`]:[],W=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([j,u0(j,"config"),u0(j,".config"),Y?u0(j,Y):void 0].filter(Boolean)));for(let K of F){if(_)g0.info(`Searching for configuration in: ${K}`);let w=[u0(j,"config"),u0(j,".config")].concat(Y?[u0(j,Y)]:[]).includes(K)?[...V,...G,...J,...W]:[...G,...V,...W,...J];for(let T of w)for(let N of E){let q=u0(K,`${T}${N}`),H=await r$(q,z,L);if(H!==null){if(_)g0.success(`Configuration loaded from: ${q}`);return H}}}if(X){let K=u0(GZ(),".config",X),D=["config",`${X}.config`];if($)D.push(`${$}.config`);if(_)g0.info(`Checking user config directory: ${K}`);for(let w of D)for(let T of E){let N=u0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user config directory: ${N}`);return q}}}if(X){let K=u0(GZ(),".config"),D=[`.${X}.config`];if($)D.push(`.${$}.config`);if(_)g0.info(`Checking user config directory for dotfile configs: ${K}`);for(let w of D)for(let T of E){let N=u0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user config directory dotfile: ${N}`);return q}}}if(X){let K=GZ(),D=[`.${X}.config`,`.${X}`];if($)D.push(`.${$}.config`),D.push(`.${$}`);if(_)g0.info(`Checking user home directory for dotfile configs: ${K}`);for(let w of D)for(let T of E){let N=u0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user home directory: ${N}`);return q}}}try{let K=u0(j,"package.json");if(A6(K)){let D=await import(K),w=D[X];if(!w&&$){if(w=D[$],w&&_)g0.success(`Using alias "${$}" configuration from package.json`)}if(w&&typeof w==="object"&&!Array.isArray(w))try{if(_)g0.success(`Configuration loaded from package.json: ${w===D[X]?X:$}`);return s1(z,w,L)}catch(T){if(_)g0.warn("Failed to merge package.json config:",T)}}}catch(K){if(_)g0.warn("Failed to load package.json:",K)}if(_)g0.info(`No configuration found for "${X}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function U4(X,$={}){let Z=S8.cwd();while(Z.includes("storage"))Z=P5(Z,"..");let Y=P5(Z,X||"");if($?.relative)return F2(S8.cwd(),Y);return Y}async function _4(){try{let X=await Y4({name:"clarity",alias:"logging",defaultConfig:V8,cwd:S8.cwd()});return{...V8,...X||{}}}catch{return V8}}function N0(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Q4(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T9<"u"){let X=T9.type;if(X==="renderer"||X==="worker")return!1;return!!(T9.versions&&(T9.versions.node||T9.versions.bun))}return!1}class h6{async format(X){let $=await Q4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:JX.pid,hostname:$(),environment:JX.env.NODE_ENV||"development",platform:JX.platform,version:JX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JX.env.NODE_ENV||JX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class v8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(X,$={}){this.name=X,this.config={...R1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new h6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??z0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...I8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...I8};return{...I8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:R1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await P2(this.config.logDirectory,b5.F_OK|b5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await T2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:R9.from(X);try{if(!d$(this.currentLogFile))await KZ(this.currentLogFile,"",{mode:420});if(U=v5(this.currentLogFile,"a",420),q2(U,z,{flag:"a"}),h5(U),U!==void 0)IZ(U),U=void 0;if((await FX(this.currentLogFile)).size===0){if(await KZ(this.currentLogFile,z,{flag:"w",mode:420}),(await FX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{IZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 OX(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 OX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return OX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return VZ(16).toString("hex")}generateKey(){return VZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=VZ(16),Y=H2("aes-256-gcm",$,Z),U=R9.isBuffer(X)?X:R9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=R9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=g5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(R9.from(R9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let X=await FX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await p$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await FX(Z).catch(()=>null))try{if(await f5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await c$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await KZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await FX(Z).catch(()=>null))await f5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await p$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await c$(OX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=y5(X),Y=w2($),U=g5();await A2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),d$(this.currentLogFile))try{let X=v5(this.currentLogFile,"r+");h5(X),IZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await p$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await c$(OX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?j0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let X=typeof z0.env.NO_COLOR<"u",$=z0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof z0.stderr<"u"&&z0.stderr.isTTY||typeof z0.stdout<"u"&&z0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=z0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${j0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=j0.underline(j0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>j0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>j0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>j0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>j0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>j0.strikethrough(Y)),$}supportsHyperlinks(){if(N0())return!1;let X=z0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=z0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(N2($)||$.startsWith("./")||$.startsWith("../"))$=S2($);else return null;return d$($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":t6[X],G=this.options.showTags!==!1&&this.name?j0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:j0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:j0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
|
|
15
|
-
`);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:
|
|
9
|
+
`;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(X){let $=performance.now();if(this.fancy&&!P0()){let Z=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:D0.blue("\u25D0"),tag:Z,message:`${D0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),j=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)j+=` ${JSON.stringify(Z)}`;if(j+=`
|
|
10
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!P0()){let E=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:D0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!P0())console.error(j.trim());await this.writeToFile(j)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new y8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Z),Z}createReadStream(){if(P0())throw Error("createReadStream is not supported in browser environments");if(!JZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return S5(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let Y=v9.isBuffer(X)?X:v9.from(X,"base64"),U=Y.slice(0,16),_=Y.slice(-16),Q=Y.slice(16,-16),L=I2("aes-256-gcm",Z,U);return L.setAuthTag(_),v9.concat([L.update(Q),L.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P0()}isServerMode(){return!P0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($);if(this.fancy&&!P0()){let _=X.split(`
|
|
11
|
+
`),Q=Math.max(..._.map((E)=>E.length))+2,L=`\u250C${"\u2500".repeat(Q)}\u2510`,z=`\u2514${"\u2500".repeat(Q)}\u2518`,j=_.map((E)=>{let V=" ".repeat(Q-E.length-2);return`\u2502 ${E}${V} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Z,message:D0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Z,message:D0.cyan(L)})),j.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:Z,message:D0.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Z,message:D0.cyan(z),showTimestamp:!1}))}else if(!P0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
12
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt(X){if(P0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${D0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();b0.stdin.removeListener("data",Z);try{if(typeof b0.stdin.setRawMode==="function")b0.stdin.setRawMode(!1)}catch{}b0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof b0.stdin.setRawMode==="function")b0.stdin.setRawMode(!0)}catch{}b0.stdin.resume(),b0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let Q=/%([sdijfo%])/g,L=0;if(Z=X.replace(Q,(z,j)=>{if(j==="%")return"%";if(L>=$.length)return z;let E=$[L++];switch(j){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return z}}),L<$.length)Z+=` ${$.slice(L).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}if(this.fancy&&!P0()){let Q=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"",L=D0.blue("\u25D0");console.error(`${L} ${Q} ${D0.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Z}
|
|
13
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress(X,$=""){if(!this.enabled||!this.fancy||P0()||X<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Z=20;return this.activeProgressBar={total:X,current:0,message:$,barLength:Z,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Q,L)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(X,Q)),L!==void 0)this.activeProgressBar.message=L;let z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,z)},finish:(Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Q!==void 0)this.activeProgressBar.message=Q;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Q,L="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;b0.stdout.write(`${"\r".padEnd(b0.stdout.columns||80)}\r`),this.log(L,Q),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(X,$=!1){if(!this.enabled||!this.fancy||P0()||!b0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=D0.green("\u2501".repeat(Y)),Q=D0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=$||Z===100?D0.green("\u2713"):D0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${D0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=b0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,b0.stdout.write(X.lastRenderedLine),$)b0.stdout.write(`
|
|
14
|
+
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||P0()||!b0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(P0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await f$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=EX(this.config.logDirectory,Y);if(X.before)try{if((await jX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await g$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function O8(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&J0($[0])&&"id"in $[0]&&$[0].id===3&&J0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(J0($)&&J0(X)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return X;if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray($)&&Array.isArray(X)){if(J0(X)&&"arr"in X&&Array.isArray(X.arr)&&J0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&J0($[0])&&J0(X[0])){let Y=[...$];for(let U of X)if(J0(U)&&"name"in U){if(!Y.find((Q)=>J0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(J0(U)&&"path"in U){if(!Y.find((Q)=>J0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>h8(_,U)))Y.push(U);return Y}if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}if(!J0($)||!J0(X))return $;let Z={...X};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let U=$[Y];if(U===null||U===void 0)continue;else if(J0(U)&&J0(Z[Y]))Z[Y]=O8(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&J0(U[0])&&J0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(J0(Q)&&"name"in Q){if(!_.find((z)=>J0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(J0(Q)&&"path"in Q){if(!_.find((z)=>J0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>h8(L,Q)))_.push(Q);Z[Y]=_}else if(U.every((_)=>typeof _==="string")&&Z[Y].every((_)=>typeof _==="string")){let _=[...U];for(let Q of Z[Y])if(!_.includes(Q))_.push(Q);Z[Y]=_}else Z[Y]=U;else Z[Y]=U}return Z}function o1(X,$,Z="replace"){if($===null||$===void 0)return X;if(Array.isArray($))return Z==="replace"?$:O8(X,$);if(Array.isArray(X))return Z==="replace"?$:O8(X,$);if(!J0($)||!J0(X))return $;let Y={...X};for(let U of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],Q=Y[U];if(_===null||_===void 0)continue;if(Array.isArray(_)||Array.isArray(Q))if(Z==="replace")Y[U]=_;else Y[U]=O8(Q,_);else if(J0(_)&&J0(Q))Y[U]=o1(Q,_,Z);else Y[U]=_}return Y}function h8(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!h8(X[Z],$[Z]))return!1;return!0}if(J0(X)&&J0($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!h8(X[U],$[U]))return!1}return!0}return!1}function J0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function r$(X,$,Z="replace"){if(!k6(X))return null;try{let Y=await import(X),U=Y.default||Y;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return o1($,U,Z)}catch{return null}}catch{return null}}function Y4(X,$,Z=!1){if(!X)return $;let Y=X.toUpperCase().replace(/-/g,"_"),U={...$};function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),J=`${Y}_${V.map(G).join("_")}`,W=`${Y}_${V.map((F)=>F.toUpperCase()).join("_")}`;if(Z)g0.info(`Checking environment variable ${J} for config ${X}.${V.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))z[j]=_(E,V);else{let F=P$.env[J]||P$.env[W];if(F!==void 0){if(Z)g0.info(`Using environment variable ${F?J:W} for config ${X}.${V.join(".")}`);if(typeof E==="number")z[j]=Number(F);else if(typeof E==="boolean")z[j]=F.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(F);if(Array.isArray(K))z[j]=K;else z[j]=F.split(",").map((D)=>D.trim())}catch{z[j]=F.split(",").map((K)=>K.trim())}else z[j]=F}}}return z}return _(U)}async function U4({name:X="",alias:$,cwd:Z,configDir:Y,defaultConfig:U,verbose:_=!1,checkEnv:Q=!0,arrayStrategy:L="replace"}){let z=Q&&typeof U==="object"&&U!==null&&!Array.isArray(U)?Y4(X,U,_):U,j=Z||P$.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(_)g0.info(`Loading configuration for "${X}"${$?` (alias: "${$}")`:""} from ${j}`);let V=[X,`.${X}`].filter(Boolean),G=[`${X}.config`,`.${X}.config`].filter(Boolean),J=$?[$,`.${$}`]:[],W=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([j,n0(j,"config"),n0(j,".config"),Y?n0(j,Y):void 0].filter(Boolean)));for(let K of F){if(_)g0.info(`Searching for configuration in: ${K}`);let w=[n0(j,"config"),n0(j,".config")].concat(Y?[n0(j,Y)]:[]).includes(K)?[...V,...G,...J,...W]:[...G,...V,...W,...J];for(let T of w)for(let N of E){let q=n0(K,`${T}${N}`),H=await r$(q,z,L);if(H!==null){if(_)g0.success(`Configuration loaded from: ${q}`);return H}}}if(X){let K=n0(GZ(),".config",X),D=["config",`${X}.config`];if($)D.push(`${$}.config`);if(_)g0.info(`Checking user config directory: ${K}`);for(let w of D)for(let T of E){let N=n0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user config directory: ${N}`);return q}}}if(X){let K=n0(GZ(),".config"),D=[`.${X}.config`];if($)D.push(`.${$}.config`);if(_)g0.info(`Checking user config directory for dotfile configs: ${K}`);for(let w of D)for(let T of E){let N=n0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user config directory dotfile: ${N}`);return q}}}if(X){let K=GZ(),D=[`.${X}.config`,`.${X}`];if($)D.push(`.${$}.config`),D.push(`.${$}`);if(_)g0.info(`Checking user home directory for dotfile configs: ${K}`);for(let w of D)for(let T of E){let N=n0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user home directory: ${N}`);return q}}}try{let K=n0(j,"package.json");if(k6(K)){let D=await import(K),w=D[X];if(!w&&$){if(w=D[$],w&&_)g0.success(`Using alias "${$}" configuration from package.json`)}if(w&&typeof w==="object"&&!Array.isArray(w))try{if(_)g0.success(`Configuration loaded from package.json: ${w===D[X]?X:$}`);return o1(z,w,L)}catch(T){if(_)g0.warn("Failed to merge package.json config:",T)}}}catch(K){if(_)g0.warn("Failed to load package.json:",K)}if(_)g0.info(`No configuration found for "${X}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function _4(X,$={}){let Z=S8.cwd();while(Z.includes("storage"))Z=T5(Z,"..");let Y=T5(Z,X||"");if($?.relative)return O2(S8.cwd(),Y);return Y}async function Q4(){try{let X=await U4({name:"clarity",alias:"logging",defaultConfig:V8,cwd:S8.cwd()});return{...V8,...X||{}}}catch{return V8}}function N0(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function z4(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof N9<"u"){let X=N9.type;if(X==="renderer"||X==="worker")return!1;return!!(N9.versions&&(N9.versions.node||N9.versions.bun))}return!1}class v6{async format(X){let $=await z4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:JX.pid,hostname:$(),environment:JX.env.NODE_ENV||"development",platform:JX.platform,version:JX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JX.env.NODE_ENV||JX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class v8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(X,$={}){this.name=X,this.config={...R1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new v6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...I8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...I8};return{...I8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:R1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await T2(this.config.logDirectory,f5.F_OK|f5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await N2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:D9.from(X);try{if(!d$(this.currentLogFile))await KZ(this.currentLogFile,"",{mode:420});if(U=b5(this.currentLogFile,"a",420),P2(U,z,{flag:"a"}),v5(U),U!==void 0)IZ(U),U=void 0;if((await FX(this.currentLogFile)).size===0){if(await KZ(this.currentLogFile,z,{flag:"w",mode:420}),(await FX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{IZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 OX(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 OX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return OX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return VZ(16).toString("hex")}generateKey(){return VZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=VZ(16),Y=C2("aes-256-gcm",$,Z),U=D9.isBuffer(X)?X:D9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=D9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=d5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(D9.from(D9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let X=await FX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await p$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await FX(Z).catch(()=>null))try{if(await g5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await c$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await KZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await FX(Z).catch(()=>null))await g5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await p$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await c$(OX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=h5(X),Y=q2($),U=d5();await k2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),d$(this.currentLogFile))try{let X=b5(this.currentLogFile,"r+");v5(X),IZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await p$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await c$(OX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?E0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let X=typeof L0.env.NO_COLOR<"u",$=L0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof L0.stderr<"u"&&L0.stderr.isTTY||typeof L0.stdout<"u"&&L0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=L0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${E0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=E0.underline(E0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>E0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>E0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>E0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>E0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>E0.strikethrough(Y)),$}supportsHyperlinks(){if(N0())return!1;let X=L0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=L0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(S2($)||$.startsWith("./")||$.startsWith("../"))$=A2($);else return null;return d$($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":e6[X],G=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:E0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:E0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
|
|
15
|
+
`);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:E0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}if(!this.shouldLog(X))return;let E=`${_} ${this.environment}.${X.toUpperCase()}: ${j}
|
|
16
16
|
`;if(L)E+=`${L}
|
|
17
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(L,z)=>{},finish:(L)=>{},interrupt:(L,z)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&
|
|
18
|
-
`);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&
|
|
19
|
-
`,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
20
|
-
`),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${
|
|
22
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
23
|
-
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||N0()||!
|
|
17
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(L,z)=>{},finish:(L)=>{},interrupt:(L,z)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!N0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,z="info")=>{if(!N0()&&L0.stdout.isTTY)L0.stdout.write(`
|
|
18
|
+
`);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":E0.blue("\u25D0"),tag:Z,message:`${E0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),j=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)j+=` ${JSON.stringify(Z)}`;if(j+=`
|
|
19
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":E0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!N0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new v8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Z),Z}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!d$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return h5(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let Y=D9.isBuffer(X)?X:D9.from(X,"base64"),U=Y.subarray(0,16),_=Y.subarray(Y.length-16),Q=Y.subarray(16,Y.length-16),L=w2("aes-256-gcm",Z,U);L.setAuthTag(_);let z=L.update(Q),j=L.final(),E=z.length+j.length,V=D9.allocUnsafe(E);return z.copy(V,0),j.copy(V,z.length),V.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($),{consoleText:U,fileText:_}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let L=U.split(`
|
|
20
|
+
`),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:E0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:E0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:E0.cyan(E),showTimestamp:!1}))}else if(!N0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
|
|
21
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${E0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();L0.stdin.removeListener("data",Z);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let z=/%([sdijfo%])/g,j=0;if(Z=X.replace(z,(E,V)=>{if(V==="%")return"%";if(j>=$.length)return E;let G=$[j++];switch(V){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return E}}),j<$.length)Z+=` ${$.slice(j).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:U}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${E0.blue("\u25D0")} `;console.error(`${j}${z} ${E0.cyan(Y)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
22
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!L0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=E0.green("\u2501".repeat(Y)),Q=E0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?E0.green("\u2713"):E0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${E0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=L0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,L0.stdout.write(X.lastRenderedLine),$)L0.stdout.write(`
|
|
23
|
+
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||N0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await p$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=OX(this.config.logDirectory,Y);if(X.before)try{if((await FX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await c$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function b6(X,$={}){let{maxRetries:Z=3,retryDelay:Y=1000,isRetryable:U=()=>!0,fallback:_}=$,Q=Error("Unknown error occurred");for(let L=0;L<=Z;L++)try{return await X()}catch(z){if(Q=z instanceof Error?z:Error(String(z)),L===Z||!U(Q))break;if(Y>0)await new Promise((j)=>setTimeout(j,Y))}if(_!==void 0)return _;throw Q instanceof Error?Q:Error(`Unknown error: ${String(Q)}`)}function f6(X){return X instanceof $9}function L4(X){return X instanceof K8}function j4(X){if(f6(X))return X.code==="FILE_SYSTEM_ERROR"||X.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Z)=>X.message.toLowerCase().includes(Z.toLowerCase()))}class $Z{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(X,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(X.toLowerCase()),parse:(X)=>{let $=X.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(X,$)=>$==="number"||!Number.isNaN(Number(X))&&!Number.isNaN(Number.parseFloat(X)),parse:(X)=>{let $=Number(X);if(Number.isNaN($))throw TypeError(`Cannot parse "${X}" as number`);return $}},{name:"array",canParse:(X,$)=>$==="array"||X.startsWith("[")||X.includes(","),parse:(X)=>{try{let $=JSON.parse(X);if(Array.isArray($))return $}catch{}return X.split(",").map(($)=>$.trim())}},{name:"json",canParse:(X,$)=>$==="object"||(X.startsWith("{")&&X.endsWith("}")||X.startsWith("[")&&X.endsWith("]")),parse:(X)=>{try{return JSON.parse(X)}catch($){throw Error(`Cannot parse "${X}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(X,$,Z={}){let{prefix:Y,useCamelCase:U=!0,useBackwardCompatibility:_=!0,customParsers:Q={},verbose:L=!1,trackPerformance:z=!0}=Z,j=async()=>{if(!X)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix(X),V={...$};return this.processObject(V,[],E,{useCamelCase:U,useBackwardCompatibility:_,customParsers:Q,verbose:L,configName:X}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return N$.track("applyEnvironmentVariables",j,{configName:X});return j()}generateEnvPrefix(X){return X.toUpperCase().replace(/-/g,"_")}formatEnvKey(X,$){if(!$)return X.toUpperCase();return X.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=Q.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),z=`${Z}_${L.join("_")}`,j=Y.useBackwardCompatibility?`${Z}_${Q.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.processObject(_,Q,Z,Y);else{let E=m$.env[z]||(j?m$.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=m$.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof R8)throw V;throw c9.envVar(z,E,typeof _,Y.configName)}}}}}parseEnvironmentValue(X,$,Z,Y,U){for(let[_,Q]of Object.entries(Y))try{return Q(X)}catch{continue}for(let _ of this.defaultParsers)if(_.canParse(X,$))try{return _.parse(X)}catch{throw c9.envVar(Z,X,`${$} (via ${_.name} parser)`,U)}return X}getEnvironmentVariables(X){let $={},Z=X.toUpperCase();for(let[Y,U]of Object.entries(m$.env))if(Y.startsWith(Z)&&U!==void 0)$[Y]=U;return $}validateEnvironmentVariable(X,$,Z){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(X))Y.push(`Environment variable key "${X}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(X,$,Z,{})}catch(U){Y.push(`Cannot parse value "${$}" as ${Z}: ${U}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(X,$,Z={}){let{prefix:Y,format:U="text"}=Z,_=Y||this.generateEnvPrefix(X),Q=[];switch(this.extractEnvVarInfo($,[],_,Q),U){case"markdown":return this.formatAsMarkdown(Q,X);case"json":return JSON.stringify(Q,null,2);default:return this.formatAsText(Q,X)}}extractEnvVarInfo(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=`${Z}_${Q.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.extractEnvVarInfo(_,Q,Z,Y);else Y.push({key:L,type:Array.isArray(_)?"array":typeof _,description:`Configuration for ${Q.join(".")}`,example:this.generateExample(_)})}}generateExample(X){if(Array.isArray(X))return JSON.stringify(X);if(typeof X==="object"&&X!==null)return JSON.stringify(X);return String(X)}formatAsText(X,$){let Z=`Environment Variables for ${$}:
|
|
24
24
|
|
|
25
25
|
`;for(let Y of X)Z+=`${Y.key}
|
|
26
26
|
`,Z+=` Type: ${Y.type}
|
|
@@ -32,25 +32,25 @@ var p0=import.meta.require;import{existsSync as M5,statSync as H5}from"fs";impor
|
|
|
32
32
|
`;Z+=`| Variable | Type | Description | Example |
|
|
33
33
|
`,Z+=`|----------|------|-------------|----------|
|
|
34
34
|
`;for(let Y of X)Z+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
35
|
-
`;return Z}}function j4(X,$){let Z=r6("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function f6(X,$,Z={}){return g6(X,$,Z,new WeakMap)}function g6(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return d6(X,$,U,Y);if(!G9($)||!G9(X))return $;return O4(X,$,Z,Y)}function d6(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return E4(X,$);case"smart":return G4(X,$,Y);default:return $}return $}function E4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>W1(U,Y)))Z.push(Y);return Z}function G4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(G9($[0])&&G9(X[0]))return F4(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function F4(X,$,Z){let Y=[...$];for(let U of X){if(!G9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((j)=>G9(j)&&(L in j)&&j[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function O4(X,$,Z,Y){let U=$;if(G9(U)&&Y.has(U))return Y.get(U);let _={...X};if(G9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(G9(L)&&G9(z))_[Q]=g6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=d6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function o1(X,$,Z="replace"){return f6(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function W1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!W1(X[Z],$[Z]))return!1;return!0}if(G9(X)&&G9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!W1(X[U],$[U]))return!1}return!0}return!1}function G9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class ZZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=xX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!u$(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new $$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new $$(X,Error("Configuration must export a valid object"),"unknown");let K={config:o1($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)xX.setWithFileCheck("file",K,X,_);return K}catch(j){throw j instanceof Error?p9.configLoad(X,j):p9.configLoad(X,Error(String(j)))}};if(Q)return N$.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(RZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);if($){if(Z.push($,`.${$}.config`,`${$}.config`,`.${$}`),X)Z.push(`${X}.${$}.config`,`.${X}.${$}.config`)}return Z.filter(Boolean)}checkFileAccess(X){return v6(async()=>{return u$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!u$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=RZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=RZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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((Z)=>Z.test(X))}async validateConfigFile(X){let $=[];try{if(!u$(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class r1{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await N$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!k2($))throw new Z$($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new Z$($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:e6},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class V1{fileLoader=new ZZ;envProcessor=new $Z;validator=new r1;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)V9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw V9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||t9.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(i0(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw p9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?lX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)V9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)V9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?lX(X,Z,U):Z,L=[i0(LX(),".config",X),i0(LX(),".config"),LX()];for(let z of L){if(U)V9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)V9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?lX(X,Y,_):Y;try{let z=i0(Z,"package.json");if(!G1(z))return null;let j=await import(z),E=j[X],V=X;if(!E&&$)E=j[$],V=$;if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)V9.success(`Configuration loaded from package.json: ${V}`);return{config:o1(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)V9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:lX(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw p9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return xX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);xX.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias)Z.push(`alias:${$.alias}`);if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,i0(X,"config"),i0(X,".config"),$?i0(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(i0(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[i0(LX(),".config",X),i0(LX(),".config"),LX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function s5(X){let Z=!(X.message.includes("EACCES")||X.message.includes("EPERM")||X.message.includes("permission denied"))&&(X.message.includes("syntax")||X.message.includes("Expected")||X.message.includes("Unexpected")||X.message.includes("BuildMessage")),Y=X.message.includes("Configuration must export a valid object")||X.message.includes("Configuration file is empty and exports nothing");return Z||Y}async function J4(X){return A9.loadConfig({...X,__strictErrorHandling:!0})}async function p6(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await A9.loadConfig(X);else Y=await A9.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)V9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let L=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await A9.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}async function W4(X={defaultConfig:{}}){if(typeof X==="string"){let{cwd:$}=await import("process");try{return(await A9.loadConfig({name:X,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&s5(Z)))return(await A9.applyEnvironmentVariables(X,{},!0,!1)).config;throw Z}}try{return(await A9.loadConfig({...X,cwd:X.cwd||t9.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&s5($)))return(await A9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function V4(X,$,Z="replace"){let Y=new ZZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function lX(X,$,Z=!1){let Y=new $Z,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=t9.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}function I4(X){let $=i0(t9.cwd(),X.configDir),Z=i0(t9.cwd(),X.generatedDir),Y=i0(Z,"config-types.ts");if(!G1(q5(Y)))L2(q5(Y),{recursive:!0,mode:511});let U=G1($)?j2($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${__}
|
|
35
|
+
`;return Z}}function E4(X,$){let Z=a6("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function g6(X,$,Z={}){return d6(X,$,Z,new WeakMap)}function d6(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return p6(X,$,U,Y);if(!G9($)||!G9(X))return $;return J4(X,$,Z,Y)}function p6(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return G4(X,$);case"smart":return F4(X,$,Y);default:return $}return $}function G4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>W1(U,Y)))Z.push(Y);return Z}function F4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(G9($[0])&&G9(X[0]))return O4(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function O4(X,$,Z){let Y=[...$];for(let U of X){if(!G9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((j)=>G9(j)&&(L in j)&&j[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function J4(X,$,Z,Y){let U=$;if(G9(U)&&Y.has(U))return Y.get(U);let _={...X};if(G9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(G9(L)&&G9(z))_[Q]=d6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=p6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function r1(X,$,Z="replace"){return g6(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function W1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!W1(X[Z],$[Z]))return!1;return!0}if(G9(X)&&G9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!W1(X[U],$[U]))return!1}return!0}return!1}function G9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class ZZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=xX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!u$(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new $$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new $$(X,Error("Configuration must export a valid object"),"unknown");let K={config:r1($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)xX.setWithFileCheck("file",K,X,_);return K}catch(j){throw j instanceof Error?c9.configLoad(X,j):c9.configLoad(X,Error(String(j)))}};if(Q)return N$.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(RZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);if($){if(Z.push($,`.${$}.config`,`${$}.config`,`.${$}`),X)Z.push(`${X}.${$}.config`,`.${X}.${$}.config`)}return Z.filter(Boolean)}checkFileAccess(X){return b6(async()=>{return u$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!u$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=RZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=RZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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((Z)=>Z.test(X))}async validateConfigFile(X){let $=[];try{if(!u$(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class a1{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await N$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!x2($))throw new Z$($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new Z$($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:XU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class V1{fileLoader=new ZZ;envProcessor=new $Z;validator=new a1;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)V9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw V9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||t9.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(l0(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw c9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?lX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)V9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)V9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?lX(X,Z,U):Z,L=[l0(LX(),".config",X),l0(LX(),".config"),LX()];for(let z of L){if(U)V9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)V9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?lX(X,Y,_):Y;try{let z=l0(Z,"package.json");if(!G1(z))return null;let j=await import(z),E=j[X],V=X;if(!E&&$)E=j[$],V=$;if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)V9.success(`Configuration loaded from package.json: ${V}`);return{config:r1(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)V9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:lX(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw c9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return xX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);xX.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias)Z.push(`alias:${$.alias}`);if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,l0(X,"config"),l0(X,".config"),$?l0(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(l0(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[l0(LX(),".config",X),l0(LX(),".config"),LX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function o5(X){let Z=!(X.message.includes("EACCES")||X.message.includes("EPERM")||X.message.includes("permission denied"))&&(X.message.includes("syntax")||X.message.includes("Expected")||X.message.includes("Unexpected")||X.message.includes("BuildMessage")),Y=X.message.includes("Configuration must export a valid object")||X.message.includes("Configuration file is empty and exports nothing");return Z||Y}async function W4(X){return k9.loadConfig({...X,__strictErrorHandling:!0})}async function c6(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await k9.loadConfig(X);else Y=await k9.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)V9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let L=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await k9.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}async function V4(X={defaultConfig:{}}){if(typeof X==="string"){let{cwd:$}=await import("process");try{return(await k9.loadConfig({name:X,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&o5(Z)))return(await k9.applyEnvironmentVariables(X,{},!0,!1)).config;throw Z}}try{return(await k9.loadConfig({...X,cwd:X.cwd||t9.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&o5($)))return(await k9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function I4(X,$,Z="replace"){let Y=new ZZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function lX(X,$,Z=!1){let Y=new $Z,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=t9.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}function K4(X){let $=l0(t9.cwd(),X.configDir),Z=l0(t9.cwd(),X.generatedDir),Y=l0(Z,"config-types.ts");if(!G1(P5(Y)))j2(P5(Y),{recursive:!0,mode:511});let U=G1($)?E2($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${Q_}
|
|
36
36
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
37
|
-
`;
|
|
38
|
-
${U.map((j)=>{let E=
|
|
37
|
+
`;G2(Y,_,{mode:438})}function R4(X){let $=null,Z=null,Y=()=>{if(!Z)Z=c6(X).then((_)=>{return $=_,_},(_)=>{let Q="defaultConfig"in X?X.defaultConfig:{};if($=Q,"verbose"in X&&X.verbose)V9.warn("Config loading failed, using defaults:",[_ instanceof Error?_:Error(String(_))]);return Q});return Z},U="defaultConfig"in X?X.defaultConfig:{};return $=U,Y(),new Proxy({},{get(_,Q){if($)return $[Q];let L=U[Q];return Y(),L},has(_,Q){return Q in($||U)},ownKeys(){return Object.keys($||U)},getOwnPropertyDescriptor(_,Q){return Object.getOwnPropertyDescriptor($||U,Q)},set(_,Q,L){if(!$)$={...U};return $[Q]=L,!0}})}function D4(X){let $=p5(h2.cwd(),X?.configDir||"./config");function Z(){if(!B2($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=y2($).filter((z)=>U.has(DZ(z))).map((z)=>({base:z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:z})),L=new Map;for(let{base:z,file:j}of Q){let E=DZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=DZ(V).toLowerCase();if(_.indexOf(E)<_.indexOf(G))L.set(z,j)}return Array.from(L.entries()).map(([z,j])=>({base:z,file:j})).sort((z,j)=>z.base.localeCompare(j.base))}function Y(){let U=Z(),_=U.map((j)=>j.base),Q=_.length?_.map((j)=>`'${j}'`).join(" | "):"string",L=U.length?`{
|
|
38
|
+
${U.map((j)=>{let E=p5($,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${E}').default`}).join(`,
|
|
39
39
|
`)}
|
|
40
40
|
}`:"Record<string, any>";return`export type ConfigNames = ${Q}
|
|
41
41
|
export type ConfigByName = ${L}
|
|
42
42
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
43
43
|
export type ConfigOf = Config
|
|
44
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(_)=>{return{path:_.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function D4(X,$={}){let Z=x8.cwd();while(Z.includes("storage"))Z=p5(Z,"..");let Y=p5(Z,X||"");if($?.relative)return v2(x8.cwd(),Y);return Y}function S0(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function M4(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof N9<"u"){let X=N9.type;if(X==="renderer"||X==="worker")return!1;return!!(N9.versions&&(N9.versions.node||N9.versions.bun))}return!1}class c6{async format(X){let $=await M4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:IX.pid,hostname:$(),environment:IX.env.NODE_ENV||"development",platform:IX.platform,version:IX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:IX.env.NODE_ENV||IX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class b8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(X,$={}){this.name=X,this.config={...Y$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new c6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...D8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...D8};return{...D8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:Y$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!S0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await p2(this.config.logDirectory,n5.F_OK|n5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await c2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:D9.from(X);try{if(!n$(this.currentLogFile))await CZ(this.currentLogFile,"",{mode:420});if(U=u5(this.currentLogFile,"a",420),d2(U,z,{flag:"a"}),m5(U),U!==void 0)HZ(U),U=void 0;if((await WX(this.currentLogFile)).size===0){if(await CZ(this.currentLogFile,z,{flag:"w",mode:420}),(await WX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{HZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 VX(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 VX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return VX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(S0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return MZ(16).toString("hex")}generateKey(){return MZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=MZ(16),Y=b2("aes-256-gcm",$,Z),U=D9.isBuffer(X)?X:D9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=D9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=l5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(D9.from(D9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(S0())return;if(!this.shouldWriteToFile())return;let X=await WX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await i$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await WX(Z).catch(()=>null))try{if(await i5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await l$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await CZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await WX(Z).catch(()=>null))await i5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await i$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await l$(VX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=c5(X),Y=g2($),U=l5();await n2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),n$(this.currentLogFile))try{let X=u5(this.currentLogFile,"r+");m5(X),HZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!S0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await i$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await l$(VX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?E0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S0())return!1;let X=typeof L0.env.NO_COLOR<"u",$=L0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof L0.stderr<"u"&&L0.stderr.isTTY||typeof L0.stdout<"u"&&L0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=L0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${E0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=E0.underline(E0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>E0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>E0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>E0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>E0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>E0.strikethrough(Y)),$}supportsHyperlinks(){if(S0())return!1;let X=L0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=L0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(m2($)||$.startsWith("./")||$.startsWith("../"))$=u2($);else return null;return n$($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){if(!this.shouldLog(X))return;let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":XU[X],G=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:E0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:E0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
|
|
45
|
-
`);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:
|
|
44
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(_)=>{return{path:_.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function M4(X,$={}){let Z=x8.cwd();while(Z.includes("storage"))Z=c5(Z,"..");let Y=c5(Z,X||"");if($?.relative)return b2(x8.cwd(),Y);return Y}function S0(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function H4(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof S9<"u"){let X=S9.type;if(X==="renderer"||X==="worker")return!1;return!!(S9.versions&&(S9.versions.node||S9.versions.bun))}return!1}class m6{async format(X){let $=await H4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:IX.pid,hostname:$(),environment:IX.env.NODE_ENV||"development",platform:IX.platform,version:IX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:IX.env.NODE_ENV||IX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class b8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(X,$={}){this.name=X,this.config={...Y$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new m6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??j0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...D8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...D8};return{...D8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:Y$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!S0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await c2(this.config.logDirectory,i5.F_OK|i5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await m2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:M9.from(X);try{if(!n$(this.currentLogFile))await CZ(this.currentLogFile,"",{mode:420});if(U=n5(this.currentLogFile,"a",420),p2(U,z,{flag:"a"}),u5(U),U!==void 0)HZ(U),U=void 0;if((await WX(this.currentLogFile)).size===0){if(await CZ(this.currentLogFile,z,{flag:"w",mode:420}),(await WX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{HZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 VX(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 VX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return VX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(S0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return MZ(16).toString("hex")}generateKey(){return MZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=MZ(16),Y=f2("aes-256-gcm",$,Z),U=M9.isBuffer(X)?X:M9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=M9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=s5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(M9.from(M9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(S0())return;if(!this.shouldWriteToFile())return;let X=await WX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await i$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await WX(Z).catch(()=>null))try{if(await l5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await l$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await CZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await WX(Z).catch(()=>null))await l5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await i$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await l$(VX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=m5(X),Y=d2($),U=s5();await i2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),n$(this.currentLogFile))try{let X=n5(this.currentLogFile,"r+");u5(X),HZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!S0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await i$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await l$(VX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?G0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S0())return!1;let X=typeof j0.env.NO_COLOR<"u",$=j0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof j0.stderr<"u"&&j0.stderr.isTTY||typeof j0.stdout<"u"&&j0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=j0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${G0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=G0.underline(G0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>G0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>G0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>G0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>G0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>G0.strikethrough(Y)),$}supportsHyperlinks(){if(S0())return!1;let X=j0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=j0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(u2($)||$.startsWith("./")||$.startsWith("../"))$=n2($);else return null;return n$($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){if(!this.shouldLog(X))return;let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":$U[X],G=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:G0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:G0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
|
|
45
|
+
`);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:G0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!S0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}let E=`${_} ${this.environment}.${X.toUpperCase()}: ${j}
|
|
46
46
|
`;if(L)E+=`${L}
|
|
47
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(L,z)=>{},finish:(L)=>{},interrupt:(L,z)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!S0()&&
|
|
48
|
-
`);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!S0()&&
|
|
49
|
-
`,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
50
|
-
`),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(S0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${
|
|
52
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
53
|
-
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||S0()||!
|
|
47
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(L,z)=>{},finish:(L)=>{},interrupt:(L,z)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!S0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!S0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,z="info")=>{if(!S0()&&j0.stdout.isTTY)j0.stdout.write(`
|
|
48
|
+
`);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!S0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":G0.blue("\u25D0"),tag:Z,message:`${G0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),j=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)j+=` ${JSON.stringify(Z)}`;if(j+=`
|
|
49
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":G0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!S0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new b8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Z),Z}createReadStream(){if(S0())throw Error("createReadStream is not supported in browser environments");if(!n$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return m5(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let Y=M9.isBuffer(X)?X:M9.from(X,"base64"),U=Y.subarray(0,16),_=Y.subarray(Y.length-16),Q=Y.subarray(16,Y.length-16),L=g2("aes-256-gcm",Z,U);L.setAuthTag(_);let z=L.update(Q),j=L.final(),E=z.length+j.length,V=M9.allocUnsafe(E);return z.copy(V,0),j.copy(V,z.length),V.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S0()}isServerMode(){return!S0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($),{consoleText:U,fileText:_}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let L=U.split(`
|
|
50
|
+
`),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:G0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:G0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:G0.cyan(E),showTimestamp:!1}))}else if(!S0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
|
|
51
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(S0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${G0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();j0.stdin.removeListener("data",Z);try{if(typeof j0.stdin.setRawMode==="function")j0.stdin.setRawMode(!1)}catch{}j0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof j0.stdin.setRawMode==="function")j0.stdin.setRawMode(!0)}catch{}j0.stdin.resume(),j0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let z=/%([sdijfo%])/g,j=0;if(Z=X.replace(z,(E,V)=>{if(V==="%")return"%";if(j>=$.length)return E;let G=$[j++];switch(V){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return E}}),j<$.length)Z+=` ${$.slice(j).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:U}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${G0.blue("\u25D0")} `;console.error(`${j}${z} ${G0.cyan(Y)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
52
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!j0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=G0.green("\u2501".repeat(Y)),Q=G0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?G0.green("\u2713"):G0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${G0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=j0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,j0.stdout.write(X.lastRenderedLine),$)j0.stdout.write(`
|
|
53
|
+
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||S0()||!j0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(S0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await i$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=VX(this.config.logDirectory,Y);if(X.before)try{if((await WX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await l$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function C4(X,$={}){let{maxRetries:Z=3,retryDelay:Y=1000,isRetryable:U=()=>!0,fallback:_}=$,Q=Error("Unknown error occurred");for(let L=0;L<=Z;L++)try{return await X()}catch(z){if(Q=z instanceof Error?z:Error(String(z)),L===Z||!U(Q))break;if(Y>0)await new Promise((j)=>setTimeout(j,Y))}if(_!==void 0)return _;throw Q instanceof Error?Q:Error(`Unknown error: ${String(Q)}`)}class t1{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(X,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(X.toLowerCase()),parse:(X)=>{let $=X.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(X,$)=>$==="number"||!Number.isNaN(Number(X))&&!Number.isNaN(Number.parseFloat(X)),parse:(X)=>{let $=Number(X);if(Number.isNaN($))throw TypeError(`Cannot parse "${X}" as number`);return $}},{name:"array",canParse:(X,$)=>$==="array"||X.startsWith("[")||X.includes(","),parse:(X)=>{try{let $=JSON.parse(X);if(Array.isArray($))return $}catch{}return X.split(",").map(($)=>$.trim())}},{name:"json",canParse:(X,$)=>$==="object"||(X.startsWith("{")&&X.endsWith("}")||X.startsWith("[")&&X.endsWith("]")),parse:(X)=>{try{return JSON.parse(X)}catch($){throw Error(`Cannot parse "${X}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(X,$,Z={}){let{prefix:Y,useCamelCase:U=!0,useBackwardCompatibility:_=!0,customParsers:Q={},verbose:L=!1,trackPerformance:z=!0}=Z,j=async()=>{if(!X)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix(X),V={...$};return this.processObject(V,[],E,{useCamelCase:U,useBackwardCompatibility:_,customParsers:Q,verbose:L,configName:X}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return YZ.track("applyEnvironmentVariables",j,{configName:X});return j()}generateEnvPrefix(X){return X.toUpperCase().replace(/-/g,"_")}formatEnvKey(X,$){if(!$)return X.toUpperCase();return X.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=Q.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),z=`${Z}_${L.join("_")}`,j=Y.useBackwardCompatibility?`${Z}_${Q.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.processObject(_,Q,Z,Y);else{let E=s$.env[z]||(j?s$.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=s$.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof D1)throw V;throw e9.envVar(z,E,typeof _,Y.configName)}}}}}parseEnvironmentValue(X,$,Z,Y,U){for(let[_,Q]of Object.entries(Y))try{return Q(X)}catch{continue}for(let _ of this.defaultParsers)if(_.canParse(X,$))try{return _.parse(X)}catch{throw e9.envVar(Z,X,`${$} (via ${_.name} parser)`,U)}return X}getEnvironmentVariables(X){let $={},Z=X.toUpperCase();for(let[Y,U]of Object.entries(s$.env))if(Y.startsWith(Z)&&U!==void 0)$[Y]=U;return $}validateEnvironmentVariable(X,$,Z){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(X))Y.push(`Environment variable key "${X}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(X,$,Z,{})}catch(U){Y.push(`Cannot parse value "${$}" as ${Z}: ${U}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(X,$,Z={}){let{prefix:Y,format:U="text"}=Z,_=Y||this.generateEnvPrefix(X),Q=[];switch(this.extractEnvVarInfo($,[],_,Q),U){case"markdown":return this.formatAsMarkdown(Q,X);case"json":return JSON.stringify(Q,null,2);default:return this.formatAsText(Q,X)}}extractEnvVarInfo(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=`${Z}_${Q.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.extractEnvVarInfo(_,Q,Z,Y);else Y.push({key:L,type:Array.isArray(_)?"array":typeof _,description:`Configuration for ${Q.join(".")}`,example:this.generateExample(_)})}}generateExample(X){if(Array.isArray(X))return JSON.stringify(X);if(typeof X==="object"&&X!==null)return JSON.stringify(X);return String(X)}formatAsText(X,$){let Z=`Environment Variables for ${$}:
|
|
54
54
|
|
|
55
55
|
`;for(let Y of X)Z+=`${Y.key}
|
|
56
56
|
`,Z+=` Type: ${Y.type}
|
|
@@ -62,9 +62,9 @@ export type ConfigOf = Config
|
|
|
62
62
|
`;Z+=`| Variable | Type | Description | Example |
|
|
63
63
|
`,Z+=`|----------|------|-------------|----------|
|
|
64
64
|
`;for(let Y of X)Z+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
65
|
-
`;return Z}}function C4(X,$,Z={}){return m6(X,$,Z,new WeakMap)}function m6(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return u6(X,$,U,Y);if(!F9($)||!F9(X))return $;return T4(X,$,Z,Y)}function u6(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return w4(X,$);case"smart":return q4(X,$,Y);default:return $}return $}function w4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>I1(U,Y)))Z.push(Y);return Z}function q4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(F9($[0])&&F9(X[0]))return P4(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function P4(X,$,Z){let Y=[...$];for(let U of X){if(!F9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((j)=>F9(j)&&(L in j)&&j[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function T4(X,$,Z,Y){let U=$;if(F9(U)&&Y.has(U))return Y.get(U);let _={...X};if(F9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(F9(L)&&F9(z))_[Q]=m6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=u6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function n6(X,$,Z="replace"){return C4(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function I1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!I1(X[Z],$[Z]))return!1;return!0}if(F9(X)&&F9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!I1(X[U],$[U]))return!1}return!0}return!1}function F9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class i6{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=T$.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!o$(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new f8(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new f8(X,Error("Configuration must export a valid object"),"unknown");let K={config:n6($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)T$.setWithFileCheck("file",K,X,_);return K}catch(j){throw j instanceof Error?e9.configLoad(X,j):e9.configLoad(X,Error(String(j)))}};if(Q)return YZ.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(wZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let Y=$===void 0?[]:Array.isArray($)?$:[$];for(let _ of Y){if(!_)continue;if(Z.push(_,`.${_}.config`,`${_}.config`,`.${_}`),X)Z.push(`${X}.${_}.config`,`.${X}.${_}.config`)}let U=new Set;return Z.filter((_)=>{if(!_||U.has(_))return!1;return U.add(_),!0})}checkFileAccess(X){return H4(async()=>{return o$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!o$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=wZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=wZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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((Z)=>Z.test(X))}async validateConfigFile(X){let $=[];try{if(!o$(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class l6{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await YZ.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!i2($))throw new g8($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new g8($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:$U},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function N4(X){if(!X)return"";let $=Array.isArray(X)?X.filter(Boolean):[X];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Z)=>`"${Z}"`).join(", ")}`}class s6{fileLoader=new i6;envProcessor=new a1;validator=new l6;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)W9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){if(L instanceof Error&&L.name==="ConfigNotFoundError")throw L;let z=Date.now()-$;throw W9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||N8.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(L9(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw e9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${N4(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?a$(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)W9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)W9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?a$(X,Z,U):Z,L=[L9(zX(),".config",X),L9(zX(),".config"),zX()];for(let z of L){if(U)W9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)W9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?a$(X,Y,_):Y;try{let z=L9(Z,"package.json");if(!Q2(z))return null;let j={};try{j=JSON.parse(z2(z,"utf8"))}catch(G){if(_)W9.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let E=j[X],V=X;if(!E&&$){let G=Array.isArray($)?$:[$];for(let J of G){if(!J)continue;if(j[J]){E=j[J],V=J;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)W9.success(`Configuration loaded from package.json: ${V}`);return{config:n6(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)W9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:a$(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw e9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return T$.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);T$.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias){let Y=Array.isArray($.alias)?$.alias.join(","):$.alias;Z.push(`alias:${Y}`)}if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,L9(X,"config"),L9(X,".config"),$?L9(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(L9(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[L9(zX(),".config",X),L9(zX(),".config"),zX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}async function S4(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await M8.loadConfig(X);else Y=await M8.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)W9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let L=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await M8.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}function a$(X,$,Z=!1){let Y=new a1,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=N8.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}var T$,YZ,o6,A4=(X)=>X,k4=(X,$)=>{for(var Z in $)o6(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:l2.bind($,Z)})},x4=(X,$)=>()=>(X&&($=X(X=0)),$),qZ,r6,xX,N$,o5,B4,y4,r5,J8,K1,f0,R0,h4,a5,v4,t5,b4,f4,PZ,g4,e5,XY,TZ,d4,p4,c4,m4,W8,a6,u4,g0,n4,i4,$Y,V8,R1,A0,j0,l4,ZY,s4,YY,o4,r4,NZ,a4,UY,_Y,t4,SZ,e4,X_,$_,Z_,Y_,I8,t6,U_,__="0.15.6",$9,K8,$$,AZ,kZ,R8,xZ,BZ,Z$,yZ,hZ,p9,QY,e6,V9,A9,zY,LY,jY,EY,vZ,Y$,Q_,k0,E0,z_,GY,L_,FY,j_,E_,bZ,G_,OY,JY,F_,fZ,O_,J_,W_,V_,I_,D8,XU,K_,J9,WY,f8,VY,IY,D1,KY,RY,g8,DY,MY,e9,$U,W9,M8,R_,D_,M_=e(()=>{T$=new x6,YZ=new B6,o6=Object.defineProperty,qZ={},k4(qZ,{withErrorRecovery:()=>v6,tryLoadConfig:()=>V4,loadConfigWithResult:()=>J4,loadConfig:()=>p6,isRetryableError:()=>L4,isConfigNotFoundError:()=>z4,isBunfigError:()=>b6,globalPerformanceMonitor:()=>N$,globalCache:()=>xX,getEnvOrDefault:()=>j4,generateConfigTypes:()=>I4,defaultGeneratedDir:()=>LY,defaultConfigDir:()=>zY,deepMergeWithArrayStrategy:()=>o1,deepMerge:()=>f6,createLibraryConfig:()=>K4,config:()=>W4,bunfigPlugin:()=>R4,applyEnvVarsToConfig:()=>lX,TypeGenerationError:()=>BZ,SchemaValidationError:()=>Z$,PluginError:()=>hZ,PerformanceMonitor:()=>J1,FileSystemError:()=>xZ,ErrorFactory:()=>p9,EnvVarError:()=>R8,EnvProcessor:()=>$Z,ConfigValidator:()=>r1,ConfigValidationError:()=>AZ,ConfigNotFoundError:()=>K8,ConfigMergeError:()=>kZ,ConfigLoader:()=>V1,ConfigLoadError:()=>$$,ConfigFileLoader:()=>ZZ,ConfigCache:()=>O1,CacheUtils:()=>o5,BunfigError:()=>$9,BrowserConfigError:()=>yZ,ArrayMergeStrategies:()=>QY}),jY=x4(async()=>{r6=import.meta.require,xX=new O1,N$=new J1,o5={createKey:s2,isEquivalent:o2,estimateMemoryUsage:r2},B4=k8(F1.cwd(),"config"),y4=k8(F1.cwd(),"src/generated"),r5=A8.env.CLARITY_LOG_DIR||O2(e2(),"logs"),J8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:r5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},K1=await X4(),f0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,reset:"\x1B[0m"},R0=f0,h4=f0.red,a5=f0.green,v4=f0.yellow,t5=f0.blue,b4=f0.magenta,f4=f0.cyan,PZ=f0.white,g4=f0.gray,e5=f0.bgRed,XY=f0.bgYellow,TZ=f0.bold,d4=f0.dim,p4=f0.italic,c4=f0.underline,m4=f0.reset,W8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a6={debug:"\uD83D\uDD0D",info:t5("\u2139"),success:a5("\u2713"),warning:XY(PZ(TZ(" WARN "))),error:e5(PZ(TZ(" ERROR ")))},u4=new y8("stacks"),g0=new y8("bunfig",{showTags:!0}),n4=u0(P$.cwd(),"config"),i4=u0(P$.cwd(),"src/generated"),$Y=S8.env.CLARITY_LOG_DIR||G2(U4(),"logs"),V8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$Y,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},R1=await _4(),A0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},j0=A0,l4=A0.red,ZY=A0.green,s4=A0.yellow,YY=A0.blue,o4=A0.magenta,r4=A0.cyan,NZ=A0.white,a4=A0.gray,UY=A0.bgRed,_Y=A0.bgYellow,t4=A0.bgGray,SZ=A0.bold,e4=A0.dim,X_=A0.italic,$_=A0.underline,Z_=A0.strikethrough,Y_=A0.reset,I8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t6={debug:"\uD83D\uDD0D",info:YY("\u2139"),success:ZY("\u2713"),warning:_Y(NZ(SZ(" WARN "))),error:UY(NZ(SZ(" ERROR ")))},U_=new v8("stacks"),$9=class extends Error{timestamp;context;constructor($,Z={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Z,Y])=>`${Z}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},K8=class extends $9{code="CONFIG_NOT_FOUND";constructor($,Z,Y){let U=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:Z,searchPathCount:Z.length})}},$$=class extends $9{code="CONFIG_LOAD_ERROR";constructor($,Z,Y){super(`Failed to load configuration from "${$}": ${Z.message}`,{configPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},AZ=class extends $9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},kZ=class extends $9{code="CONFIG_MERGE_ERROR";constructor($,Z,Y,U){super(`Failed to merge configuration from "${$}" with "${Z}": ${Y.message}`,{sourcePath:$,targetPath:Z,configName:U,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},R8=class extends $9{code="ENV_VAR_ERROR";constructor($,Z,Y,U){super(`Failed to parse environment variable "${$}" with value "${Z}" as ${Y}`,{envKey:$,envValue:Z,expectedType:Y,configName:U})}},xZ=class extends $9{code="FILE_SYSTEM_ERROR";constructor($,Z,Y){super(`File system ${$} failed for "${Z}": ${Y.message}`,{operation:$,path:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},BZ=class extends $9{code="TYPE_GENERATION_ERROR";constructor($,Z,Y){super(`Failed to generate types from "${$}" to "${Z}": ${Y.message}`,{configDir:$,outputPath:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Z$=class extends $9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},yZ=class extends $9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},hZ=class extends $9{code="PLUGIN_ERROR";constructor($,Z,Y){super(`Plugin "${$}" failed during ${Z}: ${Y.message}`,{pluginName:$,operation:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},p9={configNotFound(X,$,Z){return new K8(X,$,Z)},configLoad(X,$,Z){return new $$(X,$,Z)},configValidation(X,$,Z){return new AZ(X,$,Z)},configMerge(X,$,Z,Y){return new kZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new R8(X,$,Z,Y)},fileSystem(X,$,Z){return new xZ(X,$,Z)},typeGeneration(X,$,Z){return new BZ(X,$,Z)},schemaValidation(X,$,Z){return new Z$(X,$,Z)},browserConfig(X,$,Z,Y){return new yZ(X,$,Z,Y)},plugin(X,$,Z){return new hZ(X,$,Z)}},QY={replace:"replace",concat:"concat",smart:"smart"},e6=/^https?:\/\//,V9=new v8("bunfig",{showTags:!0}),A9=new V1,zY=i0(t9.cwd(),"config"),LY=i0(t9.cwd(),"src/generated")}),EY=x8.env.CLARITY_LOG_DIR||h2(D4(),"logs"),vZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Y$={...vZ},Q_=(async()=>{try{let{loadConfig:X}=await jY().then(()=>qZ),$=await X({name:"clarity",alias:"logging",defaultConfig:vZ,cwd:x8.cwd()});if($)Object.assign(Y$,$)}catch{}return Y$})(),k0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},E0=k0,z_=k0.red,GY=k0.green,L_=k0.yellow,FY=k0.blue,j_=k0.magenta,E_=k0.cyan,bZ=k0.white,G_=k0.gray,OY=k0.bgRed,JY=k0.bgYellow,F_=k0.bgGray,fZ=k0.bold,O_=k0.dim,J_=k0.italic,W_=k0.underline,V_=k0.strikethrough,I_=k0.reset,D8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XU={debug:"\uD83D\uDD0D",info:FY("\u2139"),success:GY("\u2713"),warning:JY(bZ(fZ(" WARN "))),error:OY(bZ(fZ(" ERROR ")))},K_=new b8("stacks"),J9=class extends Error{timestamp;context;constructor($,Z={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Z,Y])=>`${Z}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},WY=class extends J9{code="CONFIG_NOT_FOUND";constructor($,Z,Y){let U=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],_="";if(U.length===1)_=` or alias "${U[0]}"`;else if(U.length>1)_=` or aliases ${U.map((Q)=>`"${Q}"`).join(", ")}`;super(`Configuration "${$}"${_} not found`,{configName:$,alias:Y,searchPaths:Z,searchPathCount:Z.length})}},f8=class extends J9{code="CONFIG_LOAD_ERROR";constructor($,Z,Y){super(`Failed to load configuration from "${$}": ${Z.message}`,{configPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},VY=class extends J9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},IY=class extends J9{code="CONFIG_MERGE_ERROR";constructor($,Z,Y,U){super(`Failed to merge configuration from "${$}" with "${Z}": ${Y.message}`,{sourcePath:$,targetPath:Z,configName:U,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},D1=class extends J9{code="ENV_VAR_ERROR";constructor($,Z,Y,U){super(`Failed to parse environment variable "${$}" with value "${Z}" as ${Y}`,{envKey:$,envValue:Z,expectedType:Y,configName:U})}},KY=class extends J9{code="FILE_SYSTEM_ERROR";constructor($,Z,Y){super(`File system ${$} failed for "${Z}": ${Y.message}`,{operation:$,path:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},RY=class extends J9{code="TYPE_GENERATION_ERROR";constructor($,Z,Y){super(`Failed to generate types from "${$}" to "${Z}": ${Y.message}`,{configDir:$,outputPath:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},g8=class extends J9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},DY=class extends J9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},MY=class extends J9{code="PLUGIN_ERROR";constructor($,Z,Y){super(`Plugin "${$}" failed during ${Z}: ${Y.message}`,{pluginName:$,operation:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},e9={configNotFound(X,$,Z){return new WY(X,$,Z)},configLoad(X,$,Z){return new f8(X,$,Z)},configValidation(X,$,Z){return new VY(X,$,Z)},configMerge(X,$,Z,Y){return new IY(X,$,Z,Y)},envVar(X,$,Z,Y){return new D1(X,$,Z,Y)},fileSystem(X,$,Z){return new KY(X,$,Z)},typeGeneration(X,$,Z){return new RY(X,$,Z)},schemaValidation(X,$,Z){return new g8(X,$,Z)},browserConfig(X,$,Z,Y){return new DY(X,$,Z,Y)},plugin(X,$,Z){return new MY(X,$,Z)}},$U=/^https?:\/\//,W9=new b8("bunfig",{showTags:!0}),M8=new s6,R_=L9(N8.cwd(),"config"),D_=L9(N8.cwd(),"src/generated")});function J0(X=f.dialect){return X==="mysql"||X==="singlestore"}function i(X){if(f.dialect==="postgres")return`$${X}`;return"?"}function h0(X,$=1){if(X<=0)return"";if(f.dialect==="postgres"){let Z=`$${$}`;for(let Y=1;Y<X;Y++)Z+=`, $${$+Y}`;return Z}return X===1?"?":`?${", ?".repeat(X-1)}`}async function GG(){if(!U$)U$=await S4({name:"query-builder",alias:"qb",defaultConfig:M1}),H_(U$);return f}function H_(X){if(X.dialect&&mX&&X.dialect!==mX){let $=`${mX}->${X.dialect}`;if(!H1.has($))H1.add($),console.warn(`[query-builder] setConfig({ dialect: '${X.dialect}' }) overrides a previous setConfig({ dialect: '${mX}' }). Config is process-wide; in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(X.dialect)mX=X.dialect;if(Object.assign(f,X),X.database)f.database={...f.database,...X.database};if(X.timestamps)f.timestamps={...f.timestamps,...X.timestamps};if(X.pagination)f.pagination={...f.pagination,...X.pagination};if(X.softDeletes)f.softDeletes={...f.softDeletes,...X.softDeletes};if(U$)Object.assign(U$,f)}var M1,HY,f,U$=null,mX=null,H1,d0=e(()=>{M_(),M1={verbose:!0,dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},HY=Symbol.for("bun-query-builder.config"),f=globalThis[HY]??={...M1},H1=new Set});function C_(){let X=f.sqlite?.pragmas;return Array.isArray(X)?X:ZU}function t1(X){for(let $ of C_())try{X.run($)}catch{}}var ZU,e1=e(()=>{d0(),ZU=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]}),{SQL:CY}=globalThis.Bun;class YU{db;constructor(X){if(X!==":memory:"&&!X.startsWith(":")){let $=P_(X);if($&&$!==".")q_($,{recursive:!0})}this.db=new w_(X),t1(this.db)}query(X,$=[]){return this.db.prepare(X).all(...$)}run(X,$=[]){return this.db.prepare(X).run(...$)}close(){this.db.close()}get database(){return this.db}}function wY(X){return{__raw:!0,value:X,toString:()=>X}}function qY(X){let $=X.trimStart();for(;;)if($.startsWith("--")){let Z=$.indexOf(`
|
|
66
|
-
`);$=Z===-1?"":$.slice(Z+1).trimStart()}else if($.startsWith("/*")){let Z=$.indexOf("*/");$=Z===-1?"":$.slice(Z+2).trimStart()}else return $}function
|
|
67
|
-
`||j==="\r")){_=!1,Z+=j;continue}if(!Y&&!U&&!_&&j==="/"&&E==="*"){Q=!0,Z+=j;continue}if(Q&&j==="*"&&E==="/"){Q=!1,Z+=j+E,z++;continue}if(_||Q){Z+=j;continue}if(j==="'"&&!U){if(Y&&E==="'"){Z+=j+E,z++;continue}Y=!Y,Z+=j;continue}if(j==='"'&&!Y){U=!U,Z+=j;continue}if(j===";"&&!Y&&!U){let V=
|
|
65
|
+
`;return Z}}function w4(X,$,Z={}){return u6(X,$,Z,new WeakMap)}function u6(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return n6(X,$,U,Y);if(!F9($)||!F9(X))return $;return N4(X,$,Z,Y)}function n6(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return q4(X,$);case"smart":return P4(X,$,Y);default:return $}return $}function q4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>I1(U,Y)))Z.push(Y);return Z}function P4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(F9($[0])&&F9(X[0]))return T4(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function T4(X,$,Z){let Y=[...$];for(let U of X){if(!F9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((j)=>F9(j)&&(L in j)&&j[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function N4(X,$,Z,Y){let U=$;if(F9(U)&&Y.has(U))return Y.get(U);let _={...X};if(F9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(F9(L)&&F9(z))_[Q]=u6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=n6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function i6(X,$,Z="replace"){return w4(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function I1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!I1(X[Z],$[Z]))return!1;return!0}if(F9(X)&&F9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!I1(X[U],$[U]))return!1}return!0}return!1}function F9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class l6{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=T$.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!o$(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new f8(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new f8(X,Error("Configuration must export a valid object"),"unknown");let K={config:i6($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)T$.setWithFileCheck("file",K,X,_);return K}catch(j){throw j instanceof Error?e9.configLoad(X,j):e9.configLoad(X,Error(String(j)))}};if(Q)return YZ.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(wZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let Y=$===void 0?[]:Array.isArray($)?$:[$];for(let _ of Y){if(!_)continue;if(Z.push(_,`.${_}.config`,`${_}.config`,`.${_}`),X)Z.push(`${X}.${_}.config`,`.${X}.${_}.config`)}let U=new Set;return Z.filter((_)=>{if(!_||U.has(_))return!1;return U.add(_),!0})}checkFileAccess(X){return C4(async()=>{return o$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!o$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=wZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=wZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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((Z)=>Z.test(X))}async validateConfigFile(X){let $=[];try{if(!o$(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class s6{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await YZ.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!l2($))throw new g8($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new g8($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:ZU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function S4(X){if(!X)return"";let $=Array.isArray(X)?X.filter(Boolean):[X];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Z)=>`"${Z}"`).join(", ")}`}class o6{fileLoader=new l6;envProcessor=new t1;validator=new s6;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)W9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){if(L instanceof Error&&L.name==="ConfigNotFoundError")throw L;let z=Date.now()-$;throw W9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||N8.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(L9(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw e9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${S4(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?a$(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)W9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)W9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?a$(X,Z,U):Z,L=[L9(zX(),".config",X),L9(zX(),".config"),zX()];for(let z of L){if(U)W9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)W9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?a$(X,Y,_):Y;try{let z=L9(Z,"package.json");if(!z2(z))return null;let j={};try{j=JSON.parse(L2(z,"utf8"))}catch(G){if(_)W9.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let E=j[X],V=X;if(!E&&$){let G=Array.isArray($)?$:[$];for(let J of G){if(!J)continue;if(j[J]){E=j[J],V=J;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)W9.success(`Configuration loaded from package.json: ${V}`);return{config:i6(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)W9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:a$(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw e9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return T$.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);T$.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias){let Y=Array.isArray($.alias)?$.alias.join(","):$.alias;Z.push(`alias:${Y}`)}if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,L9(X,"config"),L9(X,".config"),$?L9(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(L9(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[L9(zX(),".config",X),L9(zX(),".config"),zX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}async function A4(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await M8.loadConfig(X);else Y=await M8.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)W9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let L=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await M8.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}function a$(X,$,Z=!1){let Y=new t1,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=N8.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}var T$,YZ,r6,k4=(X)=>X,x4=(X,$)=>{for(var Z in $)r6(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:s2.bind($,Z)})},B4=(X,$)=>()=>(X&&($=X(X=0)),$),qZ,a6,xX,N$,r5,y4,h4,a5,J8,K1,f0,D0,v4,t5,b4,e5,f4,g4,PZ,d4,XY,$Y,TZ,p4,c4,m4,u4,W8,t6,n4,g0,i4,l4,ZY,V8,R1,A0,E0,s4,YY,o4,UY,r4,a4,NZ,t4,_Y,QY,e4,SZ,X_,$_,Z_,Y_,U_,I8,e6,__,Q_="0.15.6",$9,K8,$$,AZ,kZ,R8,xZ,BZ,Z$,yZ,hZ,c9,zY,XU,V9,k9,LY,jY,EY,GY,vZ,Y$,z_,k0,G0,L_,FY,j_,OY,E_,G_,bZ,F_,JY,WY,O_,fZ,J_,W_,V_,I_,K_,D8,$U,R_,J9,VY,f8,IY,KY,D1,RY,DY,g8,MY,HY,e9,ZU,W9,M8,D_,M_,H_=t(()=>{T$=new B6,YZ=new y6,r6=Object.defineProperty,qZ={},x4(qZ,{withErrorRecovery:()=>b6,tryLoadConfig:()=>I4,loadConfigWithResult:()=>W4,loadConfig:()=>c6,isRetryableError:()=>j4,isConfigNotFoundError:()=>L4,isBunfigError:()=>f6,globalPerformanceMonitor:()=>N$,globalCache:()=>xX,getEnvOrDefault:()=>E4,generateConfigTypes:()=>K4,defaultGeneratedDir:()=>jY,defaultConfigDir:()=>LY,deepMergeWithArrayStrategy:()=>r1,deepMerge:()=>g6,createLibraryConfig:()=>R4,config:()=>V4,bunfigPlugin:()=>D4,applyEnvVarsToConfig:()=>lX,TypeGenerationError:()=>BZ,SchemaValidationError:()=>Z$,PluginError:()=>hZ,PerformanceMonitor:()=>J1,FileSystemError:()=>xZ,ErrorFactory:()=>c9,EnvVarError:()=>R8,EnvProcessor:()=>$Z,ConfigValidator:()=>a1,ConfigValidationError:()=>AZ,ConfigNotFoundError:()=>K8,ConfigMergeError:()=>kZ,ConfigLoader:()=>V1,ConfigLoadError:()=>$$,ConfigFileLoader:()=>ZZ,ConfigCache:()=>O1,CacheUtils:()=>r5,BunfigError:()=>$9,BrowserConfigError:()=>yZ,ArrayMergeStrategies:()=>zY}),EY=B4(async()=>{a6=import.meta.require,xX=new O1,N$=new J1,r5={createKey:o2,isEquivalent:r2,estimateMemoryUsage:a2},y4=k8(F1.cwd(),"config"),h4=k8(F1.cwd(),"src/generated"),a5=A8.env.CLARITY_LOG_DIR||J2(X4(),"logs"),J8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:a5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},K1=await $4(),f0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,reset:"\x1B[0m"},D0=f0,v4=f0.red,t5=f0.green,b4=f0.yellow,e5=f0.blue,f4=f0.magenta,g4=f0.cyan,PZ=f0.white,d4=f0.gray,XY=f0.bgRed,$Y=f0.bgYellow,TZ=f0.bold,p4=f0.dim,c4=f0.italic,m4=f0.underline,u4=f0.reset,W8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t6={debug:"\uD83D\uDD0D",info:e5("\u2139"),success:t5("\u2713"),warning:$Y(PZ(TZ(" WARN "))),error:XY(PZ(TZ(" ERROR ")))},n4=new y8("stacks"),g0=new y8("bunfig",{showTags:!0}),i4=n0(P$.cwd(),"config"),l4=n0(P$.cwd(),"src/generated"),ZY=S8.env.CLARITY_LOG_DIR||F2(_4(),"logs"),V8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ZY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},R1=await Q4(),A0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},E0=A0,s4=A0.red,YY=A0.green,o4=A0.yellow,UY=A0.blue,r4=A0.magenta,a4=A0.cyan,NZ=A0.white,t4=A0.gray,_Y=A0.bgRed,QY=A0.bgYellow,e4=A0.bgGray,SZ=A0.bold,X_=A0.dim,$_=A0.italic,Z_=A0.underline,Y_=A0.strikethrough,U_=A0.reset,I8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},e6={debug:"\uD83D\uDD0D",info:UY("\u2139"),success:YY("\u2713"),warning:QY(NZ(SZ(" WARN "))),error:_Y(NZ(SZ(" ERROR ")))},__=new v8("stacks"),$9=class extends Error{timestamp;context;constructor($,Z={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Z,Y])=>`${Z}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},K8=class extends $9{code="CONFIG_NOT_FOUND";constructor($,Z,Y){let U=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:Z,searchPathCount:Z.length})}},$$=class extends $9{code="CONFIG_LOAD_ERROR";constructor($,Z,Y){super(`Failed to load configuration from "${$}": ${Z.message}`,{configPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},AZ=class extends $9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},kZ=class extends $9{code="CONFIG_MERGE_ERROR";constructor($,Z,Y,U){super(`Failed to merge configuration from "${$}" with "${Z}": ${Y.message}`,{sourcePath:$,targetPath:Z,configName:U,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},R8=class extends $9{code="ENV_VAR_ERROR";constructor($,Z,Y,U){super(`Failed to parse environment variable "${$}" with value "${Z}" as ${Y}`,{envKey:$,envValue:Z,expectedType:Y,configName:U})}},xZ=class extends $9{code="FILE_SYSTEM_ERROR";constructor($,Z,Y){super(`File system ${$} failed for "${Z}": ${Y.message}`,{operation:$,path:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},BZ=class extends $9{code="TYPE_GENERATION_ERROR";constructor($,Z,Y){super(`Failed to generate types from "${$}" to "${Z}": ${Y.message}`,{configDir:$,outputPath:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Z$=class extends $9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},yZ=class extends $9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},hZ=class extends $9{code="PLUGIN_ERROR";constructor($,Z,Y){super(`Plugin "${$}" failed during ${Z}: ${Y.message}`,{pluginName:$,operation:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},c9={configNotFound(X,$,Z){return new K8(X,$,Z)},configLoad(X,$,Z){return new $$(X,$,Z)},configValidation(X,$,Z){return new AZ(X,$,Z)},configMerge(X,$,Z,Y){return new kZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new R8(X,$,Z,Y)},fileSystem(X,$,Z){return new xZ(X,$,Z)},typeGeneration(X,$,Z){return new BZ(X,$,Z)},schemaValidation(X,$,Z){return new Z$(X,$,Z)},browserConfig(X,$,Z,Y){return new yZ(X,$,Z,Y)},plugin(X,$,Z){return new hZ(X,$,Z)}},zY={replace:"replace",concat:"concat",smart:"smart"},XU=/^https?:\/\//,V9=new v8("bunfig",{showTags:!0}),k9=new V1,LY=l0(t9.cwd(),"config"),jY=l0(t9.cwd(),"src/generated")}),GY=x8.env.CLARITY_LOG_DIR||v2(M4(),"logs"),vZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:GY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Y$={...vZ},z_=(async()=>{try{let{loadConfig:X}=await EY().then(()=>qZ),$=await X({name:"clarity",alias:"logging",defaultConfig:vZ,cwd:x8.cwd()});if($)Object.assign(Y$,$)}catch{}return Y$})(),k0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},G0=k0,L_=k0.red,FY=k0.green,j_=k0.yellow,OY=k0.blue,E_=k0.magenta,G_=k0.cyan,bZ=k0.white,F_=k0.gray,JY=k0.bgRed,WY=k0.bgYellow,O_=k0.bgGray,fZ=k0.bold,J_=k0.dim,W_=k0.italic,V_=k0.underline,I_=k0.strikethrough,K_=k0.reset,D8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$U={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:FY("\u2713"),warning:WY(bZ(fZ(" WARN "))),error:JY(bZ(fZ(" ERROR ")))},R_=new b8("stacks"),J9=class extends Error{timestamp;context;constructor($,Z={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Z,Y])=>`${Z}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},VY=class extends J9{code="CONFIG_NOT_FOUND";constructor($,Z,Y){let U=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],_="";if(U.length===1)_=` or alias "${U[0]}"`;else if(U.length>1)_=` or aliases ${U.map((Q)=>`"${Q}"`).join(", ")}`;super(`Configuration "${$}"${_} not found`,{configName:$,alias:Y,searchPaths:Z,searchPathCount:Z.length})}},f8=class extends J9{code="CONFIG_LOAD_ERROR";constructor($,Z,Y){super(`Failed to load configuration from "${$}": ${Z.message}`,{configPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},IY=class extends J9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},KY=class extends J9{code="CONFIG_MERGE_ERROR";constructor($,Z,Y,U){super(`Failed to merge configuration from "${$}" with "${Z}": ${Y.message}`,{sourcePath:$,targetPath:Z,configName:U,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},D1=class extends J9{code="ENV_VAR_ERROR";constructor($,Z,Y,U){super(`Failed to parse environment variable "${$}" with value "${Z}" as ${Y}`,{envKey:$,envValue:Z,expectedType:Y,configName:U})}},RY=class extends J9{code="FILE_SYSTEM_ERROR";constructor($,Z,Y){super(`File system ${$} failed for "${Z}": ${Y.message}`,{operation:$,path:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},DY=class extends J9{code="TYPE_GENERATION_ERROR";constructor($,Z,Y){super(`Failed to generate types from "${$}" to "${Z}": ${Y.message}`,{configDir:$,outputPath:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},g8=class extends J9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},MY=class extends J9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},HY=class extends J9{code="PLUGIN_ERROR";constructor($,Z,Y){super(`Plugin "${$}" failed during ${Z}: ${Y.message}`,{pluginName:$,operation:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},e9={configNotFound(X,$,Z){return new VY(X,$,Z)},configLoad(X,$,Z){return new f8(X,$,Z)},configValidation(X,$,Z){return new IY(X,$,Z)},configMerge(X,$,Z,Y){return new KY(X,$,Z,Y)},envVar(X,$,Z,Y){return new D1(X,$,Z,Y)},fileSystem(X,$,Z){return new RY(X,$,Z)},typeGeneration(X,$,Z){return new DY(X,$,Z)},schemaValidation(X,$,Z){return new g8(X,$,Z)},browserConfig(X,$,Z,Y){return new MY(X,$,Z,Y)},plugin(X,$,Z){return new HY(X,$,Z)}},ZU=/^https?:\/\//,W9=new b8("bunfig",{showTags:!0}),M8=new o6,D_=L9(N8.cwd(),"config"),M_=L9(N8.cwd(),"src/generated")});function W0(X=f.dialect){return X==="mysql"||X==="singlestore"}function i(X){if(f.dialect==="postgres")return`$${X}`;return"?"}function h0(X,$=1){if(X<=0)return"";if(f.dialect==="postgres"){let Z=`$${$}`;for(let Y=1;Y<X;Y++)Z+=`, $${$+Y}`;return Z}return X===1?"?":`?${", ?".repeat(X-1)}`}async function OG(){if(!U$)U$=await A4({name:"query-builder",alias:"qb",defaultConfig:M1}),C_(U$);return f}function C_(X){if(X.dialect&&mX&&X.dialect!==mX){let $=`${mX}->${X.dialect}`;if(!H1.has($))H1.add($),console.warn(`[query-builder] setConfig({ dialect: '${X.dialect}' }) overrides a previous setConfig({ dialect: '${mX}' }). Config is process-wide; in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(X.dialect)mX=X.dialect;if(Object.assign(f,X),X.database)f.database={...f.database,...X.database};if(X.timestamps)f.timestamps={...f.timestamps,...X.timestamps};if(X.pagination)f.pagination={...f.pagination,...X.pagination};if(X.softDeletes)f.softDeletes={...f.softDeletes,...X.softDeletes};if(U$)Object.assign(U$,f)}var M1,CY,f,U$=null,mX=null,H1,d0=t(()=>{H_(),M1={verbose:!0,dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},CY=Symbol.for("bun-query-builder.config"),f=globalThis[CY]??={...M1},H1=new Set});function w_(){let X=f.sqlite?.pragmas;return Array.isArray(X)?X:YU}function e1(X){for(let $ of w_())try{X.run($)}catch{}}var YU,X5=t(()=>{d0(),YU=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]}),{SQL:wY}=globalThis.Bun;class UU{db;constructor(X){if(X!==":memory:"&&!X.startsWith(":")){let $=T_(X);if($&&$!==".")P_($,{recursive:!0})}this.db=new q_(X),e1(this.db)}query(X,$=[]){return this.db.prepare(X).all(...$)}run(X,$=[]){return this.db.prepare(X).run(...$)}close(){this.db.close()}get database(){return this.db}}function qY(X){return{__raw:!0,value:X,toString:()=>X}}function PY(X){let $=X.trimStart();for(;;)if($.startsWith("--")){let Z=$.indexOf(`
|
|
66
|
+
`);$=Z===-1?"":$.slice(Z+1).trimStart()}else if($.startsWith("/*")){let Z=$.indexOf("*/");$=Z===-1?"":$.slice(Z+2).trimStart()}else return $}function N_(X){let $=[],Z="",Y=!1,U=!1,_=!1,Q=!1;for(let z=0;z<X.length;z++){let j=X[z],E=X[z+1];if(!Y&&!U&&!Q&&j==="-"&&E==="-"){_=!0,Z+=j;continue}if(_&&(j===`
|
|
67
|
+
`||j==="\r")){_=!1,Z+=j;continue}if(!Y&&!U&&!_&&j==="/"&&E==="*"){Q=!0,Z+=j;continue}if(Q&&j==="*"&&E==="/"){Q=!1,Z+=j+E,z++;continue}if(_||Q){Z+=j;continue}if(j==="'"&&!U){if(Y&&E==="'"){Z+=j+E,z++;continue}Y=!Y,Z+=j;continue}if(j==='"'&&!Y){U=!U,Z+=j;continue}if(j===";"&&!Y&&!U){let V=PY(Z.trim());if(V)$.push(V);Z="";continue}Z+=j}let L=PY(Z.trim());if(L)$.push(L);return $}function TY(X){let $=new UU(X);function Z(_,...Q){let L=_[0],z=[];for(let j=0;j<Q.length;j++){let E=Q[j];if(E&&typeof E==="object"&&(E.__raw||E.raw)){let V=E.__raw?E.value:typeof E.raw==="string"?E.raw:E.raw();L+=V+(_[j+1]||"")}else if(E&&typeof E==="object"&&"sql"in E&&"values"in E)L+=E.sql+(_[j+1]||""),z.push(...E.values);else if(Array.isArray(E)){let V=E.map(()=>"?").join(", ");L+=V+(_[j+1]||""),z.push(...E)}else L+=`?${_[j+1]||""}`,z.push(E)}return{sql:L,values:z,execute:()=>{try{let j=L.trim().toUpperCase();if(j.startsWith("SELECT")||j.startsWith("PRAGMA")||/\bRETURNING\b/.test(j)){let E=$.query(L,z);return Promise.resolve(E)}else{let E=$.run(L,z);return Promise.resolve(E)}}catch(j){return Promise.reject(j)}},raw:()=>L,toString:()=>L,cancel:()=>{}}}function Y(_,...Q){if(Array.isArray(_)&&"raw"in _)return Z(_,...Q);if(typeof _==="string")return qY(_);return Z([""])}Y.raw=(_)=>qY(_),Y.unsafe=(_,Q=[])=>{let L=()=>{try{let z=_.trim().toUpperCase();if(z.startsWith("SELECT")||z.startsWith("PRAGMA")||/\bRETURNING\b/.test(z)){let j=$.query(_,Q);return Promise.resolve(j)}else{let j=$.run(_,Q);return Promise.resolve(j)}}catch(z){return Promise.reject(z)}};return{sql:_,values:Q,execute:L,then:(z,j)=>L().then(z,j),raw:()=>_,toString:()=>_,cancel:()=>{}}},Y.close=()=>{return $.close(),Promise.resolve()},Y.query=(_,Q)=>{try{let L=$.query(_,Q||[]);return Promise.resolve(L)}catch(L){return Promise.reject(L)}},Y.file=async(_,Q)=>{try{let{readFileSync:L}=await import("fs"),z=L(_,"utf-8"),j=N_(z);for(let E of j){let V=E.trim();if(!V||V.startsWith("--"))continue;let G=V.toUpperCase();if(G.startsWith("SELECT")||G.startsWith("PRAGMA"))$.query(E);else $.run(E)}return Promise.resolve([])}catch(L){return Promise.reject(L)}};let U=0;return Y.begin=async(_,Q)=>{let L=typeof _==="function"?_:Q;if(typeof L!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let z=U>0,j=`qb_sp_${U}`;if(z)$.run(`SAVEPOINT ${j}`);else $.run("BEGIN");U++;try{let E=await L(Y);if(U--,z)$.run(`RELEASE SAVEPOINT ${j}`);else $.run("COMMIT");return E}catch(E){U--;try{if(z)$.run(`ROLLBACK TO SAVEPOINT ${j}`),$.run(`RELEASE SAVEPOINT ${j}`);else $.run("ROLLBACK")}catch{}throw E}},Y.savepoint=Y.begin,Y.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},Y._wrapper=$,Y}function S_(X,$){if((X==="postgres"||X==="mysql"||X==="singlestore")&&t$.env.DB_CONNECTION===X){let j=t$.env,E=(j.DB_DATABASE||$.database||"").replace(/^['"]|['"]$/g,""),V=j.DB_USERNAME||$.username,G=j.DB_PASSWORD??$.password??"",J=j.DB_HOST||$.host||"localhost",W=j.DB_PORT||$.port,F=X==="postgres"?"postgres":"mysql",K=j.DB_SSL==="true"||j.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${F}://${V}:${G}@${J}${W?`:${W}`:""}/${E}${K}`}if($.url)return $.url;let{database:Z,username:Y,password:U,host:_="localhost",port:Q,ssl:L}=$,z=L||t$.env.DB_SSL==="true"||t$.env.DB_SSL==="1"?"?ssl=true":"";switch(X){case"postgres":return`postgres://${Y}:${U}@${_}${Q?`:${Q}`:""}/${Z}${z}`;case"mysql":case"singlestore":return`mysql://${Y}:${U}@${_}${Q?`:${Q}`:""}/${Z}${z}`;case"sqlite":if(Z===":memory:")return":memory:";return Z||":memory:";default:throw Error(`Unsupported dialect: ${X}`)}}function _U(X){if(!X)return{};let $={},Z=(Y)=>Math.max(0,Math.round(Y/1000));if(typeof X.max==="number"&&Number.isFinite(X.max))$.max=X.max;if(typeof X.idleTimeoutMs==="number"&&Number.isFinite(X.idleTimeoutMs))$.idleTimeout=Z(X.idleTimeoutMs);if(typeof X.acquireTimeoutMs==="number"&&Number.isFinite(X.acquireTimeoutMs))$.connectionTimeout=Z(X.acquireTimeoutMs);if(typeof X.maxLifetimeMs==="number"&&Number.isFinite(X.maxLifetimeMs))$.maxLifetime=Z(X.maxLifetimeMs);return $}function A_(){let X=f.dialect,$=S_(X,f.database);try{if(X==="sqlite")return TY($);let Z=_U(f.database.pool);return Object.keys(Z).length>0?new wY($,Z):new wY($)}catch(Z){if(console.error(`[query-builder] Failed to create database connection for dialect '${X}': ${Z.message}`),X==="sqlite")return TY(":memory:");throw Z}}function k_(){let X=f.database;return JSON.stringify({dialect:f.dialect,database:X.database,username:X.username,password:X.password,host:X.host,port:X.port,url:X.url,pool:_U(X.pool)})}function BX(X=!1){let $=k_();if(X||sX!==null&&C1!==$||!sX)sX=A_(),C1=$;return sX}function KG(){sX=null,C1=null}async function gZ(X){try{return await X(BX())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Z=BX(!0);return await X(Z)}throw $}}function x_(){return new Proxy(function(){},{get(X,$){let Z=BX(),Y=Z[$];if(typeof Y==="function")return Y.bind(Z);return Y},apply(X,$,Z){return BX()(...Z)}})}var sX=null,C1=null,m,$X=t(()=>{d0(),X5(),m=x_()});async function RG(X={}){let $=X.iterations||1000,Z=X.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${$}`),console.log(`-- Operations: ${Z.join(", ")}`),console.log();let Y=R0();console.log("-- Setting up test table...");try{await m.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await m.unsafe(`
|
|
68
68
|
CREATE TABLE bench_users (
|
|
69
69
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
70
70
|
name TEXT NOT NULL,
|
|
@@ -75,7 +75,7 @@ export type ConfigOf = Config
|
|
|
75
75
|
`).execute();for(let Q=0;Q<100;Q++)await m.unsafe(`
|
|
76
76
|
INSERT INTO bench_users (name, email, created_at)
|
|
77
77
|
VALUES (?, ?, ?)
|
|
78
|
-
`,[`User ${Q}`,`user${Q}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(Q){throw console.error("-- Failed to setup test table:",Q),Q}let U=[];if(Z.includes("select")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").where({active:1}).limit(10).execute(),Q.push(performance.now()-z)}U.push({operation:"SELECT with WHERE + LIMIT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("select")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").where({id:1}).first(),Q.push(performance.now()-z)}U.push({operation:"SELECT by ID (first)",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("count")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").count(),Q.push(performance.now()-z)}U.push({operation:"COUNT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("insert")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.insertInto("bench_users").values({name:`Bench User ${L}`,email:`bench${L}@example.com`,created_at:new Date().toISOString()}).execute(),Q.push(performance.now()-z)}U.push({operation:"INSERT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("update")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.updateTable("bench_users").set({active:0}).where({id:1}).execute(),Q.push(performance.now()-z)}U.push({operation:"UPDATE by ID",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("delete")){let Q=[],L=[];for(let z=0;z<$;z++){let j=await Y.insertInto("bench_users").values({name:"To Delete",email:`delete${z}@example.com`,created_at:new Date().toISOString()}).execute();L.push(j)}for(let z=0;z<$;z++){let j=performance.now();await Y.deleteFrom("bench_users").where({id:L[z]}).execute(),Q.push(performance.now()-j)}U.push({operation:"DELETE by ID",avgTime:Q.reduce((z,j)=>z+j,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}console.log("-- Benchmark Results"),console.log();let _=Math.max(...U.map((Q)=>Q.operation.length));console.log("Operation".padEnd(_+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(_+2+12+12+12+12));for(let Q of U){let L=Q.operation.padEnd(_+2),z=Q.avgTime.toFixed(3).padStart(12),j=Q.minTime.toFixed(3).padStart(12),E=Q.maxTime.toFixed(3).padStart(12),V=(1000/Q.avgTime).toFixed(0).padStart(12);console.log(`${L}${z}${j}${E}${V}`)}console.log();try{await m.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(Q){console.error("-- Warning: Failed to cleanup test table:",Q)}}var x_=e(()=>{$X(),y0()});function B_(X){return X.endsWith("s")?X.slice(0,-1):X}function PX(X,$,Z,Y={}){let U=Y.singularize??B_,Q=X.relations?.[$]?.belongsToMany?.[Z];if(Q==null)return null;let L=typeof Q==="object",z=L?Q:null,j=L?z.model:Q,E=X.modelToTable[j]||j,V,G;if(z?.table)V=z.table;else if(z?.through){if(G=z.through,V=X.modelToTable[z.through],!V)throw Error(`[query-builder] belongsToMany relation '${Z}' on '${$}' references unknown through model '${z.through}'. Make sure '${z.through}' is registered via defineModels({...}).`)}else{let w=U($),T=U(E);V=[w,T].sort().join("_")}let J=z?.foreignKey??`${U($)}_id`,W=z?.relatedKey??`${U(E)}_id`,F={};if(z?.pivot?.columns)Object.assign(F,z.pivot.columns);if(G&&Y.models){let w=Y.models[G],T=w?.definition??w?.getDefinition?.()??w,N=T?.attributes??{};for(let[q,H]of Object.entries(N)){if(q===J||q===W||q===(T?.primaryKey??"id"))continue;F[q]={default:H?.default,nullable:H?.nullable,validation:H?.validation}}}let K=Boolean(z?.pivot?.timestamps),D=Object.keys(F);return{pivotTable:V,fkParent:J,fkRelated:W,pivotColumns:D,pivotColumnDefs:F,pivotModelName:G,timestamps:K,relatedModelName:j,relatedTable:E,hasConfig:L}}function*KG(X,$={}){let Z=X.relations;if(!Z)return;for(let[Y,U]of Object.entries(Z)){let _=U?.belongsToMany;if(!_)continue;for(let Q of Object.keys(_)){let L=PX(X,Y,Q,$);if(L)yield{parentTable:Y,relationKey:Q,resolved:L}}}}function d8(X){return typeof X==="object"&&X!==null&&"raw"in X&&typeof X.raw==="string"}function RG(X,...$){if(typeof X==="string")return{raw:X};let Z=X[0];for(let Y=0;Y<$.length;Y++)Z+=w9($[Y])+X[Y+1];return{raw:Z}}function a0(X){return J0(f.dialect)?`\`${X.replace(/`/g,"``")}\``:`"${X.replace(/"/g,'""')}"`}function e$(X,$=1){let Z=Object.keys(X[0]??{}),Y=[],U=$,_=X.map((Q)=>{return`(${Z.map((z)=>{return Y.push(Q[z]),i(U++)}).join(", ")})`});return{colsSql:Z.map(a0).join(", "),valuesSql:_.join(", "),params:Y,nextIndex:U}}function uX(X){return Boolean(X&&(X.onSlowQuery||X.slowQueryThresholdMs!=null&&X.slowQueryThresholdMs>=0))}function TY(X){if(typeof X==="string")return X;if(d8(X))return X.raw;if(X&&typeof X==="object"){let $=X;if(typeof $.raw==="function")return String($.raw());if(typeof $.sql==="string")return $.sql;let Z=String(X);if(Z!=="[object Object]")return Z}throw TypeError(`[query-builder] select(): unsupported column ${String(X)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function u(X,$){if(!s.IDENTIFIER.test(X)){let Z=$?` in ${$}`:"";throw Error(`[query-builder] Invalid identifier${Z}: '${X}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function v0(X,$){if(typeof X!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof X}`);let Z=X.toLowerCase();if(!w1.has(Z))throw TypeError(`[query-builder] ${$}: refusing to use '${X}' as a SQL operator \u2014 not in the allowed set (${[...w1].join(", ")})`);return X}function Q9(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);if(X.length>129)throw TypeError(`[query-builder] ${$}: identifier '${X}' too long`);let Z=X.split(".");if(Z.length>2)throw TypeError(`[query-builder] ${$}: identifier '${X}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let Y of Z)if(!/^[A-Z_][A-Z0-9_]*$/i.test(Y))throw TypeError(`[query-builder] ${$}: identifier segment '${Y}' contains characters outside [A-Za-z0-9_]`)}function KX(X,$){if(typeof X==="string")return y_($),X;if(X===null||X===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${X}`);if(d8(X))return X.raw;if(typeof X==="object"){let Z=X;if(typeof Z.raw==="string")return Z.raw;if(typeof Z.raw==="function"){let U=Z.raw();if(typeof U==="string")return U}if(typeof Z.sql==="string")return Z.sql;let Y=String(X);if(Y!=="[object Object]"&&Y!=="[object Promise]")return Y}throw TypeError(`[query-builder] ${$}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function y_(X){if(q1.has(X))return;q1.add(X),console.warn(`[query-builder] ${X}: bare string passed to a *Raw method. Prefer \`sql\`...\`\` tagged-template fragments so values are parameterised `+"instead of concatenated \u2014 concatenating request input into SQL is an "+"injection vector. This will become a hard error in a future release.")}function w9(X){if(X===null)return"NULL";if(typeof X==="number"&&Number.isFinite(X))return String(X);if(typeof X==="boolean")return X?"1":"0";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof X}`)}function h_(X,$){let Z=Array.isArray(X)?X:X?[X]:[],Y=[];if(Z.length)Y.push(`PARTITION BY ${Z.join(", ")}`);if($&&$.length)Y.push(`ORDER BY ${$.map(([U,_])=>`${U} ${_==="desc"?"DESC":"ASC"}`).join(", ")}`);return Y.length?`OVER (${Y.join(" ")})`:"OVER ()"}class _U{cache=new Map;maxSize=100;get(X){let $=this.cache.get(X);if(!$)return null;if(Date.now()>$.expiresAt)return this.cache.delete(X),null;return this.cache.delete(X),this.cache.set(X,$),$.data}set(X,$,Z){if(this.cache.has(X))this.cache.delete(X);if(this.cache.size>=this.maxSize){let Y=Date.now(),U=!1;for(let[_,Q]of this.cache)if(Y>Q.expiresAt){if(this.cache.delete(_),U=!0,this.cache.size<this.maxSize)break}if(!U){let _=this.cache.keys().next().value;if(_!==void 0)this.cache.delete(_)}}this.cache.set(X,{data:$,expiresAt:Date.now()+Z})}clear(){this.cache.clear()}setMaxSize(X){this.maxSize=X}}function v_(X){let $=String(X?.message||"").toLowerCase();return $.includes("deadlock")||$.includes("serialization failure")||$.includes("could not serialize access")||$.includes("deadlock found when trying to get lock")||$.includes("lock wait timeout exceeded")||$.includes("database is locked")||$.includes("busy")}function b_(X,$){if(!$||$.length===0)return!1;let Z=X&&(X.code||X.sqlState||X.sqlstate);if(!Z)return!1;return $.includes(Z)}function f_(X){return new Promise(($)=>setTimeout($,X))}function X8(X){let $=oX.get(X);if($!==void 0)return $;let Z=g_(X);if(oX.size>=m_)oX.clear();return oX.set(X,Z),Z}function g_(X){let $=[{key:"GROUP_BY",tokens:/^GROUP\s+BY\b/i},{key:"ORDER_BY",tokens:/^ORDER\s+BY\b/i},{key:"HAVING",tokens:/^HAVING\b/i},{key:"OFFSET",tokens:/^OFFSET\b/i},{key:"LIMIT",tokens:/^LIMIT\b/i},{key:"WHERE",tokens:/^WHERE\b/i}],Z=[],Y=0,U=!1,_="";for(let E=0;E<X.length;E++){let V=X[E];if(U){if(V===_){if(X[E+1]===_){E++;continue}U=!1}continue}if(V==="'"||V==='"'||V==="`"){U=!0,_=V;continue}if(V==="("){Y++;continue}if(V===")"){Y--;continue}if(Y!==0)continue;if(E===0||!/\s/.test(X[E-1]))continue;let G=X.charCodeAt(E)&-33;if(G!==71&&G!==79&&G!==72&&G!==76&&G!==87)continue;let J=X.slice(E);for(let{key:W,tokens:F}of $){let K=J.match(F);if(!K)continue;Z.push({key:W,start:E}),E+=K[0].length-1;break}}if(Z.length<=1)return X;let Q=X.slice(0,Z[0].start).trimEnd(),L={};for(let E=0;E<Z.length;E++){let V=Z[E].start,G=E+1<Z.length?Z[E+1].start:X.length,J=X.slice(V,G).trim();if(!L[Z[E].key])L[Z[E].key]=[];L[Z[E].key].push(J)}let j=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((E)=>L[E]).map((E)=>L[E].join(" ")).join(" ");return j?`${Q} ${j}`:Q}function d_(X,$){let Z=Math.max(1,$?.baseMs??50),Y=Math.max(1,$?.factor??2),U=Math.max(Z,$?.maxMs??2000),_=Math.min(U,Z*Y**Math.max(0,X-1));if($?.jitter){let Q=Math.random()*_*0.2;_=_-Q/2}return Math.floor(_)}function K0(X){let $=X?.sql??BX(),Z=X?.meta,Y=X?.schema,U=new Map;function _(G){if(Array.isArray(G)){let[D,w,T]=G;u(D,"where(column)");let N=String(D);switch(w){case"in":if(Array.isArray(T)){let q=h0(T.length);return $.unsafe(`${N} IN (${q})`,T)}return $.unsafe(`${N} IN (${i(1)})`,[T]);case"not in":if(Array.isArray(T)){let q=h0(T.length);return $.unsafe(`${N} NOT IN (${q})`,T)}return $.unsafe(`${N} NOT IN (${i(1)})`,[T]);case"like":return $.unsafe(`${N} LIKE ${i(1)}`,[T]);case"is":case"is not":{if(T!==null&&T!==void 0)throw TypeError(`[query-builder] where(..., '${w}', ?): operator '${w}' only accepts NULL/undefined as value, got ${typeof T} (${String(T)})`);return $.unsafe(`${N} IS ${w==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${N} <> ${i(1)}`,[T]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${N} ${w} ${i(1)}`,[T]);default:throw TypeError(`[query-builder] where(..., '${String(w)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in G)return G.raw;let J=Object.keys(G);if(J.length===0)return $.unsafe("");let W=[],F=[],K=1;for(let D of J){u(D,"where(object key)");let w=G[D];if(Array.isArray(w)){let T=h0(w.length,K);W.push(`${D} IN (${T})`),F.push(...w),K+=w.length}else W.push(`${D} = ${i(K++)}`),F.push(w)}return $.unsafe(W.join(" AND "),F)}function Q(G,J,W){if(!W)return J;let F=_(W);return $`${J} WHERE ${F}`}function L(G){let J=f.debug?.captureText;if(f.debug)f.debug.captureText=!0;let W=String(G);if(f.debug)f.debug.captureText=J;return W}function z(G){if(!G||typeof G!=="object")return;if(Array.isArray(G.values))return G.values;if(Array.isArray(G.parameters))return G.parameters;if(Array.isArray(G.params))return G.params;return}function j(G,J,W){let F=f.hooks,K=F?.slowQueryThresholdMs,D=K!=null&&K>=0,w=Boolean(F?.onSlowQuery||D),T=F&&(F.onQueryStart||F.onQueryEnd||F.onQueryError||F.startSpan||w),N=W?.timeoutMs&&W.timeoutMs>0||W?.signal;if(!T&&!N)return G.execute();let q=L(G),H=z(G),x=Date.now(),h;try{if(F?.onQueryStart?.({sql:q,params:H,kind:J}),F?.startSpan)h=F.startSpan({sql:q,params:H,kind:J})}catch{}let c=!1,y=(p,o)=>{if(c)return;c=!0;let D0=Date.now()-x;try{if(p)F?.onQueryError?.({sql:q,params:H,error:p,durationMs:D0,kind:J});else if(F?.onQueryEnd?.({sql:q,params:H,durationMs:D0,rowCount:o,kind:J}),D&&D0>=K)if(F?.onSlowQuery)F.onSlowQuery({sql:q,params:H,durationMs:D0,kind:J});else console.warn(`[query-builder] slow query (${D0}ms >= ${K}ms): ${q}`)}catch{}try{h?.end(p)}catch{}},g=G.execute(),v=[g],n;if(W?.timeoutMs&&W.timeoutMs>0){let p=new Promise((o,D0)=>{n=setTimeout(()=>{try{G.cancel?.()}catch{}let M0=Error(`Query timed out after ${W.timeoutMs}ms`);M0.code="EBQBTIMEOUT",D0(M0)},W.timeoutMs)});v.push(p)}if(W?.signal){if(W.signal.aborted){try{G.cancel?.()}catch{}let o=Error("Query aborted");return o.code="EBQBABORT",y(o),Promise.reject(o)}let p=()=>{try{G.cancel?.()}catch{}};W.signal.addEventListener("abort",p,{once:!0}),g.finally(()=>{W.signal?.removeEventListener("abort",p)})}return Promise.race(v).then((p)=>{clearTimeout(n);let o=Array.isArray(p)?p.length:typeof p==="number"?p:void 0;return y(void 0,o),p}).catch((p)=>{throw clearTimeout(n),y(p),p})}function E(G,J){let W=J??L(G);return{sql:W,toString:()=>W,execute:()=>G.execute(),values:()=>G.values(),raw:()=>G.raw()}}function V(G,J){let W=$,F=J&&J.length>0?`SELECT ${J.join(", ")} FROM ${String(G)}`:`SELECT * FROM ${String(G)}`,K=null,D=()=>{if(K===null){let O=X8(F);K=B.length>0?$.unsafe(O,B):$.unsafe(O)}return K},w=(O,I)=>{let M=!s.WHERE.test(F)?"WHERE":O==="WHERE"?"AND":O;F=`${F} ${M} ${I}`},T=(O,I)=>{let R=I.__rawState?.();if(R){let M=B.length,C=f.dialect==="postgres"?R.sql.replace(/\$(\d+)/g,(P,S)=>`$${Number(S)+M}`):R.sql;F+=` ${O} ${C}`,B.push(...R.params)}else F+=` ${O} ${String(I.toSQL())}`;K=null},N=(O)=>{let I=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,R=0,M=-1,C;while(C=I.exec(F))if(C[0]==="(")R++;else if(C[0]===")")R=Math.max(0,R-1);else if(R===0){M=C.index;break}F=M>=0?`${F.slice(0,M)}${O} ${F.slice(M)}`:`${F} ${O}`,K=null},q=new Set,H,x,h=!1,c=!1,y=!1,g=new Map,v=new Set,n=60000,p=(O)=>{if(f.relations.singularizeStrategy==="none")return O;return O.endsWith("s")?O.slice(0,-1):O},o=(O)=>{if(!Z)return null;return PX(Z,String(G),O,{singularize:p,models:Z.models})},D0=(O)=>{if(!O||typeof O!=="object"||v.size===0)return O;let I;for(let R of Object.keys(O))if(R.startsWith("pivot_")){if(!I)I={};I[R.slice(6)]=O[R],delete O[R]}if(I)O.pivot=I;return O},M0=(O)=>{if(v.size===0||!O)return O;if(Array.isArray(O))for(let I=0;I<O.length;I++)D0(O[I]);else D0(O);return O},o0=(O)=>{if(!Z)return;if(q.has(O.pivotTable))return;let I=String(G),R=Z.primaryKeys[I]??"id";u(O.pivotTable,"wherePivot auto-join (pivot table)"),u(O.fkParent,"wherePivot auto-join (parent FK)"),u(I,"wherePivot auto-join (parent table)"),u(R,"wherePivot auto-join (parent PK)"),K=W`${D()} LEFT JOIN ${W(O.pivotTable)} ON ${W(`${O.pivotTable}.${O.fkParent}`)} = ${W(`${I}.${R}`)}`,F=`${F} LEFT JOIN ${O.pivotTable} ON ${O.pivotTable}.${O.fkParent} = ${I}.${R}`,q.add(O.pivotTable)},a=[],B=[],u9=(O)=>{if(s.SELECT_STAR.test(F))F=F.replace(s.SELECT_STAR,`SELECT *, ${O}`);else if(s.SELECT.test(F))F=F.replace(s.SELECT_FROM,`SELECT $1, ${O} FROM`);let I=String(D());if(s.SELECT_STAR.test(I)){let R=I.replace(s.SELECT_STAR,`SELECT *, ${O}`);K=$.unsafe(R)}else if(s.SELECT.test(I)){if(s.SELECT_FROM.exec(I)){let M=I.replace(s.SELECT_FROM,`SELECT $1, ${O} FROM`);K=$.unsafe(M)}}},e0=(O,I,R,M)=>{u9(`${O} ${h_(R,M)} AS ${I}`)},UX=(O,I,R,M)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)");let C=`${O.endsWith("s")?O.slice(0,-1):O}_id`;u(C,"relationship subquery (foreign key)");let P=`SELECT 1 FROM ${I} WHERE ${I}.${C} = ${O}.${R}`;if(M){let A=M({where:(d,k,b)=>{return u(d,"relationship subquery condition"),`${I}.${d} ${v0(k,"whereHas callback")} ${w9(b)}`}});if(A)P+=` AND ${A}`}return P},h$=(O,I,R,M)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)");let C=`${I.endsWith("s")?I.slice(0,-1):I}_id`;u(C,"relationship subquery (foreign key)");let P=`SELECT 1 FROM ${I} WHERE ${I}.${R} = ${O}.${C}`;if(M){let A=M({where:(d,k,b)=>{return u(d,"relationship subquery condition"),`${I}.${d} ${v0(k,"whereHas callback")} ${w9(b)}`}});if(A)P+=` AND ${A}`}return P},v$=(O,I,R,M,C,P)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)"),u(M,"relationship subquery (target primary key)");let S=P&&Z?PX(Z,O,P,{singularize:p,models:Z.models}):null,A=p(O),d=p(I),k=S?.pivotTable??[A,d].sort().join("_"),b=S?.fkParent??`${A}_id`,l=S?.fkRelated??`${d}_id`;u(k,"relationship subquery (pivot table)"),u(b,"relationship subquery (foreign key A)"),u(l,"relationship subquery (foreign key B)");let X0=`SELECT 1 FROM ${k} JOIN ${I} ON ${I}.${M} = ${k}.${l} WHERE ${k}.${b} = ${O}.${R}`;if(C){let r=C({where:(T0,X9,_9)=>{return u(T0,"relationship subquery condition"),`${I}.${T0} ${v0(X9,"whereHas callback")} ${w9(_9)}`}});if(r)X0+=` AND ${r}`}return X0},S7=(O,I,R)=>{u(O,"withCount (parent table)"),u(I,"withCount (target table)"),u(R,"withCount (primary key)");let M=`${O.endsWith("s")?O.slice(0,-1):O}_id`;return u(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${I} WHERE ${I}.${M} = ${O}.${R})`},A7=(O,I,R,M)=>{u(O,"withCount (parent table)"),u(I,"withCount (target table)"),u(R,"withCount (primary key)");let C=M&&Z?PX(Z,O,M,{singularize:p,models:Z.models}):null,P=p(O),S=p(I),A=C?.pivotTable??[P,S].sort().join("_"),d=C?.fkParent??`${P}_id`;return u(A,"withCount (pivot table)"),u(d,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${A} WHERE ${A}.${d} = ${O}.${R})`},b$=(O,I,R)=>{if(!Z)return;u(R,`with${O[0]}${O.slice(1).toLowerCase()} (column)`);let M=String(G),C=Z.relations?.[M];if(!C)return;let P=Object.entries(C).find(([r,T0])=>T0&&typeof T0==="object"&&(I in T0));if(!P)return;let[S,A]=P,d=A[I],k=typeof d==="string"?d:d?.model||d?.target||d,b=Z.modelToTable[k]||k,l=Z.primaryKeys[M]??"id";u(b,`with${O} (target table)`);let X0=`${O}(${b}.${R})`,w0;if(S==="hasMany"||S==="hasOne"){let r=`${M.endsWith("s")?M.slice(0,-1):M}_id`;u(r,`with${O} (foreign key)`),w0=`(SELECT ${X0} FROM ${b} WHERE ${b}.${r} = ${M}.${l})`}else if(S==="belongsToMany"){let r=Z?PX(Z,M,I,{singularize:p,models:Z.models}):null,T0=p(M),X9=p(b),_9=r?.pivotTable??[T0,X9].sort().join("_"),_X=r?.fkParent??`${T0}_id`,U0=r?.fkRelated??`${X9}_id`,pX=Z.primaryKeys[b]??"id";u(_9,`with${O} (pivot table)`),u(_X,`with${O} (foreign key)`),u(U0,`with${O} (related key)`),w0=`(SELECT ${X0} FROM ${_9} JOIN ${b} ON ${b}.${pX} = ${_9}.${U0} WHERE ${_9}.${_X} = ${M}.${l})`}else return;u9(`${w0} AS ${I}_${O.toLowerCase()}_${R}`)},I5=()=>{if(g.size===0)return;let O=[];for(let[I,R]of g.entries()){let M=o(I);if(!M)continue;for(let P of R)u(P,"withPivot");let C=R.map((P)=>`${M.pivotTable}.${P} AS pivot_${P}`);O.push(...C)}if(O.length>0){let I=O.join(", ");u9(I)}};return new Proxy({distinct(){return F=F.replace(/^SELECT\s+/i,"SELECT DISTINCT "),K=null,this},distinctOn(...O){let I=O.map(String).join(", ");return F=F.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${I}) `),K=null,this},selectRaw(O){let I=KX(O,"selectRaw(fragment)"),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${I}${F.substring(R)}`;else F+=`, ${I}`;return K=null,this},rowNumber(O="row_number",I,R){let M=[];if(I){let A=Array.isArray(I)?I:[I];M.push(`PARTITION BY ${A.join(", ")}`)}if(R&&R.length)M.push(`ORDER BY ${R.map(([A,d])=>`${A} ${d==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${O}`,S=F.indexOf(" FROM ");if(S!==-1)F=`${F.substring(0,S)}, ${P}${F.substring(S)}`;else F+=`, ${P}`;return K=null,this},denseRank(O="dense_rank",I,R){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(R&&R.length)C.push(`ORDER BY ${R.map(([d,k])=>`${d} ${k==="desc"?"DESC":"ASC"}`).join(", ")}`);let S=`DENSE_RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,A=F.indexOf(" FROM ");if(A!==-1)F=`${F.substring(0,A)}, ${S}${F.substring(A)}`;else F+=`, ${S}`;return K=null,this},rank(O="rank",I,R){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(R&&R.length)C.push(`ORDER BY ${R.map(([d,k])=>`${d} ${k==="desc"?"DESC":"ASC"}`).join(", ")}`);let S=`RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,A=F.indexOf(" FROM ");if(A!==-1)F=`${F.substring(0,A)}, ${S}${F.substring(A)}`;else F+=`, ${S}`;return K=null,this},over(O,I,R={}){return e0(O,I,R.partitionBy,R.orderBy),this},lag(O,I={}){let R=[O,String(I.offset??1)];if(I.defaultValue!==void 0)R.push(String(I.defaultValue));return e0(`LAG(${R.join(", ")})`,I.alias??`${O}_lag`,I.partitionBy,I.orderBy),this},lead(O,I={}){let R=[O,String(I.offset??1)];if(I.defaultValue!==void 0)R.push(String(I.defaultValue));return e0(`LEAD(${R.join(", ")})`,I.alias??`${O}_lead`,I.partitionBy,I.orderBy),this},sumOver(O,I={}){return e0(`SUM(${O})`,I.alias??`${O}_sum`,I.partitionBy,I.orderBy),this},avgOver(O,I={}){return e0(`AVG(${O})`,I.alias??`${O}_avg`,I.partitionBy,I.orderBy),this},countOver(O="*",I={}){return e0(`COUNT(${O})`,I.alias??"count_over",I.partitionBy,I.orderBy),this},minOver(O,I={}){return e0(`MIN(${O})`,I.alias??`${O}_min`,I.partitionBy,I.orderBy),this},maxOver(O,I={}){return e0(`MAX(${O})`,I.alias??`${O}_max`,I.partitionBy,I.orderBy),this},firstValue(O,I={}){return e0(`FIRST_VALUE(${O})`,I.alias??`${O}_first`,I.partitionBy,I.orderBy),this},lastValue(O,I={}){return e0(`LAST_VALUE(${O})`,I.alias??`${O}_last`,I.partitionBy,I.orderBy),this},selectAll(){return this},select(O){if(!O)return this;let I=Array.isArray(O)?O:[O];if(I.length===0)return this;let R=I.map(TY),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(F),C=M?M[1]:"",P=F.indexOf(" FROM ");if(P!==-1)F=`SELECT ${C}${R.join(", ")}${F.substring(P)}`;else F=`SELECT ${C}${R.join(", ")} FROM ${G}`;return K=null,this},addSelect(...O){if(!O.length)return this;let I=O.map(TY),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${I.join(", ")}${F.substring(R)}`;else F+=`, ${I.join(", ")}`;return K=null,this},with(...O){if(!Z||!O||O.length===0)return this;let I=[];for(let k of O){if(!k)continue;if(typeof k==="string")I.push({name:k});else if(typeof k==="object"&&!Array.isArray(k))for(let[b,l]of Object.entries(k))if(typeof l==="function")I.push({name:b,callback:l});else I.push({name:b})}if(I.length===0)return this;let R=f.relations.maxEagerLoad??50;if(I.length>R)throw Error(`[query-builder] Too many relationships to eager load (${I.length}). Maximum allowed: ${R}`);let M=String(G),C=new Set,P=new Set,S=new Map,A=(k)=>{let b=Z.relations?.[k];if(!b)return[];return[...Object.keys(b.hasOne||{}),...Object.keys(b.hasMany||{}),...Object.keys(b.belongsTo||{}),...Object.keys(b.belongsToMany||{}),...Object.keys(b.hasOneThrough||{}),...Object.keys(b.hasManyThrough||{}),...Object.keys(b.morphOne||{}),...Object.keys(b.morphMany||{}),...Object.keys(b.morphToMany||{}),...Object.keys(b.morphedByMany||{})]},d=(k,b,l=0,X0)=>{let w0=f.relations.maxDepth??10;if(l>=w0)throw Error(`[query-builder] Maximum relationship depth (${w0}) exceeded at '${b}'. Consider using separate queries or increasing maxDepth.`);let r=Z.relations?.[k];if(!r)return k;let T0=($0)=>{if(f.softDeletes?.enabled&&f.softDeletes?.defaultFilter){let Z0=f.softDeletes.column||"deleted_at";return` AND ${$0}.${Z0} IS NULL`}return""},X9=($0)=>{if(!X0)return"";let Z0=[],H0=(Q0,r0,I9)=>{u(String(Q0),"with() constraint column");let QX=v0(r0,"with() constraint operator");Z0.push(`${$0}.${String(Q0)} ${QX} ${w9(I9)}`)},W0=(Q0)=>()=>{throw Error(`[query-builder] with('${b}', ...): ${Q0} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},q0={where:(Q0,r0,I9)=>{if(Array.isArray(Q0))H0(Q0[0],Q0[1],Q0[2]);else if(Q0&&typeof Q0==="object")for(let QX of Object.keys(Q0))H0(QX,"=",Q0[QX]);else if(r0!==void 0&&I9!==void 0)H0(Q0,r0,I9);else if(r0!==void 0)H0(Q0,"=",r0);return q0},whereIn:(Q0,r0)=>{return u(String(Q0),"with() constraint column"),Z0.push(`${$0}.${String(Q0)} IN (${r0.map(w9).join(", ")})`),q0},whereNull:(Q0)=>{return u(String(Q0),"with() constraint column"),Z0.push(`${$0}.${String(Q0)} IS NULL`),q0},whereNotNull:(Q0)=>{return u(String(Q0),"with() constraint column"),Z0.push(`${$0}.${String(Q0)} IS NOT NULL`),q0},orderBy:W0("orderBy()"),limit:W0("limit()"),offset:W0("offset()"),take:W0("take()")};return X0(q0),Z0.length?` AND ${Z0.join(" AND ")}`:""},_9=()=>{let $0=(W0)=>{let q0=W0?.[b];return q0?Z.modelToTable[q0]:void 0},Z0=(W0)=>{let q0=W0?.[b],Q0=typeof q0==="string"?q0:q0?.model;return Q0?Z.modelToTable[Q0]:void 0},H0=(W0)=>{let q0=W0?.[b];return q0?.target?Z.modelToTable[q0.target]:void 0};return $0(r?.hasOne)||$0(r?.hasMany)||$0(r?.belongsTo)||Z0(r?.belongsToMany)||H0(r?.hasOneThrough)||H0(r?.hasManyThrough)||$0(r?.morphOne)||$0(r?.morphMany)||$0(r?.morphToMany)||$0(r?.morphedByMany)},_X=_9()??(Z.modelToTable[b]||Z.tableToModel[b]?Z.modelToTable[b]??b:b),U0=String(_X);if(!_X||!_9()&&!Z.modelToTable[b]&&!Z.tableToModel[b]){let $0=A(k);if($0.length>0&&!$0.includes(b)){let Z0=` Available relationships: ${$0.join(", ")}`;throw Error(`[query-builder] Relationship '${b}' not found on table '${k}'.${Z0}`)}}if(f.relations.detectCycles!==!1){let $0=`${k}->${U0}`;if(C.has($0))throw Error(`[query-builder] Circular relationship detected: ${$0}. This would cause an infinite loop.`);C.add($0)}if(!U0||U0===k)return k;let pX=r?.hasOneThrough?.[b]||r?.hasManyThrough?.[b];if(pX){let{through:$0,target:Z0}=pX,H0=Z.modelToTable[$0]||$0,W0=Z.modelToTable[Z0]||Z0,q0=Z.primaryKeys[k]??"id",Q0=Z.primaryKeys[H0]??"id",r0=`${p(k)}_id`,I9=`${p(H0)}_id`;return N(`LEFT JOIN ${H0} ON ${H0}.${r0} = ${k}.${q0} LEFT JOIN ${W0} ON ${W0}.${I9} = ${H0}.${Q0}`),q.add(H0),q.add(W0),W0}if(Boolean(r?.belongsToMany?.[b])){let $0=PX(Z,k,b,{singularize:p,models:Z.models}),Z0=$0?.pivotTable??[p(k),p(U0)].sort().join("_"),H0=Z.primaryKeys[k]??"id",W0=Z.primaryKeys[U0]??"id",q0=$0?.fkParent??`${p(k)}_id`,Q0=$0?.fkRelated??`${p(U0)}_id`;return N(`LEFT JOIN ${Z0} ON ${Z0}.${q0} = ${k}.${H0} LEFT JOIN ${U0} ON ${U0}.${W0} = ${Z0}.${Q0}${X9(U0)}`),q.add(Z0),q.add(U0),U0}if(Boolean(r?.morphToMany?.[b])){let $0=b,Z0=`${p(U0)}_${$0}`,H0=Z.primaryKeys[k]??"id",W0=Z.primaryKeys[U0]??"id",q0=`${$0}_type`,Q0=`${$0}_id`,r0=`${p(U0)}_id`,I9=w9(Z.tableToModel[k]||k);return N(`LEFT JOIN ${Z0} ON ${Z0}.${Q0} = ${k}.${H0} AND ${Z0}.${q0} = ${I9} LEFT JOIN ${U0} ON ${U0}.${W0} = ${Z0}.${r0}`),q.add(Z0),q.add(U0),U0}if(Boolean(r?.morphedByMany?.[b])){let $0=r.morphedByMany?.[b]||b,Z0=Z.modelToTable[$0]||$0,H0=p(k),W0=`${p(Z0)}_${H0}`,q0=Z.primaryKeys[k]??"id",Q0=Z.primaryKeys[Z0]??"id",r0=`${H0}_type`,I9=`${H0}_id`,QX=`${p(Z0)}_id`,v7=w9(Z.tableToModel[Z0]||Z0);return N(`LEFT JOIN ${W0} ON ${W0}.${QX} = ${k}.${q0} LEFT JOIN ${Z0} ON ${Z0}.${Q0} = ${W0}.${I9} AND ${W0}.${r0} = ${v7}`),q.add(W0),q.add(Z0),Z0}if(Boolean(r?.belongsTo?.[b])){let $0=`${p(U0)}_id`,Z0=Z.primaryKeys[U0]??"id";return N(`LEFT JOIN ${U0} ON ${k}.${$0} = ${U0}.${Z0}${X9(U0)}`),q.add(U0),U0}let k7=Boolean(r?.morphOne?.[b]),x7=Boolean(r?.morphMany?.[b]);if(k7||x7){let $0=`${b}_type`,Z0=`${b}_id`,H0=Z.primaryKeys[k]??"id",W0=w9(Z.tableToModel[k]||k);return N(`LEFT JOIN ${U0} ON ${U0}.${Z0} = ${k}.${H0} AND ${U0}.${$0} = ${W0}`),q.add(U0),U0}let B7=`${p(k)}_id`,y7=Z.primaryKeys[k]??"id",h7=`${T0(U0)}${X9(U0)}`;return N(`LEFT JOIN ${U0} ON ${U0}.${B7} = ${k}.${y7}${h7}`),q.add(U0),U0};for(let k of I){let b=k.name.trim();if(k.callback)S.set(b,k.callback);let l=b.split("."),X0=M,w0=0;for(let r of l){if(!r||r.trim().length===0)continue;let T0=r.trim(),X9=S.get(T0);X0=d(X0,T0,w0,X9)||X0,w0++}P.add(b)}if(g.size>0){let k=[];for(let[b,l]of g.entries()){let X0=o(b);if(!X0)continue;let w0=l.map((r)=>`${X0.pivotTable}.${r} AS pivot_${r}`);k.push(...w0)}if(k.length>0){let b=k.join(", ");u9(b)}}return K=null,this},whereHas(O,I){if(!Z)return this;let R=String(G),M=Z.relations?.[R];if(!M)throw Error(`[query-builder] No relationships defined for table '${R}'`);let C=Object.entries(M).find(([l,X0])=>X0&&typeof X0==="object"&&(O in X0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${R}'`);let[P,S]=C,A=S[O],d=typeof A==="string"?A:A?.model||A?.target||A,k=Z.modelToTable[d]||d,b;if(P==="hasMany"||P==="hasOne"){let l=Z.primaryKeys[R]??"id";b=UX(R,k,l,I)}else if(P==="belongsTo"){let l=Z.primaryKeys[k]??"id";b=h$(R,k,l,I)}else if(P==="belongsToMany"){let l=Z.primaryKeys[R]??"id",X0=Z.primaryKeys[k]??"id";b=v$(R,k,l,X0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${P}' for whereHas`);K=W`${D()} WHERE EXISTS (${W([b])})`;try{w("WHERE",`EXISTS (${b})`)}catch{}return this},whereDoesntHave(O,I){if(!Z)return this;let R=String(G),M=Z.relations?.[R];if(!M)throw Error(`[query-builder] No relationships defined for table '${R}'`);let C=Object.entries(M).find(([l,X0])=>X0&&typeof X0==="object"&&(O in X0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${R}'`);let[P,S]=C,A=S[O],d=typeof A==="string"?A:A?.model||A?.target||A,k=Z.modelToTable[d]||d,b;if(P==="hasMany"||P==="hasOne"){let l=Z.primaryKeys[R]??"id";b=UX(R,k,l,I)}else if(P==="belongsTo"){let l=Z.primaryKeys[k]??"id";b=h$(R,k,l,I)}else if(P==="belongsToMany"){let l=Z.primaryKeys[R]??"id",X0=Z.primaryKeys[k]??"id";b=v$(R,k,l,X0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${P}' for whereDoesntHave`);K=W`${D()} WHERE NOT EXISTS (${W([b])})`;try{w("WHERE",`NOT EXISTS (${b})`)}catch{}return this},has(O){if(!Z)return this;let I=String(G),R=Z.relations?.[I];if(!R)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(R).find(([b,l])=>l&&typeof l==="object"&&(O in l));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,P]=M,S=P[O],A=typeof S==="string"?S:S?.model||S?.target||S,d=Z.modelToTable[A]||A,k;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";k=UX(I,d,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[d]??"id";k=h$(I,d,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",l=Z.primaryKeys[d]??"id";k=v$(I,d,b,l,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for has`);K=W`${D()} WHERE EXISTS (${W([k])})`;try{w("WHERE",`EXISTS (${k})`)}catch{}return this},doesntHave(O){if(!Z)return this;let I=String(G),R=Z.relations?.[I];if(!R)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(R).find(([b,l])=>l&&typeof l==="object"&&(O in l));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,P]=M,S=P[O],A=typeof S==="string"?S:S?.model||S?.target||S,d=Z.modelToTable[A]||A,k;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";k=UX(I,d,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[d]??"id";k=h$(I,d,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",l=Z.primaryKeys[d]??"id";k=v$(I,d,b,l,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for doesntHave`);K=W`${D()} WHERE NOT EXISTS (${W([k])})`;try{w("WHERE",`NOT EXISTS (${k})`)}catch{}return this},withCount(...O){if(!Z||!O||O.length===0)return this;let I=String(G);for(let R of O){let M=Z.relations?.[I];if(!M)continue;let C=Object.entries(M).find(([w0,r])=>r&&typeof r==="object"&&(R in r));if(!C)continue;let[P,S]=C,A=S[R],d=typeof A==="string"?A:A?.model||A?.target||A,k=Z.modelToTable[d]||d,b=Z.primaryKeys[I]??"id",l;if(P==="hasMany"||P==="hasOne")l=S7(I,k,b);else if(P==="belongsToMany")l=A7(I,k,b,R);else continue;let X0=`${R}_count`;u9(`${l} AS ${X0}`)}return this},withSum(O,I){return b$("SUM",O,I),this},withAvg(O,I){return b$("AVG",O,I),this},withMax(O,I){return b$("MAX",O,I),this},withMin(O,I){return b$("MIN",O,I),this},applyPivotColumns(){return I5(),this},withPivot(O,...I){if(!Z)return this;let R=String(G),M=o(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${R}'`);let C=I&&I.length>0?I:M.hasConfig?M.pivotColumns:[];if(C.length===0)return this;if(g.set(O,C),M.hasConfig)v.add(O);return I5(),this},wherePivot(O,I,R,M){if(!Z)return this;let C=o(O);if(!C)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(C.pivotTable,"wherePivot (pivot table)"),u(I,"wherePivot (column)"),o0(C);let P=M===void 0?"=":String(R),S=M===void 0?R:M,A=B.length+1,d=`${C.pivotTable}.${I} ${P} ${i(A)}`;a.push(d),B.push(S);let k=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${k} ${d}`,K=null,C.hasConfig)v.add(O);return this},wherePivotIn(O,I,R){if(!Z||!Array.isArray(R)||R.length===0)return this;let M=o(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(M.pivotTable,"wherePivotIn (pivot table)"),u(I,"wherePivotIn (column)"),o0(M);let C=h0(R.length,B.length+1),P=`${M.pivotTable}.${I} IN (${C})`;a.push(P),B.push(...R);let S=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${S} ${P}`,K=null,M.hasConfig)v.add(O);return this},wherePivotNotIn(O,I,R){if(!Z||!Array.isArray(R)||R.length===0)return this;let M=o(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(M.pivotTable,"wherePivotNotIn (pivot table)"),u(I,"wherePivotNotIn (column)"),o0(M);let C=h0(R.length,B.length+1),P=`${M.pivotTable}.${I} NOT IN (${C})`;a.push(P),B.push(...R);let S=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${S} ${P}`,K=null,M.hasConfig)v.add(O);return this},wherePivotNull(O,I){if(!Z)return this;let R=o(O);if(!R)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(R.pivotTable,"wherePivotNull (pivot table)"),u(I,"wherePivotNull (column)"),o0(R);let M=`${R.pivotTable}.${I} IS NULL`;a.push(M);let C=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,K=null,R.hasConfig)v.add(O);return this},wherePivotNotNull(O,I){if(!Z)return this;let R=o(O);if(!R)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(R.pivotTable,"wherePivotNotNull (pivot table)"),u(I,"wherePivotNotNull (column)"),o0(R);let M=`${R.pivotTable}.${I} IS NOT NULL`;a.push(M);let C=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,K=null,R.hasConfig)v.add(O);return this},where(O,I,R){let M=()=>s.WHERE.test(F)?"AND":"WHERE";if(typeof O==="string"&&I!==void 0){u(String(O),"where(column)"),v0(I,"where(operator)");let C=String(I).toLowerCase();if(C==="in"||C==="not in"){let S=Array.isArray(R)?R:[R],A=h0(S.length,B.length+1),d=`${String(O)} ${C.toUpperCase()} (${A})`;return a.push(d),B.push(...S),F=`${F} ${M()} ${d}`,K=null,this}let P=B.length+1;return a.push(`${String(O)} ${String(I)} ${i(P)}`),B.push(R),F=`${F} ${M()} ${String(O)} ${String(I)} ${i(P)}`,K=null,this}if(Array.isArray(O)){let[C,P,S]=O,A=String(C);u(A,"where(column)");let d=v0(P,"where(operator)");if(d==="in"||d==="not in"){let k=Array.isArray(S)?S:[S],b=h0(k.length,B.length+1);a.push(`${A} ${d.toUpperCase()} (${b})`),B.push(...k),F=`${F} ${M()} ${A} ${d.toUpperCase()} (${b})`,K=null}else{let k=B.length+1;a.push(`${A} ${d} ${i(k)}`),B.push(S),F=`${F} ${M()} ${A} ${d} ${i(k)}`,K=null}return this}if(O&&typeof O==="object"&&!d8(O)){let C=O,P=Object.keys(C),S=[];for(let A of P){u(A,"where(column)");let d=C[A];if(Array.isArray(d)){let k=h0(d.length,B.length+1);S.push(`${A} IN (${k})`),a.push(`${A} IN (${k})`),B.push(...d)}else{let k=B.length+1;S.push(`${A} = ${i(k)}`),a.push(`${A} = ${i(k)}`),B.push(d)}}if(S.length>0)F=`${F} ${M()} ${S.join(" AND ")}`,K=null;return this}if(d8(O))return a.push(O.raw),F=`${F} ${M()} ${O.raw}`,K=null,this;return this},whereNull(O){u(String(O),"whereNull(column)");let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NULL`,K=null,this},whereNotNull(O){u(String(O),"whereNotNull(column)");let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NOT NULL`,K=null,this},whereBetween(O,I,R){u(String(O),"whereBetween(column)");let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1;return F=`${F} ${M} ${String(O)} BETWEEN ${i(C)} AND ${i(C+1)}`,B.push(I,R),K=null,this},whereExists(O){let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} EXISTS (${O.toSQL()})`,K=null,this},whereJsonContains(O,I){u(String(O),"whereJsonContains(column)");let R=s.WHERE.test(F)?"AND":"WHERE",M=f.dialect,C=B.length+1;if(M==="postgres"){if(f.sql?.jsonContainsMode==="function")F+=` ${R} jsonb_contains(${O}, ${i(C)})`;else F+=` ${R} ${O} @> ${i(C)}`;B.push(JSON.stringify(I))}else if(J0(M))F+=` ${R} JSON_CONTAINS(${O}, ${i(C)})`,B.push(JSON.stringify(I));else if(Array.isArray(I)){let P=I.map((S,A)=>`EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${i(C+A)})`);F+=` ${R} (${P.join(" AND ")})`;for(let S of I)B.push(S)}else if(I!==null&&typeof I==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else F+=` ${R} EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${i(C)})`,B.push(I);return K=null,this},whereJsonPath(O,I,R){if(v0(I,"whereJsonPath(op)"),typeof O!=="string"||O.length===0||O.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof O==="string"?`'${O.slice(0,32)}...'`:typeof O}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(O))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${O}' \u2014 contains characters outside the allowed JSON-path set`);let M=f.dialect,C=s.WHERE.test(F)?"AND":"WHERE",P=B.length+1;if(M==="postgres")F+=` ${C} ${O} ${I} ${i(P)}`;else if(J0(M))F+=` ${C} JSON_EXTRACT(${O}) ${I} ${i(P)}`;else F+=` ${C} json_extract(${O}) ${I} ${i(P)}`;return B.push(R),K=null,this},whereLike(O,I,R=!1){let M=i(B.length+1);return w("WHERE",`${R?String(O):`LOWER(${String(O)})`} LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},whereILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("WHERE",`${String(O)} ILIKE ${R}`);else w("WHERE",`LOWER(${String(O)}) LIKE LOWER(${R})`);return B.push(I),K=null,this},orWhereLike(O,I,R=!1){let M=i(B.length+1);return w("OR",`${R?String(O):`LOWER(${String(O)})`} LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},orWhereILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("OR",`${String(O)} ILIKE ${R}`);else w("OR",`LOWER(${String(O)}) LIKE LOWER(${R})`);return B.push(I),K=null,this},whereNotLike(O,I,R=!1){let M=i(B.length+1);return w("WHERE",`${R?String(O):`LOWER(${String(O)})`} NOT LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},whereNotILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("WHERE",`${String(O)} NOT ILIKE ${R}`);else w("WHERE",`LOWER(${String(O)}) NOT LIKE LOWER(${R})`);return B.push(I),K=null,this},orWhereNotLike(O,I,R=!1){let M=i(B.length+1);return w("OR",`${R?String(O):`LOWER(${String(O)})`} NOT LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},orWhereNotILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("OR",`${String(O)} NOT ILIKE ${R}`);else w("OR",`LOWER(${String(O)}) NOT LIKE LOWER(${R})`);return B.push(I),K=null,this},whereAny(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1,P=O.map((S,A)=>`${S} ${I} ${i(C+A)}`);F+=` ${M} (${P.join(" OR ")})`;for(let S=0;S<O.length;S++)B.push(R);return K=null,this},whereAll(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1,P=O.map((S,A)=>`${S} ${I} ${i(C+A)}`);F+=` ${M} (${P.join(" AND ")})`;for(let S=0;S<O.length;S++)B.push(R);return K=null,this},whereNone(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1,P=O.map((S,A)=>`${S} ${I} ${i(C+A)}`);F+=` ${M} NOT (${P.join(" OR ")})`;for(let S=0;S<O.length;S++)B.push(R);return K=null,this},whereNotBetween(O,I,R){u(String(O),"whereNotBetween(column)");let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1;return F+=` ${M} ${O} NOT BETWEEN ${i(C)} AND ${i(C+1)}`,B.push(I,R),K=null,this},whereDate(O,I,R){u(O,"whereDate(column)");let M=R instanceof Date?R.toISOString():typeof R==="string"?R:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof R}`)})(),C=s.WHERE.test(F)?"AND":"WHERE",P=B.length+1;return F+=` ${C} ${O} ${I} ${i(P)}`,B.push(M),K=null,this},whereRaw(O){let I=KX(O,"whereRaw(fragment)"),R=s.WHERE.test(F)?"AND":"WHERE";return F+=` ${R} ${I}`,K=null,this},whereColumn(O,I,R){u(O,"whereColumn(left)"),u(R,"whereColumn(right)");let M=s.WHERE.test(F)?"AND":"WHERE";return F+=` ${M} ${O} ${I} ${R}`,K=null,this},orWhereColumn(O,I,R){return u(O,"orWhereColumn(left)"),u(R,"orWhereColumn(right)"),F+=` OR ${O} ${I} ${R}`,K=null,this},whereIn(O,I){u(String(O),"whereIn(column)");let R=s.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=h0(I.length,B.length+1);F+=` ${R} ${O} IN (${M})`,B.push(...I)}else F+=` ${R} ${O} IN (${String(I.toSQL())})`;return K=null,this},orWhereIn(O,I){if(u(String(O),"orWhereIn(column)"),Array.isArray(I)){let R=h0(I.length,B.length+1);F+=` OR ${O} IN (${R})`,B.push(...I)}else F+=` OR ${O} IN (${String(I.toSQL())})`;return K=null,this},whereNotIn(O,I){u(String(O),"whereNotIn(column)");let R=s.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=h0(I.length,B.length+1);F+=` ${R} ${O} NOT IN (${M})`,B.push(...I)}else F+=` ${R} ${O} NOT IN (${String(I.toSQL())})`;return K=null,this},orWhereNotIn(O,I){if(u(String(O),"orWhereNotIn(column)"),Array.isArray(I)){let R=h0(I.length,B.length+1);F+=` OR ${O} NOT IN (${R})`,B.push(...I)}else F+=` OR ${O} NOT IN (${String(I.toSQL())})`;return K=null,this},whereNested(O){let I=s.WHERE.test(F)?"AND":"WHERE",R=O.toSQL?String(O.toSQL()):String(O);return F+=` ${I} (${R})`,K=null,this},orWhereNested(O){let I=O.toSQL?String(O.toSQL()):String(O);return F+=` OR (${I})`,K=null,this},andWhere(O,I,R){if(typeof O==="string"&&I!==void 0){u(String(O),"andWhere(column)"),v0(I,"andWhere(operator)");let M=B.length+1;return a.push(`${String(O)} ${String(I)} ${i(M)}`),B.push(R),F=`${F} AND ${String(O)} ${String(I)} ${i(M)}`,K=null,this}if(Array.isArray(O)){let[M,C,P]=O,S=String(M);u(S,"andWhere(column)");let A=v0(C,"andWhere(operator)");if(A==="in"||A==="not in"){let d=Array.isArray(P)?P:[P],k=h0(d.length,B.length+1);a.push(`${S} ${A.toUpperCase()} (${k})`),B.push(...d),F=`${F} AND ${S} ${A.toUpperCase()} (${k})`,K=null}else{let d=B.length+1;a.push(`${S} ${A} ${i(d)}`),B.push(P),F=`${F} AND ${S} ${A} ${i(d)}`,K=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let P of M){let S=O[P];if(Array.isArray(S)){let A=h0(S.length,B.length+1);C.push(`${P} IN (${A})`),a.push(`${P} IN (${A})`),B.push(...S)}else{let A=B.length+1;C.push(`${P} = ${i(A)}`),a.push(`${P} = ${i(A)}`),B.push(S)}}if(C.length>0)F=`${F} AND ${C.join(" AND ")}`,K=null;return this}if(O&&typeof O.raw<"u")return a.push(O.raw),F=`${F} AND ${O.raw}`,K=null,this;return this},orWhere(O,I,R){if(typeof O==="string"&&I!==void 0){u(String(O),"orWhere(column)"),v0(I,"orWhere(operator)");let M=B.length+1;return a.push(`OR ${String(O)} ${String(I)} ${i(M)}`),B.push(R),F=`${F} OR ${String(O)} ${String(I)} ${i(M)}`,K=null,this}if(Array.isArray(O)){let[M,C,P]=O,S=String(M);u(S,"orWhere(column)");let A=v0(C,"orWhere(operator)");if(A==="in"||A==="not in"){let d=Array.isArray(P)?P:[P],k=h0(d.length,B.length+1);a.push(`OR ${S} ${A.toUpperCase()} (${k})`),B.push(...d),F=`${F} OR ${S} ${A.toUpperCase()} (${k})`,K=null}else{let d=B.length+1;a.push(`OR ${S} ${A} ${i(d)}`),B.push(P),F=`${F} OR ${S} ${A} ${i(d)}`,K=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let P of M){let S=O[P];if(Array.isArray(S)){let A=h0(S.length,B.length+1);C.push(`${P} IN (${A})`),a.push(`OR ${P} IN (${A})`),B.push(...S)}else{let A=B.length+1;C.push(`${P} = ${i(A)}`),a.push(`OR ${P} = ${i(A)}`),B.push(S)}}if(C.length>0)F=`${F} OR ${C.join(" AND ")}`,K=null;return this}if(O&&typeof O.raw<"u")return a.push(`OR ${O.raw}`),F=`${F} OR ${O.raw}`,K=null,this;return this},orderBy(O,I="asc"){let R=I==="asc"?"ASC":"DESC";return F=s.ORDER_BY.test(F)?`${F}, ${O} ${R}`:`${F} ORDER BY ${O} ${R}`,K=null,this},orderByDesc(O){return F=s.ORDER_BY.test(F)?`${F}, ${O} DESC`:`${F} ORDER BY ${O} DESC`,K=null,this},inRandomOrder(){let O=f.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return F=s.ORDER_BY.test(F)?`${F}, ${O}`:`${F} ORDER BY ${O}`,K=null,this},reorder(O,I="asc"){return F=F.replace(/ORDER BY[\s\S]*$/i,""),F+=` ORDER BY ${O} ${I==="asc"?"ASC":"DESC"}`,K=null,this},latest(O){let I=O??f.timestamps.defaultOrderColumn;return F=s.ORDER_BY.test(F)?`${F}, ${I} DESC`:`${F} ORDER BY ${I} DESC`,K=null,this},oldest(O){let I=O??f.timestamps.defaultOrderColumn;return F=s.ORDER_BY.test(F)?`${F}, ${I} ASC`:`${F} ORDER BY ${I} ASC`,K=null,this},limit(O){if(!Number.isFinite(O)||O<0||!Number.isInteger(O))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${O}`);return F=s.LIMIT.test(F)?F.replace(s.LIMIT,` LIMIT ${O}`):`${F} LIMIT ${O}`,K=null,this},offset(O){if(!Number.isFinite(O)||O<0||!Number.isInteger(O))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${O}`);return F=s.OFFSET.test(F)?F.replace(s.OFFSET,` OFFSET ${O}`):`${F} OFFSET ${O}`,K=null,this},join(O,I,R,M){return u(O,"join(table)"),Q9(I,"join(onLeft)"),Q9(M,"join(onRight)"),v0(R,"join(operator)"),N(`JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},joinSub(O,I,R,M,C){return u(I,"joinSub(alias)"),Q9(R,"joinSub(onLeft)"),Q9(C,"joinSub(onRight)"),v0(M,"joinSub(operator)"),N(`JOIN (${String(O.toSQL())}) AS ${I} ON ${R} ${M} ${C}`),q.add(I),this},innerJoin(O,I,R,M){return u(O,"innerJoin(table)"),Q9(I,"innerJoin(onLeft)"),Q9(M,"innerJoin(onRight)"),v0(R,"innerJoin(operator)"),N(`INNER JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},leftJoin(O,I,R,M){return u(O,"leftJoin(table)"),Q9(I,"leftJoin(onLeft)"),Q9(M,"leftJoin(onRight)"),v0(R,"leftJoin(operator)"),N(`LEFT JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},leftJoinSub(O,I,R,M,C){return u(I,"leftJoinSub(alias)"),Q9(R,"leftJoinSub(onLeft)"),Q9(C,"leftJoinSub(onRight)"),v0(M,"leftJoinSub(operator)"),N(`LEFT JOIN (${String(O.toSQL())}) AS ${I} ON ${R} ${M} ${C}`),q.add(I),this},rightJoin(O,I,R,M){return u(O,"rightJoin(table)"),Q9(I,"rightJoin(onLeft)"),Q9(M,"rightJoin(onRight)"),v0(R,"rightJoin(operator)"),N(`RIGHT JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},crossJoin(O){return u(O,"crossJoin(table)"),N(`CROSS JOIN ${O}`),q.add(O),this},crossJoinSub(O,I){return u(I,"crossJoinSub(alias)"),N(`CROSS JOIN (${String(O.toSQL())}) AS ${I}`),q.add(I),this},selectAllRelations(){if(!Y)return this;let O=String(G),I=Object.keys(Y[O]?.columns??{}),R=[];if(I.length>0)R.push(W`${W(O)}.*`);for(let M of q){let C=Object.keys(Y[M]?.columns??{});for(let P of C){let S=f.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${P}`.replace(/_([a-z])/g,(A,d)=>d.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${P}`:`${M}_${P}`;R.push(W`${W(`${M}.${P}`)} AS ${W(S)}`)}}if(R.length>0){let M=I.length>0?`${O}.*`:"",C=[];for(let A of q){let d=Object.keys(Y[A]?.columns??{});for(let k of d){let b=f.aliasing.relationColumnAliasFormat==="camelCase"?`${A}_${k}`.replace(/_([a-z])/g,(l,X0)=>X0.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${A}.${k}`:`${A}_${k}`;C.push(`${A}.${k} AS ${b}`)}}let P=[M,...C].filter(Boolean).join(", "),S=F.indexOf(" FROM ");if(S!==-1)F=`SELECT ${P}${F.substring(S)}`;else F=`SELECT ${P} FROM ${O}`;K=null}return this},groupBy(...O){if(O.length)F=s.GROUP_BY.test(F)?`${F}, ${O.join(", ")}`:`${F} GROUP BY ${O.join(", ")}`,K=null;return this},groupByRaw(O){let I=KX(O,"groupByRaw(fragment)");return F=s.GROUP_BY.test(F)?`${F}, ${I}`:`${F} GROUP BY ${I}`,K=null,this},having(O){let I=/\bHAVING\b/i.test(F)?"AND":"HAVING";if(Array.isArray(O)){let R=B.length+1;F=`${F} ${I} ${O[0]} ${O[1]} ${i(R)}`,B.push(O[2]),K=null}else if(O&&typeof O==="object"&&!("raw"in O)){let R=Object.keys(O),M=R.length;if(M){let C=B.length,P=Array.from({length:M});for(let S=0;S<M;S++){let A=R[S];P[S]=`${A} = ${i(C+S+1)}`,B.push(O[A])}F=`${F} ${I} ${P.join(" AND ")}`,K=null}}else if(O&&typeof O.raw<"u")F+=` ${I} ${O.raw}`,K=null;return this},havingRaw(O){let I=KX(O,"havingRaw(fragment)"),R=/\bHAVING\b/i.test(F)?"AND":"HAVING";return F+=` ${R} ${I}`,K=null,this},orderByRaw(O){let I=KX(O,"orderByRaw(fragment)");return F=s.ORDER_BY.test(F)?`${F}, ${I}`:`${F} ORDER BY ${I}`,K=null,this},union(O){return T("UNION",O),this},unionAll(O){return T("UNION ALL",O),this},intersect(O){return T("INTERSECT",O),this},intersectAll(O){return T("INTERSECT ALL",O),this},except(O){return T("EXCEPT",O),this},exceptAll(O){return T("EXCEPT ALL",O),this},forPage(O,I){let R=Math.max(1,Math.floor(O)),M=Math.max(1,Math.floor(I));return F+=` LIMIT ${M} OFFSET ${(R-1)*M}`,K=null,this},toSQL(){let O=X8(F);return{sql:O,toString:()=>O,execute:()=>D().execute(),values:()=>D().values(),raw:()=>D().raw()}},async value(O){let I=W`${D()} LIMIT 1`,R=await j(I,"select",{signal:x,timeoutMs:H}),[M]=R;return M?.[O]},async pluck(O,I){let R=await j(D(),"select",{signal:x,timeoutMs:H});if(I){let M={};for(let C of R){let P=String(C?.[I]);if(Object.prototype.hasOwnProperty.call(M,P))throw Error(`[query-builder] pluck(${O}, ${I}): duplicate key '${P}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);M[P]=C?.[O]}return M}return R.map((M)=>M?.[O])},async exists(){let O=W`SELECT EXISTS (${D()}) as e`,I=await j(O,"select",{signal:x,timeoutMs:H}),[R]=I;return Boolean(R?.e)},async doesntExist(){return!await this.exists()},async paginate(O,I=1,R={}){if(!Number.isFinite(O)||O<=0||!Number.isInteger(O))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${O}`);if(!Number.isFinite(I)||I<1||!Number.isInteger(I))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${I}`);if(R.tx){let l=X8(F),X0=[...B],w0=await R.tx.unsafe(`SELECT COUNT(*) as c FROM (${l}) as sub`,X0),r=Number(w0?.[0]?.c??0),T0=Math.max(1,Math.ceil(r/O)),X9=Math.max(1,Math.min(I,T0)),_9=(X9-1)*O;return{data:await R.tx.unsafe(`${l} LIMIT ${O} OFFSET ${_9}`,X0),meta:{perPage:O,page:X9,total:r,lastPage:T0}}}let M=W`SELECT COUNT(*) as c FROM (${D()}) as sub`,C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C,S=Number(P?.c??0),A=Math.max(1,Math.ceil(S/O)),d=Math.max(1,Math.min(I,A)),k=(d-1)*O;return{data:await j(W`${D()} LIMIT ${O} OFFSET ${k}`,"select",{signal:x,timeoutMs:H}),meta:{perPage:O,page:d,total:S,lastPage:A}}},async simplePaginate(O,I=1){let R=Math.max(1,I),M=(R-1)*O,C=await j(W`${D()} LIMIT ${O+1} OFFSET ${M}`,"select",{signal:x,timeoutMs:H}),P=C.length>O;return{data:P?C.slice(0,O):C,meta:{perPage:O,page:R,hasMore:P}}},async cursorPaginate(O,I,R="id",M="asc"){let C=D();if(I!==void 0&&I!==null)if(Array.isArray(R)){let l=R.map((T0)=>W(String(T0))),X0=M==="asc"?W`>`:W`<`,w0=W`(${W(l)})`,r=W`(${W(I)})`;C=W`${C} WHERE ${w0} ${X0} ${r}`}else C=M==="asc"?W`${C} WHERE ${W(String(R))} > ${I}`:W`${C} WHERE ${W(String(R))} < ${I}`;if(Array.isArray(R)){let X0=R.map((w0)=>W`${W(String(w0))} ${M==="asc"?W`ASC`:W`DESC`}`).reduce((w0,r,T0)=>T0===0?r:W`${w0}, ${r}`);C=W`${C} ORDER BY ${X0} LIMIT ${O+1}`}else C=W`${C} ORDER BY ${W(String(R))} ${M==="asc"?W`ASC`:W`DESC`} LIMIT ${O+1}`;let P=await j(C,"select",{signal:x,timeoutMs:H}),S=P.length>O,A=P.slice(0,O),d=A[A.length-1],k=S&&d?Array.isArray(R)?R.map((l)=>d[l]):d[R]:null,b=A.length?Array.isArray(R)?R.map((l)=>A[0]?.[l]):A[0]?.[R]:null;return{data:A,meta:{perPage:O,nextCursor:k??null,prevCursor:b}}},async chunk(O,I){let R=1;while(!0){let{data:M,meta:C}=await this.paginate(O,R);if(M.length===0)break;if(await I(M),R>=C.lastPage)break;R+=1}},async chunkById(O,I="id",R){let M;while(!0){let{data:C,meta:P}=await this.cursorPaginate(O,M,I,"asc");if(C.length===0)break;if(R)await R(C);if(M=P.nextCursor,!M)break}},async eachById(O,I="id",R){await this.chunkById(O,I,async(M)=>{for(let C of M)await R?.(C)})},withTimeout(O){return H=Math.max(1,Math.floor(O)),this},abort(O){return x=O,this},withTrashed(){return h=!0,c=!1,this},onlyTrashed(){h=!0,c=!0;let O=f.softDeletes?.column||"deleted_at",I=(C,P)=>{let S=C.toUpperCase(),A=0;for(let d=0;d<C.length;d++){let k=C[d];if(k==="(")A++;else if(k===")")A--;else if(A===0&&S.substring(d,d+5)==="WHERE"&&(d===0||/\s/.test(C[d-1]??""))&&/\s/.test(C[d+5]??""))return`${C.substring(0,d)}WHERE ${P} AND ${C.substring(d+6)}`}return`${C} WHERE ${P}`},R=`${G}.${O} IS NOT NULL`;F=I(F,R);let M=String(D());return K=W([I(M,R)]),this},scope(O,I){let R=String(G),C=Z?.scopes?.[R]?.[O];if(C)return C(this,I);return this},when(O,I,R){if(O)return I(this);if(R)return R(this);return this},tap(O){return O(this),this},dump(){return console.log(String(D())),this},dd(){throw console.log(String(D())),Error("Dump and Die")},cache(O=60000){return n=O,y=!0,this},async explain(){let O=W`EXPLAIN ${D()}`;return await j(O,"select",{signal:x,timeoutMs:H})},simple(){return D().simple()},toText(){return F},async get(){let O=f.hooks,I=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan||uX(O));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!I){let P=$._prepareStatement;if(P){let S=P(F);return M0(B.length>0?S.all(...B):S.all())}}if(K=B.length>0?$.unsafe(F,B):$.unsafe(F),!f.softDeletes?.enabled&&!y&&!H&&!x&&!I){let P=D()._stmt,S=D()._params;if(P)return M0(S&&S.length>0?P.all(...S):P.all());return M0(await D().execute())}if(!f.softDeletes?.enabled&&!y&&!H&&!x)return M0(await j(D(),"select"));let R=D();if(f.softDeletes?.enabled&&f.softDeletes.defaultFilter&&!h){let P=f.softDeletes.column,S=String(G);if((Y?Boolean(Y[S]?.columns?.[P]):!0)&&!s.DELETED_AT.test(F))R=W`${D()} WHERE ${W(String(P))} IS ${c?W`NOT NULL`:W`NULL`}`,w("WHERE",`${String(P)} IS ${c?"NOT ":""}NULL`)}let M=y?`${String(R)}\x00${JSON.stringify(B)}`:"";if(y){let P=S$.get(M);if(P)return P}let C=await j(R,"select",{signal:x,timeoutMs:H});if(y)S$.set(M,C,n);return M0(C)},async executeTakeFirst(){let O=await j(D(),"select",{signal:x,timeoutMs:H});return D0(Array.isArray(O)?O[0]:O)},async executeTakeFirstOrThrow(){let O=await this.executeTakeFirst();if(!O)throw Error("Record not found");return O},async first(){let O=f.hooks,I=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan||uX(O));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!I){let C=$._prepareStatement;if(C){let P=F.includes(" LIMIT ")?F:`${F} LIMIT 1`,S=C(P),A=B.length>0?S.all(...B):S.all();return D0(A[0])}}let R=await j(W`${D()} LIMIT 1`,"select",{signal:x,timeoutMs:H}),[M]=R;return D0(M)},async firstOrFail(){let O=await this.first();if(!O)throw Error("Record not found");return O},async find(O){let I=Z?.primaryKeys[String(G)]??"id",R=await j(W`${D()} WHERE ${W(I)} = ${O} LIMIT 1`,"select",{signal:x,timeoutMs:H}),[M]=R;return M},async findOrFail(O){let I=await this.find(O);if(!I)throw Error("Record not found");return I},async findMany(O){let I=Z?.primaryKeys[String(G)]??"id";return await j(W`${D()} WHERE ${W(String(I))} IN ${W(O)}`,"select",{signal:x,timeoutMs:H})},async*lazy(){let O,I=Z?.primaryKeys[String(G)]??"id";while(!0){let M=await(O==null?W`${D()} ORDER BY ${W(String(I))} ASC LIMIT 100`:W`${D()} WHERE ${W(String(I))} > ${O} ORDER BY ${W(String(I))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let C of M)yield C;if(O=M[M.length-1]?.[I],O==null)break}},async*lazyById(){let O=Z?.primaryKeys[String(G)]??"id",I;while(!0){let M=await(I==null?W`${D()} ORDER BY ${W(String(O))} ASC LIMIT 100`:W`${D()} WHERE ${W(String(O))} > ${I} ORDER BY ${W(String(O))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let C of M)yield C;if(I=M[M.length-1]?.[O],I==null)break}},pipe(O){return O(this)},async count(){let O=F.indexOf(" FROM "),I=/ GROUP BY /i.test(F),R;if(I)R=`SELECT COUNT(*) as c FROM (${F}) AS _bqb_count_sub`;else if(O!==-1)R=`SELECT COUNT(*) as c${F.substring(O)}`;else R=`SELECT COUNT(*) as c FROM ${G}`;let M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||uX(M));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!C){let d=$._prepareStatement;if(d){let k=d(R),b=B.length>0?k.all(...B):k.all();return Number(b[0]?.c??0)}}let P=B.length>0?$.unsafe(R,B):$.unsafe(R),S=await j(P,"select",{signal:x,timeoutMs:H}),[A]=S;return Number(A?.c??0)},async avg(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT AVG(${O}) as a${F.substring(I)}`:`SELECT AVG(${O}) as a FROM ${G}`,M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||uX(M));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!C){let d=$._prepareStatement;if(d){let k=d(R),b=B.length>0?k.all(...B):k.all();return Number(b[0]?.a??0)}}let P=B.length>0?$.unsafe(R,B):$.unsafe(R),S=await j(P,"select",{signal:x,timeoutMs:H}),[A]=S;return Number(A?.a??0)},async sum(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT SUM(${O}) as s${F.substring(I)}`:`SELECT SUM(${O}) as s FROM ${G}`,M=B.length>0?$.unsafe(R,B):$.unsafe(R),C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C;return Number(P?.s??0)},async max(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT MAX(${O}) as m${F.substring(I)}`:`SELECT MAX(${O}) as m FROM ${G}`,M=B.length>0?$.unsafe(R,B):$.unsafe(R),C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C;return P?.m},async min(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT MIN(${O}) as m${F.substring(I)}`:`SELECT MIN(${O}) as m FROM ${G}`,M=B.length>0?$.unsafe(R,B):$.unsafe(R),C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C;return P?.m},lockForUpdate(){return F+=" FOR UPDATE",K=null,this},sharedLock(){let O=f.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return F+=` ${O}`,K=null,this},withCTE(O,I){return u(O,"withCTE(name)"),F=`WITH ${O} AS (${String(I.toSQL())}) ${F}`,K=null,this},withRecursive(O,I){return u(O,"withRecursive(name)"),F=`WITH RECURSIVE ${O} AS (${String(I.toSQL())}) ${F}`,K=null,this},execute(){return j(D(),"select",{signal:x,timeoutMs:H})},values(){return D().values()},toParams(){return[...B]},__rawState(){return{sql:X8(F),params:[...B]}},raw(){return D().raw()},get rows(){return},get row(){return},cancel(){try{D().cancel()}catch{}}},{get(O,I,R){let M=Reflect.get(O,I,R);if(M!==void 0)return M;if(typeof I==="string"&&(I.startsWith("where")||I.startsWith("orWhere")||I.startsWith("andWhere"))){let C=I.startsWith("orWhere"),P=I.startsWith("andWhere"),S=`${String(G)}|${I}`,A=U.get(S);if(A===void 0){let k=I.replace(/^(?:or|and)?where/i,"");if(!k)U.set(S,""),A="";else{let b=k.charAt(0).toLowerCase()+k.slice(1),l=k.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),X0=Y?Object.keys(Y[String(G)]?.columns??{}):[];A=[l,b,b.toLowerCase()].find((w0)=>X0.includes(w0))??l,U.set(S,A)}}if(A==="")return()=>R;let d=A;return(k)=>{let b=Array.isArray(k)?W`${W(d)} IN ${W(k)}`:W`${W(d)} = ${k}`;if(K=C?W`${D()} OR ${b}`:P?W`${D()} AND ${b}`:W`${D()} WHERE ${b}`,Array.isArray(k)){let l=h0(k.length,B.length+1);w(C?"OR":P?"AND":"WHERE",`${d} IN (${l})`),B.push(...k)}else{let l=i(B.length+1);w(C?"OR":P?"AND":"WHERE",`${d} = ${l}`),B.push(k)}return R}}return Reflect.get(O,I,R)}})}return{configure(G){return Object.assign(f,G),this},id(G){if(!s.IDENTIFIER.test(G))throw Error(`[query-builder] Invalid identifier: '${G}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(String(G))},ids(...G){for(let J of G)if(!s.IDENTIFIER.test(J))throw Error(`[query-builder] Invalid identifier: '${J}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(G)},select(G,...J){return V(G,J)},selectFrom(G){return V(G)},selectFromSub(G,J){function W(H){return()=>{throw Error(`[query-builder] selectFromSub(...).${H}() is not supported. Apply ${H}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}u(String(J),"selectFromSub(alias)");let F=typeof G.__rawState==="function"?G.__rawState():null,K=G.toSQL(),D=F?.sql??(typeof K==="string"?K:K?.sql??String(K)),w=F?.params??(Array.isArray(K?.values)?K.values:[]),T=`SELECT * FROM (${D}) AS ${String(J)}`,N=(H,x,h,c,y,g,v)=>{let n=!h?"WHERE":v==="WHERE"?"AND":v,p=[...x],o=(M0,o0,a)=>{u(M0,"selectFromSub where(column)");let B=v0(o0,"selectFromSub where(operator)");if(B==="in"||B==="not in"){let e0=Array.isArray(a)?a:[a],UX=h0(e0.length,p.length+1);return p.push(...e0),`${M0} ${B.toUpperCase()} (${UX})`}let u9=i(p.length+1);return p.push(a),`${M0} ${B} ${u9}`},D0;if(typeof c==="string"&&y!==void 0)D0=o(c,y,g);else if(Array.isArray(c)&&c.length===3)D0=o(c[0],c[1],c[2]);else if(c&&typeof c==="object")D0=Object.entries(c).map(([M0,o0])=>o(M0,"=",o0)).join(" AND ");else return{text:H,params:x};return{text:`${H} ${n} ${D0}`,params:p}};function q(H,x,h=!1){let c=()=>x.length>0?$.unsafe(H,x):$.unsafe(H),y={distinct(){return q(H.replace(/^SELECT\s+/i,"SELECT DISTINCT "),x,h)},distinctOn(...g){let v=g.map(String).join(", ");return q(H.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${v}) `),x,h)},selectRaw(g){let v=KX(g,"selectFromSub.selectRaw(fragment)"),n=H.indexOf(" FROM "),p=n!==-1?`${H.slice(0,n)}, ${v}${H.slice(n)}`:`${H}, ${v}`;return q(p,x,h)},where(g,v,n){let p=N(H,x,h,g,v,n,"WHERE");return q(p.text,p.params,!0)},andWhere(g,v,n){let p=N(H,x,h,g,v,n,"AND");return q(p.text,p.params,!0)},orWhere(g,v,n){let p=N(H,x,h,g,v,n,"OR");return q(p.text,p.params,!0)},orderBy(g,v="asc"){u(String(g),"selectFromSub.orderBy(column)");let n=v==="asc"?"ASC":"DESC",p=s.ORDER_BY.test(H)?`${H}, ${g} ${n}`:`${H} ORDER BY ${g} ${n}`;return q(p,x,h)},limit(g){if(!Number.isInteger(g)||g<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${g}`);let v=s.LIMIT.test(H)?H.replace(s.LIMIT,` LIMIT ${g}`):`${H} LIMIT ${g}`;return q(v,x,h)},offset(g){if(!Number.isInteger(g)||g<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${g}`);let v=s.OFFSET.test(H)?H.replace(s.OFFSET,` OFFSET ${g}`):`${H} OFFSET ${g}`;return q(v,x,h)},toSQL(){return E(c(),H)},async execute(){return j(c(),"select")},async executeTakeFirst(){let g=await j(c(),"select");return Array.isArray(g)?g[0]:g},async executeTakeFirstOrThrow(){let g=await j(c(),"select"),v=Array.isArray(g)?g[0]:g;if(!v)throw Error("Record not found");return v},async get(){return j(c(),"select")},async first(){let g=await j(c(),"select");return Array.isArray(g)?g[0]:g},async firstOrFail(){let g=await j(c(),"select"),v=Array.isArray(g)?g[0]:g;if(!v)throw Error("No rows found");return v},async count(){let g=x.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,x):$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),v=await j(g,"select");return Number(v?.[0]?.c??0)},async exists(){let g=x.length>0?$.unsafe(`SELECT EXISTS(${H}) as e`,x):$.unsafe(`SELECT EXISTS(${H}) as e`),v=await j(g,"select");return Boolean(v?.[0]?.e)},async doesntExist(){return!await y.exists()},values(){return c().values()},raw(){return c().raw()},cancel(){try{c().cancel()}catch{}},whereRaw:W("whereRaw"),whereColumn:W("whereColumn"),orWhereColumn:W("orWhereColumn"),whereIn:W("whereIn"),orWhereIn:W("orWhereIn"),whereNotIn:W("whereNotIn"),orWhereNotIn:W("orWhereNotIn"),whereLike:W("whereLike"),whereILike:W("whereILike"),orWhereLike:W("orWhereLike"),orWhereILike:W("orWhereILike"),whereNotLike:W("whereNotLike"),whereNotILike:W("whereNotILike"),orWhereNotLike:W("orWhereNotLike"),orWhereNotILike:W("orWhereNotILike"),whereAny:W("whereAny"),whereAll:W("whereAll"),whereNone:W("whereNone"),whereNested:W("whereNested"),orWhereNested:W("orWhereNested"),whereDate:W("whereDate"),whereBetween:W("whereBetween"),whereNotBetween:W("whereNotBetween"),whereJsonContains:W("whereJsonContains"),whereJsonPath:W("whereJsonPath"),whereNull:W("whereNull"),whereNotNull:W("whereNotNull"),whereExists:W("whereExists"),whereJsonDoesntContain:W("whereJsonDoesntContain"),whereJsonContainsKey:W("whereJsonContainsKey"),whereJsonDoesntContainKey:W("whereJsonDoesntContainKey"),whereJsonLength:W("whereJsonLength"),join:W("join"),joinSub:W("joinSub"),innerJoin:W("innerJoin"),leftJoin:W("leftJoin"),leftJoinSub:W("leftJoinSub"),rightJoin:W("rightJoin"),crossJoin:W("crossJoin"),crossJoinSub:W("crossJoinSub"),groupBy:W("groupBy"),groupByRaw:W("groupByRaw"),having:W("having"),havingRaw:W("havingRaw"),addSelect:W("addSelect"),select:W("select"),selectAll:W("selectAll"),orderByDesc:W("orderByDesc"),inRandomOrder:W("inRandomOrder"),reorder:W("reorder"),orderByRaw:W("orderByRaw"),union:W("union"),unionAll:W("unionAll"),forPage:W("forPage"),selectAllRelations:W("selectAllRelations"),with:W("with"),value:W("value"),pluck:W("pluck"),cursorPaginate:W("cursorPaginate"),paginate:W("paginate"),simplePaginate:W("simplePaginate"),chunk:W("chunk"),chunkById:W("chunkById"),eachById:W("eachById"),avg:W("avg"),sum:W("sum"),max:W("max"),min:W("min"),find:W("find"),findOrFail:W("findOrFail"),findMany:W("findMany"),latest:W("latest"),oldest:W("oldest"),lazy:W("lazy"),lazyById:W("lazyById"),pipe:(g)=>g(y),when:W("when"),tap:()=>y,dump:()=>y,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>c().simple(),toText:()=>H,toParams:()=>[...x],withTimeout:()=>y,abort:()=>y,lockForUpdate:()=>y,sharedLock:()=>y,withCTE:()=>y,withRecursive:()=>y,cache:()=>y,clone:()=>y,withTrashed:()=>y,onlyTrashed:()=>y,scope:()=>y,get rows(){return[]},get row(){return}};return y}return q(T,w)},insertInto(G){let J,W="",F=[],K=f.dialect==="postgres",D=K?(T)=>`"${String(T).replace(/"/g,'""')}"`:J0(f.dialect)?(T)=>`\`${String(T).replace(/`/g,"``")}\``:(T)=>`"${String(T).replace(/"/g,'""')}"`,w=K?(T)=>`$${T+1}`:(T)=>"?";return{values(T){let N=Array.isArray(T)?T:[T],q=N.length;if(q===0)return J=$.unsafe("SELECT 1"),this;let H=N[0],x=Object.keys(H),h=x.length,c=q*h;if(F.length=c,q===1)if(!K){let y=D(x[0]),g="?";F[0]=H[x[0]];for(let v=1;v<h;v++)y+=`,${D(x[v])}`,g+=",?",F[v]=H[x[v]];W=`INSERT INTO ${D(G)}(${y})VALUES(${g})`}else{let y=x.map((g)=>D(g)).join(",");W=`INSERT INTO ${D(G)}(${y})VALUES(`;for(let g=0;g<h;g++){if(g>0)W+=",";W+=w(g),F[g]=H[x[g]]}W+=")"}else{let y=x.map((v)=>D(v)).join(",");W=`INSERT INTO ${D(G)}(${y})VALUES`;let g=0;for(let v=0;v<q;v++){let n=N[v];if(v===0)W+="(";else W+="),(";for(let p=0;p<h;p++){if(p>0)W+=",";W+=w(g),F[g++]=n[x[p]]}}W+=")"}if(!$._prepareStatement)J=$.unsafe(W,F);return this},returning(...T){let N=`${W} RETURNING ${T.join(", ")}`,q=$.unsafe(N,F),H=async()=>{let x=await j(q,"insert");return Array.isArray(x)?x[0]:x};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>E(q,N),execute:()=>j(q,"insert"),get:()=>j(q,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let x=await H();if(!x)throw Error("Insert with RETURNING returned no rows");return x},async executeTakeFirstOrThrow(){let x=await H();if(!x)throw Error("Insert with RETURNING returned no rows");return x}}},toSQL(){if(!J)J=$.unsafe(W,F);return E(J,W)},execute(){let T=f.hooks;if(!(T&&(T.onQueryStart||T.onQueryEnd||T.onQueryError||T.startSpan||T.beforeCreate||T.afterCreate||uX(T)))){let q=$._prepareStatement;if(q){let H=q(W);return F.length>0?H.run(...F):H.run()}}if(!J)J=$.unsafe(W,F);return j(J,"insert")},async executeTakeFirst(){if(!J)J=$.unsafe(W,F);return await j(J,"insert")},async executeTakeFirstOrThrow(){if(!J)J=$.unsafe(W,F);let T=await j(J,"insert");if(!T)throw Error("Insert failed");return T},returningAll(){let T=`${W} RETURNING *`,N=$.unsafe(T,F),q=async()=>{let H=await j(N,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>E(N,T),execute:()=>j(N,"insert"),get:()=>j(N,"insert"),first:q,executeTakeFirst:q,async firstOrFail(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(G){let J,W=[],F=(D)=>{let w=String(D);if(J0(f.dialect))return`\`${w.replace(/`/g,"``")}\``;return`"${w.replace(/"/g,'""')}"`},K=`UPDATE ${F(String(G))}`;return{set(D){let w=Object.keys(D),T=w.length,N=Array.from({length:T});for(let q=0;q<T;q++){let H=w[q];N[q]=`${F(H)} = ${i(q+1)}`,W.push(D[H])}return K=`${K} SET ${N.join(", ")}`,J=$.unsafe(K,W),this},where(D,w,T){let N=()=>s.WHERE.test(K)?"AND":"WHERE";if(typeof D==="string"&&w!==void 0){let q=W.length+1;return K=`${K} ${N()} ${F(D)} ${w} ${i(q)}`,W.push(T),J=$.unsafe(K,W),this}if(Array.isArray(D)){let[q,H,x]=D,h=W.length+1;return K=`${K} ${N()} ${F(String(q))} ${String(H)} ${i(h)}`,W.push(x),J=$.unsafe(K,W),this}if(D&&typeof D==="object"&&!("raw"in D)){let q=Object.keys(D),H=q.length,x=W.length,h=Array.from({length:H});for(let c=0;c<H;c++)h[c]=`${F(q[c])} = ${i(x+c+1)}`,W.push(D[q[c]]);K=`${K} ${N()} ${h.join(" AND ")}`,J=$.unsafe(K,W)}return this},returning(...D){let w=`${K} RETURNING ${D.join(", ")}`,T=W.length>0?$.unsafe(w,W):$.unsafe(w),N=async()=>{let H=await j(T,"update");return Array.isArray(H)?H[0]:H},q={where:()=>q,andWhere:()=>q,orWhere:()=>q,orderBy:()=>q,limit:()=>q,offset:()=>q,toSQL:()=>E(T,w),execute:()=>j(T,"update"),get:()=>j(T,"update"),first:N,executeTakeFirst:N,async firstOrFail(){let H=await N();if(!H)throw Error("Update with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await N();if(!H)throw Error("Update with RETURNING returned no rows");return H}};return q},toSQL(){if(!J)J=W.length>0?$.unsafe(K,W):$.unsafe(K);return E(J,K)},execute(){return j(J,"update")},async executeTakeFirst(){return{numUpdatedRows:await j(J,"update")}},async executeTakeFirstOrThrow(){let D=await j(J,"update");if(D===0)throw Error("No rows updated");return{numUpdatedRows:D}},returningAll(){let D=`${K} RETURNING *`,w=W.length>0?$.unsafe(D,W):$.unsafe(D);return{toSQL:()=>E(w,D),execute:()=>j(w,"update"),async executeTakeFirst(){let T=await j(w,"update");return Array.isArray(T)?T[0]:T},async executeTakeFirstOrThrow(){let T=await j(w,"update"),N=Array.isArray(T)?T[0]:T;if(!N)throw Error("Update with RETURNING failed");return N}}}}},deleteFrom(G){let J=(q)=>{let H=String(q);if(J0(f.dialect))return`\`${H.replace(/`/g,"``")}\``;return`"${H.replace(/"/g,'""')}"`},F=`DELETE FROM ${J(String(G))}`,K=null,D=[],w=null,T=()=>s.WHERE.test(F)?"AND":"WHERE",N=()=>{if(K===null)K=D.length>0?$.unsafe(F,D):$.unsafe(F);return K};return{where(q,H,x){if(w=q,typeof q==="string"&&H!==void 0){let h=D.length+1;return F+=` ${T()} ${J(q)} ${H} ${i(h)}`,D.push(x),K=null,this}if(Array.isArray(q)){let[h,c,y]=q,g=D.length+1;return F+=` ${T()} ${J(String(h))} ${c} ${i(g)}`,D.push(y),K=null,this}if(q&&typeof q==="object"&&!("raw"in q)){let h=Object.keys(q),c=[];for(let y of h){let g=D.length+1;c.push(`${J(y)} = ${i(g)}`),D.push(q[y])}return F+=` ${T()} ${c.join(" AND ")}`,K=null,this}return K=Q({},N(),q),this},returning(...q){let H=`${F} RETURNING ${q.join(", ")}`,x=D.length>0?$.unsafe(H,D):$.unsafe(H),h=async()=>{let y=await j(x,"delete");return Array.isArray(y)?y[0]:y},c={where:()=>c,andWhere:()=>c,orWhere:()=>c,orderBy:()=>c,limit:()=>c,offset:()=>c,toSQL:()=>E(x,H),execute:()=>j(x,"delete"),get:()=>j(x,"delete"),first:h,executeTakeFirst:h,async firstOrFail(){let y=await h();if(!y)throw Error("Delete with RETURNING returned no rows");return y},async executeTakeFirstOrThrow(){let y=await h();if(!y)throw Error("Delete with RETURNING returned no rows");return y}};return c},toSQL(){return E(N(),F)},async execute(){try{await f.hooks?.beforeDelete?.({table:String(G),where:w})}catch(H){throw H}let q=await j(N(),"delete");try{await f.hooks?.afterDelete?.({table:String(G),where:w,result:q})}catch{}return q},async executeTakeFirst(){return{numDeletedRows:await j(N(),"delete")}},async executeTakeFirstOrThrow(){let q=await j(N(),"delete");if(q===0)throw Error("No rows deleted");return{numDeletedRows:q}},returningAll(){let q=`${F} RETURNING *`,H=D.length>0?$.unsafe(q,D):$.unsafe(q);return{toSQL:()=>E(H,q),execute:()=>j(H,"delete"),async executeTakeFirst(){let x=await j(H,"delete");return Array.isArray(x)?x[0]:x},async executeTakeFirstOrThrow(){let x=await j(H,"delete"),h=Array.isArray(x)?x[0]:x;if(!h)throw Error("Delete with RETURNING failed");return h}}}}},table(G){let J=this;return{insert(W){return J.insertInto(G).values(W)},update(W){return J.updateTable(G).set(W)},delete(){return J.deleteFrom(G)},select(...W){if(W.length===0)return J.selectFrom(G);return J.select(G,...W)}}},sql:$,raw(G,...J){return $(G,...J)},simple(G,...J){return $(G,...J).simple()},async advisoryLock(G){if(f.dialect==="postgres"){let J=String(G),W=7;for(let D=0;D<J.length;D++)W=W*31+J.charCodeAt(D)|0;let F=typeof G==="number"?G:Math.abs(W),K=m`SELECT pg_advisory_lock(${F})`;await j(K,"raw");return}if(J0(f.dialect)){let J=`bqb:${String(G)}`,W=m`SELECT GET_LOCK(${J}, -1) AS ok`;await j(W,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(G){if(f.dialect==="postgres"){let J=String(G),W=7;for(let w=0;w<J.length;w++)W=W*31+J.charCodeAt(w)|0;let F=typeof G==="number"?G:Math.abs(W),K=m`SELECT pg_try_advisory_lock(${F}) as ok`,D=await j(K,"raw");return Boolean(D?.[0]?.ok)}if(J0(f.dialect)){let J=`bqb:${String(G)}`,W=m`SELECT GET_LOCK(${J}, 0) AS ok`,F=await j(W,"raw");return Number(F?.[0]?.ok)===1}return!1},unsafe(G,J){return m.unsafe(G,J)},file(G,J){return m.file(G,J)},async reserve(){let G=await m.reserve(),J=K0({sql:G,meta:Z,schema:Y});return J.release=()=>G.release(),J},async close(G){await m.close(G)},async listen(G,J){},async unlisten(G){},async notify(G,J){},async copyTo(G,J){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(G,J,W){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let G=m`SELECT 1`;return await j(G,"select"),!0}catch{return!1}},async waitForReady(G){let J=Math.max(1,G?.attempts??10),W=Math.max(10,G?.delayMs??100);for(let F=0;F<J;F++){if(await this.ping())return;await new Promise((K)=>setTimeout(K,W))}throw Error("Database not ready after waiting")},async transaction(G,J){let F={...X?.txDefaults,...J},K=X?.sql??m,D=X?.inTransaction===!0,w=D&&typeof K?.savepoint==="function"?"savepoint":"begin",T=async(H)=>{F.logger?.({type:"start",attempt:H});let x=Date.now();return await K[w](async(h)=>{let c=K0({sql:h,meta:Z,schema:Y,inTransaction:!0});if(F?.isolation&&!D){let v=F.isolation,n=v==="read committed"?"READ COMMITTED":v==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(f.dialect==="postgres")await h.unsafe(`SET TRANSACTION ISOLATION LEVEL ${n}`);else if(J0(f.dialect))await h.unsafe(`SET TRANSACTION ISOLATION LEVEL ${n}`);else if(v!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${v}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(F?.readOnly)if(f.dialect==="postgres")await h.unsafe("SET TRANSACTION READ ONLY");else if(J0(f.dialect))await h.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let y=await G(c),g=Date.now()-x;return F.logger?.({type:"commit",attempt:H,durationMs:g}),y})},N=Math.max(0,F?.retries??0),q=0;for(;;)try{let H=await T(q+1);return F?.afterCommit?.(),H}catch(H){let x=v_(H)||b_(H,F.sqlStates);if(q<N&&x){q++,F?.onRetry?.(q,H);let h=d_(q,F.backoff);if(h>0)await f_(h);continue}try{F.onRollback?.(H)}catch{}try{F.afterRollback?.()}catch{}throw H}},async savepoint(G){let J=$;if(!J||typeof J.savepoint!=="function")throw Error("savepoint() must be called inside a transaction");return await J.savepoint(async(W)=>{let F=K0({sql:W,meta:Z,schema:Y});return await G(F)})},async beginDistributed(G,J){return await(X?.sql??m).beginDistributed(G,async(K)=>{let D=K0({sql:K,meta:Z,schema:Y});return await J(D)})},async commitDistributed(G){await m.commitDistributed(G)},async rollbackDistributed(G){await m.rollbackDistributed(G)},setTransactionDefaults(G){X={...X,txDefaults:{...X?.txDefaults,...G}}},transactional(G,J){return(...W)=>{return this.transaction((F)=>G(F,...W),J)}},async insertOrIgnore(G,J){let W=Array.isArray(J)?J:[J];if(!W.length)return;let{colsSql:F,valuesSql:K,params:D}=e$(W),w=a0(String(G)),T=J0(f.dialect)?`INSERT IGNORE INTO ${w} (${F}) VALUES ${K}`:`INSERT INTO ${w} (${F}) VALUES ${K} ON CONFLICT DO NOTHING`;return m.unsafe(T,D).execute()},async insertGetId(G,J,W="id"){let{colsSql:F,valuesSql:K,params:D}=e$([J]),w=a0(String(G));if(J0(f.dialect)){await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K}`,D).execute();let[N]=await m.unsafe("SELECT LAST_INSERT_ID() as id").execute();return N?.id}if(f.dialect==="sqlite"){let N=await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K}`,D).execute();if(N?.lastInsertRowid!=null)return N.lastInsertRowid;let[q]=await m.unsafe("SELECT last_insert_rowid() as id").execute();return q?.id}let[T]=await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K} RETURNING ${a0(String(W))} as id`,D).execute();return T?.id},async updateOrInsert(G,J,W){let F=a0(String(G)),K=Object.keys(J),D=1,w=K.map((h)=>`${a0(h)} = ${i(D++)}`).join(" AND "),T=K.map((h)=>J[h]);if((await m.unsafe(`SELECT 1 FROM ${F} WHERE ${w} LIMIT 1`,T).execute()).length){let h=Object.keys(W),c=1,y=h.map((n)=>`${a0(n)} = ${i(c++)}`).join(", "),g=K.map((n)=>`${a0(n)} = ${i(c++)}`).join(" AND "),v=[...h.map((n)=>W[n]),...K.map((n)=>J[n])];return await m.unsafe(`UPDATE ${F} SET ${y} WHERE ${g}`,v).execute(),!0}let{colsSql:q,valuesSql:H,params:x}=e$([{...J,...W}]);return await m.unsafe(`INSERT INTO ${F} (${q}) VALUES ${H}`,x).execute(),!0},async upsert(G,J,W,F){let K=W.map((y)=>String(y)),D=(F??[]).map((y)=>String(y)),w=J;if(!w.length)return;let{colsSql:T,valuesSql:N,params:q}=e$(w),H=a0(String(G)),x=`INSERT INTO ${H} (${T}) VALUES ${N}`;if(J0(f.dialect)){if(D.length===0)return m.unsafe(`INSERT IGNORE INTO ${H} (${T}) VALUES ${N}`,q).execute();let y=D.map((g)=>`${a0(g)} = VALUES(${a0(g)})`).join(", ");return m.unsafe(`${x} ON DUPLICATE KEY UPDATE ${y}`,q).execute()}let h=K.map(a0).join(", ");if(D.length===0)return m.unsafe(`${x} ON CONFLICT (${h}) DO NOTHING`,q).execute();let c=D.map((y)=>`${a0(y)} = EXCLUDED.${a0(y)}`).join(", ");return m.unsafe(`${x} ON CONFLICT (${h}) DO UPDATE SET ${c}`,q).execute()},async save(G,J){let W=Z?.primaryKeys[String(G)]??"id",F=J[W];if(F!=null)if(await this.selectFrom(G).find(F)){await this.updateTable(G).set(J).where({[W]:F}).execute();let D=await this.selectFrom(G).find(F);if(!D)throw Error("save() failed to retrieve updated row");return D}else return await this.create(G,J);return await this.create(G,J)},async remove(G,J){return await this.deleteFrom(G).where({id:J}).execute()},async find(G,J){return await this.selectFrom(G).find(J)},async findOrFail(G,J){return await this.selectFrom(G).findOrFail(J)},async findMany(G,J){return await this.selectFrom(G).findMany(J)},async latest(G,J){return await this.selectFrom(G).latest(J).first()},async oldest(G,J){return await this.selectFrom(G).oldest(J).first()},skip(G,J){return this.selectFrom(G).offset(J)},async rawQuery(G){let J=Date.now();try{f.hooks?.onQueryStart?.({sql:G,kind:"raw"});let W=await m.unsafe(G);return f.hooks?.onQueryEnd?.({sql:G,durationMs:Date.now()-J,kind:"raw"}),W}catch(W){throw f.hooks?.onQueryError?.({sql:G,error:W,durationMs:Date.now()-J,kind:"raw"}),W}},async create(G,J){let W=Z?.primaryKeys[String(G)]??"id";try{await f.hooks?.beforeCreate?.({table:String(G),data:J})}catch(F){throw F}if(f.dialect==="postgres"){let F=m`INSERT INTO ${m(String(G))} ${m(J)} RETURNING ${m(String(W))} as id`,[K]=await F.execute();if(console.log("resultId",K),!K?.id)throw console.error(`create() failed to get insert ID for table ${String(G)}`),console.error("Inserted values:",J),Error(`create() failed to get insert ID for table ${String(G)}`);let D=await this.selectFrom(G).find(K.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${K.id}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${K.id}`);try{await f.hooks?.afterCreate?.({table:String(G),data:J,result:D})}catch{}return D}else{let F=await this.insertGetId(G,J,W);if(F==null)throw Error(`create() failed to get insert ID for table ${String(G)}`);let K=await this.selectFrom(G).find(F);if(!K)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${F}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${F}`);try{await f.hooks?.afterCreate?.({table:String(G),data:J,result:K})}catch{}return K}},async createMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),K=F.length,D=J.length,w=Array.from({length:D*K}),T=J0(f.dialect)?(H)=>`\`${String(H).replace(/`/g,"``")}\``:(H)=>`"${String(H).replace(/"/g,'""')}"`,N=`INSERT INTO ${T(String(G))}(${F.map(T).join(",")})VALUES`,q=0;for(let H=0;H<D;H++){if(H>0)N+=",";N+="(";let x=J[H];for(let h=0;h<K;h++){if(h>0)N+=",";N+=i(q+1),w[q++]=x[F[h]]}N+=")"}return $.unsafe(N,w).execute()},async insertMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),K=F.length,D=J.length,w=D*K,T=Array(w),N=f.dialect==="postgres",q;if(!N){let h=Array(K);for(let c=0;c<K;c++)h[c]="?";q=`(${h.join(",")})`}else q="";let H=Array(D+2);H[0]=`INSERT INTO ${G}(${F.join(",")})VALUES`;let x=0;if(!N){for(let h=0;h<D;h++){let c=J[h];H[h+1]=q;for(let y=0;y<K;y++)T[x++]=c[F[y]]}return $.unsafe(H[0]+H.slice(1,D+1).join(","),T).execute()}for(let h=0;h<D;h++){let c=J[h],y=Array(K);for(let g=0;g<K;g++)y[g]=`$${x+1}`,T[x++]=c[F[g]];H[h+1]=`(${y.join(",")})`}return $.unsafe(H[0]+H.slice(1,D+1).join(","),T).execute()},async updateMany(G,J,W){let F=Object.keys(W),K=F.length;if(K===0)return 0;let D=[],w=Array.from({length:K});for(let N=0;N<K;N++)w[N]=`${F[N]}=${i(N+1)}`,D.push(W[F[N]]);let T=`UPDATE ${G} SET ${w.join(",")}`;if(Array.isArray(J))T+=` WHERE ${J[0]}${J[1]}${i(D.length+1)}`,D.push(J[2]);else if(J&&typeof J==="object"&&!("raw"in J)){let N=Object.keys(J),q=N.length;if(q>0){let H=D.length,x=Array.from({length:q});for(let h=0;h<q;h++)x[h]=`${N[h]}=${i(H+h+1)}`,D.push(J[N[h]]);T+=` WHERE ${x.join(" AND ")}`}}return $.unsafe(T,D).execute()},async deleteMany(G,J){if(!Array.isArray(J)||J.length===0)return 0;let W=Z?.primaryKeys[String(G)]??"id",F=J.length;if(f.dialect==="postgres"){let D=Array(F);for(let w=0;w<F;w++)D[w]=`$${w+1}`;return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${D.join(",")})`,J).execute()}let K=Array(F);for(let D=0;D<F;D++)K[D]="?";return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${K.join(",")})`,J).execute()},async firstOrCreate(G,J,W){let F=await this.selectFrom(G).where(J).first();if(F)return F;return await this.create(G,{...J,...W})},async updateOrCreate(G,J,W){let F=await this.selectFrom(G).where(J).first();if(F){await this.updateTable(G).set(W).where(J).execute();let K=Z?.primaryKeys[String(G)]??"id",D=F[K],w=D!=null?await this.selectFrom(G).find(D):await this.selectFrom(G).where(J).first();if(!w)throw Error("updateOrCreate() failed to retrieve updated row");return w}return await this.create(G,{...J,...W})},async count(G,J){let W=J?m(String(J)):m`*`,F=m`SELECT COUNT(${W}) as c FROM ${m(String(G))}`,[K]=await F.execute();return Number(K?.c??0)},async sum(G,J){let W=m`SELECT SUM(${m(String(J))}) as s FROM ${m(String(G))}`,[F]=await W.execute();return Number(F?.s??0)},async avg(G,J){let W=m`SELECT AVG(${m(String(J))}) as a FROM ${m(String(G))}`,[F]=await W.execute();return Number(F?.a??0)},async min(G,J){let W=m`SELECT MIN(${m(String(J))}) as m FROM ${m(String(G))}`,[F]=await W.execute();return F?.m},async max(G,J){let W=m`SELECT MAX(${m(String(J))}) as m FROM ${m(String(G))}`,[F]=await W.execute();return F?.m},getRelationships(G){if(!Z?.relations)return{};let J=Z.relations[G];if(!J)return{};let W={};for(let[F,K]of Object.entries(J))if(K&&typeof K==="object"&&Object.keys(K).length>0)W[F]=K;return W},hasRelationship(G,J){if(!Z?.relations)return!1;let W=Z.relations[G];if(!W)return!1;return Object.values(W).some((F)=>F&&typeof F==="object"&&(J in F))},getRelationshipType(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,K]of Object.entries(W))if(K&&typeof K==="object"&&J in K)return F;return null},getRelationshipTarget(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,K]of Object.entries(W))if(K&&typeof K==="object"&&J in K){let D=K[J];if(typeof D==="string")return Z.modelToTable[D]||D;else if(D&&typeof D==="object"){if("model"in D)return Z.modelToTable[D.model]||D.model;if("target"in D)return Z.modelToTable[D.target]||D.target}}return null}}}function p_(){S$.clear()}function c_(X){S$.setMaxSize(X)}var s,w1,q1,S$,oX,m_=500,UZ=e(()=>{d0(),$X(),s={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},w1=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]),q1=new Set,S$=new _U,oX=new Map});async function DG(){console.log("-- Clearing query cache..."),p_(),console.log("-- \u2713 Query cache cleared")}async function MG(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function HG(X={}){if(console.log("-- Configuring query cache..."),console.log(),X.size!==void 0){let $=Number(X.size);if(Number.isNaN($)||$<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");c_($),console.log(`-- \u2713 Cache max size set to: ${$}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}var u_=e(()=>{UZ()});async function i_(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let X=K0(),$=n_({input:$8.stdin,output:$8.stdout,prompt:"qb> "}),Z="",Y=!1,U=`
|
|
78
|
+
`,[`User ${Q}`,`user${Q}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(Q){throw console.error("-- Failed to setup test table:",Q),Q}let U=[];if(Z.includes("select")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").where({active:1}).limit(10).execute(),Q.push(performance.now()-z)}U.push({operation:"SELECT with WHERE + LIMIT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("select")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").where({id:1}).first(),Q.push(performance.now()-z)}U.push({operation:"SELECT by ID (first)",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("count")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").count(),Q.push(performance.now()-z)}U.push({operation:"COUNT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("insert")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.insertInto("bench_users").values({name:`Bench User ${L}`,email:`bench${L}@example.com`,created_at:new Date().toISOString()}).execute(),Q.push(performance.now()-z)}U.push({operation:"INSERT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("update")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.updateTable("bench_users").set({active:0}).where({id:1}).execute(),Q.push(performance.now()-z)}U.push({operation:"UPDATE by ID",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("delete")){let Q=[],L=[];for(let z=0;z<$;z++){let j=await Y.insertInto("bench_users").values({name:"To Delete",email:`delete${z}@example.com`,created_at:new Date().toISOString()}).execute();L.push(j)}for(let z=0;z<$;z++){let j=performance.now();await Y.deleteFrom("bench_users").where({id:L[z]}).execute(),Q.push(performance.now()-j)}U.push({operation:"DELETE by ID",avgTime:Q.reduce((z,j)=>z+j,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}console.log("-- Benchmark Results"),console.log();let _=Math.max(...U.map((Q)=>Q.operation.length));console.log("Operation".padEnd(_+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(_+2+12+12+12+12));for(let Q of U){let L=Q.operation.padEnd(_+2),z=Q.avgTime.toFixed(3).padStart(12),j=Q.minTime.toFixed(3).padStart(12),E=Q.maxTime.toFixed(3).padStart(12),V=(1000/Q.avgTime).toFixed(0).padStart(12);console.log(`${L}${z}${j}${E}${V}`)}console.log();try{await m.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(Q){console.error("-- Warning: Failed to cleanup test table:",Q)}}var B_=t(()=>{$X(),y0()});function y_(X){return X.endsWith("s")?X.slice(0,-1):X}function PX(X,$,Z,Y={}){let U=Y.singularize??y_,Q=X.relations?.[$]?.belongsToMany?.[Z];if(Q==null)return null;let L=typeof Q==="object",z=L?Q:null,j=L?z.model:Q,E=X.modelToTable[j]||j,V,G;if(z?.table)V=z.table;else if(z?.through){if(G=z.through,V=X.modelToTable[z.through],!V)throw Error(`[query-builder] belongsToMany relation '${Z}' on '${$}' references unknown through model '${z.through}'. Make sure '${z.through}' is registered via defineModels({...}).`)}else{let w=U($),T=U(E);V=[w,T].sort().join("_")}let J=z?.foreignKey??`${U($)}_id`,W=z?.relatedKey??`${U(E)}_id`,F={};if(z?.pivot?.columns)Object.assign(F,z.pivot.columns);if(G&&Y.models){let w=Y.models[G],T=w?.definition??w?.getDefinition?.()??w,N=T?.attributes??{};for(let[q,H]of Object.entries(N)){if(q===J||q===W||q===(T?.primaryKey??"id"))continue;F[q]={default:H?.default,nullable:H?.nullable,validation:H?.validation}}}let K=Boolean(z?.pivot?.timestamps),D=Object.keys(F);return{pivotTable:V,fkParent:J,fkRelated:W,pivotColumns:D,pivotColumnDefs:F,pivotModelName:G,timestamps:K,relatedModelName:j,relatedTable:E,hasConfig:L}}function*DG(X,$={}){let Z=X.relations;if(!Z)return;for(let[Y,U]of Object.entries(Z)){let _=U?.belongsToMany;if(!_)continue;for(let Q of Object.keys(_)){let L=PX(X,Y,Q,$);if(L)yield{parentTable:Y,relationKey:Q,resolved:L}}}}function d8(X){return typeof X==="object"&&X!==null&&"raw"in X&&typeof X.raw==="string"}function MG(X,...$){if(typeof X==="string")return{raw:X};let Z=X[0];for(let Y=0;Y<$.length;Y++)Z+=q9($[Y])+X[Y+1];return{raw:Z}}function a0(X){return W0(f.dialect)?`\`${X.replace(/`/g,"``")}\``:`"${X.replace(/"/g,'""')}"`}function e$(X,$=1){let Z=Object.keys(X[0]??{}),Y=[],U=$,_=X.map((Q)=>{return`(${Z.map((z)=>{return Y.push(Q[z]),i(U++)}).join(", ")})`});return{colsSql:Z.map(a0).join(", "),valuesSql:_.join(", "),params:Y,nextIndex:U}}function uX(X){return Boolean(X&&(X.onSlowQuery||X.slowQueryThresholdMs!=null&&X.slowQueryThresholdMs>=0))}function NY(X){if(typeof X==="string")return X;if(d8(X))return X.raw;if(X&&typeof X==="object"){let $=X;if(typeof $.raw==="function")return String($.raw());if(typeof $.sql==="string")return $.sql;let Z=String(X);if(Z!=="[object Object]")return Z}throw TypeError(`[query-builder] select(): unsupported column ${String(X)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function u(X,$){if(!s.IDENTIFIER.test(X)){let Z=$?` in ${$}`:"";throw Error(`[query-builder] Invalid identifier${Z}: '${X}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function v0(X,$){if(typeof X!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof X}`);let Z=X.toLowerCase();if(!w1.has(Z))throw TypeError(`[query-builder] ${$}: refusing to use '${X}' as a SQL operator \u2014 not in the allowed set (${[...w1].join(", ")})`);return X}function Q9(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);if(X.length>129)throw TypeError(`[query-builder] ${$}: identifier '${X}' too long`);let Z=X.split(".");if(Z.length>2)throw TypeError(`[query-builder] ${$}: identifier '${X}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let Y of Z)if(!/^[A-Z_][A-Z0-9_]*$/i.test(Y))throw TypeError(`[query-builder] ${$}: identifier segment '${Y}' contains characters outside [A-Za-z0-9_]`)}function KX(X,$){if(typeof X==="string")return h_($),X;if(X===null||X===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${X}`);if(d8(X))return X.raw;if(typeof X==="object"){let Z=X;if(typeof Z.raw==="string")return Z.raw;if(typeof Z.raw==="function"){let U=Z.raw();if(typeof U==="string")return U}if(typeof Z.sql==="string")return Z.sql;let Y=String(X);if(Y!=="[object Object]"&&Y!=="[object Promise]")return Y}throw TypeError(`[query-builder] ${$}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function h_(X){if(q1.has(X))return;q1.add(X),console.warn(`[query-builder] ${X}: bare string passed to a *Raw method. Prefer \`sql\`...\`\` tagged-template fragments so values are parameterised `+"instead of concatenated \u2014 concatenating request input into SQL is an "+"injection vector. This will become a hard error in a future release.")}function q9(X){if(X===null)return"NULL";if(typeof X==="number"&&Number.isFinite(X))return String(X);if(typeof X==="boolean")return X?"1":"0";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof X}`)}function v_(X,$){let Z=Array.isArray(X)?X:X?[X]:[],Y=[];if(Z.length)Y.push(`PARTITION BY ${Z.join(", ")}`);if($&&$.length)Y.push(`ORDER BY ${$.map(([U,_])=>`${U} ${_==="desc"?"DESC":"ASC"}`).join(", ")}`);return Y.length?`OVER (${Y.join(" ")})`:"OVER ()"}class QU{cache=new Map;maxSize=100;get(X){let $=this.cache.get(X);if(!$)return null;if(Date.now()>$.expiresAt)return this.cache.delete(X),null;return this.cache.delete(X),this.cache.set(X,$),$.data}set(X,$,Z){if(this.cache.has(X))this.cache.delete(X);if(this.cache.size>=this.maxSize){let Y=Date.now(),U=!1;for(let[_,Q]of this.cache)if(Y>Q.expiresAt){if(this.cache.delete(_),U=!0,this.cache.size<this.maxSize)break}if(!U){let _=this.cache.keys().next().value;if(_!==void 0)this.cache.delete(_)}}this.cache.set(X,{data:$,expiresAt:Date.now()+Z})}clear(){this.cache.clear()}setMaxSize(X){this.maxSize=X}}function b_(X){let $=String(X?.message||"").toLowerCase();return $.includes("deadlock")||$.includes("serialization failure")||$.includes("could not serialize access")||$.includes("deadlock found when trying to get lock")||$.includes("lock wait timeout exceeded")||$.includes("database is locked")||$.includes("busy")}function f_(X,$){if(!$||$.length===0)return!1;let Z=X&&(X.code||X.sqlState||X.sqlstate);if(!Z)return!1;return $.includes(Z)}function g_(X){return new Promise(($)=>setTimeout($,X))}function X8(X){let $=oX.get(X);if($!==void 0)return $;let Z=d_(X);if(oX.size>=u_)oX.clear();return oX.set(X,Z),Z}function d_(X){let $=[{key:"GROUP_BY",tokens:/^GROUP\s+BY\b/i},{key:"ORDER_BY",tokens:/^ORDER\s+BY\b/i},{key:"HAVING",tokens:/^HAVING\b/i},{key:"OFFSET",tokens:/^OFFSET\b/i},{key:"LIMIT",tokens:/^LIMIT\b/i},{key:"WHERE",tokens:/^WHERE\b/i}],Z=[],Y=0,U=!1,_="";for(let E=0;E<X.length;E++){let V=X[E];if(U){if(V===_){if(X[E+1]===_){E++;continue}U=!1}continue}if(V==="'"||V==='"'||V==="`"){U=!0,_=V;continue}if(V==="("){Y++;continue}if(V===")"){Y--;continue}if(Y!==0)continue;if(E===0||!/\s/.test(X[E-1]))continue;let G=X.charCodeAt(E)&-33;if(G!==71&&G!==79&&G!==72&&G!==76&&G!==87)continue;let J=X.slice(E);for(let{key:W,tokens:F}of $){let K=J.match(F);if(!K)continue;Z.push({key:W,start:E}),E+=K[0].length-1;break}}if(Z.length<=1)return X;let Q=X.slice(0,Z[0].start).trimEnd(),L={};for(let E=0;E<Z.length;E++){let V=Z[E].start,G=E+1<Z.length?Z[E+1].start:X.length,J=X.slice(V,G).trim();if(!L[Z[E].key])L[Z[E].key]=[];L[Z[E].key].push(J)}let j=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((E)=>L[E]).map((E)=>L[E].join(" ")).join(" ");return j?`${Q} ${j}`:Q}function p_(X,$){let Z=Math.max(1,$?.baseMs??50),Y=Math.max(1,$?.factor??2),U=Math.max(Z,$?.maxMs??2000),_=Math.min(U,Z*Y**Math.max(0,X-1));if($?.jitter){let Q=Math.random()*_*0.2;_=_-Q/2}return Math.floor(_)}function R0(X){let $=X?.sql??BX(),Z=X?.meta,Y=X?.schema,U=new Map;function _(G){if(Array.isArray(G)){let[D,w,T]=G;u(D,"where(column)");let N=String(D);switch(w){case"in":if(Array.isArray(T)){let q=h0(T.length);return $.unsafe(`${N} IN (${q})`,T)}return $.unsafe(`${N} IN (${i(1)})`,[T]);case"not in":if(Array.isArray(T)){let q=h0(T.length);return $.unsafe(`${N} NOT IN (${q})`,T)}return $.unsafe(`${N} NOT IN (${i(1)})`,[T]);case"like":return $.unsafe(`${N} LIKE ${i(1)}`,[T]);case"is":case"is not":{if(T!==null&&T!==void 0)throw TypeError(`[query-builder] where(..., '${w}', ?): operator '${w}' only accepts NULL/undefined as value, got ${typeof T} (${String(T)})`);return $.unsafe(`${N} IS ${w==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${N} <> ${i(1)}`,[T]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${N} ${w} ${i(1)}`,[T]);default:throw TypeError(`[query-builder] where(..., '${String(w)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in G)return G.raw;let J=Object.keys(G);if(J.length===0)return $.unsafe("");let W=[],F=[],K=1;for(let D of J){u(D,"where(object key)");let w=G[D];if(Array.isArray(w)){let T=h0(w.length,K);W.push(`${D} IN (${T})`),F.push(...w),K+=w.length}else W.push(`${D} = ${i(K++)}`),F.push(w)}return $.unsafe(W.join(" AND "),F)}function Q(G,J,W){if(!W)return J;let F=_(W);return $`${J} WHERE ${F}`}function L(G){let J=f.debug?.captureText;if(f.debug)f.debug.captureText=!0;let W=String(G);if(f.debug)f.debug.captureText=J;return W}function z(G){if(!G||typeof G!=="object")return;if(Array.isArray(G.values))return G.values;if(Array.isArray(G.parameters))return G.parameters;if(Array.isArray(G.params))return G.params;return}function j(G,J,W){let F=f.hooks,K=F?.slowQueryThresholdMs,D=K!=null&&K>=0,w=Boolean(F?.onSlowQuery||D),T=F&&(F.onQueryStart||F.onQueryEnd||F.onQueryError||F.startSpan||w),N=W?.timeoutMs&&W.timeoutMs>0||W?.signal;if(!T&&!N)return G.execute();let q=L(G),H=z(G),S=Date.now(),h;try{if(F?.onQueryStart?.({sql:q,params:H,kind:J}),F?.startSpan)h=F.startSpan({sql:q,params:H,kind:J})}catch{}let p=!1,d=(c,X0)=>{if(p)return;p=!0;let e=Date.now()-S;try{if(c)F?.onQueryError?.({sql:q,params:H,error:c,durationMs:e,kind:J});else if(F?.onQueryEnd?.({sql:q,params:H,durationMs:e,rowCount:X0,kind:J}),D&&e>=K)if(F?.onSlowQuery)F.onSlowQuery({sql:q,params:H,durationMs:e,kind:J});else console.warn(`[query-builder] slow query (${e}ms >= ${K}ms): ${q}`)}catch{}try{h?.end(c)}catch{}},B=G.execute(),v=[B],n;if(W?.timeoutMs&&W.timeoutMs>0){let c=new Promise((X0,e)=>{n=setTimeout(()=>{try{G.cancel?.()}catch{}let q0=Error(`Query timed out after ${W.timeoutMs}ms`);q0.code="EBQBTIMEOUT",e(q0)},W.timeoutMs)});v.push(c)}if(W?.signal){if(W.signal.aborted){try{G.cancel?.()}catch{}let X0=Error("Query aborted");return X0.code="EBQBABORT",d(X0),Promise.reject(X0)}let c=()=>{try{G.cancel?.()}catch{}};W.signal.addEventListener("abort",c,{once:!0}),B.finally(()=>{W.signal?.removeEventListener("abort",c)})}return Promise.race(v).then((c)=>{clearTimeout(n);let X0=Array.isArray(c)?c.length:typeof c==="number"?c:void 0;return d(void 0,X0),c}).catch((c)=>{throw clearTimeout(n),d(c),c})}function E(G,J){let W=J??L(G);return{sql:W,toString:()=>W,execute:()=>G.execute(),values:()=>G.values(),raw:()=>G.raw()}}function V(G,J){let W=$,F=J&&J.length>0?`SELECT ${J.join(", ")} FROM ${String(G)}`:`SELECT * FROM ${String(G)}`,K=null,D=()=>{if(K===null){let O=X8(F);K=y.length>0?$.unsafe(O,y):$.unsafe(O)}return K},w=(O,I)=>{let M=!s.WHERE.test(F)?"WHERE":O==="WHERE"?"AND":O;F=`${F} ${M} ${I}`},T=(O,I)=>{let R=I.__rawState?.();if(R){let M=y.length,C=f.dialect==="postgres"?R.sql.replace(/\$(\d+)/g,(P,A)=>`$${Number(A)+M}`):R.sql;F+=` ${O} ${C}`,y.push(...R.params)}else F+=` ${O} ${String(I.toSQL())}`;K=null},N=(O)=>{let I=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,R=0,M=-1,C;while(C=I.exec(F))if(C[0]==="(")R++;else if(C[0]===")")R=Math.max(0,R-1);else if(R===0){M=C.index;break}F=M>=0?`${F.slice(0,M)}${O} ${F.slice(M)}`:`${F} ${O}`,K=null},q=new Set,H,S,h=!1,p=!1,d=!1,B=new Map,v=new Set,n=60000,c=(O)=>{if(f.relations.singularizeStrategy==="none")return O;return O.endsWith("s")?O.slice(0,-1):O},X0=(O)=>{if(!Z)return null;return PX(Z,String(G),O,{singularize:c,models:Z.models})},e=(O)=>{if(!O||typeof O!=="object"||v.size===0)return O;let I;for(let R of Object.keys(O))if(R.startsWith("pivot_")){if(!I)I={};I[R.slice(6)]=O[R],delete O[R]}if(I)O.pivot=I;return O},q0=(O)=>{if(v.size===0||!O)return O;if(Array.isArray(O))for(let I=0;I<O.length;I++)e(O[I]);else e(O);return O},u0=(O)=>{if(!Z)return;if(q.has(O.pivotTable))return;let I=String(G),R=Z.primaryKeys[I]??"id";u(O.pivotTable,"wherePivot auto-join (pivot table)"),u(O.fkParent,"wherePivot auto-join (parent FK)"),u(I,"wherePivot auto-join (parent table)"),u(R,"wherePivot auto-join (parent PK)"),K=W`${D()} LEFT JOIN ${W(O.pivotTable)} ON ${W(`${O.pivotTable}.${O.fkParent}`)} = ${W(`${I}.${R}`)}`,F=`${F} LEFT JOIN ${O.pivotTable} ON ${O.pivotTable}.${O.fkParent} = ${I}.${R}`,q.add(O.pivotTable)},o=[],y=[],K9=(O)=>{if(s.SELECT_STAR.test(F))F=F.replace(s.SELECT_STAR,`SELECT *, ${O}`);else if(s.SELECT.test(F))F=F.replace(s.SELECT_FROM,`SELECT $1, ${O} FROM`);let I=String(D());if(s.SELECT_STAR.test(I)){let R=I.replace(s.SELECT_STAR,`SELECT *, ${O}`);K=$.unsafe(R)}else if(s.SELECT.test(I)){if(s.SELECT_FROM.exec(I)){let M=I.replace(s.SELECT_FROM,`SELECT $1, ${O} FROM`);K=$.unsafe(M)}}},e0=(O,I,R,M)=>{K9(`${O} ${v_(R,M)} AS ${I}`)},UX=(O,I,R,M)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)");let C=`${O.endsWith("s")?O.slice(0,-1):O}_id`;u(C,"relationship subquery (foreign key)");let P=`SELECT 1 FROM ${I} WHERE ${I}.${C} = ${O}.${R}`;if(M){let k=M({where:(g,x,b)=>{return u(g,"relationship subquery condition"),`${I}.${g} ${v0(x,"whereHas callback")} ${q9(b)}`}});if(k)P+=` AND ${k}`}return P},h$=(O,I,R,M)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)");let C=`${I.endsWith("s")?I.slice(0,-1):I}_id`;u(C,"relationship subquery (foreign key)");let P=`SELECT 1 FROM ${I} WHERE ${I}.${R} = ${O}.${C}`;if(M){let k=M({where:(g,x,b)=>{return u(g,"relationship subquery condition"),`${I}.${g} ${v0(x,"whereHas callback")} ${q9(b)}`}});if(k)P+=` AND ${k}`}return P},v$=(O,I,R,M,C,P)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)"),u(M,"relationship subquery (target primary key)");let A=P&&Z?PX(Z,O,P,{singularize:c,models:Z.models}):null,k=c(O),g=c(I),x=A?.pivotTable??[k,g].sort().join("_"),b=A?.fkParent??`${k}_id`,l=A?.fkRelated??`${g}_id`;u(x,"relationship subquery (pivot table)"),u(b,"relationship subquery (foreign key A)"),u(l,"relationship subquery (foreign key B)");let $0=`SELECT 1 FROM ${x} JOIN ${I} ON ${I}.${M} = ${x}.${l} WHERE ${x}.${b} = ${O}.${R}`;if(C){let r=C({where:(T0,X9,_9)=>{return u(T0,"relationship subquery condition"),`${I}.${T0} ${v0(X9,"whereHas callback")} ${q9(_9)}`}});if(r)$0+=` AND ${r}`}return $0},A7=(O,I,R)=>{u(O,"withCount (parent table)"),u(I,"withCount (target table)"),u(R,"withCount (primary key)");let M=`${O.endsWith("s")?O.slice(0,-1):O}_id`;return u(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${I} WHERE ${I}.${M} = ${O}.${R})`},k7=(O,I,R,M)=>{u(O,"withCount (parent table)"),u(I,"withCount (target table)"),u(R,"withCount (primary key)");let C=M&&Z?PX(Z,O,M,{singularize:c,models:Z.models}):null,P=c(O),A=c(I),k=C?.pivotTable??[P,A].sort().join("_"),g=C?.fkParent??`${P}_id`;return u(k,"withCount (pivot table)"),u(g,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${k} WHERE ${k}.${g} = ${O}.${R})`},b$=(O,I,R)=>{if(!Z)return;u(R,`with${O[0]}${O.slice(1).toLowerCase()} (column)`);let M=String(G),C=Z.relations?.[M];if(!C)return;let P=Object.entries(C).find(([r,T0])=>T0&&typeof T0==="object"&&(I in T0));if(!P)return;let[A,k]=P,g=k[I],x=typeof g==="string"?g:g?.model||g?.target||g,b=Z.modelToTable[x]||x,l=Z.primaryKeys[M]??"id";u(b,`with${O} (target table)`);let $0=`${O}(${b}.${R})`,C0;if(A==="hasMany"||A==="hasOne"){let r=`${M.endsWith("s")?M.slice(0,-1):M}_id`;u(r,`with${O} (foreign key)`),C0=`(SELECT ${$0} FROM ${b} WHERE ${b}.${r} = ${M}.${l})`}else if(A==="belongsToMany"){let r=Z?PX(Z,M,I,{singularize:c,models:Z.models}):null,T0=c(M),X9=c(b),_9=r?.pivotTable??[T0,X9].sort().join("_"),_X=r?.fkParent??`${T0}_id`,_0=r?.fkRelated??`${X9}_id`,pX=Z.primaryKeys[b]??"id";u(_9,`with${O} (pivot table)`),u(_X,`with${O} (foreign key)`),u(_0,`with${O} (related key)`),C0=`(SELECT ${$0} FROM ${_9} JOIN ${b} ON ${b}.${pX} = ${_9}.${_0} WHERE ${_9}.${_X} = ${M}.${l})`}else return;K9(`${C0} AS ${I}_${O.toLowerCase()}_${R}`)},K5=()=>{if(B.size===0)return;let O=[];for(let[I,R]of B.entries()){let M=X0(I);if(!M)continue;for(let P of R)u(P,"withPivot");let C=R.map((P)=>`${M.pivotTable}.${P} AS pivot_${P}`);O.push(...C)}if(O.length>0){let I=O.join(", ");K9(I)}};return new Proxy({distinct(){return F=F.replace(/^SELECT\s+/i,"SELECT DISTINCT "),K=null,this},distinctOn(...O){let I=O.map(String).join(", ");return F=F.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${I}) `),K=null,this},selectRaw(O){let I=KX(O,"selectRaw(fragment)"),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${I}${F.substring(R)}`;else F+=`, ${I}`;return K=null,this},rowNumber(O="row_number",I,R){let M=[];if(I){let k=Array.isArray(I)?I:[I];M.push(`PARTITION BY ${k.join(", ")}`)}if(R&&R.length)M.push(`ORDER BY ${R.map(([k,g])=>`${k} ${g==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${O}`,A=F.indexOf(" FROM ");if(A!==-1)F=`${F.substring(0,A)}, ${P}${F.substring(A)}`;else F+=`, ${P}`;return K=null,this},denseRank(O="dense_rank",I,R){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(R&&R.length)C.push(`ORDER BY ${R.map(([g,x])=>`${g} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let A=`DENSE_RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,k=F.indexOf(" FROM ");if(k!==-1)F=`${F.substring(0,k)}, ${A}${F.substring(k)}`;else F+=`, ${A}`;return K=null,this},rank(O="rank",I,R){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(R&&R.length)C.push(`ORDER BY ${R.map(([g,x])=>`${g} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let A=`RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,k=F.indexOf(" FROM ");if(k!==-1)F=`${F.substring(0,k)}, ${A}${F.substring(k)}`;else F+=`, ${A}`;return K=null,this},over(O,I,R={}){return e0(O,I,R.partitionBy,R.orderBy),this},lag(O,I={}){let R=[O,String(I.offset??1)];if(I.defaultValue!==void 0)R.push(String(I.defaultValue));return e0(`LAG(${R.join(", ")})`,I.alias??`${O}_lag`,I.partitionBy,I.orderBy),this},lead(O,I={}){let R=[O,String(I.offset??1)];if(I.defaultValue!==void 0)R.push(String(I.defaultValue));return e0(`LEAD(${R.join(", ")})`,I.alias??`${O}_lead`,I.partitionBy,I.orderBy),this},sumOver(O,I={}){return e0(`SUM(${O})`,I.alias??`${O}_sum`,I.partitionBy,I.orderBy),this},avgOver(O,I={}){return e0(`AVG(${O})`,I.alias??`${O}_avg`,I.partitionBy,I.orderBy),this},countOver(O="*",I={}){return e0(`COUNT(${O})`,I.alias??"count_over",I.partitionBy,I.orderBy),this},minOver(O,I={}){return e0(`MIN(${O})`,I.alias??`${O}_min`,I.partitionBy,I.orderBy),this},maxOver(O,I={}){return e0(`MAX(${O})`,I.alias??`${O}_max`,I.partitionBy,I.orderBy),this},firstValue(O,I={}){return e0(`FIRST_VALUE(${O})`,I.alias??`${O}_first`,I.partitionBy,I.orderBy),this},lastValue(O,I={}){return e0(`LAST_VALUE(${O})`,I.alias??`${O}_last`,I.partitionBy,I.orderBy),this},selectAll(){return this},select(O){if(!O)return this;let I=Array.isArray(O)?O:[O];if(I.length===0)return this;let R=I.map(NY),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(F),C=M?M[1]:"",P=F.indexOf(" FROM ");if(P!==-1)F=`SELECT ${C}${R.join(", ")}${F.substring(P)}`;else F=`SELECT ${C}${R.join(", ")} FROM ${G}`;return K=null,this},addSelect(...O){if(!O.length)return this;let I=O.map(NY),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${I.join(", ")}${F.substring(R)}`;else F+=`, ${I.join(", ")}`;return K=null,this},with(...O){if(!Z||!O||O.length===0)return this;let I=[];for(let x of O){if(!x)continue;if(typeof x==="string")I.push({name:x});else if(typeof x==="object"&&!Array.isArray(x))for(let[b,l]of Object.entries(x))if(typeof l==="function")I.push({name:b,callback:l});else I.push({name:b})}if(I.length===0)return this;let R=f.relations.maxEagerLoad??50;if(I.length>R)throw Error(`[query-builder] Too many relationships to eager load (${I.length}). Maximum allowed: ${R}`);let M=String(G),C=new Set,P=new Set,A=new Map,k=(x)=>{let b=Z.relations?.[x];if(!b)return[];return[...Object.keys(b.hasOne||{}),...Object.keys(b.hasMany||{}),...Object.keys(b.belongsTo||{}),...Object.keys(b.belongsToMany||{}),...Object.keys(b.hasOneThrough||{}),...Object.keys(b.hasManyThrough||{}),...Object.keys(b.morphOne||{}),...Object.keys(b.morphMany||{}),...Object.keys(b.morphToMany||{}),...Object.keys(b.morphedByMany||{})]},g=(x,b,l=0,$0)=>{let C0=f.relations.maxDepth??10;if(l>=C0)throw Error(`[query-builder] Maximum relationship depth (${C0}) exceeded at '${b}'. Consider using separate queries or increasing maxDepth.`);let r=Z.relations?.[x];if(!r)return x;let T0=(Z0)=>{if(f.softDeletes?.enabled&&f.softDeletes?.defaultFilter){let Y0=f.softDeletes.column||"deleted_at";return` AND ${Z0}.${Y0} IS NULL`}return""},X9=(Z0)=>{if(!$0)return"";let Y0=[],M0=(z0,r0,I9)=>{u(String(z0),"with() constraint column");let QX=v0(r0,"with() constraint operator");Y0.push(`${Z0}.${String(z0)} ${QX} ${q9(I9)}`)},V0=(z0)=>()=>{throw Error(`[query-builder] with('${b}', ...): ${z0} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},w0={where:(z0,r0,I9)=>{if(Array.isArray(z0))M0(z0[0],z0[1],z0[2]);else if(z0&&typeof z0==="object")for(let QX of Object.keys(z0))M0(QX,"=",z0[QX]);else if(r0!==void 0&&I9!==void 0)M0(z0,r0,I9);else if(r0!==void 0)M0(z0,"=",r0);return w0},whereIn:(z0,r0)=>{return u(String(z0),"with() constraint column"),Y0.push(`${Z0}.${String(z0)} IN (${r0.map(q9).join(", ")})`),w0},whereNull:(z0)=>{return u(String(z0),"with() constraint column"),Y0.push(`${Z0}.${String(z0)} IS NULL`),w0},whereNotNull:(z0)=>{return u(String(z0),"with() constraint column"),Y0.push(`${Z0}.${String(z0)} IS NOT NULL`),w0},orderBy:V0("orderBy()"),limit:V0("limit()"),offset:V0("offset()"),take:V0("take()")};return $0(w0),Y0.length?` AND ${Y0.join(" AND ")}`:""},_9=()=>{let Z0=(V0)=>{let w0=V0?.[b];return w0?Z.modelToTable[w0]:void 0},Y0=(V0)=>{let w0=V0?.[b],z0=typeof w0==="string"?w0:w0?.model;return z0?Z.modelToTable[z0]:void 0},M0=(V0)=>{let w0=V0?.[b];return w0?.target?Z.modelToTable[w0.target]:void 0};return Z0(r?.hasOne)||Z0(r?.hasMany)||Z0(r?.belongsTo)||Y0(r?.belongsToMany)||M0(r?.hasOneThrough)||M0(r?.hasManyThrough)||Z0(r?.morphOne)||Z0(r?.morphMany)||Z0(r?.morphToMany)||Z0(r?.morphedByMany)},_X=_9()??(Z.modelToTable[b]||Z.tableToModel[b]?Z.modelToTable[b]??b:b),_0=String(_X);if(!_X||!_9()&&!Z.modelToTable[b]&&!Z.tableToModel[b]){let Z0=k(x);if(Z0.length>0&&!Z0.includes(b)){let Y0=` Available relationships: ${Z0.join(", ")}`;throw Error(`[query-builder] Relationship '${b}' not found on table '${x}'.${Y0}`)}}if(f.relations.detectCycles!==!1){let Z0=`${x}->${_0}`;if(C.has(Z0))throw Error(`[query-builder] Circular relationship detected: ${Z0}. This would cause an infinite loop.`);C.add(Z0)}if(!_0||_0===x)return x;let pX=r?.hasOneThrough?.[b]||r?.hasManyThrough?.[b];if(pX){let{through:Z0,target:Y0}=pX,M0=Z.modelToTable[Z0]||Z0,V0=Z.modelToTable[Y0]||Y0,w0=Z.primaryKeys[x]??"id",z0=Z.primaryKeys[M0]??"id",r0=`${c(x)}_id`,I9=`${c(M0)}_id`;return N(`LEFT JOIN ${M0} ON ${M0}.${r0} = ${x}.${w0} LEFT JOIN ${V0} ON ${V0}.${I9} = ${M0}.${z0}`),q.add(M0),q.add(V0),V0}if(Boolean(r?.belongsToMany?.[b])){let Z0=PX(Z,x,b,{singularize:c,models:Z.models}),Y0=Z0?.pivotTable??[c(x),c(_0)].sort().join("_"),M0=Z.primaryKeys[x]??"id",V0=Z.primaryKeys[_0]??"id",w0=Z0?.fkParent??`${c(x)}_id`,z0=Z0?.fkRelated??`${c(_0)}_id`;return N(`LEFT JOIN ${Y0} ON ${Y0}.${w0} = ${x}.${M0} LEFT JOIN ${_0} ON ${_0}.${V0} = ${Y0}.${z0}${X9(_0)}`),q.add(Y0),q.add(_0),_0}if(Boolean(r?.morphToMany?.[b])){let Z0=b,Y0=`${c(_0)}_${Z0}`,M0=Z.primaryKeys[x]??"id",V0=Z.primaryKeys[_0]??"id",w0=`${Z0}_type`,z0=`${Z0}_id`,r0=`${c(_0)}_id`,I9=q9(Z.tableToModel[x]||x);return N(`LEFT JOIN ${Y0} ON ${Y0}.${z0} = ${x}.${M0} AND ${Y0}.${w0} = ${I9} LEFT JOIN ${_0} ON ${_0}.${V0} = ${Y0}.${r0}`),q.add(Y0),q.add(_0),_0}if(Boolean(r?.morphedByMany?.[b])){let Z0=r.morphedByMany?.[b]||b,Y0=Z.modelToTable[Z0]||Z0,M0=c(x),V0=`${c(Y0)}_${M0}`,w0=Z.primaryKeys[x]??"id",z0=Z.primaryKeys[Y0]??"id",r0=`${M0}_type`,I9=`${M0}_id`,QX=`${c(Y0)}_id`,b7=q9(Z.tableToModel[Y0]||Y0);return N(`LEFT JOIN ${V0} ON ${V0}.${QX} = ${x}.${w0} LEFT JOIN ${Y0} ON ${Y0}.${z0} = ${V0}.${I9} AND ${V0}.${r0} = ${b7}`),q.add(V0),q.add(Y0),Y0}if(Boolean(r?.belongsTo?.[b])){let Z0=`${c(_0)}_id`,Y0=Z.primaryKeys[_0]??"id";return N(`LEFT JOIN ${_0} ON ${x}.${Z0} = ${_0}.${Y0}${X9(_0)}`),q.add(_0),_0}let x7=Boolean(r?.morphOne?.[b]),B7=Boolean(r?.morphMany?.[b]);if(x7||B7){let Z0=`${b}_type`,Y0=`${b}_id`,M0=Z.primaryKeys[x]??"id",V0=q9(Z.tableToModel[x]||x);return N(`LEFT JOIN ${_0} ON ${_0}.${Y0} = ${x}.${M0} AND ${_0}.${Z0} = ${V0}`),q.add(_0),_0}let y7=`${c(x)}_id`,h7=Z.primaryKeys[x]??"id",v7=`${T0(_0)}${X9(_0)}`;return N(`LEFT JOIN ${_0} ON ${_0}.${y7} = ${x}.${h7}${v7}`),q.add(_0),_0};for(let x of I){let b=x.name.trim();if(x.callback)A.set(b,x.callback);let l=b.split("."),$0=M,C0=0;for(let r of l){if(!r||r.trim().length===0)continue;let T0=r.trim(),X9=A.get(T0);$0=g($0,T0,C0,X9)||$0,C0++}P.add(b)}if(B.size>0){let x=[];for(let[b,l]of B.entries()){let $0=X0(b);if(!$0)continue;let C0=l.map((r)=>`${$0.pivotTable}.${r} AS pivot_${r}`);x.push(...C0)}if(x.length>0){let b=x.join(", ");K9(b)}}return K=null,this},whereHas(O,I){if(!Z)return this;let R=String(G),M=Z.relations?.[R];if(!M)throw Error(`[query-builder] No relationships defined for table '${R}'`);let C=Object.entries(M).find(([l,$0])=>$0&&typeof $0==="object"&&(O in $0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${R}'`);let[P,A]=C,k=A[O],g=typeof k==="string"?k:k?.model||k?.target||k,x=Z.modelToTable[g]||g,b;if(P==="hasMany"||P==="hasOne"){let l=Z.primaryKeys[R]??"id";b=UX(R,x,l,I)}else if(P==="belongsTo"){let l=Z.primaryKeys[x]??"id";b=h$(R,x,l,I)}else if(P==="belongsToMany"){let l=Z.primaryKeys[R]??"id",$0=Z.primaryKeys[x]??"id";b=v$(R,x,l,$0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${P}' for whereHas`);K=W`${D()} WHERE EXISTS (${W([b])})`;try{w("WHERE",`EXISTS (${b})`)}catch{}return this},whereDoesntHave(O,I){if(!Z)return this;let R=String(G),M=Z.relations?.[R];if(!M)throw Error(`[query-builder] No relationships defined for table '${R}'`);let C=Object.entries(M).find(([l,$0])=>$0&&typeof $0==="object"&&(O in $0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${R}'`);let[P,A]=C,k=A[O],g=typeof k==="string"?k:k?.model||k?.target||k,x=Z.modelToTable[g]||g,b;if(P==="hasMany"||P==="hasOne"){let l=Z.primaryKeys[R]??"id";b=UX(R,x,l,I)}else if(P==="belongsTo"){let l=Z.primaryKeys[x]??"id";b=h$(R,x,l,I)}else if(P==="belongsToMany"){let l=Z.primaryKeys[R]??"id",$0=Z.primaryKeys[x]??"id";b=v$(R,x,l,$0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${P}' for whereDoesntHave`);K=W`${D()} WHERE NOT EXISTS (${W([b])})`;try{w("WHERE",`NOT EXISTS (${b})`)}catch{}return this},has(O){if(!Z)return this;let I=String(G),R=Z.relations?.[I];if(!R)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(R).find(([b,l])=>l&&typeof l==="object"&&(O in l));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,P]=M,A=P[O],k=typeof A==="string"?A:A?.model||A?.target||A,g=Z.modelToTable[k]||k,x;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";x=UX(I,g,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[g]??"id";x=h$(I,g,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",l=Z.primaryKeys[g]??"id";x=v$(I,g,b,l,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for has`);K=W`${D()} WHERE EXISTS (${W([x])})`;try{w("WHERE",`EXISTS (${x})`)}catch{}return this},doesntHave(O){if(!Z)return this;let I=String(G),R=Z.relations?.[I];if(!R)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(R).find(([b,l])=>l&&typeof l==="object"&&(O in l));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,P]=M,A=P[O],k=typeof A==="string"?A:A?.model||A?.target||A,g=Z.modelToTable[k]||k,x;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";x=UX(I,g,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[g]??"id";x=h$(I,g,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",l=Z.primaryKeys[g]??"id";x=v$(I,g,b,l,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for doesntHave`);K=W`${D()} WHERE NOT EXISTS (${W([x])})`;try{w("WHERE",`NOT EXISTS (${x})`)}catch{}return this},withCount(...O){if(!Z||!O||O.length===0)return this;let I=String(G);for(let R of O){let M=Z.relations?.[I];if(!M)continue;let C=Object.entries(M).find(([C0,r])=>r&&typeof r==="object"&&(R in r));if(!C)continue;let[P,A]=C,k=A[R],g=typeof k==="string"?k:k?.model||k?.target||k,x=Z.modelToTable[g]||g,b=Z.primaryKeys[I]??"id",l;if(P==="hasMany"||P==="hasOne")l=A7(I,x,b);else if(P==="belongsToMany")l=k7(I,x,b,R);else continue;let $0=`${R}_count`;K9(`${l} AS ${$0}`)}return this},withSum(O,I){return b$("SUM",O,I),this},withAvg(O,I){return b$("AVG",O,I),this},withMax(O,I){return b$("MAX",O,I),this},withMin(O,I){return b$("MIN",O,I),this},applyPivotColumns(){return K5(),this},withPivot(O,...I){if(!Z)return this;let R=String(G),M=X0(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${R}'`);let C=I&&I.length>0?I:M.hasConfig?M.pivotColumns:[];if(C.length===0)return this;if(B.set(O,C),M.hasConfig)v.add(O);return K5(),this},wherePivot(O,I,R,M){if(!Z)return this;let C=X0(O);if(!C)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(C.pivotTable,"wherePivot (pivot table)"),u(I,"wherePivot (column)"),u0(C);let P=M===void 0?"=":String(R),A=M===void 0?R:M,k=y.length+1,g=`${C.pivotTable}.${I} ${P} ${i(k)}`;o.push(g),y.push(A);let x=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${x} ${g}`,K=null,C.hasConfig)v.add(O);return this},wherePivotIn(O,I,R){if(!Z||!Array.isArray(R)||R.length===0)return this;let M=X0(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(M.pivotTable,"wherePivotIn (pivot table)"),u(I,"wherePivotIn (column)"),u0(M);let C=h0(R.length,y.length+1),P=`${M.pivotTable}.${I} IN (${C})`;o.push(P),y.push(...R);let A=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${A} ${P}`,K=null,M.hasConfig)v.add(O);return this},wherePivotNotIn(O,I,R){if(!Z||!Array.isArray(R)||R.length===0)return this;let M=X0(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(M.pivotTable,"wherePivotNotIn (pivot table)"),u(I,"wherePivotNotIn (column)"),u0(M);let C=h0(R.length,y.length+1),P=`${M.pivotTable}.${I} NOT IN (${C})`;o.push(P),y.push(...R);let A=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${A} ${P}`,K=null,M.hasConfig)v.add(O);return this},wherePivotNull(O,I){if(!Z)return this;let R=X0(O);if(!R)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(R.pivotTable,"wherePivotNull (pivot table)"),u(I,"wherePivotNull (column)"),u0(R);let M=`${R.pivotTable}.${I} IS NULL`;o.push(M);let C=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,K=null,R.hasConfig)v.add(O);return this},wherePivotNotNull(O,I){if(!Z)return this;let R=X0(O);if(!R)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(R.pivotTable,"wherePivotNotNull (pivot table)"),u(I,"wherePivotNotNull (column)"),u0(R);let M=`${R.pivotTable}.${I} IS NOT NULL`;o.push(M);let C=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,K=null,R.hasConfig)v.add(O);return this},where(O,I,R){let M=()=>s.WHERE.test(F)?"AND":"WHERE";if(typeof O==="string"&&I!==void 0){u(String(O),"where(column)"),v0(I,"where(operator)");let C=String(I).toLowerCase();if(C==="in"||C==="not in"){let A=Array.isArray(R)?R:[R],k=h0(A.length,y.length+1),g=`${String(O)} ${C.toUpperCase()} (${k})`;return o.push(g),y.push(...A),F=`${F} ${M()} ${g}`,K=null,this}let P=y.length+1;return o.push(`${String(O)} ${String(I)} ${i(P)}`),y.push(R),F=`${F} ${M()} ${String(O)} ${String(I)} ${i(P)}`,K=null,this}if(Array.isArray(O)){let[C,P,A]=O,k=String(C);u(k,"where(column)");let g=v0(P,"where(operator)");if(g==="in"||g==="not in"){let x=Array.isArray(A)?A:[A],b=h0(x.length,y.length+1);o.push(`${k} ${g.toUpperCase()} (${b})`),y.push(...x),F=`${F} ${M()} ${k} ${g.toUpperCase()} (${b})`,K=null}else{let x=y.length+1;o.push(`${k} ${g} ${i(x)}`),y.push(A),F=`${F} ${M()} ${k} ${g} ${i(x)}`,K=null}return this}if(O&&typeof O==="object"&&!d8(O)){let C=O,P=Object.keys(C),A=[];for(let k of P){u(k,"where(column)");let g=C[k];if(Array.isArray(g)){let x=h0(g.length,y.length+1);A.push(`${k} IN (${x})`),o.push(`${k} IN (${x})`),y.push(...g)}else{let x=y.length+1;A.push(`${k} = ${i(x)}`),o.push(`${k} = ${i(x)}`),y.push(g)}}if(A.length>0)F=`${F} ${M()} ${A.join(" AND ")}`,K=null;return this}if(d8(O))return o.push(O.raw),F=`${F} ${M()} ${O.raw}`,K=null,this;return this},whereNull(O){u(String(O),"whereNull(column)");let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NULL`,K=null,this},whereNotNull(O){u(String(O),"whereNotNull(column)");let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NOT NULL`,K=null,this},whereBetween(O,I,R){u(String(O),"whereBetween(column)");let M=s.WHERE.test(F)?"AND":"WHERE",C=y.length+1;return F=`${F} ${M} ${String(O)} BETWEEN ${i(C)} AND ${i(C+1)}`,y.push(I,R),K=null,this},whereExists(O){let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} EXISTS (${O.toSQL()})`,K=null,this},whereJsonContains(O,I){u(String(O),"whereJsonContains(column)");let R=s.WHERE.test(F)?"AND":"WHERE",M=f.dialect,C=y.length+1;if(M==="postgres"){if(f.sql?.jsonContainsMode==="function")F+=` ${R} jsonb_contains(${O}, ${i(C)})`;else F+=` ${R} ${O} @> ${i(C)}`;y.push(JSON.stringify(I))}else if(W0(M))F+=` ${R} JSON_CONTAINS(${O}, ${i(C)})`,y.push(JSON.stringify(I));else if(Array.isArray(I)){let P=I.map((A,k)=>`EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${i(C+k)})`);F+=` ${R} (${P.join(" AND ")})`;for(let A of I)y.push(A)}else if(I!==null&&typeof I==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else F+=` ${R} EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${i(C)})`,y.push(I);return K=null,this},whereJsonPath(O,I,R){if(v0(I,"whereJsonPath(op)"),typeof O!=="string"||O.length===0||O.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof O==="string"?`'${O.slice(0,32)}...'`:typeof O}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(O))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${O}' \u2014 contains characters outside the allowed JSON-path set`);let M=f.dialect,C=s.WHERE.test(F)?"AND":"WHERE",P=y.length+1;if(M==="postgres")F+=` ${C} ${O} ${I} ${i(P)}`;else if(W0(M))F+=` ${C} JSON_EXTRACT(${O}) ${I} ${i(P)}`;else F+=` ${C} json_extract(${O}) ${I} ${i(P)}`;return y.push(R),K=null,this},whereLike(O,I,R=!1){let M=i(y.length+1);return w("WHERE",`${R?String(O):`LOWER(${String(O)})`} LIKE ${R?M:`LOWER(${M})`}`),y.push(I),K=null,this},whereILike(O,I){let R=i(y.length+1);if(f.dialect==="postgres")w("WHERE",`${String(O)} ILIKE ${R}`);else w("WHERE",`LOWER(${String(O)}) LIKE LOWER(${R})`);return y.push(I),K=null,this},orWhereLike(O,I,R=!1){let M=i(y.length+1);return w("OR",`${R?String(O):`LOWER(${String(O)})`} LIKE ${R?M:`LOWER(${M})`}`),y.push(I),K=null,this},orWhereILike(O,I){let R=i(y.length+1);if(f.dialect==="postgres")w("OR",`${String(O)} ILIKE ${R}`);else w("OR",`LOWER(${String(O)}) LIKE LOWER(${R})`);return y.push(I),K=null,this},whereNotLike(O,I,R=!1){let M=i(y.length+1);return w("WHERE",`${R?String(O):`LOWER(${String(O)})`} NOT LIKE ${R?M:`LOWER(${M})`}`),y.push(I),K=null,this},whereNotILike(O,I){let R=i(y.length+1);if(f.dialect==="postgres")w("WHERE",`${String(O)} NOT ILIKE ${R}`);else w("WHERE",`LOWER(${String(O)}) NOT LIKE LOWER(${R})`);return y.push(I),K=null,this},orWhereNotLike(O,I,R=!1){let M=i(y.length+1);return w("OR",`${R?String(O):`LOWER(${String(O)})`} NOT LIKE ${R?M:`LOWER(${M})`}`),y.push(I),K=null,this},orWhereNotILike(O,I){let R=i(y.length+1);if(f.dialect==="postgres")w("OR",`${String(O)} NOT ILIKE ${R}`);else w("OR",`LOWER(${String(O)}) NOT LIKE LOWER(${R})`);return y.push(I),K=null,this},whereAny(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=y.length+1,P=O.map((A,k)=>`${A} ${I} ${i(C+k)}`);F+=` ${M} (${P.join(" OR ")})`;for(let A=0;A<O.length;A++)y.push(R);return K=null,this},whereAll(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=y.length+1,P=O.map((A,k)=>`${A} ${I} ${i(C+k)}`);F+=` ${M} (${P.join(" AND ")})`;for(let A=0;A<O.length;A++)y.push(R);return K=null,this},whereNone(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=y.length+1,P=O.map((A,k)=>`${A} ${I} ${i(C+k)}`);F+=` ${M} NOT (${P.join(" OR ")})`;for(let A=0;A<O.length;A++)y.push(R);return K=null,this},whereNotBetween(O,I,R){u(String(O),"whereNotBetween(column)");let M=s.WHERE.test(F)?"AND":"WHERE",C=y.length+1;return F+=` ${M} ${O} NOT BETWEEN ${i(C)} AND ${i(C+1)}`,y.push(I,R),K=null,this},whereDate(O,I,R){u(O,"whereDate(column)");let M=R instanceof Date?R.toISOString():typeof R==="string"?R:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof R}`)})(),C=s.WHERE.test(F)?"AND":"WHERE",P=y.length+1;return F+=` ${C} ${O} ${I} ${i(P)}`,y.push(M),K=null,this},whereRaw(O){let I=KX(O,"whereRaw(fragment)"),R=s.WHERE.test(F)?"AND":"WHERE";return F+=` ${R} ${I}`,K=null,this},whereColumn(O,I,R){u(O,"whereColumn(left)"),u(R,"whereColumn(right)");let M=s.WHERE.test(F)?"AND":"WHERE";return F+=` ${M} ${O} ${I} ${R}`,K=null,this},orWhereColumn(O,I,R){return u(O,"orWhereColumn(left)"),u(R,"orWhereColumn(right)"),F+=` OR ${O} ${I} ${R}`,K=null,this},whereIn(O,I){u(String(O),"whereIn(column)");let R=s.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=h0(I.length,y.length+1);F+=` ${R} ${O} IN (${M})`,y.push(...I)}else F+=` ${R} ${O} IN (${String(I.toSQL())})`;return K=null,this},orWhereIn(O,I){if(u(String(O),"orWhereIn(column)"),Array.isArray(I)){let R=h0(I.length,y.length+1);F+=` OR ${O} IN (${R})`,y.push(...I)}else F+=` OR ${O} IN (${String(I.toSQL())})`;return K=null,this},whereNotIn(O,I){u(String(O),"whereNotIn(column)");let R=s.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=h0(I.length,y.length+1);F+=` ${R} ${O} NOT IN (${M})`,y.push(...I)}else F+=` ${R} ${O} NOT IN (${String(I.toSQL())})`;return K=null,this},orWhereNotIn(O,I){if(u(String(O),"orWhereNotIn(column)"),Array.isArray(I)){let R=h0(I.length,y.length+1);F+=` OR ${O} NOT IN (${R})`,y.push(...I)}else F+=` OR ${O} NOT IN (${String(I.toSQL())})`;return K=null,this},whereNested(O){let I=s.WHERE.test(F)?"AND":"WHERE",R=O.toSQL?String(O.toSQL()):String(O);return F+=` ${I} (${R})`,K=null,this},orWhereNested(O){let I=O.toSQL?String(O.toSQL()):String(O);return F+=` OR (${I})`,K=null,this},andWhere(O,I,R){if(typeof O==="string"&&I!==void 0){u(String(O),"andWhere(column)"),v0(I,"andWhere(operator)");let M=y.length+1;return o.push(`${String(O)} ${String(I)} ${i(M)}`),y.push(R),F=`${F} AND ${String(O)} ${String(I)} ${i(M)}`,K=null,this}if(Array.isArray(O)){let[M,C,P]=O,A=String(M);u(A,"andWhere(column)");let k=v0(C,"andWhere(operator)");if(k==="in"||k==="not in"){let g=Array.isArray(P)?P:[P],x=h0(g.length,y.length+1);o.push(`${A} ${k.toUpperCase()} (${x})`),y.push(...g),F=`${F} AND ${A} ${k.toUpperCase()} (${x})`,K=null}else{let g=y.length+1;o.push(`${A} ${k} ${i(g)}`),y.push(P),F=`${F} AND ${A} ${k} ${i(g)}`,K=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let P of M){let A=O[P];if(Array.isArray(A)){let k=h0(A.length,y.length+1);C.push(`${P} IN (${k})`),o.push(`${P} IN (${k})`),y.push(...A)}else{let k=y.length+1;C.push(`${P} = ${i(k)}`),o.push(`${P} = ${i(k)}`),y.push(A)}}if(C.length>0)F=`${F} AND ${C.join(" AND ")}`,K=null;return this}if(O&&typeof O.raw<"u")return o.push(O.raw),F=`${F} AND ${O.raw}`,K=null,this;return this},orWhere(O,I,R){if(typeof O==="string"&&I!==void 0){u(String(O),"orWhere(column)"),v0(I,"orWhere(operator)");let M=y.length+1;return o.push(`OR ${String(O)} ${String(I)} ${i(M)}`),y.push(R),F=`${F} OR ${String(O)} ${String(I)} ${i(M)}`,K=null,this}if(Array.isArray(O)){let[M,C,P]=O,A=String(M);u(A,"orWhere(column)");let k=v0(C,"orWhere(operator)");if(k==="in"||k==="not in"){let g=Array.isArray(P)?P:[P],x=h0(g.length,y.length+1);o.push(`OR ${A} ${k.toUpperCase()} (${x})`),y.push(...g),F=`${F} OR ${A} ${k.toUpperCase()} (${x})`,K=null}else{let g=y.length+1;o.push(`OR ${A} ${k} ${i(g)}`),y.push(P),F=`${F} OR ${A} ${k} ${i(g)}`,K=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let P of M){let A=O[P];if(Array.isArray(A)){let k=h0(A.length,y.length+1);C.push(`${P} IN (${k})`),o.push(`OR ${P} IN (${k})`),y.push(...A)}else{let k=y.length+1;C.push(`${P} = ${i(k)}`),o.push(`OR ${P} = ${i(k)}`),y.push(A)}}if(C.length>0)F=`${F} OR ${C.join(" AND ")}`,K=null;return this}if(O&&typeof O.raw<"u")return o.push(`OR ${O.raw}`),F=`${F} OR ${O.raw}`,K=null,this;return this},orderBy(O,I="asc"){let R=I==="asc"?"ASC":"DESC";return F=s.ORDER_BY.test(F)?`${F}, ${O} ${R}`:`${F} ORDER BY ${O} ${R}`,K=null,this},orderByDesc(O){return F=s.ORDER_BY.test(F)?`${F}, ${O} DESC`:`${F} ORDER BY ${O} DESC`,K=null,this},inRandomOrder(){let O=f.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return F=s.ORDER_BY.test(F)?`${F}, ${O}`:`${F} ORDER BY ${O}`,K=null,this},reorder(O,I="asc"){return F=F.replace(/ORDER BY[\s\S]*$/i,""),F+=` ORDER BY ${O} ${I==="asc"?"ASC":"DESC"}`,K=null,this},latest(O){let I=O??f.timestamps.defaultOrderColumn;return F=s.ORDER_BY.test(F)?`${F}, ${I} DESC`:`${F} ORDER BY ${I} DESC`,K=null,this},oldest(O){let I=O??f.timestamps.defaultOrderColumn;return F=s.ORDER_BY.test(F)?`${F}, ${I} ASC`:`${F} ORDER BY ${I} ASC`,K=null,this},limit(O){if(!Number.isFinite(O)||O<0||!Number.isInteger(O))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${O}`);return F=s.LIMIT.test(F)?F.replace(s.LIMIT,` LIMIT ${O}`):`${F} LIMIT ${O}`,K=null,this},offset(O){if(!Number.isFinite(O)||O<0||!Number.isInteger(O))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${O}`);return F=s.OFFSET.test(F)?F.replace(s.OFFSET,` OFFSET ${O}`):`${F} OFFSET ${O}`,K=null,this},join(O,I,R,M){return u(O,"join(table)"),Q9(I,"join(onLeft)"),Q9(M,"join(onRight)"),v0(R,"join(operator)"),N(`JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},joinSub(O,I,R,M,C){return u(I,"joinSub(alias)"),Q9(R,"joinSub(onLeft)"),Q9(C,"joinSub(onRight)"),v0(M,"joinSub(operator)"),N(`JOIN (${String(O.toSQL())}) AS ${I} ON ${R} ${M} ${C}`),q.add(I),this},innerJoin(O,I,R,M){return u(O,"innerJoin(table)"),Q9(I,"innerJoin(onLeft)"),Q9(M,"innerJoin(onRight)"),v0(R,"innerJoin(operator)"),N(`INNER JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},leftJoin(O,I,R,M){return u(O,"leftJoin(table)"),Q9(I,"leftJoin(onLeft)"),Q9(M,"leftJoin(onRight)"),v0(R,"leftJoin(operator)"),N(`LEFT JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},leftJoinSub(O,I,R,M,C){return u(I,"leftJoinSub(alias)"),Q9(R,"leftJoinSub(onLeft)"),Q9(C,"leftJoinSub(onRight)"),v0(M,"leftJoinSub(operator)"),N(`LEFT JOIN (${String(O.toSQL())}) AS ${I} ON ${R} ${M} ${C}`),q.add(I),this},rightJoin(O,I,R,M){return u(O,"rightJoin(table)"),Q9(I,"rightJoin(onLeft)"),Q9(M,"rightJoin(onRight)"),v0(R,"rightJoin(operator)"),N(`RIGHT JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},crossJoin(O){return u(O,"crossJoin(table)"),N(`CROSS JOIN ${O}`),q.add(O),this},crossJoinSub(O,I){return u(I,"crossJoinSub(alias)"),N(`CROSS JOIN (${String(O.toSQL())}) AS ${I}`),q.add(I),this},selectAllRelations(){if(!Y)return this;let O=String(G),I=Object.keys(Y[O]?.columns??{}),R=[];if(I.length>0)R.push(W`${W(O)}.*`);for(let M of q){let C=Object.keys(Y[M]?.columns??{});for(let P of C){let A=f.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${P}`.replace(/_([a-z])/g,(k,g)=>g.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${P}`:`${M}_${P}`;R.push(W`${W(`${M}.${P}`)} AS ${W(A)}`)}}if(R.length>0){let M=I.length>0?`${O}.*`:"",C=[];for(let k of q){let g=Object.keys(Y[k]?.columns??{});for(let x of g){let b=f.aliasing.relationColumnAliasFormat==="camelCase"?`${k}_${x}`.replace(/_([a-z])/g,(l,$0)=>$0.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${k}.${x}`:`${k}_${x}`;C.push(`${k}.${x} AS ${b}`)}}let P=[M,...C].filter(Boolean).join(", "),A=F.indexOf(" FROM ");if(A!==-1)F=`SELECT ${P}${F.substring(A)}`;else F=`SELECT ${P} FROM ${O}`;K=null}return this},groupBy(...O){if(O.length)F=s.GROUP_BY.test(F)?`${F}, ${O.join(", ")}`:`${F} GROUP BY ${O.join(", ")}`,K=null;return this},groupByRaw(O){let I=KX(O,"groupByRaw(fragment)");return F=s.GROUP_BY.test(F)?`${F}, ${I}`:`${F} GROUP BY ${I}`,K=null,this},having(O){let I=/\bHAVING\b/i.test(F)?"AND":"HAVING";if(Array.isArray(O)){let R=y.length+1;F=`${F} ${I} ${O[0]} ${O[1]} ${i(R)}`,y.push(O[2]),K=null}else if(O&&typeof O==="object"&&!("raw"in O)){let R=Object.keys(O),M=R.length;if(M){let C=y.length,P=Array.from({length:M});for(let A=0;A<M;A++){let k=R[A];P[A]=`${k} = ${i(C+A+1)}`,y.push(O[k])}F=`${F} ${I} ${P.join(" AND ")}`,K=null}}else if(O&&typeof O.raw<"u")F+=` ${I} ${O.raw}`,K=null;return this},havingRaw(O){let I=KX(O,"havingRaw(fragment)"),R=/\bHAVING\b/i.test(F)?"AND":"HAVING";return F+=` ${R} ${I}`,K=null,this},orderByRaw(O){let I=KX(O,"orderByRaw(fragment)");return F=s.ORDER_BY.test(F)?`${F}, ${I}`:`${F} ORDER BY ${I}`,K=null,this},union(O){return T("UNION",O),this},unionAll(O){return T("UNION ALL",O),this},intersect(O){return T("INTERSECT",O),this},intersectAll(O){return T("INTERSECT ALL",O),this},except(O){return T("EXCEPT",O),this},exceptAll(O){return T("EXCEPT ALL",O),this},forPage(O,I){let R=Math.max(1,Math.floor(O)),M=Math.max(1,Math.floor(I));return F+=` LIMIT ${M} OFFSET ${(R-1)*M}`,K=null,this},toSQL(){let O=X8(F);return{sql:O,toString:()=>O,execute:()=>D().execute(),values:()=>D().values(),raw:()=>D().raw()}},async value(O){let I=W`${D()} LIMIT 1`,R=await j(I,"select",{signal:S,timeoutMs:H}),[M]=R;return M?.[O]},async pluck(O,I){let R=await j(D(),"select",{signal:S,timeoutMs:H});if(I){let M={};for(let C of R){let P=String(C?.[I]);if(Object.prototype.hasOwnProperty.call(M,P))throw Error(`[query-builder] pluck(${O}, ${I}): duplicate key '${P}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);M[P]=C?.[O]}return M}return R.map((M)=>M?.[O])},async exists(){let O=W`SELECT EXISTS (${D()}) as e`,I=await j(O,"select",{signal:S,timeoutMs:H}),[R]=I;return Boolean(R?.e)},async doesntExist(){return!await this.exists()},async paginate(O,I=1,R={}){if(!Number.isFinite(O)||O<=0||!Number.isInteger(O))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${O}`);if(!Number.isFinite(I)||I<1||!Number.isInteger(I))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${I}`);if(R.tx){let l=X8(F),$0=[...y],C0=await R.tx.unsafe(`SELECT COUNT(*) as c FROM (${l}) as sub`,$0),r=Number(C0?.[0]?.c??0),T0=Math.max(1,Math.ceil(r/O)),X9=Math.max(1,Math.min(I,T0)),_9=(X9-1)*O;return{data:await R.tx.unsafe(`${l} LIMIT ${O} OFFSET ${_9}`,$0),meta:{perPage:O,page:X9,total:r,lastPage:T0}}}let M=W`SELECT COUNT(*) as c FROM (${D()}) as sub`,C=await j(M,"select",{signal:S,timeoutMs:H}),[P]=C,A=Number(P?.c??0),k=Math.max(1,Math.ceil(A/O)),g=Math.max(1,Math.min(I,k)),x=(g-1)*O;return{data:await j(W`${D()} LIMIT ${O} OFFSET ${x}`,"select",{signal:S,timeoutMs:H}),meta:{perPage:O,page:g,total:A,lastPage:k}}},async simplePaginate(O,I=1){let R=Math.max(1,I),M=(R-1)*O,C=await j(W`${D()} LIMIT ${O+1} OFFSET ${M}`,"select",{signal:S,timeoutMs:H}),P=C.length>O;return{data:P?C.slice(0,O):C,meta:{perPage:O,page:R,hasMore:P}}},async cursorPaginate(O,I,R="id",M="asc"){let C=D();if(I!==void 0&&I!==null)if(Array.isArray(R)){let l=R.map((T0)=>W(String(T0))),$0=M==="asc"?W`>`:W`<`,C0=W`(${W(l)})`,r=W`(${W(I)})`;C=W`${C} WHERE ${C0} ${$0} ${r}`}else C=M==="asc"?W`${C} WHERE ${W(String(R))} > ${I}`:W`${C} WHERE ${W(String(R))} < ${I}`;if(Array.isArray(R)){let $0=R.map((C0)=>W`${W(String(C0))} ${M==="asc"?W`ASC`:W`DESC`}`).reduce((C0,r,T0)=>T0===0?r:W`${C0}, ${r}`);C=W`${C} ORDER BY ${$0} LIMIT ${O+1}`}else C=W`${C} ORDER BY ${W(String(R))} ${M==="asc"?W`ASC`:W`DESC`} LIMIT ${O+1}`;let P=await j(C,"select",{signal:S,timeoutMs:H}),A=P.length>O,k=P.slice(0,O),g=k[k.length-1],x=A&&g?Array.isArray(R)?R.map((l)=>g[l]):g[R]:null,b=k.length?Array.isArray(R)?R.map((l)=>k[0]?.[l]):k[0]?.[R]:null;return{data:k,meta:{perPage:O,nextCursor:x??null,prevCursor:b}}},async chunk(O,I){let R=1;while(!0){let{data:M,meta:C}=await this.paginate(O,R);if(M.length===0)break;if(await I(M),R>=C.lastPage)break;R+=1}},async chunkById(O,I="id",R){let M;while(!0){let{data:C,meta:P}=await this.cursorPaginate(O,M,I,"asc");if(C.length===0)break;if(R)await R(C);if(M=P.nextCursor,!M)break}},async eachById(O,I="id",R){await this.chunkById(O,I,async(M)=>{for(let C of M)await R?.(C)})},withTimeout(O){return H=Math.max(1,Math.floor(O)),this},abort(O){return S=O,this},withTrashed(){return h=!0,p=!1,this},onlyTrashed(){h=!0,p=!0;let O=f.softDeletes?.column||"deleted_at",I=(C,P)=>{let A=C.toUpperCase(),k=0;for(let g=0;g<C.length;g++){let x=C[g];if(x==="(")k++;else if(x===")")k--;else if(k===0&&A.substring(g,g+5)==="WHERE"&&(g===0||/\s/.test(C[g-1]??""))&&/\s/.test(C[g+5]??""))return`${C.substring(0,g)}WHERE ${P} AND ${C.substring(g+6)}`}return`${C} WHERE ${P}`},R=`${G}.${O} IS NOT NULL`;F=I(F,R);let M=String(D());return K=W([I(M,R)]),this},scope(O,I){let R=String(G),C=Z?.scopes?.[R]?.[O];if(C)return C(this,I);return this},when(O,I,R){if(O)return I(this);if(R)return R(this);return this},tap(O){return O(this),this},dump(){return console.log(String(D())),this},dd(){throw console.log(String(D())),Error("Dump and Die")},cache(O=60000){return n=O,d=!0,this},async explain(){let O=W`EXPLAIN ${D()}`;return await j(O,"select",{signal:S,timeoutMs:H})},simple(){return D().simple()},toText(){return F},async get(){let O=f.hooks,I=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan||uX(O));if(!f.softDeletes?.enabled&&!d&&!H&&!S&&!I){let P=$._prepareStatement;if(P){let A=P(F);return q0(y.length>0?A.all(...y):A.all())}}if(K=y.length>0?$.unsafe(F,y):$.unsafe(F),!f.softDeletes?.enabled&&!d&&!H&&!S&&!I){let P=D()._stmt,A=D()._params;if(P)return q0(A&&A.length>0?P.all(...A):P.all());return q0(await D().execute())}if(!f.softDeletes?.enabled&&!d&&!H&&!S)return q0(await j(D(),"select"));let R=D();if(f.softDeletes?.enabled&&f.softDeletes.defaultFilter&&!h){let P=f.softDeletes.column,A=String(G);if((Y?Boolean(Y[A]?.columns?.[P]):!0)&&!s.DELETED_AT.test(F))R=W`${D()} WHERE ${W(String(P))} IS ${p?W`NOT NULL`:W`NULL`}`,w("WHERE",`${String(P)} IS ${p?"NOT ":""}NULL`)}let M=d?`${String(R)}\x00${JSON.stringify(y)}`:"";if(d){let P=S$.get(M);if(P)return P}let C=await j(R,"select",{signal:S,timeoutMs:H});if(d)S$.set(M,C,n);return q0(C)},async executeTakeFirst(){let O=await j(D(),"select",{signal:S,timeoutMs:H});return e(Array.isArray(O)?O[0]:O)},async executeTakeFirstOrThrow(){let O=await this.executeTakeFirst();if(!O)throw Error("Record not found");return O},async first(){let O=f.hooks,I=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan||uX(O));if(!f.softDeletes?.enabled&&!d&&!H&&!S&&!I){let C=$._prepareStatement;if(C){let P=F.includes(" LIMIT ")?F:`${F} LIMIT 1`,A=C(P),k=y.length>0?A.all(...y):A.all();return e(k[0])}}let R=await j(W`${D()} LIMIT 1`,"select",{signal:S,timeoutMs:H}),[M]=R;return e(M)},async firstOrFail(){let O=await this.first();if(!O)throw Error("Record not found");return O},async find(O){let I=Z?.primaryKeys[String(G)]??"id",R=await j(W`${D()} WHERE ${W(I)} = ${O} LIMIT 1`,"select",{signal:S,timeoutMs:H}),[M]=R;return M},async findOrFail(O){let I=await this.find(O);if(!I)throw Error("Record not found");return I},async findMany(O){let I=Z?.primaryKeys[String(G)]??"id";return await j(W`${D()} WHERE ${W(String(I))} IN ${W(O)}`,"select",{signal:S,timeoutMs:H})},async*lazy(){let O,I=Z?.primaryKeys[String(G)]??"id";while(!0){let M=await(O==null?W`${D()} ORDER BY ${W(String(I))} ASC LIMIT 100`:W`${D()} WHERE ${W(String(I))} > ${O} ORDER BY ${W(String(I))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let C of M)yield C;if(O=M[M.length-1]?.[I],O==null)break}},async*lazyById(){let O=Z?.primaryKeys[String(G)]??"id",I;while(!0){let M=await(I==null?W`${D()} ORDER BY ${W(String(O))} ASC LIMIT 100`:W`${D()} WHERE ${W(String(O))} > ${I} ORDER BY ${W(String(O))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let C of M)yield C;if(I=M[M.length-1]?.[O],I==null)break}},pipe(O){return O(this)},async count(){let O=F.indexOf(" FROM "),I=/ GROUP BY /i.test(F),R;if(I)R=`SELECT COUNT(*) as c FROM (${F}) AS _bqb_count_sub`;else if(O!==-1)R=`SELECT COUNT(*) as c${F.substring(O)}`;else R=`SELECT COUNT(*) as c FROM ${G}`;let M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||uX(M));if(!f.softDeletes?.enabled&&!d&&!H&&!S&&!C){let g=$._prepareStatement;if(g){let x=g(R),b=y.length>0?x.all(...y):x.all();return Number(b[0]?.c??0)}}let P=y.length>0?$.unsafe(R,y):$.unsafe(R),A=await j(P,"select",{signal:S,timeoutMs:H}),[k]=A;return Number(k?.c??0)},async avg(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT AVG(${O}) as a${F.substring(I)}`:`SELECT AVG(${O}) as a FROM ${G}`,M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||uX(M));if(!f.softDeletes?.enabled&&!d&&!H&&!S&&!C){let g=$._prepareStatement;if(g){let x=g(R),b=y.length>0?x.all(...y):x.all();return Number(b[0]?.a??0)}}let P=y.length>0?$.unsafe(R,y):$.unsafe(R),A=await j(P,"select",{signal:S,timeoutMs:H}),[k]=A;return Number(k?.a??0)},async sum(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT SUM(${O}) as s${F.substring(I)}`:`SELECT SUM(${O}) as s FROM ${G}`,M=y.length>0?$.unsafe(R,y):$.unsafe(R),C=await j(M,"select",{signal:S,timeoutMs:H}),[P]=C;return Number(P?.s??0)},async max(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT MAX(${O}) as m${F.substring(I)}`:`SELECT MAX(${O}) as m FROM ${G}`,M=y.length>0?$.unsafe(R,y):$.unsafe(R),C=await j(M,"select",{signal:S,timeoutMs:H}),[P]=C;return P?.m},async min(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT MIN(${O}) as m${F.substring(I)}`:`SELECT MIN(${O}) as m FROM ${G}`,M=y.length>0?$.unsafe(R,y):$.unsafe(R),C=await j(M,"select",{signal:S,timeoutMs:H}),[P]=C;return P?.m},lockForUpdate(){return F+=" FOR UPDATE",K=null,this},sharedLock(){let O=f.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return F+=` ${O}`,K=null,this},withCTE(O,I){return u(O,"withCTE(name)"),F=`WITH ${O} AS (${String(I.toSQL())}) ${F}`,K=null,this},withRecursive(O,I){return u(O,"withRecursive(name)"),F=`WITH RECURSIVE ${O} AS (${String(I.toSQL())}) ${F}`,K=null,this},execute(){return j(D(),"select",{signal:S,timeoutMs:H})},values(){return D().values()},toParams(){return[...y]},__rawState(){return{sql:X8(F),params:[...y]}},raw(){return D().raw()},get rows(){return},get row(){return},cancel(){try{D().cancel()}catch{}}},{get(O,I,R){let M=Reflect.get(O,I,R);if(M!==void 0)return M;if(typeof I==="string"&&(I.startsWith("where")||I.startsWith("orWhere")||I.startsWith("andWhere"))){let C=I.startsWith("orWhere"),P=I.startsWith("andWhere"),A=`${String(G)}|${I}`,k=U.get(A);if(k===void 0){let x=I.replace(/^(?:or|and)?where/i,"");if(!x)U.set(A,""),k="";else{let b=x.charAt(0).toLowerCase()+x.slice(1),l=x.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),$0=Y?Object.keys(Y[String(G)]?.columns??{}):[];k=[l,b,b.toLowerCase()].find((C0)=>$0.includes(C0))??l,U.set(A,k)}}if(k==="")return()=>R;let g=k;return(x)=>{let b=Array.isArray(x)?W`${W(g)} IN ${W(x)}`:W`${W(g)} = ${x}`;if(K=C?W`${D()} OR ${b}`:P?W`${D()} AND ${b}`:W`${D()} WHERE ${b}`,Array.isArray(x)){let l=h0(x.length,y.length+1);w(C?"OR":P?"AND":"WHERE",`${g} IN (${l})`),y.push(...x)}else{let l=i(y.length+1);w(C?"OR":P?"AND":"WHERE",`${g} = ${l}`),y.push(x)}return R}}return Reflect.get(O,I,R)}})}return{configure(G){return Object.assign(f,G),this},id(G){if(!s.IDENTIFIER.test(G))throw Error(`[query-builder] Invalid identifier: '${G}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(String(G))},ids(...G){for(let J of G)if(!s.IDENTIFIER.test(J))throw Error(`[query-builder] Invalid identifier: '${J}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(G)},select(G,...J){return V(G,J)},selectFrom(G){return V(G)},selectFromSub(G,J){function W(H){return()=>{throw Error(`[query-builder] selectFromSub(...).${H}() is not supported. Apply ${H}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}u(String(J),"selectFromSub(alias)");let F=typeof G.__rawState==="function"?G.__rawState():null,K=G.toSQL(),D=F?.sql??(typeof K==="string"?K:K?.sql??String(K)),w=F?.params??(Array.isArray(K?.values)?K.values:[]),T=`SELECT * FROM (${D}) AS ${String(J)}`,N=(H,S,h,p,d,B,v)=>{let n=!h?"WHERE":v==="WHERE"?"AND":v,c=[...S],X0=(q0,u0,o)=>{u(q0,"selectFromSub where(column)");let y=v0(u0,"selectFromSub where(operator)");if(y==="in"||y==="not in"){let e0=Array.isArray(o)?o:[o],UX=h0(e0.length,c.length+1);return c.push(...e0),`${q0} ${y.toUpperCase()} (${UX})`}let K9=i(c.length+1);return c.push(o),`${q0} ${y} ${K9}`},e;if(typeof p==="string"&&d!==void 0)e=X0(p,d,B);else if(Array.isArray(p)&&p.length===3)e=X0(p[0],p[1],p[2]);else if(p&&typeof p==="object")e=Object.entries(p).map(([q0,u0])=>X0(q0,"=",u0)).join(" AND ");else return{text:H,params:S};return{text:`${H} ${n} ${e}`,params:c}};function q(H,S,h=!1){let p=()=>S.length>0?$.unsafe(H,S):$.unsafe(H),d={distinct(){return q(H.replace(/^SELECT\s+/i,"SELECT DISTINCT "),S,h)},distinctOn(...B){let v=B.map(String).join(", ");return q(H.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${v}) `),S,h)},selectRaw(B){let v=KX(B,"selectFromSub.selectRaw(fragment)"),n=H.indexOf(" FROM "),c=n!==-1?`${H.slice(0,n)}, ${v}${H.slice(n)}`:`${H}, ${v}`;return q(c,S,h)},where(B,v,n){let c=N(H,S,h,B,v,n,"WHERE");return q(c.text,c.params,!0)},andWhere(B,v,n){let c=N(H,S,h,B,v,n,"AND");return q(c.text,c.params,!0)},orWhere(B,v,n){let c=N(H,S,h,B,v,n,"OR");return q(c.text,c.params,!0)},orderBy(B,v="asc"){u(String(B),"selectFromSub.orderBy(column)");let n=v==="asc"?"ASC":"DESC",c=s.ORDER_BY.test(H)?`${H}, ${B} ${n}`:`${H} ORDER BY ${B} ${n}`;return q(c,S,h)},limit(B){if(!Number.isInteger(B)||B<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${B}`);let v=s.LIMIT.test(H)?H.replace(s.LIMIT,` LIMIT ${B}`):`${H} LIMIT ${B}`;return q(v,S,h)},offset(B){if(!Number.isInteger(B)||B<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${B}`);let v=s.OFFSET.test(H)?H.replace(s.OFFSET,` OFFSET ${B}`):`${H} OFFSET ${B}`;return q(v,S,h)},toSQL(){return E(p(),H)},async execute(){return j(p(),"select")},async executeTakeFirst(){let B=await j(p(),"select");return Array.isArray(B)?B[0]:B},async executeTakeFirstOrThrow(){let B=await j(p(),"select"),v=Array.isArray(B)?B[0]:B;if(!v)throw Error("Record not found");return v},async get(){return j(p(),"select")},async first(){let B=await j(p(),"select");return Array.isArray(B)?B[0]:B},async firstOrFail(){let B=await j(p(),"select"),v=Array.isArray(B)?B[0]:B;if(!v)throw Error("No rows found");return v},async count(){let B=S.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,S):$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),v=await j(B,"select");return Number(v?.[0]?.c??0)},async exists(){let B=S.length>0?$.unsafe(`SELECT EXISTS(${H}) as e`,S):$.unsafe(`SELECT EXISTS(${H}) as e`),v=await j(B,"select");return Boolean(v?.[0]?.e)},async doesntExist(){return!await d.exists()},values(){return p().values()},raw(){return p().raw()},cancel(){try{p().cancel()}catch{}},whereRaw:W("whereRaw"),whereColumn:W("whereColumn"),orWhereColumn:W("orWhereColumn"),whereIn:W("whereIn"),orWhereIn:W("orWhereIn"),whereNotIn:W("whereNotIn"),orWhereNotIn:W("orWhereNotIn"),whereLike:W("whereLike"),whereILike:W("whereILike"),orWhereLike:W("orWhereLike"),orWhereILike:W("orWhereILike"),whereNotLike:W("whereNotLike"),whereNotILike:W("whereNotILike"),orWhereNotLike:W("orWhereNotLike"),orWhereNotILike:W("orWhereNotILike"),whereAny:W("whereAny"),whereAll:W("whereAll"),whereNone:W("whereNone"),whereNested:W("whereNested"),orWhereNested:W("orWhereNested"),whereDate:W("whereDate"),whereBetween:W("whereBetween"),whereNotBetween:W("whereNotBetween"),whereJsonContains:W("whereJsonContains"),whereJsonPath:W("whereJsonPath"),whereNull:W("whereNull"),whereNotNull:W("whereNotNull"),whereExists:W("whereExists"),whereJsonDoesntContain:W("whereJsonDoesntContain"),whereJsonContainsKey:W("whereJsonContainsKey"),whereJsonDoesntContainKey:W("whereJsonDoesntContainKey"),whereJsonLength:W("whereJsonLength"),join:W("join"),joinSub:W("joinSub"),innerJoin:W("innerJoin"),leftJoin:W("leftJoin"),leftJoinSub:W("leftJoinSub"),rightJoin:W("rightJoin"),crossJoin:W("crossJoin"),crossJoinSub:W("crossJoinSub"),groupBy:W("groupBy"),groupByRaw:W("groupByRaw"),having:W("having"),havingRaw:W("havingRaw"),addSelect:W("addSelect"),select:W("select"),selectAll:W("selectAll"),orderByDesc:W("orderByDesc"),inRandomOrder:W("inRandomOrder"),reorder:W("reorder"),orderByRaw:W("orderByRaw"),union:W("union"),unionAll:W("unionAll"),forPage:W("forPage"),selectAllRelations:W("selectAllRelations"),with:W("with"),value:W("value"),pluck:W("pluck"),cursorPaginate:W("cursorPaginate"),paginate:W("paginate"),simplePaginate:W("simplePaginate"),chunk:W("chunk"),chunkById:W("chunkById"),eachById:W("eachById"),avg:W("avg"),sum:W("sum"),max:W("max"),min:W("min"),find:W("find"),findOrFail:W("findOrFail"),findMany:W("findMany"),latest:W("latest"),oldest:W("oldest"),lazy:W("lazy"),lazyById:W("lazyById"),pipe:(B)=>B(d),when:W("when"),tap:()=>d,dump:()=>d,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>p().simple(),toText:()=>H,toParams:()=>[...S],withTimeout:()=>d,abort:()=>d,lockForUpdate:()=>d,sharedLock:()=>d,withCTE:()=>d,withRecursive:()=>d,cache:()=>d,clone:()=>d,withTrashed:()=>d,onlyTrashed:()=>d,scope:()=>d,get rows(){return[]},get row(){return}};return d}return q(T,w)},insertInto(G){let J,W="",F=[],K=f.dialect==="postgres",D=K?(T)=>`"${String(T).replace(/"/g,'""')}"`:W0(f.dialect)?(T)=>`\`${String(T).replace(/`/g,"``")}\``:(T)=>`"${String(T).replace(/"/g,'""')}"`,w=K?(T)=>`$${T+1}`:(T)=>"?";return{values(T){let N=Array.isArray(T)?T:[T],q=N.length;if(q===0)return J=$.unsafe("SELECT 1"),this;let H=N[0],S=Object.keys(H),h=S.length,p=q*h;if(F.length=p,q===1)if(!K){let d=D(S[0]),B="?";F[0]=H[S[0]];for(let v=1;v<h;v++)d+=`,${D(S[v])}`,B+=",?",F[v]=H[S[v]];W=`INSERT INTO ${D(G)}(${d})VALUES(${B})`}else{let d=S.map((B)=>D(B)).join(",");W=`INSERT INTO ${D(G)}(${d})VALUES(`;for(let B=0;B<h;B++){if(B>0)W+=",";W+=w(B),F[B]=H[S[B]]}W+=")"}else{let d=S.map((v)=>D(v)).join(",");W=`INSERT INTO ${D(G)}(${d})VALUES`;let B=0;for(let v=0;v<q;v++){let n=N[v];if(v===0)W+="(";else W+="),(";for(let c=0;c<h;c++){if(c>0)W+=",";W+=w(B),F[B++]=n[S[c]]}}W+=")"}if(!$._prepareStatement)J=$.unsafe(W,F);return this},returning(...T){let N=`${W} RETURNING ${T.join(", ")}`,q=$.unsafe(N,F),H=async()=>{let S=await j(q,"insert");return Array.isArray(S)?S[0]:S};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>E(q,N),execute:()=>j(q,"insert"),get:()=>j(q,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let S=await H();if(!S)throw Error("Insert with RETURNING returned no rows");return S},async executeTakeFirstOrThrow(){let S=await H();if(!S)throw Error("Insert with RETURNING returned no rows");return S}}},toSQL(){if(!J)J=$.unsafe(W,F);return E(J,W)},execute(){let T=f.hooks;if(!(T&&(T.onQueryStart||T.onQueryEnd||T.onQueryError||T.startSpan||T.beforeCreate||T.afterCreate||uX(T)))){let q=$._prepareStatement;if(q){let H=q(W);return F.length>0?H.run(...F):H.run()}}if(!J)J=$.unsafe(W,F);return j(J,"insert")},async executeTakeFirst(){if(!J)J=$.unsafe(W,F);return await j(J,"insert")},async executeTakeFirstOrThrow(){if(!J)J=$.unsafe(W,F);let T=await j(J,"insert");if(!T)throw Error("Insert failed");return T},returningAll(){let T=`${W} RETURNING *`,N=$.unsafe(T,F),q=async()=>{let H=await j(N,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>E(N,T),execute:()=>j(N,"insert"),get:()=>j(N,"insert"),first:q,executeTakeFirst:q,async firstOrFail(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(G){let J,W=[],F=(D)=>{let w=String(D);if(W0(f.dialect))return`\`${w.replace(/`/g,"``")}\``;return`"${w.replace(/"/g,'""')}"`},K=`UPDATE ${F(String(G))}`;return{set(D){let w=Object.keys(D),T=w.length,N=Array.from({length:T});for(let q=0;q<T;q++){let H=w[q];N[q]=`${F(H)} = ${i(q+1)}`,W.push(D[H])}return K=`${K} SET ${N.join(", ")}`,J=$.unsafe(K,W),this},where(D,w,T){let N=()=>s.WHERE.test(K)?"AND":"WHERE";if(typeof D==="string"&&w!==void 0){let q=W.length+1;return K=`${K} ${N()} ${F(D)} ${w} ${i(q)}`,W.push(T),J=$.unsafe(K,W),this}if(Array.isArray(D)){let[q,H,S]=D,h=W.length+1;return K=`${K} ${N()} ${F(String(q))} ${String(H)} ${i(h)}`,W.push(S),J=$.unsafe(K,W),this}if(D&&typeof D==="object"&&!("raw"in D)){let q=Object.keys(D),H=q.length,S=W.length,h=Array.from({length:H});for(let p=0;p<H;p++)h[p]=`${F(q[p])} = ${i(S+p+1)}`,W.push(D[q[p]]);K=`${K} ${N()} ${h.join(" AND ")}`,J=$.unsafe(K,W)}return this},returning(...D){let w=`${K} RETURNING ${D.join(", ")}`,T=W.length>0?$.unsafe(w,W):$.unsafe(w),N=async()=>{let H=await j(T,"update");return Array.isArray(H)?H[0]:H},q={where:()=>q,andWhere:()=>q,orWhere:()=>q,orderBy:()=>q,limit:()=>q,offset:()=>q,toSQL:()=>E(T,w),execute:()=>j(T,"update"),get:()=>j(T,"update"),first:N,executeTakeFirst:N,async firstOrFail(){let H=await N();if(!H)throw Error("Update with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await N();if(!H)throw Error("Update with RETURNING returned no rows");return H}};return q},toSQL(){if(!J)J=W.length>0?$.unsafe(K,W):$.unsafe(K);return E(J,K)},execute(){return j(J,"update")},async executeTakeFirst(){return{numUpdatedRows:await j(J,"update")}},async executeTakeFirstOrThrow(){let D=await j(J,"update");if(D===0)throw Error("No rows updated");return{numUpdatedRows:D}},returningAll(){let D=`${K} RETURNING *`,w=W.length>0?$.unsafe(D,W):$.unsafe(D);return{toSQL:()=>E(w,D),execute:()=>j(w,"update"),async executeTakeFirst(){let T=await j(w,"update");return Array.isArray(T)?T[0]:T},async executeTakeFirstOrThrow(){let T=await j(w,"update"),N=Array.isArray(T)?T[0]:T;if(!N)throw Error("Update with RETURNING failed");return N}}}}},deleteFrom(G){let J=(q)=>{let H=String(q);if(W0(f.dialect))return`\`${H.replace(/`/g,"``")}\``;return`"${H.replace(/"/g,'""')}"`},F=`DELETE FROM ${J(String(G))}`,K=null,D=[],w=null,T=()=>s.WHERE.test(F)?"AND":"WHERE",N=()=>{if(K===null)K=D.length>0?$.unsafe(F,D):$.unsafe(F);return K};return{where(q,H,S){if(w=q,typeof q==="string"&&H!==void 0){let h=D.length+1;return F+=` ${T()} ${J(q)} ${H} ${i(h)}`,D.push(S),K=null,this}if(Array.isArray(q)){let[h,p,d]=q,B=D.length+1;return F+=` ${T()} ${J(String(h))} ${p} ${i(B)}`,D.push(d),K=null,this}if(q&&typeof q==="object"&&!("raw"in q)){let h=Object.keys(q),p=[];for(let d of h){let B=D.length+1;p.push(`${J(d)} = ${i(B)}`),D.push(q[d])}return F+=` ${T()} ${p.join(" AND ")}`,K=null,this}return K=Q({},N(),q),this},returning(...q){let H=`${F} RETURNING ${q.join(", ")}`,S=D.length>0?$.unsafe(H,D):$.unsafe(H),h=async()=>{let d=await j(S,"delete");return Array.isArray(d)?d[0]:d},p={where:()=>p,andWhere:()=>p,orWhere:()=>p,orderBy:()=>p,limit:()=>p,offset:()=>p,toSQL:()=>E(S,H),execute:()=>j(S,"delete"),get:()=>j(S,"delete"),first:h,executeTakeFirst:h,async firstOrFail(){let d=await h();if(!d)throw Error("Delete with RETURNING returned no rows");return d},async executeTakeFirstOrThrow(){let d=await h();if(!d)throw Error("Delete with RETURNING returned no rows");return d}};return p},toSQL(){return E(N(),F)},async execute(){try{await f.hooks?.beforeDelete?.({table:String(G),where:w})}catch(H){throw H}let q=await j(N(),"delete");try{await f.hooks?.afterDelete?.({table:String(G),where:w,result:q})}catch{}return q},async executeTakeFirst(){return{numDeletedRows:await j(N(),"delete")}},async executeTakeFirstOrThrow(){let q=await j(N(),"delete");if(q===0)throw Error("No rows deleted");return{numDeletedRows:q}},returningAll(){let q=`${F} RETURNING *`,H=D.length>0?$.unsafe(q,D):$.unsafe(q);return{toSQL:()=>E(H,q),execute:()=>j(H,"delete"),async executeTakeFirst(){let S=await j(H,"delete");return Array.isArray(S)?S[0]:S},async executeTakeFirstOrThrow(){let S=await j(H,"delete"),h=Array.isArray(S)?S[0]:S;if(!h)throw Error("Delete with RETURNING failed");return h}}}}},table(G){let J=this;return{insert(W){return J.insertInto(G).values(W)},update(W){return J.updateTable(G).set(W)},delete(){return J.deleteFrom(G)},select(...W){if(W.length===0)return J.selectFrom(G);return J.select(G,...W)}}},sql:$,raw(G,...J){return $(G,...J)},simple(G,...J){return $(G,...J).simple()},async advisoryLock(G){if(f.dialect==="postgres"){let J=String(G),W=7;for(let D=0;D<J.length;D++)W=W*31+J.charCodeAt(D)|0;let F=typeof G==="number"?G:Math.abs(W),K=m`SELECT pg_advisory_lock(${F})`;await j(K,"raw");return}if(W0(f.dialect)){let J=`bqb:${String(G)}`,W=m`SELECT GET_LOCK(${J}, -1) AS ok`;await j(W,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(G){if(f.dialect==="postgres"){let J=String(G),W=7;for(let w=0;w<J.length;w++)W=W*31+J.charCodeAt(w)|0;let F=typeof G==="number"?G:Math.abs(W),K=m`SELECT pg_try_advisory_lock(${F}) as ok`,D=await j(K,"raw");return Boolean(D?.[0]?.ok)}if(W0(f.dialect)){let J=`bqb:${String(G)}`,W=m`SELECT GET_LOCK(${J}, 0) AS ok`,F=await j(W,"raw");return Number(F?.[0]?.ok)===1}return!1},unsafe(G,J){return m.unsafe(G,J)},file(G,J){return m.file(G,J)},async reserve(){let G=await m.reserve(),J=R0({sql:G,meta:Z,schema:Y});return J.release=()=>G.release(),J},async close(G){await m.close(G)},async listen(G,J){},async unlisten(G){},async notify(G,J){},async copyTo(G,J){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(G,J,W){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let G=m`SELECT 1`;return await j(G,"select"),!0}catch{return!1}},async waitForReady(G){let J=Math.max(1,G?.attempts??10),W=Math.max(10,G?.delayMs??100);for(let F=0;F<J;F++){if(await this.ping())return;await new Promise((K)=>setTimeout(K,W))}throw Error("Database not ready after waiting")},async transaction(G,J){let F={...X?.txDefaults,...J},K=X?.sql??m,D=X?.inTransaction===!0,w=D&&typeof K?.savepoint==="function"?"savepoint":"begin",T=async(H)=>{F.logger?.({type:"start",attempt:H});let S=Date.now();return await K[w](async(h)=>{let p=R0({sql:h,meta:Z,schema:Y,inTransaction:!0});if(F?.isolation&&!D){let v=F.isolation,n=v==="read committed"?"READ COMMITTED":v==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(f.dialect==="postgres")await h.unsafe(`SET TRANSACTION ISOLATION LEVEL ${n}`);else if(W0(f.dialect))await h.unsafe(`SET TRANSACTION ISOLATION LEVEL ${n}`);else if(v!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${v}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(F?.readOnly)if(f.dialect==="postgres")await h.unsafe("SET TRANSACTION READ ONLY");else if(W0(f.dialect))await h.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let d=await G(p),B=Date.now()-S;return F.logger?.({type:"commit",attempt:H,durationMs:B}),d})},N=Math.max(0,F?.retries??0),q=0;for(;;)try{let H=await T(q+1);return F?.afterCommit?.(),H}catch(H){let S=b_(H)||f_(H,F.sqlStates);if(q<N&&S){q++,F?.onRetry?.(q,H);let h=p_(q,F.backoff);if(h>0)await g_(h);continue}try{F.onRollback?.(H)}catch{}try{F.afterRollback?.()}catch{}throw H}},async savepoint(G){let J=$;if(!J||typeof J.savepoint!=="function")throw Error("savepoint() must be called inside a transaction");return await J.savepoint(async(W)=>{let F=R0({sql:W,meta:Z,schema:Y});return await G(F)})},async beginDistributed(G,J){return await(X?.sql??m).beginDistributed(G,async(K)=>{let D=R0({sql:K,meta:Z,schema:Y});return await J(D)})},async commitDistributed(G){await m.commitDistributed(G)},async rollbackDistributed(G){await m.rollbackDistributed(G)},setTransactionDefaults(G){X={...X,txDefaults:{...X?.txDefaults,...G}}},transactional(G,J){return(...W)=>{return this.transaction((F)=>G(F,...W),J)}},async insertOrIgnore(G,J){let W=Array.isArray(J)?J:[J];if(!W.length)return;let{colsSql:F,valuesSql:K,params:D}=e$(W),w=a0(String(G)),T=W0(f.dialect)?`INSERT IGNORE INTO ${w} (${F}) VALUES ${K}`:`INSERT INTO ${w} (${F}) VALUES ${K} ON CONFLICT DO NOTHING`;return m.unsafe(T,D).execute()},async insertGetId(G,J,W="id"){let{colsSql:F,valuesSql:K,params:D}=e$([J]),w=a0(String(G));if(W0(f.dialect)){await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K}`,D).execute();let[N]=await m.unsafe("SELECT LAST_INSERT_ID() as id").execute();return N?.id}if(f.dialect==="sqlite"){let N=await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K}`,D).execute();if(N?.lastInsertRowid!=null)return N.lastInsertRowid;let[q]=await m.unsafe("SELECT last_insert_rowid() as id").execute();return q?.id}let[T]=await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K} RETURNING ${a0(String(W))} as id`,D).execute();return T?.id},async updateOrInsert(G,J,W){let F=a0(String(G)),K=Object.keys(J),D=1,w=K.map((h)=>`${a0(h)} = ${i(D++)}`).join(" AND "),T=K.map((h)=>J[h]);if((await m.unsafe(`SELECT 1 FROM ${F} WHERE ${w} LIMIT 1`,T).execute()).length){let h=Object.keys(W),p=1,d=h.map((n)=>`${a0(n)} = ${i(p++)}`).join(", "),B=K.map((n)=>`${a0(n)} = ${i(p++)}`).join(" AND "),v=[...h.map((n)=>W[n]),...K.map((n)=>J[n])];return await m.unsafe(`UPDATE ${F} SET ${d} WHERE ${B}`,v).execute(),!0}let{colsSql:q,valuesSql:H,params:S}=e$([{...J,...W}]);return await m.unsafe(`INSERT INTO ${F} (${q}) VALUES ${H}`,S).execute(),!0},async upsert(G,J,W,F){let K=W.map((d)=>String(d)),D=(F??[]).map((d)=>String(d)),w=J;if(!w.length)return;let{colsSql:T,valuesSql:N,params:q}=e$(w),H=a0(String(G)),S=`INSERT INTO ${H} (${T}) VALUES ${N}`;if(W0(f.dialect)){if(D.length===0)return m.unsafe(`INSERT IGNORE INTO ${H} (${T}) VALUES ${N}`,q).execute();let d=D.map((B)=>`${a0(B)} = VALUES(${a0(B)})`).join(", ");return m.unsafe(`${S} ON DUPLICATE KEY UPDATE ${d}`,q).execute()}let h=K.map(a0).join(", ");if(D.length===0)return m.unsafe(`${S} ON CONFLICT (${h}) DO NOTHING`,q).execute();let p=D.map((d)=>`${a0(d)} = EXCLUDED.${a0(d)}`).join(", ");return m.unsafe(`${S} ON CONFLICT (${h}) DO UPDATE SET ${p}`,q).execute()},async save(G,J){let W=Z?.primaryKeys[String(G)]??"id",F=J[W];if(F!=null)if(await this.selectFrom(G).find(F)){await this.updateTable(G).set(J).where({[W]:F}).execute();let D=await this.selectFrom(G).find(F);if(!D)throw Error("save() failed to retrieve updated row");return D}else return await this.create(G,J);return await this.create(G,J)},async remove(G,J){return await this.deleteFrom(G).where({id:J}).execute()},async find(G,J){return await this.selectFrom(G).find(J)},async findOrFail(G,J){return await this.selectFrom(G).findOrFail(J)},async findMany(G,J){return await this.selectFrom(G).findMany(J)},async latest(G,J){return await this.selectFrom(G).latest(J).first()},async oldest(G,J){return await this.selectFrom(G).oldest(J).first()},skip(G,J){return this.selectFrom(G).offset(J)},async rawQuery(G){let J=Date.now();try{f.hooks?.onQueryStart?.({sql:G,kind:"raw"});let W=await m.unsafe(G);return f.hooks?.onQueryEnd?.({sql:G,durationMs:Date.now()-J,kind:"raw"}),W}catch(W){throw f.hooks?.onQueryError?.({sql:G,error:W,durationMs:Date.now()-J,kind:"raw"}),W}},async create(G,J){let W=Z?.primaryKeys[String(G)]??"id";try{await f.hooks?.beforeCreate?.({table:String(G),data:J})}catch(F){throw F}if(f.dialect==="postgres"){let F=m`INSERT INTO ${m(String(G))} ${m(J)} RETURNING ${m(String(W))} as id`,[K]=await F.execute();if(console.log("resultId",K),!K?.id)throw console.error(`create() failed to get insert ID for table ${String(G)}`),console.error("Inserted values:",J),Error(`create() failed to get insert ID for table ${String(G)}`);let D=await this.selectFrom(G).find(K.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${K.id}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${K.id}`);try{await f.hooks?.afterCreate?.({table:String(G),data:J,result:D})}catch{}return D}else{let F=await this.insertGetId(G,J,W);if(F==null)throw Error(`create() failed to get insert ID for table ${String(G)}`);let K=await this.selectFrom(G).find(F);if(!K)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${F}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${F}`);try{await f.hooks?.afterCreate?.({table:String(G),data:J,result:K})}catch{}return K}},async createMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),K=F.length,D=J.length,w=Array.from({length:D*K}),T=W0(f.dialect)?(H)=>`\`${String(H).replace(/`/g,"``")}\``:(H)=>`"${String(H).replace(/"/g,'""')}"`,N=`INSERT INTO ${T(String(G))}(${F.map(T).join(",")})VALUES`,q=0;for(let H=0;H<D;H++){if(H>0)N+=",";N+="(";let S=J[H];for(let h=0;h<K;h++){if(h>0)N+=",";N+=i(q+1),w[q++]=S[F[h]]}N+=")"}return $.unsafe(N,w).execute()},async insertMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),K=F.length,D=J.length,w=D*K,T=Array(w),N=f.dialect==="postgres",q;if(!N){let h=Array(K);for(let p=0;p<K;p++)h[p]="?";q=`(${h.join(",")})`}else q="";let H=Array(D+2);H[0]=`INSERT INTO ${G}(${F.join(",")})VALUES`;let S=0;if(!N){for(let h=0;h<D;h++){let p=J[h];H[h+1]=q;for(let d=0;d<K;d++)T[S++]=p[F[d]]}return $.unsafe(H[0]+H.slice(1,D+1).join(","),T).execute()}for(let h=0;h<D;h++){let p=J[h],d=Array(K);for(let B=0;B<K;B++)d[B]=`$${S+1}`,T[S++]=p[F[B]];H[h+1]=`(${d.join(",")})`}return $.unsafe(H[0]+H.slice(1,D+1).join(","),T).execute()},async updateMany(G,J,W){let F=Object.keys(W),K=F.length;if(K===0)return 0;let D=[],w=Array.from({length:K});for(let N=0;N<K;N++)w[N]=`${F[N]}=${i(N+1)}`,D.push(W[F[N]]);let T=`UPDATE ${G} SET ${w.join(",")}`;if(Array.isArray(J))T+=` WHERE ${J[0]}${J[1]}${i(D.length+1)}`,D.push(J[2]);else if(J&&typeof J==="object"&&!("raw"in J)){let N=Object.keys(J),q=N.length;if(q>0){let H=D.length,S=Array.from({length:q});for(let h=0;h<q;h++)S[h]=`${N[h]}=${i(H+h+1)}`,D.push(J[N[h]]);T+=` WHERE ${S.join(" AND ")}`}}return $.unsafe(T,D).execute()},async deleteMany(G,J){if(!Array.isArray(J)||J.length===0)return 0;let W=Z?.primaryKeys[String(G)]??"id",F=J.length;if(f.dialect==="postgres"){let D=Array(F);for(let w=0;w<F;w++)D[w]=`$${w+1}`;return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${D.join(",")})`,J).execute()}let K=Array(F);for(let D=0;D<F;D++)K[D]="?";return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${K.join(",")})`,J).execute()},async firstOrCreate(G,J,W){let F=await this.selectFrom(G).where(J).first();if(F)return F;return await this.create(G,{...J,...W})},async updateOrCreate(G,J,W){let F=await this.selectFrom(G).where(J).first();if(F){await this.updateTable(G).set(W).where(J).execute();let K=Z?.primaryKeys[String(G)]??"id",D=F[K],w=D!=null?await this.selectFrom(G).find(D):await this.selectFrom(G).where(J).first();if(!w)throw Error("updateOrCreate() failed to retrieve updated row");return w}return await this.create(G,{...J,...W})},async count(G,J){let W=J?m(String(J)):m`*`,F=m`SELECT COUNT(${W}) as c FROM ${m(String(G))}`,[K]=await F.execute();return Number(K?.c??0)},async sum(G,J){let W=m`SELECT SUM(${m(String(J))}) as s FROM ${m(String(G))}`,[F]=await W.execute();return Number(F?.s??0)},async avg(G,J){let W=m`SELECT AVG(${m(String(J))}) as a FROM ${m(String(G))}`,[F]=await W.execute();return Number(F?.a??0)},async min(G,J){let W=m`SELECT MIN(${m(String(J))}) as m FROM ${m(String(G))}`,[F]=await W.execute();return F?.m},async max(G,J){let W=m`SELECT MAX(${m(String(J))}) as m FROM ${m(String(G))}`,[F]=await W.execute();return F?.m},getRelationships(G){if(!Z?.relations)return{};let J=Z.relations[G];if(!J)return{};let W={};for(let[F,K]of Object.entries(J))if(K&&typeof K==="object"&&Object.keys(K).length>0)W[F]=K;return W},hasRelationship(G,J){if(!Z?.relations)return!1;let W=Z.relations[G];if(!W)return!1;return Object.values(W).some((F)=>F&&typeof F==="object"&&(J in F))},getRelationshipType(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,K]of Object.entries(W))if(K&&typeof K==="object"&&J in K)return F;return null},getRelationshipTarget(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,K]of Object.entries(W))if(K&&typeof K==="object"&&J in K){let D=K[J];if(typeof D==="string")return Z.modelToTable[D]||D;else if(D&&typeof D==="object"){if("model"in D)return Z.modelToTable[D.model]||D.model;if("target"in D)return Z.modelToTable[D.target]||D.target}}return null}}}function c_(){S$.clear()}function m_(X){S$.setMaxSize(X)}var s,w1,q1,S$,oX,u_=500,UZ=t(()=>{d0(),$X(),s={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},w1=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]),q1=new Set,S$=new QU,oX=new Map});async function HG(){console.log("-- Clearing query cache..."),c_(),console.log("-- \u2713 Query cache cleared")}async function CG(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function wG(X={}){if(console.log("-- Configuring query cache..."),console.log(),X.size!==void 0){let $=Number(X.size);if(Number.isNaN($)||$<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");m_($),console.log(`-- \u2713 Cache max size set to: ${$}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}var n_=t(()=>{UZ()});async function l_(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let X=R0(),$=i_({input:$8.stdin,output:$8.stdout,prompt:"qb> "}),Z="",Y=!1,U=`
|
|
79
79
|
Available Commands:
|
|
80
80
|
.help Show this help message
|
|
81
81
|
.exit Exit the console
|
|
@@ -104,11 +104,11 @@ Tips:
|
|
|
104
104
|
`;return}if(z)await _(z)};$.on("line",async(L)=>{await Q(L),$.prompt()}),$.on("SIGINT",()=>{if(Y)console.log(`
|
|
105
105
|
-- Multi-line input cancelled`),Z="",Y=!1,$.prompt();else console.log(`
|
|
106
106
|
-- Type .exit to quit`),$.prompt()}),$.on("close",()=>{console.log(`
|
|
107
|
-
Goodbye!`),$8.exit(0)}),$.prompt()}async function
|
|
107
|
+
Goodbye!`),$8.exit(0)}),$.prompt()}async function TG(){return l_()}var s_=t(()=>{y0()});async function SG(X,$={}){let Z=$.format||"json",Y=$.output||`${X}.${Z}`,U=$.limit;if(console.log(`-- Exporting data from table: ${X}`),console.log(`-- Format: ${Z}`),console.log(`-- Output: ${Y}`),U)console.log(`-- Limit: ${U} rows`);console.log();try{let Q=R0().selectFrom(X);if(U)Q=Q.limit(U);let L=await Q.execute();if(console.log(`-- Retrieved ${L.length} rows`),Z==="json")rX(Y,JSON.stringify(L,null,2)),console.log(`-- \u2713 Exported to JSON: ${Y}`);else if(Z==="csv"){if(L.length===0){rX(Y,""),console.log(`-- \u2713 Exported to CSV: ${Y} (empty)`);return}let z=Object.keys(L[0]),j=[z.join(",")];for(let E of L){let V=z.map((G)=>{let J=E[G];if(J===null||J===void 0)return"";let W=String(J);if(W.includes(",")||W.includes('"')||W.includes(`
|
|
108
108
|
`))return`"${W.replace(/"/g,'""')}"`;return W});j.push(V.join(","))}rX(Y,j.join(`
|
|
109
109
|
`)),console.log(`-- \u2713 Exported to CSV: ${Y}`)}else if(Z==="sql"){let z=[];for(let j of L){let E=Object.keys(j),V=E.map((G)=>{let J=j[G];if(J===null||J===void 0)return"NULL";if(typeof J==="number")return String(J);return`'${String(J).replace(/'/g,"''")}'`});z.push(`INSERT INTO ${X} (${E.join(", ")}) VALUES (${V.join(", ")});`)}rX(Y,z.join(`
|
|
110
|
-
`)),console.log(`-- \u2713 Exported to SQL: ${Y}`)}}catch(_){throw console.error(`-- Failed to export data from ${X}:`,_),_}}async function
|
|
111
|
-
`).filter((G)=>G.trim());if(E.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let V=E[0].split(",").map((G)=>G.trim());for(let G=1;G<E.length;G++){let J=E[G].split(",").map((F)=>F.trim()),W={};for(let F=0;F<V.length;F++){let K=J[F];if(K.startsWith('"')&&K.endsWith('"'))K=K.slice(1,-1).replace(/""/g,'"');if(K==="")K=null;else if(!Number.isNaN(Number(K)))K=Number(K);W[V[F]]=K}L.push(W)}}if(L.length===0){console.log("-- No data to import");return}let z=100,j=0;for(let E=0;E<L.length;E+=z){let V=L.slice(E,E+z);await _.insertInto(X).values(V).execute(),j+=V.length,console.log(`-- Imported ${j}/${L.length} rows...`)}console.log(`-- \u2713 Successfully imported ${L.length} rows`)}catch(_){throw console.error(`-- Failed to import data into ${X}:`,_),_}}async function
|
|
110
|
+
`)),console.log(`-- \u2713 Exported to SQL: ${Y}`)}}catch(_){throw console.error(`-- Failed to export data from ${X}:`,_),_}}async function AG(X,$,Z={}){if(!o_($))throw console.error(`-- File not found: ${$}`),Error(`File not found: ${$}`);let Y=Z.format||($.endsWith(".json")?"json":"csv"),U=Z.truncate??!1;console.log(`-- Importing data into table: ${X}`),console.log(`-- Format: ${Y}`),console.log(`-- File: ${$}`),console.log(`-- Truncate: ${U}`),console.log();try{let _=R0();if(U)await _.deleteFrom(X).execute(),console.log("-- Table truncated");let Q=r_($,"utf8"),L=[];if(Y==="json"){if(L=JSON.parse(Q),!Array.isArray(L))throw TypeError("JSON file must contain an array of objects")}else if(Y==="csv"){let E=Q.split(`
|
|
111
|
+
`).filter((G)=>G.trim());if(E.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let V=E[0].split(",").map((G)=>G.trim());for(let G=1;G<E.length;G++){let J=E[G].split(",").map((F)=>F.trim()),W={};for(let F=0;F<V.length;F++){let K=J[F];if(K.startsWith('"')&&K.endsWith('"'))K=K.slice(1,-1).replace(/""/g,'"');if(K==="")K=null;else if(!Number.isNaN(Number(K)))K=Number(K);W[V[F]]=K}L.push(W)}}if(L.length===0){console.log("-- No data to import");return}let z=100,j=0;for(let E=0;E<L.length;E+=z){let V=L.slice(E,E+z);await _.insertInto(X).values(V).execute(),j+=V.length,console.log(`-- Imported ${j}/${L.length} rows...`)}console.log(`-- \u2713 Successfully imported ${L.length} rows`)}catch(_){throw console.error(`-- Failed to import data into ${X}:`,_),_}}async function kG(X={}){let $=f.dialect||"postgres",Z=X.output||`dump-${Date.now()}.sql`,Y=X.tables?.split(",").map((U)=>U.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${$}`),console.log(`-- Output: ${Z}`),Y)console.log(`-- Tables: ${Y.join(", ")}`);console.log();try{let U=R0(),_=[];if($==="sqlite")_=(await U.unsafe(`
|
|
112
112
|
SELECT name FROM sqlite_master
|
|
113
113
|
WHERE type = 'table'
|
|
114
114
|
AND name NOT LIKE 'sqlite_%'
|
|
@@ -119,20 +119,20 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
119
119
|
WHERE table_schema = 'public'
|
|
120
120
|
AND table_type = 'BASE TABLE'
|
|
121
121
|
ORDER BY table_name
|
|
122
|
-
`)).map((z)=>z.table_name);else if(
|
|
122
|
+
`)).map((z)=>z.table_name);else if(W0($))_=(await U.unsafe(`
|
|
123
123
|
SELECT table_name
|
|
124
124
|
FROM information_schema.tables
|
|
125
125
|
WHERE table_schema = DATABASE()
|
|
126
126
|
AND table_type = 'BASE TABLE'
|
|
127
127
|
ORDER BY table_name
|
|
128
128
|
`)).map((z)=>z.table_name);if(Y)_=_.filter((L)=>Y.includes(L));if(_.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${_.length} table(s)`);let Q=[];Q.push("-- Database dump"),Q.push(`-- Generated at: ${new Date().toISOString()}`),Q.push(`-- Dialect: ${$}`),Q.push("");for(let L of _){console.log(`-- Dumping table: ${L}`);let z=await U.selectFrom(L).execute();Q.push(`-- Table: ${L}`),Q.push(`-- Rows: ${z.length}`),Q.push("");for(let j of z){let E=Object.keys(j),V=E.map((G)=>{let J=j[G];if(J===null||J===void 0)return"NULL";if(typeof J==="number")return String(J);return`'${String(J).replace(/'/g,"''")}'`});Q.push(`INSERT INTO ${L} (${E.join(", ")}) VALUES (${V.join(", ")});`)}Q.push("")}rX(Z,Q.join(`
|
|
129
|
-
`)),console.log(),console.log(`-- \u2713 Database dump saved to: ${Z}`)}catch(U){throw console.error("-- Failed to dump database:",U),U}}var
|
|
129
|
+
`)),console.log(),console.log(`-- \u2713 Database dump saved to: ${Z}`)}catch(U){throw console.error("-- Failed to dump database:",U),U}}var a_=t(()=>{d0(),UZ()});async function t_(){let X=f.dialect||"postgres",$=f.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${X}`),console.log(`-- Database: ${$}`),console.log();try{let Z=R0(),Y=[],U=[];if(X==="postgres")U=(await Z.unsafe(`
|
|
130
130
|
SELECT table_name
|
|
131
131
|
FROM information_schema.tables
|
|
132
132
|
WHERE table_schema = 'public'
|
|
133
133
|
AND table_type = 'BASE TABLE'
|
|
134
134
|
ORDER BY table_name
|
|
135
|
-
`)).map((L)=>L.table_name);else if(
|
|
135
|
+
`)).map((L)=>L.table_name);else if(W0(X))U=(await Z.unsafe(`
|
|
136
136
|
SELECT table_name
|
|
137
137
|
FROM information_schema.tables
|
|
138
138
|
WHERE table_schema = DATABASE()
|
|
@@ -152,7 +152,7 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
152
152
|
SELECT COUNT(*) as count
|
|
153
153
|
FROM pg_indexes
|
|
154
154
|
WHERE tablename = $1
|
|
155
|
-
`,[Q]);E=Number(G[0]?.count||0)}else if(
|
|
155
|
+
`,[Q]);E=Number(G[0]?.count||0)}else if(W0(X)){let V=await Z.unsafe(`
|
|
156
156
|
SELECT COUNT(*) as count
|
|
157
157
|
FROM information_schema.columns
|
|
158
158
|
WHERE table_name = ?
|
|
@@ -162,15 +162,15 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
162
162
|
FROM information_schema.statistics
|
|
163
163
|
WHERE table_name = ?
|
|
164
164
|
AND table_schema = DATABASE()
|
|
165
|
-
`,[Q]);E=Number(G[0]?.count||0)}else if(X==="sqlite")j=(await Z.unsafe(`PRAGMA table_info(${Q})`)).length,E=(await Z.unsafe(`PRAGMA index_list(${Q})`)).length;Y.push({name:Q,rowCount:z,columns:j,indexes:E})}catch(L){console.error(`-- Error getting info for table ${Q}:`,L)}let _=Y.reduce((Q,L)=>Q+L.rowCount,0);if(console.log(`-- Total Tables: ${Y.length}`),console.log(`-- Total Rows: ${_.toLocaleString()}`),console.log(),Y.length>0){console.log("Tables:"),console.log();let Q=Math.max(...Y.map((j)=>j.name.length)),L=Q+2,z="Table".padEnd(L)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(z),console.log("-".repeat(z.length));for(let j of Y){let E=j.name.padEnd(Q+2),V=j.rowCount.toLocaleString().padStart(12),G=(j.columns||0).toString().padStart(10),J=(j.indexes||0).toString().padStart(10);console.log(`${E}${V}${G}${J}`)}}else console.log("-- No tables found");return{dialect:X,database:$,tables:Y,totalTables:Y.length,totalRows:_}}catch(Z){throw console.error("-- Failed to get database info:",Z),Z}}async function
|
|
165
|
+
`,[Q]);E=Number(G[0]?.count||0)}else if(X==="sqlite")j=(await Z.unsafe(`PRAGMA table_info(${Q})`)).length,E=(await Z.unsafe(`PRAGMA index_list(${Q})`)).length;Y.push({name:Q,rowCount:z,columns:j,indexes:E})}catch(L){console.error(`-- Error getting info for table ${Q}:`,L)}let _=Y.reduce((Q,L)=>Q+L.rowCount,0);if(console.log(`-- Total Tables: ${Y.length}`),console.log(`-- Total Rows: ${_.toLocaleString()}`),console.log(),Y.length>0){console.log("Tables:"),console.log();let Q=Math.max(...Y.map((j)=>j.name.length)),L=Q+2,z="Table".padEnd(L)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(z),console.log("-".repeat(z.length));for(let j of Y){let E=j.name.padEnd(Q+2),V=j.rowCount.toLocaleString().padStart(12),G=(j.columns||0).toString().padStart(10),J=(j.indexes||0).toString().padStart(10);console.log(`${E}${V}${G}${J}`)}}else console.log("-- No tables found");return{dialect:X,database:$,tables:Y,totalTables:Y.length,totalRows:_}}catch(Z){throw console.error("-- Failed to get database info:",Z),Z}}async function xG(){return t_()}var e_=t(()=>{d0(),y0()});async function yG(X={}){let $=X.dialect||SY.env.DB_DIALECT||"postgres",Z=X.aggressive||!1;if(X.verbose)console.log(`Optimizing ${$} database${Z?" (aggressive mode)":""}...`);try{if($==="postgres"){if(X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);if(Z)await m`VACUUM FULL ANALYZE ${m(Y)}`;else await m`VACUUM ANALYZE ${m(Y)}`}else{if(X.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Z)await m`VACUUM FULL`,await m`ANALYZE`;else await m`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(W0($)){if(X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Optimizing table: ${Y}`);await m`OPTIMIZE TABLE ${m(Y)}`,await m`ANALYZE TABLE ${m(Y)}`}else{let Y=SY.env.DB_NAME||"test",U=await m`
|
|
166
166
|
SELECT table_name
|
|
167
167
|
FROM information_schema.tables
|
|
168
168
|
WHERE table_schema = ${Y}
|
|
169
|
-
`;for(let _ of U){let Q=_.table_name||_.TABLE_NAME;if(X.verbose)console.log(`Optimizing table: ${Q}`);await m`OPTIMIZE TABLE ${m(Q)}`,await m`ANALYZE TABLE ${m(Q)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(X.verbose)console.log("Running VACUUM on SQLite database...");if(await m`VACUUM`,X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);await m`ANALYZE ${m(Y)}`}else await m`ANALYZE`;if(Z){if(X.verbose)console.log("Running aggressive SQLite optimizations...");await m`PRAGMA optimize`,await m`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${$}`)}catch(Y){throw console.error("Error optimizing database:",Y.message),Y}}var
|
|
169
|
+
`;for(let _ of U){let Q=_.table_name||_.TABLE_NAME;if(X.verbose)console.log(`Optimizing table: ${Q}`);await m`OPTIMIZE TABLE ${m(Q)}`,await m`ANALYZE TABLE ${m(Q)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(X.verbose)console.log("Running VACUUM on SQLite database...");if(await m`VACUUM`,X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);await m`ANALYZE ${m(Y)}`}else await m`ANALYZE`;if(Z){if(X.verbose)console.log("Running aggressive SQLite optimizations...");await m`PRAGMA optimize`,await m`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${$}`)}catch(Y){throw console.error("Error optimizing database:",Y.message),Y}}var XQ=t(()=>{d0(),$X()});async function vG(X={}){let $=X.dialect||AY.env.DB_DIALECT||"postgres";if(X.verbose)console.log(`Wiping all tables from ${$} database...`);try{let Z=[];if($==="postgres")Z=(await m`
|
|
170
170
|
SELECT tablename
|
|
171
171
|
FROM pg_tables
|
|
172
172
|
WHERE schemaname = 'public'
|
|
173
|
-
`).map((U)=>U.tablename);else if(
|
|
173
|
+
`).map((U)=>U.tablename);else if(W0($)){let Y=AY.env.DB_NAME||"test";Z=(await m`
|
|
174
174
|
SELECT table_name
|
|
175
175
|
FROM information_schema.tables
|
|
176
176
|
WHERE table_schema = ${Y}
|
|
@@ -179,7 +179,7 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
179
179
|
FROM sqlite_master
|
|
180
180
|
WHERE type = 'table'
|
|
181
181
|
AND name NOT LIKE 'sqlite_%'
|
|
182
|
-
`).map((U)=>U.name);if(Z.length===0){console.log("No tables found to drop.");return}if(X.verbose)console.log(`Found ${Z.length} tables: ${Z.join(", ")}`);if($==="postgres")for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)} CASCADE`}else if(
|
|
182
|
+
`).map((U)=>U.name);if(Z.length===0){console.log("No tables found to drop.");return}if(X.verbose)console.log(`Found ${Z.length} tables: ${Z.join(", ")}`);if($==="postgres")for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)} CASCADE`}else if(W0($)){await m`SET FOREIGN_KEY_CHECKS = 0`;for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)}`}await m`SET FOREIGN_KEY_CHECKS = 1`}else if($==="sqlite"){await m`PRAGMA foreign_keys = OFF`;for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)}`}await m`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${Z.length} tables`)}catch(Z){throw console.error("Error wiping database:",Z.message),Z}}var $Q=t(()=>{d0(),$X()});async function bG(X){let Y=await(R0().raw([X]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(Y,null,2)),Y}var ZQ=t(()=>{y0()});async function fG(X,$={}){let Z=R0(),Y=$.params?JSON.parse($.params):void 0,U=await Z.file(X,Y);return console.log(JSON.stringify(U)),U}var YQ=t(()=>{y0()});async function UQ(X,$={}){let Z=f.dialect||"postgres",Y=$.verbose??!0;if(Y)console.log(`-- Inspecting table: ${X}`),console.log(`-- Dialect: ${Z}`),console.log();try{let U=R0(),_=[],Q=[],L=await U.unsafe(`SELECT COUNT(*) as count FROM ${X}`),z=Number(L[0]?.count||0);if(Z==="postgres"){let j=await U.unsafe(`
|
|
183
183
|
SELECT
|
|
184
184
|
c.column_name,
|
|
185
185
|
c.data_type,
|
|
@@ -221,7 +221,7 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
221
221
|
JOIN pg_class c ON c.relname = i.indexname
|
|
222
222
|
JOIN pg_index ix ON ix.indexrelid = c.oid
|
|
223
223
|
WHERE i.tablename = $1
|
|
224
|
-
`,[X]);for(let V of E){let G=V.indexdef?.match(/\(([^)]+)\)/),W=(G?G[1]:"").split(",").map((F)=>F.trim());Q.push({name:V.name,columns:W,unique:V.is_unique})}}else if(
|
|
224
|
+
`,[X]);for(let V of E){let G=V.indexdef?.match(/\(([^)]+)\)/),W=(G?G[1]:"").split(",").map((F)=>F.trim());Q.push({name:V.name,columns:W,unique:V.is_unique})}}else if(W0(Z)){let j=await U.unsafe(`
|
|
225
225
|
SELECT
|
|
226
226
|
COLUMN_NAME as column_name,
|
|
227
227
|
DATA_TYPE as data_type,
|
|
@@ -234,7 +234,7 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
234
234
|
ORDER BY ORDINAL_POSITION
|
|
235
235
|
`,[X]);for(let G of j)_.push({name:G.column_name,type:G.data_type,nullable:G.is_nullable==="YES",default:G.column_default,isPrimaryKey:G.column_key==="PRI",isForeignKey:G.column_key==="MUL"});let E=await U.unsafe(`
|
|
236
236
|
SHOW INDEXES FROM ${X}
|
|
237
|
-
`),V=new Map;for(let G of E){let J=G.Key_name;if(!V.has(J))V.set(J,{columns:[],unique:G.Non_unique===0});V.get(J).columns.push(G.Column_name)}for(let[G,J]of V)Q.push({name:G,columns:J.columns,unique:J.unique})}else if(Z==="sqlite"){let j=await U.unsafe(`PRAGMA table_info(${X})`);for(let V of j)_.push({name:V.name,type:V.type,nullable:V.notnull===0,default:V.dflt_value,isPrimaryKey:V.pk===1});let E=await U.unsafe(`PRAGMA index_list(${X})`);for(let V of E){let G=await U.unsafe(`PRAGMA index_info(${V.name})`);Q.push({name:V.name,columns:G.map((J)=>J.name),unique:V.unique===1})}}if(Y){console.log(`Table: ${X}`),console.log(`Rows: ${z.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let j=Math.max(..._.map((W)=>W.name.length),10),E=Math.max(..._.map((W)=>W.type.length),10),V=j+2,G=E+2,J=`${"Name".padEnd(V)+"Type".padEnd(G)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(J),console.log("-".repeat(J.length));for(let W of _){let F=W.name.padEnd(V),K=W.type.padEnd(G),D=(W.nullable?"YES":"NO").padEnd(10),w=String(W.default||"").padEnd(20),T=[W.isPrimaryKey?"PK":"",W.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${F}${K}${D}${w}${T}`)}if(console.log(),Q.length>0){console.log("Indexes:"),console.log();for(let W of Q){let F=W.unique?" (UNIQUE)":"";console.log(` - ${W.name}${F}: [${W.columns.join(", ")}]`)}console.log()}}return{tableName:X,rowCount:z,columns:_,indexes:Q}}catch(U){throw console.error(`-- Failed to inspect table ${X}:`,U),U}}async function
|
|
237
|
+
`),V=new Map;for(let G of E){let J=G.Key_name;if(!V.has(J))V.set(J,{columns:[],unique:G.Non_unique===0});V.get(J).columns.push(G.Column_name)}for(let[G,J]of V)Q.push({name:G,columns:J.columns,unique:J.unique})}else if(Z==="sqlite"){let j=await U.unsafe(`PRAGMA table_info(${X})`);for(let V of j)_.push({name:V.name,type:V.type,nullable:V.notnull===0,default:V.dflt_value,isPrimaryKey:V.pk===1});let E=await U.unsafe(`PRAGMA index_list(${X})`);for(let V of E){let G=await U.unsafe(`PRAGMA index_info(${V.name})`);Q.push({name:V.name,columns:G.map((J)=>J.name),unique:V.unique===1})}}if(Y){console.log(`Table: ${X}`),console.log(`Rows: ${z.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let j=Math.max(..._.map((W)=>W.name.length),10),E=Math.max(..._.map((W)=>W.type.length),10),V=j+2,G=E+2,J=`${"Name".padEnd(V)+"Type".padEnd(G)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(J),console.log("-".repeat(J.length));for(let W of _){let F=W.name.padEnd(V),K=W.type.padEnd(G),D=(W.nullable?"YES":"NO").padEnd(10),w=String(W.default||"").padEnd(20),T=[W.isPrimaryKey?"PK":"",W.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${F}${K}${D}${w}${T}`)}if(console.log(),Q.length>0){console.log("Indexes:"),console.log();for(let W of Q){let F=W.unique?" (UNIQUE)":"";console.log(` - ${W.name}${F}: [${W.columns.join(", ")}]`)}console.log()}}return{tableName:X,rowCount:z,columns:_,indexes:Q}}catch(U){throw console.error(`-- Failed to inspect table ${X}:`,U),U}}async function gG(X,$={}){return UQ(X,$)}var _Q=t(()=>{d0(),y0()});async function dG(X,$={}){let Z=await dX({modelsDir:X}),Y=R7(Z);return console.log(JSON.stringify(Y,null,2)),{models:Z,schema:Y}}var QQ=t(()=>{y0()});function zQ(X){let $=X.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test($))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test($))return"number";if(/timestamp|datetime|date|time/.test($))return"datetime";if(/json/.test($))return"json";return"string"}function LQ(X){if(/ies$/i.test(X))return X.replace(/ies$/i,"y");if(/ses$/i.test(X))return X.replace(/es$/i,"");if(/s$/i.test(X)&&!/ss$/i.test(X))return X.replace(/s$/i,"");return X}function jQ(X){return X.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function zU(X){return jQ(LQ(X))}async function LU(X,$){if($==="postgres")return(await X.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((U)=>U.table_name);if(W0($))return(await X.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((U)=>U.table_name??U.TABLE_NAME);return(await X.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((Y)=>Y.name)}async function EQ(X,$,Z){if($==="sqlite")return(await X.unsafe(`PRAGMA table_info(${Z})`)).map((_)=>({name:_.name,sqlType:String(_.type||""),nullable:Number(_.notnull)===0,isPrimaryKey:Number(_.pk)>0}));if($==="postgres")return(await X.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
|
|
238
238
|
(SELECT COUNT(*) FROM information_schema.table_constraints tc
|
|
239
239
|
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
|
|
240
240
|
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
|
|
@@ -243,7 +243,7 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
243
243
|
ORDER BY c.ordinal_position`,[Z])).map((_)=>({name:_.column_name,sqlType:String(_.data_type||""),nullable:String(_.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(_.is_pk)>0}));return(await X.unsafe(`SELECT column_name, data_type, is_nullable, column_key
|
|
244
244
|
FROM information_schema.columns
|
|
245
245
|
WHERE table_name = ? AND table_schema = DATABASE()
|
|
246
|
-
ORDER BY ordinal_position`,[Z])).map((U)=>({name:U.column_name??U.COLUMN_NAME,sqlType:String(U.data_type??U.DATA_TYPE??""),nullable:String(U.is_nullable??U.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(U.column_key??U.COLUMN_KEY).toUpperCase()==="PRI"}))}function
|
|
246
|
+
ORDER BY ordinal_position`,[Z])).map((U)=>({name:U.column_name??U.COLUMN_NAME,sqlType:String(U.data_type??U.DATA_TYPE??""),nullable:String(U.is_nullable??U.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(U.column_key??U.COLUMN_KEY).toUpperCase()==="PRI"}))}function GQ(X,$){let Z=zU(X),Y=$.find((_)=>_.isPrimaryKey)?.name??"id",U=$.map((_)=>{let Q=[`type: '${zQ(_.sqlType)}'`];if(!_.nullable&&!_.isPrimaryKey)Q.push("required: true");return` ${_.name}: { ${Q.join(", ")} },`}).join(`
|
|
247
247
|
`);return`export const ${Z} = defineModel({
|
|
248
248
|
name: '${Z}',
|
|
249
249
|
table: '${X}',
|
|
@@ -252,7 +252,7 @@ Goodbye!`),$8.exit(0)}),$.prompt()}async function qG(){return i_()}var l_=e(()=>
|
|
|
252
252
|
${U}
|
|
253
253
|
},
|
|
254
254
|
})
|
|
255
|
-
`}async function
|
|
255
|
+
`}async function pG(X={}){let $=f.dialect||"postgres",Z=R0(),Y=X.tables?.length?X.tables:await LU(Z,$),U=[];for(let _ of Y){let Q=await EQ(Z,$,_);if(!Q.length)continue;U.push({table:_,modelName:zU(_),primaryKey:Q.find((L)=>L.isPrimaryKey)?.name??"id",columns:Q,source:GQ(_,Q)})}return U}function $5(X,$,Z){if(Z?.enumValues&&Z.enumValues.length>0)return"enum";let Y=String(X||"").toLowerCase().trim(),U=Y.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(W0($)&&/^tinyint\(1\)/.test(Y))return"boolean";if(/^bool/.test(U))return"boolean";if(U==="int8"||U==="bigint"||U==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(U))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(U)){let _=Y.match(/\((\d+)\)/),Q=_?Number(_[1]):void 0;return Q!==void 0&&Q>255?"text":"string"}if(/text|clob/.test(U))return"text";if(U==="float8"||/^double/.test(U))return"double";if(/^(?:real|float4|float)/.test(U))return"float";if(/^(?:numeric|decimal|money)/.test(U))return"decimal";if(U==="date")return"date";if(/^(?:timestamp|datetime)/.test(U))return"datetime";if(/^time/.test(U))return"string";if(/json/.test(U))return"json";if(/^enum/.test(U))return"enum";return"string"}function jU(X,$){let Z=`${$}_`;return X.startsWith(Z)?X.slice(Z.length):X}function yX(X){let $=String(X??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function FQ(X,$){let Z=await X.unsafe(`PRAGMA table_info(${JSON.stringify($)})`),Y=await X.unsafe(`PRAGMA index_list(${JSON.stringify($)})`),U=await X.unsafe(`PRAGMA foreign_key_list(${JSON.stringify($)})`),_=await X.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[$]),Q=String(_?.[0]?.sql??""),L=new Map;for(let V of U)L.set(String(V.from),{table:String(V.table),column:String(V.to??"id"),onDelete:yX(V.on_delete),onUpdate:yX(V.on_update)});let z=[],j=new Set;for(let V of Y){let G=String(V.origin??""),J=String(V.name??"");if(G==="pk"||J.startsWith("sqlite_autoindex_"))continue;let F=(await X.unsafe(`PRAGMA index_info(${JSON.stringify(J)})`)).map((D)=>String(D.name)).filter(Boolean);if(F.length===0)continue;let K=Number(V.unique)===1;if(K&&F.length===1)j.add(F[0]);z.push({name:jU(J,$),columns:F,type:K?"unique":"index"})}let E=Z.map((V)=>{let G=String(V.name),J=OQ(Q,G),W=Number(V.pk)>0,F=V.dflt_value,K=F!==null&&F!==void 0;return{name:G,type:$5(String(V.type??""),"sqlite",{enumValues:J}),isPrimaryKey:W,isUnique:j.has(G),isNullable:W?!1:Number(V.notnull)===0,hasDefault:K,defaultValue:K?Z5(F):void 0,enumValues:J,references:L.get(G)}});return{table:$,columns:E,indexes:z}}function OQ(X,$){if(!X)return;let Z=new RegExp(`(?:"${$}"|\`${$}\`|\\b${$}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),Y=X.match(Z);if(!Y)return;let U=Y[1].split(",").map((_)=>_.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((_)=>_.length>0);return U.length>0?U:void 0}function Z5(X){if(typeof X==="number"||typeof X==="boolean")return X;return String(X)}async function JQ(X,$){let Z=await X.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
|
|
256
256
|
(SELECT COUNT(*) FROM information_schema.table_constraints tc
|
|
257
257
|
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
|
|
258
258
|
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
|
|
@@ -272,7 +272,7 @@ ${U}
|
|
|
272
272
|
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
|
|
273
273
|
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
|
|
274
274
|
JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
|
|
275
|
-
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[$]),_=new Map;for(let j of U)_.set(String(j.column_name),{table:String(j.ref_table),column:String(j.ref_column??"id"),onDelete:yX(j.delete_rule),onUpdate:yX(j.update_rule)});let{indexes:Q,uniqueColumns:L}=
|
|
275
|
+
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[$]),_=new Map;for(let j of U)_.set(String(j.column_name),{table:String(j.ref_table),column:String(j.ref_column??"id"),onDelete:yX(j.delete_rule),onUpdate:yX(j.update_rule)});let{indexes:Q,uniqueColumns:L}=EU($,Y.map((j)=>({indexName:String(j.index_name),isUnique:j.is_unique===!0||j.is_unique==="t",isPrimary:j.is_primary===!0||j.is_primary==="t",column:String(j.column_name),where:j.where_clause?String(j.where_clause):void 0}))),z=Z.map((j)=>{let E=String(j.column_name),V=Number(j.is_pk)>0,G=j.column_default==null?null:String(j.column_default),J=G!=null&&/nextval\(/i.test(G),W=G!=null&&!J;return{name:E,type:$5(String(j.data_type??j.udt_name??""),"postgres"),isPrimaryKey:V,isUnique:L.has(E),isNullable:V?!1:String(j.is_nullable).toUpperCase()==="YES",hasDefault:W,defaultValue:W?Z5(G):void 0,references:_.get(E)}});return{table:$,columns:z,indexes:Q}}async function WQ(X,$){let Z=await X.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
|
|
276
276
|
FROM information_schema.columns
|
|
277
277
|
WHERE table_name = ? AND table_schema = DATABASE()
|
|
278
278
|
ORDER BY ordinal_position`,[$]),Y=await X.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
|
|
@@ -283,7 +283,7 @@ ${U}
|
|
|
283
283
|
FROM information_schema.key_column_usage kcu
|
|
284
284
|
JOIN information_schema.referential_constraints rc
|
|
285
285
|
ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
|
|
286
|
-
WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[$]),_=new Map;for(let j of U)_.set(String(j.column_name??j.COLUMN_NAME),{table:String(j.ref_table??j.REF_TABLE),column:String(j.ref_column??j.REF_COLUMN??"id"),onDelete:yX(j.delete_rule??j.DELETE_RULE),onUpdate:yX(j.update_rule??j.UPDATE_RULE)});let{indexes:Q,uniqueColumns:L}=
|
|
286
|
+
WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[$]),_=new Map;for(let j of U)_.set(String(j.column_name??j.COLUMN_NAME),{table:String(j.ref_table??j.REF_TABLE),column:String(j.ref_column??j.REF_COLUMN??"id"),onDelete:yX(j.delete_rule??j.DELETE_RULE),onUpdate:yX(j.update_rule??j.UPDATE_RULE)});let{indexes:Q,uniqueColumns:L}=EU($,Y.map((j)=>({indexName:String(j.index_name??j.INDEX_NAME),isUnique:Number(j.non_unique??j.NON_UNIQUE)===0,isPrimary:String(j.index_name??j.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(j.column_name??j.COLUMN_NAME)}))),z=Z.map((j)=>{let E=String(j.column_name??j.COLUMN_NAME),V=String(j.column_type??j.COLUMN_TYPE??""),G=VQ(V),W=String(j.column_key??j.COLUMN_KEY??"").toUpperCase()==="PRI",F=j.column_default??j.COLUMN_DEFAULT,K=F!=null;return{name:E,type:$5(String(j.data_type??j.DATA_TYPE??V),"mysql",{enumValues:G}),isPrimaryKey:W,isUnique:L.has(E),isNullable:W?!1:String(j.is_nullable??j.IS_NULLABLE).toUpperCase()==="YES",hasDefault:K,defaultValue:K?Z5(F):void 0,enumValues:G,references:_.get(E)}});return{table:$,columns:z,indexes:Q}}function VQ(X){let $=X.match(/^enum\((.*)\)$/i);if(!$)return;return $[1].split(",").map((Z)=>Z.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((Z)=>Z.length>0)}function EU(X,$){let Z=new Map;for(let _ of $){if(_.isPrimary)continue;let Q=Z.get(_.indexName)??{isUnique:_.isUnique,isPrimary:_.isPrimary,columns:[],where:_.where};Q.columns.push(_.column),Z.set(_.indexName,Q)}let Y=[],U=new Set;for(let[_,Q]of Z){if(Q.columns.length===0)continue;if(Q.isUnique&&Q.columns.length===1)U.add(Q.columns[0]);Y.push({name:jU(_,X),columns:Q.columns,type:Q.isUnique?"unique":"index",where:Q.where})}return{indexes:Y,uniqueColumns:U}}async function IQ(X,$={}){let Z=X||f.dialect||"postgres",Y=R0(),_=(($.tables?.length)?$.tables:await LU(Y,Z)).filter((L)=>L!=="migrations"),Q=[];for(let L of _){let z;if(Z==="sqlite")z=await FQ(Y,L);else if(Z==="postgres")z=await JQ(Y,L);else z=await WQ(Y,L);if(z.columns.length>0)Q.push(z)}return{dialect:Z,tables:Q}}var GU=t(()=>{d0(),y0()});function DQ(X){let $=X;while($!==kY($)){if(P1(T1($,"package.json")))return $;$=kY($)}return FU.cwd()}async function nG(X,$={}){let Z=DQ(FU.cwd()),Y=$.dir||T1(Z,"app/Models");if(!P1(Y))KQ(Y,{recursive:!0}),console.log(`-- Created models directory: ${Y}`);let U=X.charAt(0).toUpperCase()+X.slice(1),_=$.table||`${X.toLowerCase()}s`,Q=`${U}.ts`,L=T1(Y,Q);if(P1(L))throw console.error(`-- Model already exists: ${L}`),Error(`Model already exists: ${L}`);let j=$.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
|
|
287
287
|
updated_at: { validation: { rule: v.date() } },`:"",E=`import { v } from '@stacksjs/ts-validation'
|
|
288
288
|
import { defineModel } from 'bun-query-builder'
|
|
289
289
|
|
|
@@ -303,25 +303,25 @@ ${j}
|
|
|
303
303
|
})
|
|
304
304
|
|
|
305
305
|
export default model
|
|
306
|
-
`;
|
|
306
|
+
`;RQ(L,E),console.log(`-- \u2713 Created model: ${L}`),console.log(`-- Table: ${_}`)}var MQ=()=>{};class Y5{quoteIdentifier(X){return`\`${X.replace(/`/g,"``")}\``}getColumnType(X){switch(X.type){case"string":return`varchar(${X.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"json":return"json";case"enum":if(X.enumValues&&X.enumValues.length>0)return`ENUM(${X.enumValues.map((Z)=>`'${Z.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(X){return this.getColumnType(X)}getAutoIncrementClause(X){if(X.isPrimaryKey&&(X.type==="integer"||X.type==="bigint"))return"auto_increment";return""}getDefaultValue(X){if(!X.hasDefault||X.defaultValue===void 0)return"";let $=X.defaultValue;if(typeof $==="string"){let Z=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],Y=$.toUpperCase();if(Z.includes(Y))return`default ${Y}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?1:0}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(X,$){return""}createTable(X){let $=X.columns.map((Z)=>this.renderColumn(Z)).join(`,
|
|
307
307
|
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(X.table)} (
|
|
308
308
|
${$}
|
|
309
309
|
);`}createIndex(X,$){if($.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${$.name}' on table '${X}' uses WHERE clause: ${$.where}`);let Z=$.type==="unique"?"UNIQUE ":"",Y=`${X}_${$.name}`,U=$.columns.map((_)=>this.quoteIdentifier(_)).join(", ");return`CREATE ${Z}INDEX ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(X)} (${U});`}addForeignKey(X,$,Z,Y,U,_){let Q=`${X}_${$}_fk`,L=`ALTER TABLE ${this.quoteIdentifier(X)} ADD CONSTRAINT ${this.quoteIdentifier(Q)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Z)}(${this.quoteIdentifier(Y)})`;if(U)L+=` ON DELETE ${U.toUpperCase()}`;if(_)L+=` ON UPDATE ${_.toUpperCase()}`;return`${L};`}addColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} ADD COLUMN ${Y.join(" ")};`}modifyColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} MODIFY COLUMN ${Y.join(" ")};`}renameColumn(X,$,Z){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Z)};`}renameTable(X,$){return`RENAME TABLE ${this.quoteIdentifier(X)} TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable(X){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(X)}`}dropColumn(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(X,$){let Z=`${X}_${$}`;return`DROP INDEX ${this.quoteIdentifier(Z)} ON ${this.quoteIdentifier(X)};`}dropEnumType(X){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
310
310
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
311
311
|
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
312
312
|
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
313
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(X){let $=this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey){Z.push("PRIMARY KEY");let U=this.getAutoIncrementClause(X);if(U)Z.push(U)}if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);return Z.join(" ")}}class
|
|
313
|
+
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(X){let $=this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey){Z.push("PRIMARY KEY");let U=this.getAutoIncrementClause(X);if(U)Z.push(U)}if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);if(X.references){let U=`REFERENCES ${this.quoteIdentifier(X.references.table)}(${this.quoteIdentifier(X.references.column)})`;if(X.references.onDelete)U+=` ON DELETE ${X.references.onDelete.toUpperCase()}`;if(X.references.onUpdate)U+=` ON UPDATE ${X.references.onUpdate.toUpperCase()}`;Z.push(U)}return Z.join(" ")}}class OU{quoteIdentifier(X){return`"${X.replace(/"/g,'""')}"`}getColumnType(X){switch(X.type){case"string":return`varchar(${X.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"timestamp";case"json":return"jsonb";case"enum":if(X.enumValues&&X.enumValues.length>0)return this.quoteIdentifier(X.enumTypeName??`${X.name}_type`);return"text";default:return"text"}}getPrimaryKeyType(X){switch(X.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(X)}}getAutoIncrementClause(X){return""}getDefaultValue(X){if(!X.hasDefault||X.defaultValue===void 0)return"";let $=X.defaultValue;if(typeof $==="string"){let Z=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],Y=$.toUpperCase();if(Z.includes(Y))return`default ${Y}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?"true":"false"}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(X,$){let Z=$.map((Y)=>`'${Y.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(X)} AS ENUM (${Z});`}createTable(X){let $=X.columns.map((Z)=>this.renderColumn(Z)).join(`,
|
|
314
314
|
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(X.table)} (
|
|
315
315
|
${$}
|
|
316
316
|
);`}createIndex(X,$){let Z=$.type==="unique"?"UNIQUE ":"",Y=`${X}_${$.name}`,U=$.columns.map((Q)=>this.quoteIdentifier(Q)).join(", "),_=$.where?` WHERE ${$.where}`:"";return`CREATE ${Z}INDEX IF NOT EXISTS ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(X)} (${U})${_};`}addForeignKey(X,$,Z,Y,U,_){let Q=`${X}_${$}_fk`,L=`ALTER TABLE ${this.quoteIdentifier(X)} ADD CONSTRAINT ${this.quoteIdentifier(Q)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Z)}(${this.quoteIdentifier(Y)})`;if(U)L+=` ON DELETE ${U.toUpperCase()}`;if(_)L+=` ON UPDATE ${_.toUpperCase()}`;return`${L};`}addColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} ADD COLUMN ${Y.join(" ")};`}modifyColumn(X,$){let Z=this.getColumnType($);return`ALTER TABLE ${this.quoteIdentifier(X)} ALTER COLUMN ${this.quoteIdentifier($.name)} TYPE ${Z} USING ${this.quoteIdentifier($.name)}::${Z};`}renameColumn(X,$,Z){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Z)};`}renameTable(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable(X){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(X)} CASCADE`}dropColumn(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(X,$){let Z=`${X}_${$}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Z)};`}dropEnumType(X){return`DROP TYPE IF EXISTS ${this.quoteIdentifier(X)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
317
317
|
id SERIAL PRIMARY KEY,
|
|
318
318
|
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
319
319
|
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
320
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}renderColumn(X){let $=X.isPrimaryKey?this.getPrimaryKeyType(X):this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey)Z.push("PRIMARY KEY");if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);return Z.join(" ")}}var
|
|
320
|
+
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}renderColumn(X){let $=X.isPrimaryKey?this.getPrimaryKeyType(X):this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey)Z.push("PRIMARY KEY");if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);if(X.references){let U=`REFERENCES ${this.quoteIdentifier(X.references.table)}(${this.quoteIdentifier(X.references.column)})`;if(X.references.onDelete)U+=` ON DELETE ${X.references.onDelete.toUpperCase()}`;if(X.references.onUpdate)U+=` ON UPDATE ${X.references.onUpdate.toUpperCase()}`;Z.push(U)}return Z.join(" ")}}var JU,xY=t(()=>{JU=class extends Y5{createTable($){let Z=$.columns.map((Q)=>this.renderColumn(Q)).join(`,
|
|
321
321
|
`),Y=[];if($.tableKind!=="reference"){let Q=$.shardKey?.length?$.shardKey:$.columns.filter((L)=>L.isPrimaryKey).map((L)=>L.name);if(Q&&Q.length>0)Y.push(`SHARD KEY (${Q.map((L)=>this.quoteIdentifier(L)).join(", ")})`)}if($.tableKind!=="rowstore"&&$.tableKind!=="reference"){let Q=$.sortKey?.length?$.sortKey:void 0;Y.push(`SORT KEY (${(Q??[]).map((L)=>this.quoteIdentifier(L)).join(", ")})`)}let U=[Z,...Y].join(`,
|
|
322
322
|
`);return`CREATE${this.tableKindSuffix($.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
323
323
|
${U}
|
|
324
|
-
);`}tableKindSuffix($){switch($){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex($,Z){if(Z.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${Z.name}' on table '${$}' uses WHERE clause: ${Z.where}`);return super.createIndex($,Z)}}});function
|
|
324
|
+
);`}tableKindSuffix($){switch($){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex($,Z){if(Z.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${Z.name}' on table '${$}' uses WHERE clause: ${Z.where}`);return super.createIndex($,Z)}}});function WU(X){return X==="integer"||X==="bigint"||X==="float"||X==="double"||X==="decimal"}class VU{quoteIdentifier(X){return`"${X.replace(/"/g,'""')}"`}getColumnType(X){if(X.name.endsWith("_id")&&WU(X.type))return"INTEGER";switch(X.type){case"string":return"TEXT";case"text":return"TEXT";case"boolean":return"INTEGER";case"integer":return"INTEGER";case"bigint":return"INTEGER";case"float":return"REAL";case"double":return"REAL";case"decimal":return"REAL";case"date":return"TEXT";case"datetime":return"TEXT";case"json":return"TEXT";case"enum":if(X.enumValues&&X.enumValues.length>0){let $=X.enumValues.map((Z)=>`'${Z.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(X.name)} IN (${$}))`}return"TEXT";default:return"TEXT"}}getPrimaryKeyType(X){return this.getColumnType(X)}getAutoIncrementClause(X){if(X.isPrimaryKey&&(X.type==="integer"||X.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(X){if(!X.hasDefault||X.defaultValue===void 0)return"";let $=X.defaultValue;if(typeof $==="string"){if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes($.toUpperCase()))return`default ${$.toUpperCase()}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?1:0}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(X,$){return""}createTable(X){let $=X.columns.map((Z)=>this.renderColumn(Z)).join(`,
|
|
325
325
|
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(X.table)} (
|
|
326
326
|
${$}
|
|
327
327
|
);`}createIndex(X,$){let Z=$.type==="unique"?"UNIQUE ":"",Y=`${X}_${$.name}`,U=$.columns.map((Q)=>this.quoteIdentifier(Q)).join(", "),_=$.where?` WHERE ${$.where}`:"";return`CREATE ${Z}INDEX IF NOT EXISTS ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(X)} (${U})${_};`}addForeignKey(X,$,Z,Y,U,_){return""}addColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} ADD COLUMN ${Y.join(" ")};`}modifyColumn(X,$){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(X)}.${this.quoteIdentifier($.name)}`}renameColumn(X,$,Z){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Z)};`}renameTable(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(X){let{target:$,tempName:Z,columnSource:Y}=X,U=(j)=>this.quoteIdentifier(j),_=$.columns.map((j)=>this.renderColumn(j)).join(`,
|
|
@@ -332,24 +332,24 @@ export default model
|
|
|
332
332
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
333
333
|
migration TEXT NOT NULL UNIQUE,
|
|
334
334
|
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
335
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(X){let $=this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey){Z.push("PRIMARY KEY");let U=this.getAutoIncrementClause(X);if(U)Z.push(U)}if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);if(X.references){if(Z.push(`REFERENCES ${this.quoteIdentifier(X.references.table)}(${this.quoteIdentifier(X.references.column)})`),X.references.onDelete)Z.push(`ON DELETE ${X.references.onDelete.toUpperCase()}`);if(X.references.onUpdate)Z.push(`ON UPDATE ${X.references.onUpdate.toUpperCase()}`)}return Z.join(" ")}}function ZX(X){switch(X){case"postgres":return new
|
|
336
|
-
`),V=z.some((G)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(G));if($.apply){let G=
|
|
335
|
+
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(X){let $=this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey){Z.push("PRIMARY KEY");let U=this.getAutoIncrementClause(X);if(U)Z.push(U)}if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);if(X.references){if(Z.push(`REFERENCES ${this.quoteIdentifier(X.references.table)}(${this.quoteIdentifier(X.references.column)})`),X.references.onDelete)Z.push(`ON DELETE ${X.references.onDelete.toUpperCase()}`);if(X.references.onUpdate)Z.push(`ON UPDATE ${X.references.onUpdate.toUpperCase()}`)}return Z.join(" ")}}function ZX(X){switch(X){case"postgres":return new OU;case"mysql":return new Y5;case"singlestore":return new JU;case"sqlite":return new VU;default:throw Error(`Unsupported dialect: ${X}`)}}var _Z=t(()=>{xY(),xY()}),IU={};i1(IU,{resetDatabase:()=>SQ,generateMigration:()=>HU,executeMigration:()=>NQ,deleteMigrationFiles:()=>CU,copyModelsToGenerated:()=>AQ,clearGeneratedDirectory:()=>wU});function a(X){if(f.verbose)console.log(X)}function U5(X,$){let Z=m0(X,".qb");return m0(Z,`model-snapshot.${$}.json`)}function qQ(X,$){let Z=U5(X,$);if(!d9(Z))return;try{let Y=DU(Z,"utf8"),U=JSON.parse(Y);if(U?.plan&&Array.isArray(U.plan.tables)&&U.plan.dialect)return U.plan;if(Array.isArray(U?.tables)&&U?.dialect)return U;a("-- Invalid snapshot format, treating as no previous state");return}catch(Y){a(`-- Could not load snapshot, treating as no previous state: ${Y instanceof Error?Y.message:String(Y)}`);return}}function PQ(X,$,Z){let Y=U5(X,$),U=m0(X,".qb");if(!d9(U))KU(U,{recursive:!0}),a(`-- Created snapshot directory: ${U}`);let _={plan:Z,hash:Vj(Z),dialect:$,updatedAt:new Date().toISOString()};MU(Y,JSON.stringify(_,null,2)),a(`-- Model snapshot saved to ${Y}`)}function fX(){return B$.cwd()}function TQ(X){let $=qU(X);if(!d9($))KU($,{recursive:!0}),a(`-- Created SQL directory: ${$}`);return $}async function HU(X,$={}){if(!X)X=m0(B$.cwd(),"app/Models");let Z=$.dialect||f.dialect||"postgres",Y=fX(),U=await dX({modelsDir:X}),_=W5(U,{dialect:Z}),Q;if(!$.full)if(Q=qQ(Y,Z),Q)a("-- Comparing with stored model snapshot");else{let G=m0(X,`.qb-migrations.${Z}.json`),J=String($.state||G);if(d9(J))try{let W=DU(J,"utf8"),F=JSON.parse(W);if(Q=F?.plan&&F.plan.tables?F.plan:F?.tables?F:void 0,Q)a("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!Q||$.fromDb)try{let W=await IQ(Z),F=new Set(_.tables.map((D)=>D.table)),K=W.tables.filter((D)=>F.has(D.table));if(K.length>0)Q={dialect:W.dialect,tables:K},a(`-- No snapshot; reconciling against live database (${K.length} matching table${K.length===1?"":"s"})`)}catch(W){a(`-- Could not introspect live database, treating as no previous state: ${W instanceof Error?W.message:String(W)}`)}if(!Q)a("-- No previous snapshot found, generating full migration")}else a("-- Full migration requested, ignoring any previous state");let L=$.full?{statements:V5(_,{dryRun:$.dryRun}),operations:_.tables.map((G)=>({kind:"create_table",table:G.table,destructive:!1,sql:""}))}:q7(Q,_,{applyRenames:$.applyRenames,dryRun:$.dryRun}),z=L.statements,j=L.operations,E=z.join(`
|
|
336
|
+
`),V=z.some((G)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(G));if($.apply){let G=HQ(m0(wQ(),"qb-migrate-")),J=m0(G,"migration.sql");try{if(V)MU(J,E),a("-- Migration applied");else a("-- No changes; nothing to apply")}catch(W){throw console.error("-- Migration failed:",W),W}}if(!$.dryRun)PQ(Y,Z,_);return{sql:E,sqlStatements:z,hasChanges:V,plan:_,operations:j}}async function NQ(X){if(!X)X=m0(B$.cwd(),"app/Models");let $=fX(),Z=TQ($),Y=f.dialect||"postgres",_=RU(Z).filter((Q)=>Q.endsWith(".sql")).sort();if(_.length===0)return a("-- No migration files found to execute"),!0;a(`-- Found ${_.length} script files to execute`);try{let Q=R0();await kQ(Q,Y);let L=await xQ(Q,Y),z=[],j=[];for(let V of _)if(V.includes("alter-")&&V.includes("-table"))j.push(V);else if(!L.includes(V))z.push(V);let E=z.length+j.length;if(E===0)return a("-- No pending migrations to execute"),!0;a(`-- Executing ${E} migrations (${z.length} permanent, ${j.length} transient)`);for(let V of z){let G=m0(Z,V);a(`-- Executing: ${V}`);try{await Q.file(G),await BQ(Q,V,Y),a(`-- \u2713 Migration ${V} executed and recorded`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}for(let V of j){let G=m0(Z,V);a(`-- Executing: ${V} (transient)`);try{await Q.file(G),a(`-- \u2713 Migration ${V} executed (not recorded)`),H8(G),a(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${V}`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}a("-- All migrations executed successfully")}catch(Q){throw console.error("-- Migration execution failed:",Q),Q}return!0}async function SQ(X,$={}){if(!X)X=m0(B$.cwd(),"app/Models");let Z=$.dialect||"postgres",Y=ZX(Z),U=fX();try{let _=Y.dropTable("migrations");try{await gZ(async(z)=>{await z.unsafe(_).execute(),a("-- Dropped migrations table")})}catch(z){console.error(z)}let Q=[],L=[];try{let z=await dX({modelsDir:X}),j=W5(z,{dialect:Z});Q=j.tables.map((V)=>V.table);let E=new Set;for(let V of j.tables)for(let G of V.columns)if(G.type==="enum"&&G.enumValues&&G.enumValues.length>0){let J=`${V.table}_${G.name}_type`;E.add(J)}L=Array.from(E)}catch(z){console.error(z),Q=[],L=[]}if(Q.length===0)a("-- No tables found to drop");else{a(`-- Dropping ${Q.length} tables: ${Q.join(", ")}`);for(let z of Q.reverse())try{let j=Y.dropTable(z);await gZ(async(E)=>{await E.unsafe(j).execute(),a(`-- Dropped table: ${z}`)})}catch(j){console.error(j),a(`-- Table ${z} may not exist, skipping drop`)}}if(L.length>0){a(`-- Dropping ${L.length} enum types: ${L.join(", ")}`);for(let z of L)try{let j=Y.dropEnumType(z);if(j)await gZ(async(E)=>{await E.unsafe(j).execute(),a(`-- Dropped enum type: ${z}`)})}catch(j){console.error(j),a(`-- Enum type ${z} may not exist, skipping drop`)}}else a("-- No enum types found to drop");if(Q.length>0)try{await CU(X,U,$)}catch(z){console.error(z),a("-- Could not clean up migration files")}else a("-- No models directory found; keeping committed migration files in place");try{await wU(U)}catch(z){console.error(z),a("-- Could not clear generated directory")}return a("-- Database reset completed successfully"),!0}catch(_){return console.error("-- Database reset failed:",_),!1}}async function CU(X,$,Z={}){if(!X)X=m0(B$.cwd(),"app/Models");if(!$)$=fX();let Y=String(Z.dialect||"postgres"),U=U5($,Y);if(d9(U))H8(U),a(`-- Removed model snapshot file: ${U}`);let _=m0(X,`.qb-migrations.${Y}.json`),Q=String(Z.state||_);if(d9(Q))H8(Q),a(`-- Removed legacy migration state file: ${Q}`);let L=qU($);if(d9(L)){let j=RU(L).filter((E)=>E.endsWith(".sql"));for(let E of j){let V=m0(L,E);H8(V),a(`-- Removed migration file: ${E}`)}a(`-- Cleaned up ${j.length} migration files from migrations directory`)}}async function AQ(X,$){}async function wU(X){if(!X)X=fX();let $=m0(X,"generated");if(d9($))try{CQ($,{recursive:!0,force:!0}),a("-- Cleared generated directory")}catch(Z){console.error("-- Failed to clear generated directory:",Z)}}function qU(X){if(!X)X=fX();return m0(X,"database","migrations")}async function kQ(X,$){let Y=ZX($).createMigrationsTable();try{await X.unsafe(Y).execute(),a("-- Migrations table ready")}catch(U){throw console.error("-- Failed to create migrations table:",U),U}}async function xQ(X,$){let Z=ZX($);try{return(await X.unsafe(Z.getExecutedMigrationsQuery()).execute()).map((U)=>U.migration)}catch(Y){return console.error("-- Failed to get executed migrations:",Y),[]}}async function BQ(X,$,Z){let Y=ZX(Z);try{a(`-- Recording migration: ${$}`),await X.unsafe(Y.recordMigrationQuery(),[$]).execute(),a(`-- Successfully recorded migration: ${$}`)}catch(U){throw console.error(`-- Failed to record migration ${$}:`,U),U}}var _5=t(()=>{d0(),$X(),_Z(),y0(),GU()});async function rG(X,$={}){return HU(X,$)}var yQ=t(()=>{_5()});function bQ(X){let $=[],Z="",Y=!1,_=X.split(`
|
|
337
337
|
`).filter((Q)=>!/^\s*--/.test(Q)).join(`
|
|
338
|
-
`);for(let Q=0;Q<_.length;Q++){let L=_[Q];if(L==="'")Y=!Y;if(L===";"&&!Y){if(Z.trim())$.push(Z.trim());Z=""}else Z+=L}if(Z.trim())$.push(Z.trim());return $}function
|
|
338
|
+
`);for(let Q=0;Q<_.length;Q++){let L=_[Q];if(L==="'")Y=!Y;if(L===";"&&!Y){if(Z.trim())$.push(Z.trim());Z=""}else Z+=L}if(Z.trim())$.push(Z.trim());return $}function fQ(X,$=f.dialect){let Z=(_)=>W0($)?`\`${_}\``:`"${_}"`,Y=[],U=[];for(let _ of bQ(X)){let Q;if(Q=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(_))Y.push(`DROP TABLE IF EXISTS ${Z(Q[1])}`);else if(Q=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+)?["`']?(\w+)["`']?/i.exec(_))Y.push(`ALTER TABLE ${Z(Q[1])} DROP COLUMN ${Z(Q[2])}`);else if(Q=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(_))Y.push(W0($)&&Q[2]?`DROP INDEX ${Z(Q[1])} ON ${Z(Q[2])}`:`DROP INDEX IF EXISTS ${Z(Q[1])}`);else U.push(_)}return{down:Y.reverse(),skipped:U}}function gQ(X){let $=X;while($!==BY($)){if(N1(Q5($,"package.json")))return $;$=BY($)}return PU.cwd()}function dQ(X){if(!X)X=gQ(PU.cwd());return Q5(X,"database","migrations")}async function XF(X={}){let $=X.steps||1,Z=X.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let Y=R0(),U=[];try{U=await Y.unsafe(`
|
|
339
339
|
SELECT migration, executed_at
|
|
340
340
|
FROM migrations
|
|
341
341
|
ORDER BY executed_at DESC, migration DESC
|
|
342
|
-
`)}catch(z){console.log("-- Migrations table not found. Nothing to rollback.",z);return}if(U.length===0){console.log("-- No migrations to rollback");return}let _=U.slice(0,$);console.log(`-- Found ${U.length} executed migrations`),console.log(`-- Rolling back ${_.length} migration(s):`),console.log();for(let z of _)console.log(` - ${z.migration}`);console.log();let Q=
|
|
342
|
+
`)}catch(z){console.log("-- Migrations table not found. Nothing to rollback.",z);return}if(U.length===0){console.log("-- No migrations to rollback");return}let _=U.slice(0,$);console.log(`-- Found ${U.length} executed migrations`),console.log(`-- Rolling back ${_.length} migration(s):`),console.log();for(let z of _)console.log(` - ${z.migration}`);console.log();let Q=dQ(),L=!1;for(let z of _)try{let j=Q5(Q,z.migration);if(Z&&N1(j)){let V=hQ(j,"utf8"),{down:G,skipped:J}=fQ(V);for(let W of G)await Y.unsafe(W),console.log(`-- \u21A9 ${W}`),L=!0;if(J.length>0)console.log(`-- \u26A0\uFE0F ${J.length} statement(s) in ${z.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let E="DELETE FROM migrations WHERE migration = $1";if(await Y.unsafe(E,[z.migration]),console.log(`-- \u2713 Removed migration record: ${z.migration}`),N1(j))vQ(j),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${z.migration}`)}catch(j){throw console.error(`-- \u2717 Failed to rollback migration ${z.migration}:`,j),j}if(console.log(),Z)console.log(L?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(Y){throw console.error("-- Rollback failed:",Y),Y}}var pQ=t(()=>{d0(),y0()});function mQ(X){let $=X;while($!==yY($)){if(TU(NU($,"package.json")))return $;$=yY($)}return SU.cwd()}function uQ(X){if(!X)X=mQ(SU.cwd());return NU(X,"database","migrations")}async function nQ(){let X=f.dialect||"postgres",$=ZX(X),Z=uQ();if(console.log("-- Migration Status"),console.log(`-- Dialect: ${X}`),console.log(`-- SQL directory: ${Z}`),console.log(),!TU(Z))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let U=cQ(Z).filter((_)=>_.endsWith(".sql")).sort();if(U.length===0)return console.log("-- No migration files found"),[];try{let _=R0(),Q=[];try{Q=await _.unsafe($.getExecutedMigrationsQuery())}catch(G){console.log("-- Migrations table not found. All migrations are pending.",G),console.log()}let L=new Map(Q.map((G)=>[G.migration,G.executed_at])),z=U.map((G)=>{if(G.includes("alter-")&&G.includes("-table"))return{file:G,status:"transient"};let J=L.get(G);return{file:G,status:J?"executed":"pending",executedAt:J}}),j=z.filter((G)=>G.status==="executed"),E=z.filter((G)=>G.status==="pending"),V=z.filter((G)=>G.status==="transient");if(console.log(`-- Total migrations: ${U.length}`),console.log(`-- Executed: ${j.length}`),console.log(`-- Pending: ${E.length}`),console.log(`-- Transient: ${V.length}`),console.log(),j.length>0){console.log("\u2713 Executed Migrations:");for(let G of j)console.log(` - ${G.file} ${G.executedAt?`(${new Date(G.executedAt).toLocaleString()})`:""}`);console.log()}if(E.length>0){console.log("\u25CB Pending Migrations:");for(let G of E)console.log(` - ${G.file}`);console.log()}if(V.length>0){console.log("\u26A1 Transient Migrations (ALTER TABLE - not tracked):");for(let G of V)console.log(` - ${G.file}`);console.log()}return z}catch(_){throw console.error("-- Failed to get migration status:",_),_}}async function UF(){return nQ()}var iQ=t(()=>{d0(),_Z(),y0()});async function LF(X,$={}){let Z=$.dir||hY(sQ.cwd(),"app/Models");try{let Y=lQ(Z),U=Y.find((E)=>{return E.replace(dZ(E),"").toLowerCase()===X.toLowerCase()});if(!U){console.error(`Model "${X}" not found in ${Z}`),console.log(`Available models: ${Y.filter((E)=>[".ts",".js"].includes(dZ(E))).map((E)=>E.replace(dZ(E),"")).join(", ")}`);return}let Q=await import(hY(Z,U)),L=Q.default||Q[Object.keys(Q)[0]];if(!L||!L.name){console.error(`Invalid model file: ${U}`);return}let z={name:L.name,table:L.table||`${L.name.toLowerCase()}s`,primaryKey:L.primaryKey||"id",attributes:L.attributes||{},relations:L.relations,scopes:L.scopes,indexes:L.indexes,timestamps:L.timestamps!==!1,softDeletes:L.softDeletes===!0},j=[];if(L.beforeCreate)j.push("beforeCreate");if(L.afterCreate)j.push("afterCreate");if(L.beforeUpdate)j.push("beforeUpdate");if(L.afterUpdate)j.push("afterUpdate");if(L.beforeDelete)j.push("beforeDelete");if(L.afterDelete)j.push("afterDelete");if(j.length>0)z.hooks=j;if($.json)return console.log(JSON.stringify(z,null,2)),z;console.log(`
|
|
343
343
|
\uD83D\uDCE6 Model: ${z.name}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Table: ${z.table}`),console.log(`Primary Key: ${z.primaryKey}`),console.log(`Timestamps: ${z.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${z.softDeletes?"\u2713":"\u2717"}`),console.log(`
|
|
344
344
|
\uD83D\uDCCB Attributes (${Object.keys(z.attributes).length}):`);for(let[E,V]of Object.entries(z.attributes)){let G=V.type||"string",J=V.required?"(required)":"",W=V.unique?"(unique)":"",F=V.default!==void 0?`= ${JSON.stringify(V.default)}`:"";console.log(` \u2022 ${E}: ${G} ${J} ${W} ${F}`.trim())}if(z.relations&&Object.keys(z.relations).length>0){console.log(`
|
|
345
345
|
\uD83D\uDD17 Relations (${Object.keys(z.relations).length}):`);for(let[E,V]of Object.entries(z.relations)){let G=V.type||"unknown",J=V.model||V.table||"unknown";console.log(` \u2022 ${E}: ${G} \u2192 ${J}`)}}if(z.scopes&&Object.keys(z.scopes).length>0){console.log(`
|
|
346
346
|
\uD83D\uDD0D Scopes (${Object.keys(z.scopes).length}):`);for(let E of Object.keys(z.scopes))console.log(` \u2022 ${E}()`)}if(z.hooks&&z.hooks.length>0){console.log(`
|
|
347
347
|
\uD83E\uDE9D Hooks (${z.hooks.length}):`);for(let E of z.hooks)console.log(` \u2022 ${E}`)}if(z.indexes&&z.indexes.length>0){console.log(`
|
|
348
|
-
\uD83D\uDCC7 Indexes (${z.indexes.length}):`);for(let E of z.indexes){let V=Array.isArray(E.columns)?E.columns.join(", "):E.columns,G=E.unique?"(unique)":"";console.log(` \u2022 ${E.name||"unnamed"}: [${V}] ${G}`.trim())}}return console.log(),z}catch(Y){throw console.error(`Error loading model "${X}":`,Y.message),Y}}var
|
|
349
|
-
`);for(let L of U)try{let z=
|
|
350
|
-
`)}let _=Z.filter((L)=>!L.error).length,Q=Z.filter((L)=>L.error).length;if($.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${_} successful, ${Q} failed`);if($.json)console.log(JSON.stringify(Z,null,2));return Z}catch(Y){throw console.error("Error explaining queries:",Y.message),Y}}var
|
|
351
|
-
`)}function
|
|
352
|
-
`)}var
|
|
348
|
+
\uD83D\uDCC7 Indexes (${z.indexes.length}):`);for(let E of z.indexes){let V=Array.isArray(E.columns)?E.columns.join(", "):E.columns,G=E.unique?"(unique)":"";console.log(` \u2022 ${E.name||"unnamed"}: [${V}] ${G}`.trim())}}return console.log(),z}catch(Y){throw console.error(`Error loading model "${X}":`,Y.message),Y}}var oQ=()=>{};async function jF(){let $=await R0().ping();return console.log($?"OK":"NOT READY"),$}var rQ=t(()=>{y0()});async function FF(X,$={}){let Z=[];try{let Y=tQ(X),U=[];if(Y.isDirectory())U=aQ(X).filter((z)=>bY(z)===".sql").map((z)=>eQ(X,z));else if(Y.isFile()&&bY(X)===".sql")U=[X];else return console.error("Path must be a .sql file or directory containing .sql files"),Z;if(U.length===0)return console.log("No .sql files found"),Z;if($.verbose)console.log(`Analyzing ${U.length} SQL file(s)...
|
|
349
|
+
`);for(let L of U)try{let z=vY(L,"utf8").trim();if(!z){if($.verbose)console.log(`\u2298 ${L}: empty file`);continue}if($.verbose)console.log(`\uD83D\uDCC4 ${L}`),console.log(` Query: ${z.substring(0,60)}${z.length>60?"...":""}`);let j=await m`EXPLAIN ${m.unsafe(z)}`;if(Z.push({file:L,query:z,plan:Array.isArray(j)?j:[j]}),$.verbose&&!$.json){if(console.log(" Plan:"),Array.isArray(j))for(let E of j)if(typeof E==="string")console.log(` ${E}`);else if(E["QUERY PLAN"])console.log(` ${E["QUERY PLAN"]}`);else if(E.plan)console.log(` ${JSON.stringify(E.plan)}`);else console.log(` ${JSON.stringify(E)}`);console.log()}}catch(z){if(Z.push({file:L,query:vY(L,"utf8").trim(),plan:[],error:z.message}),$.verbose)console.log(` \u2717 Error: ${z.message}
|
|
350
|
+
`)}let _=Z.filter((L)=>!L.error).length,Q=Z.filter((L)=>L.error).length;if($.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${_} successful, ${Q} failed`);if($.json)console.log(JSON.stringify(Z,null,2));return Z}catch(Y){throw console.error("Error explaining queries:",Y.message),Y}}var Xz=t(()=>{$X()});async function VF(X={}){let $=X.dir||Zz(Yz.cwd(),"app/Models"),Z=X.format||"mermaid";try{let Y=await dX({modelsDir:$});if(!Y||Object.keys(Y).length===0)return console.error("No models found"),"";let U="";if(Z==="mermaid")U=Uz(Y);else if(Z==="dot")U=_z(Y);else return console.error(`Unsupported format: ${Z}`),"";if(X.output)$z(X.output,U,"utf8"),console.log(`\u2713 Diagram written to: ${X.output}`);else console.log(U);return U}catch(Y){throw console.error("Error generating diagram:",Y.message),Y}}function Uz(X){let $=["erDiagram"];for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.attributes||{};$.push(` ${U} {`);for(let[Q,L]of Object.entries(_)){let z=L.type||"string",j=Y.primaryKey===Q?"PK":"",E=L.unique?"UK":"",V=[j,E].filter(Boolean).join(","),G=V?` "${V}"`:"";$.push(` ${z} ${Q}${G}`)}$.push(" }")}for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.relations||{};for(let[Q,L]of Object.entries(_)){let{type:z,model:j}=L,E=X[j]?.table||`${j?.toLowerCase()}s`||"unknown",V="";if(z==="hasOne")V="||--||";else if(z==="hasMany")V="||--o{";else if(z==="belongsTo")V="}o--||";else if(z==="belongsToMany"||z==="manyToMany")V="}o--o{";else V="||--||";$.push(` ${U} ${V} ${E} : "${Q}"`)}}return $.join(`
|
|
351
|
+
`)}function _z(X){let $=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.attributes||{},Q=[];for(let[z,j]of Object.entries(_)){let E=j.type||"string",V=Y.primaryKey===z?" (PK)":"",G=j.unique?" (UK)":"";Q.push(`${z}: ${E}${V}${G}`)}let L=`${Q.join("\\l")}\\l`;$.push(` ${U} [label="{${U}|${L}}"];`)}$.push("");for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.relations||{};for(let[Q,L]of Object.entries(_)){let{type:z,model:j}=L,E=X[j]?.table||`${j?.toLowerCase()}s`||"unknown",V="";if(z==="hasOne")V="arrowhead=none, arrowtail=normal";else if(z==="hasMany")V="arrowhead=crow, arrowtail=none";else if(z==="belongsTo")V="arrowhead=normal, arrowtail=none";else if(z==="belongsToMany"||z==="manyToMany")V="arrowhead=crow, arrowtail=crow";$.push(` ${U} -> ${E} [label="${Q}", ${V}];`)}}return $.push("}"),$.join(`
|
|
352
|
+
`)}var Qz=t(()=>{y0()});function QZ(X){let $=X;while($!==fY($)){if(p8(m9($,"package.json")))return $;$=fY($)}return y$.cwd()}async function AU(X){if(!p8(X))return console.log(`-- Seeders directory not found: ${X}`),[];let Z=Lz(X).filter((U)=>(U.endsWith(".ts")||U.endsWith(".js"))&&U!=="index.ts"&&U!=="index.js"),Y=[];for(let U of Z){let _=m9(X,U);try{let Q=await import(_),L=Q.default||Q[Object.keys(Q)[0]];if(L&&typeof L==="function"){let z=new L;if(z&&typeof z.run==="function")Y.push({name:U.replace(/\.(ts|js)$/,""),instance:z})}}catch(Q){console.error(`-- Failed to load seeder ${U}:`,Q)}}return Y.sort((U,_)=>U.instance.order-_.instance.order),Y}async function Ez(X={}){let $=QZ(y$.cwd()),Z=X.seedersDir||m9($,"database/seeders"),Y=X.verbose??!0;if(Y)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${Z}`);let U=await AU(Z);if(U.length===0){console.log("-- No seeders found");return}if(Y)console.log(`-- Found ${U.length} seeder(s)`);let _=R0();for(let{name:Q,instance:L}of U)try{if(Y)console.log(`-- Seeding: ${Q}`);if(await L.run(_),Y)console.log(`-- \u2713 Seeded: ${Q}`)}catch(z){throw console.error(`-- \u2717 Failed to seed ${Q}:`,z),z}if(Y)console.log("-- All seeders completed successfully")}async function DF(X,$={}){let Z=QZ(y$.cwd()),Y=m9(Z,"database/seeders"),U=$.verbose??!0;if(U)console.log(`-- Running seeder: ${X}`);let Q=(await AU(Y)).find((z)=>z.name===X);if(!Q)throw console.error(`-- Seeder not found: ${X}`),Error(`Seeder not found: ${X}`);let L=R0();try{if(await Q.instance.run(L),U)console.log(`-- \u2713 Seeder completed: ${X}`)}catch(z){throw console.error(`-- \u2717 Seeder failed: ${X}`,z),z}}async function MF(X){let $=QZ(y$.cwd()),Z=m9($,"database/seeders");if(!p8(Z))zz(Z,{recursive:!0}),console.log(`-- Created seeders directory: ${Z}`);let U=`${X.replace(/Seeder$/i,"")}Seeder`,_=`${U}.ts`,Q=m9(Z,_);if(p8(Q))throw console.error(`-- Seeder already exists: ${Q}`),Error(`Seeder already exists: ${Q}`);let L=`import type { QueryBuilder } from 'bun-query-builder'
|
|
353
353
|
import { Seeder } from 'bun-query-builder'
|
|
354
354
|
import { faker } from '@stacksjs/ts-faker'
|
|
355
355
|
|
|
@@ -394,7 +394,7 @@ export default class ${U} extends Seeder {
|
|
|
394
394
|
return 100
|
|
395
395
|
}
|
|
396
396
|
}
|
|
397
|
-
`;
|
|
397
|
+
`;jz(Q,L),console.log(`-- \u2713 Created seeder: ${Q}`)}async function HF(X={}){let $=QZ(y$.cwd()),Z=X.modelsDir||m9($,"app/Models"),Y=X.seedersDir||m9($,"database/seeders"),U=X.verbose??!0;try{let{resetDatabase:_,generateMigration:Q,executeMigration:L}=await Promise.resolve().then(()=>(_5(),IU));if(U)console.log("-- Refreshing database...");if(await _(Z),U)console.log("-- Running migrations...");if(await Q(Z,{full:!0}),await L(),U)console.log("-- Running seeders...");if(await Ez({seedersDir:Y,verbose:U}),U)console.log("-- \u2713 Database refreshed successfully")}catch(_){throw console.error("-- \u2717 Database refresh failed:",_),_}}var Gz=t(()=>{y0()});function CF(X,$,Z={}){let Y=dX({modelsDir:X}),U=R7(Y);if(f.debug)f.debug.captureText=!0;let _=R0({schema:U}),Q=_.selectFrom($).limit(Number(Z.limit||10)).toText?.()??"";return console.log(Q||"[query]"),{sql:Q,qb:_,schema:U}}var Fz=t(()=>{d0(),y0()});async function wF(X,$={}){let Z=R0(),Y=$.params?JSON.parse($.params):void 0,U=await Z.unsafe(X,Y);return console.log(JSON.stringify(U)),U}var Oz=t(()=>{y0()});function Wz(X){let $=X;while($!==gY($)){if(Jz(kU($,"package.json")))return $;$=gY($)}return xU.cwd()}async function Vz(X){if(!X)X=kU(Wz(xU.cwd()),"app/Models");let $=f.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${X}`),console.log(`-- Dialect: ${$}`),console.log();let Z=[];try{let Y=await dX({modelsDir:X}),U=W5(Y,{dialect:$}),_=R0(),Q=[];if($==="sqlite")Q=(await _.unsafe(`
|
|
398
398
|
SELECT name FROM sqlite_master
|
|
399
399
|
WHERE type = 'table'
|
|
400
400
|
AND name NOT LIKE 'sqlite_%'
|
|
@@ -405,7 +405,7 @@ export default class ${U} extends Seeder {
|
|
|
405
405
|
WHERE table_schema = 'public'
|
|
406
406
|
AND table_type = 'BASE TABLE'
|
|
407
407
|
AND table_name != 'migrations'
|
|
408
|
-
`)).map((E)=>E.table_name);else if(
|
|
408
|
+
`)).map((E)=>E.table_name);else if(W0($))Q=(await _.unsafe(`
|
|
409
409
|
SELECT table_name
|
|
410
410
|
FROM information_schema.tables
|
|
411
411
|
WHERE table_schema = DATABASE()
|
|
@@ -415,21 +415,21 @@ export default class ${U} extends Seeder {
|
|
|
415
415
|
SELECT column_name, data_type
|
|
416
416
|
FROM information_schema.columns
|
|
417
417
|
WHERE table_name = $1
|
|
418
|
-
`,[j.table])).map((W)=>({name:W.column_name,type:W.data_type.toLowerCase()}));else if(
|
|
418
|
+
`,[j.table])).map((W)=>({name:W.column_name,type:W.data_type.toLowerCase()}));else if(W0($))E=(await _.unsafe(`
|
|
419
419
|
SELECT column_name, data_type
|
|
420
420
|
FROM information_schema.columns
|
|
421
421
|
WHERE table_name = ?
|
|
422
422
|
AND table_schema = DATABASE()
|
|
423
|
-
`,[j.table])).map((W)=>({name:W.column_name,type:W.data_type.toLowerCase()}));let V=E.map((J)=>J.name),G=j.columns.map((J)=>J.name);for(let J of j.columns)if(!V.includes(J.name))Z.push({type:"missing_column",severity:"error",table:j.table,column:J.name,expected:J.type,message:`Column '${j.table}.${J.name}' defined in model but not found in database`});for(let J of E)if(!G.includes(J.name))Z.push({type:"extra_column",severity:"warning",table:j.table,column:J.name,actual:J.type,message:`Column '${j.table}.${J.name}' exists in database but not defined in model`});for(let J of j.columns){let W=E.find((F)=>F.name===J.name);if(W){let F=(w)=>{return w.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},K=F(J.type),D=F(W.type);if(K!==D)Z.push({type:"type_mismatch",severity:"warning",table:j.table,column:J.name,expected:J.type,actual:W.type,message:`Column '${j.table}.${J.name}' type mismatch: expected '${J.type}', found '${W.type}'`})}}}let z=Z.filter((j)=>j.severity==="error").length===0;if(z&&Z.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${Z.length} issue(s)`),console.log();let j=Z.filter((V)=>V.severity==="error"),E=Z.filter((V)=>V.severity==="warning");if(j.length>0){console.log(`\u2717 Errors (${j.length}):`);for(let V of j)console.log(` - ${V.message}`);console.log()}if(E.length>0){console.log(`\u26A0 Warnings (${E.length}):`);for(let V of E)console.log(` - ${V.message}`);console.log()}if(!z)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:z,issues:Z}}catch(Y){throw console.error("-- Schema validation failed:",Y),Y}}async function PF(X){return Wz(X)}var Vz=e(()=>{d0(),UZ(),y0()});async function TF(X={}){let $=Number(X.attempts||10),Z=Number(X.delay||100),Y=K0();try{return await Y.waitForReady({attempts:$,delayMs:Z}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var Iz=e(()=>{y0()}),Kz=e(()=>{x_(),u_(),l_(),r_(),t_(),e_(),XQ(),$Q(),ZQ(),UQ(),_Q(),EU(),DQ(),U5(),BQ(),dQ(),nQ(),sQ(),oQ(),eQ(),_z(),Ez(),Gz(),Fz(),Vz(),Iz()});function mz(X,$){this[X]=JL.bind(null,$)}class A1{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!gY(X))return!0;return dY(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=gY(Z)?dY(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.timestamp).sort();return{size:$,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class k1{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function uz(X,$={}){let Z=Object.keys($).sort().map((Y)=>`${Y}:${$[Y]}`).join("|");return Z?`${X}:${Z}`:X}function nz(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function iz(X){return X.getStats().size*2}function lz(X,$={}){let Z=c8.cwd();while(Z.includes("storage"))Z=pY(Z,"..");let Y=pY(Z,X||"");if($?.relative)return Cz(c8.cwd(),Y);return Y}function x0(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sz(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof S9<"u"){let X=S9.type;if(X==="renderer"||X==="worker")return!1;return!!(S9.versions&&(S9.versions.node||S9.versions.bun))}return!1}class BU{async format(X){let $=await sz(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:MX.pid,hostname:$(),environment:MX.env.NODE_ENV||"development",platform:MX.platform,version:MX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:MX.env.NODE_ENV||MX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class m8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(X,$={}){this.name=X,this.config={...H$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new BU,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??F0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...C8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...C8};return{...C8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:H$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!x0()&&this.config.writeToFile===!0}async writeToFile(X){let $=(async()=>{let Y,U=0,_=3,Q=1000;while(U<_)try{try{try{await Nz(this.config.logDirectory,nY.F_OK|nY.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await Sz(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let L=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:M9.from(X);try{if(!Z8(this.currentLogFile))await mZ(this.currentLogFile,"",{mode:420});if(Y=uY(this.currentLogFile,"a",420),Tz(Y,L,{flag:"a"}),mY(Y),Y!==void 0)cZ(Y),Y=void 0;if((await RX(this.currentLogFile)).size===0){if(await mZ(this.currentLogFile,L,{flag:"w",mode:420}),(await RX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let j=z;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<_-1){let E=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${_}:`,E);let V=Q*2**U;await new Promise((G)=>setTimeout(G,V)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{cZ(Y)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(L){if(U===_-1){let j=L,E=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),L}U++;let z=Q*2**(U-1);await new Promise((j)=>setTimeout(j,z))}})();this.pendingOperations.push($);let Z=this.pendingOperations.length-1;try{await $}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 DX(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 DX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return DX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(x0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof X.interval==="number"?X.interval:60,Z=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,$=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=$,this.keys.set($,Z),this.encryptionKeys.set($,{key:Z,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,L])=>L.createdAt.getTime()-Q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,_=Math.max(1,U);if(Y.length>_)for(let[Q]of Y.slice(_))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return pZ(16).toString("hex")}generateKey(){return pZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=pZ(16),Y=wz("aes-256-gcm",$,Z),U=M9.isBuffer(X)?X:M9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=M9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=lY(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(M9.from(M9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(x0())return;if(!this.shouldWriteToFile())return;let X=await RX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await Y8(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await RX(Z).catch(()=>null))try{if(await iY(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await U8(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await mZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await RX(Z).catch(()=>null))await iY(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let U=(await Y8(this.config.logDirectory)).filter((_)=>_.startsWith(this.name)).sort((_,Q)=>Q.localeCompare(_));for(let _ of U.slice($.maxFiles))await U8(DX(this.config.logDirectory,_))}}}async compressLogFile(X,$){let Z=cY(X),Y=Pz($),U=lY();await xz(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),Z8(this.currentLogFile))try{let X=uY(this.currentLogFile,"r+");mY(X),cZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!x0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await Y8(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await U8(DX(this.config.logDirectory,$))}catch(Z){console.error(`Failed to delete temp file ${$}:`,Z)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?G0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||x0())return!1;let X=typeof F0.env.NO_COLOR<"u",$=F0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof F0.stderr<"u"&&F0.stderr.isTTY||typeof F0.stdout<"u"&&F0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=F0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${G0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=G0.underline(G0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>G0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>G0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>G0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>G0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>G0.strikethrough(Y)),$}supportsHyperlinks(){if(x0())return!1;let X=F0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=F0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(Az($)||$.startsWith("./")||$.startsWith("../"))$=kz($);else return null;return Z8($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){if(!this.shouldLog(X))return;let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":uU[X],G=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:G0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:G0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
|
|
424
|
-
`);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:
|
|
423
|
+
`,[j.table])).map((W)=>({name:W.column_name,type:W.data_type.toLowerCase()}));let V=E.map((J)=>J.name),G=j.columns.map((J)=>J.name);for(let J of j.columns)if(!V.includes(J.name))Z.push({type:"missing_column",severity:"error",table:j.table,column:J.name,expected:J.type,message:`Column '${j.table}.${J.name}' defined in model but not found in database`});for(let J of E)if(!G.includes(J.name))Z.push({type:"extra_column",severity:"warning",table:j.table,column:J.name,actual:J.type,message:`Column '${j.table}.${J.name}' exists in database but not defined in model`});for(let J of j.columns){let W=E.find((F)=>F.name===J.name);if(W){let F=(w)=>{return w.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},K=F(J.type),D=F(W.type);if(K!==D)Z.push({type:"type_mismatch",severity:"warning",table:j.table,column:J.name,expected:J.type,actual:W.type,message:`Column '${j.table}.${J.name}' type mismatch: expected '${J.type}', found '${W.type}'`})}}}let z=Z.filter((j)=>j.severity==="error").length===0;if(z&&Z.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${Z.length} issue(s)`),console.log();let j=Z.filter((V)=>V.severity==="error"),E=Z.filter((V)=>V.severity==="warning");if(j.length>0){console.log(`\u2717 Errors (${j.length}):`);for(let V of j)console.log(` - ${V.message}`);console.log()}if(E.length>0){console.log(`\u26A0 Warnings (${E.length}):`);for(let V of E)console.log(` - ${V.message}`);console.log()}if(!z)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:z,issues:Z}}catch(Y){throw console.error("-- Schema validation failed:",Y),Y}}async function NF(X){return Vz(X)}var Iz=t(()=>{d0(),UZ(),y0()});async function SF(X={}){let $=Number(X.attempts||10),Z=Number(X.delay||100),Y=R0();try{return await Y.waitForReady({attempts:$,delayMs:Z}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var Kz=t(()=>{y0()}),Rz=t(()=>{B_(),n_(),s_(),a_(),e_(),XQ(),$Q(),ZQ(),YQ(),_Q(),QQ(),GU(),MQ(),_5(),yQ(),pQ(),iQ(),oQ(),rQ(),Xz(),Qz(),Gz(),Fz(),Oz(),Iz(),Kz()});function uz(X,$){this[X]=WL.bind(null,$)}class A1{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!dY(X))return!0;return pY(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=dY(Z)?pY(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.timestamp).sort();return{size:$,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class k1{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function nz(X,$={}){let Z=Object.keys($).sort().map((Y)=>`${Y}:${$[Y]}`).join("|");return Z?`${X}:${Z}`:X}function iz(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function lz(X){return X.getStats().size*2}function sz(X,$={}){let Z=c8.cwd();while(Z.includes("storage"))Z=cY(Z,"..");let Y=cY(Z,X||"");if($?.relative)return wz(c8.cwd(),Y);return Y}function x0(){if(A9.env.NODE_ENV==="test"||A9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oz(){if(A9.env.NODE_ENV==="test"||A9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof A9<"u"){let X=A9.type;if(X==="renderer"||X==="worker")return!1;return!!(A9.versions&&(A9.versions.node||A9.versions.bun))}return!1}class yU{async format(X){let $=await oz(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:MX.pid,hostname:$(),environment:MX.env.NODE_ENV||"development",platform:MX.platform,version:MX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:MX.env.NODE_ENV||MX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class m8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(X,$={}){this.name=X,this.config={...H$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new yU,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...C8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...C8};return{...C8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:H$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!x0()&&this.config.writeToFile===!0}async writeToFile(X){let $=(async()=>{let Y,U=0,_=3,Q=1000;while(U<_)try{try{try{await Sz(this.config.logDirectory,iY.F_OK|iY.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await Az(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let L=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:H9.from(X);try{if(!Z8(this.currentLogFile))await mZ(this.currentLogFile,"",{mode:420});if(Y=nY(this.currentLogFile,"a",420),Nz(Y,L,{flag:"a"}),uY(Y),Y!==void 0)cZ(Y),Y=void 0;if((await RX(this.currentLogFile)).size===0){if(await mZ(this.currentLogFile,L,{flag:"w",mode:420}),(await RX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let j=z;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<_-1){let E=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${_}:`,E);let V=Q*2**U;await new Promise((G)=>setTimeout(G,V)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{cZ(Y)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(L){if(U===_-1){let j=L,E=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),L}U++;let z=Q*2**(U-1);await new Promise((j)=>setTimeout(j,z))}})();this.pendingOperations.push($);let Z=this.pendingOperations.length-1;try{await $}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 DX(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 DX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return DX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(x0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof X.interval==="number"?X.interval:60,Z=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,$=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=$,this.keys.set($,Z),this.encryptionKeys.set($,{key:Z,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,L])=>L.createdAt.getTime()-Q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,_=Math.max(1,U);if(Y.length>_)for(let[Q]of Y.slice(_))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return pZ(16).toString("hex")}generateKey(){return pZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=pZ(16),Y=qz("aes-256-gcm",$,Z),U=H9.isBuffer(X)?X:H9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=H9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=sY(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(H9.from(H9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(x0())return;if(!this.shouldWriteToFile())return;let X=await RX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await Y8(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await RX(Z).catch(()=>null))try{if(await lY(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await U8(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await mZ(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await RX(Z).catch(()=>null))await lY(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let U=(await Y8(this.config.logDirectory)).filter((_)=>_.startsWith(this.name)).sort((_,Q)=>Q.localeCompare(_));for(let _ of U.slice($.maxFiles))await U8(DX(this.config.logDirectory,_))}}}async compressLogFile(X,$){let Z=mY(X),Y=Tz($),U=sY();await Bz(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),Z8(this.currentLogFile))try{let X=nY(this.currentLogFile,"r+");uY(X),cZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!x0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await Y8(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await U8(DX(this.config.logDirectory,$))}catch(Z){console.error(`Failed to delete temp file ${$}:`,Z)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?F0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||x0())return!1;let X=typeof O0.env.NO_COLOR<"u",$=O0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof O0.stderr<"u"&&O0.stderr.isTTY||typeof O0.stdout<"u"&&O0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=O0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${F0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=F0.underline(F0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>F0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>F0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>F0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>F0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>F0.strikethrough(Y)),$}supportsHyperlinks(){if(x0())return!1;let X=O0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=O0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(kz($)||$.startsWith("./")||$.startsWith("../"))$=xz($);else return null;return Z8($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){if(!this.shouldLog(X))return;let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":nU[X],G=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:F0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:F0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
|
|
424
|
+
`);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:F0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!x0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}let E=`${_} ${this.environment}.${X.toUpperCase()}: ${j}
|
|
425
425
|
`;if(L)E+=`${L}
|
|
426
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(U,_)=>{},finish:(U)=>{},interrupt:(U,_)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!x0()&&
|
|
427
|
-
`);if(this[_==="warning"?"warn":_](U),this.activeProgressBar&&this.shouldStyleConsole()&&!x0()&&
|
|
428
|
-
`,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?
|
|
429
|
-
`),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:
|
|
430
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(x0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${
|
|
431
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
432
|
-
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||x0()||!
|
|
426
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(U,_)=>{},finish:(U)=>{},interrupt:(U,_)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!x0()&&O0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,_)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),_!==void 0)this.activeProgressBar.message=_;if(this.shouldStyleConsole()&&!x0()&&O0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,_="info")=>{if(!x0()&&O0.stdout.isTTY)O0.stdout.write(`
|
|
427
|
+
`);if(this[_==="warning"?"warn":_](U),this.activeProgressBar&&this.shouldStyleConsole()&&!x0()&&O0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":F0.blue("\u25D0"),tag:Z,message:`${F0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),z=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)z+=` ${JSON.stringify(Z)}`;if(z+=`
|
|
428
|
+
`,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":F0.green("\u2713"),tag:j,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!x0())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new m8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Z),Z}createReadStream(){if(x0())throw Error("createReadStream is not supported in browser environments");if(!Z8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mY(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let Y=H9.isBuffer(X)?X:H9.from(X,"base64"),U=Y.subarray(0,16),_=Y.subarray(Y.length-16),Q=Y.subarray(16,Y.length-16),L=Pz("aes-256-gcm",Z,U);L.setAuthTag(_);let z=L.update(Q),j=L.final(),E=z.length+j.length,V=H9.allocUnsafe(E);return z.copy(V,0),j.copy(V,z.length),V.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x0()}isServerMode(){return!x0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($),{consoleText:U,fileText:_}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let L=U.split(`
|
|
429
|
+
`),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:F0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:F0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:F0.cyan(E),showTimestamp:!1}))}else if(!x0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
|
|
430
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(x0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${F0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();O0.stdin.removeListener("data",Z);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let Q=/%([sdijfo%])/g,L=0;if(Z=X.replace(Q,(z,j)=>{if(j==="%")return"%";if(L>=$.length)return z;let E=$[L++];switch(j){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return z}}),L<$.length)Z+=` ${$.slice(L).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:Y,fileText:U}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"",L=this.options.showIcons===!1?"":`${F0.blue("\u25D0")} `;console.error(`${L}${Q} ${F0.cyan(Y)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
431
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!O0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=F0.green("\u2501".repeat(Y)),Q=F0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?F0.green("\u2713"):F0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${F0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=O0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,O0.stdout.write(X.lastRenderedLine),$)O0.stdout.write(`
|
|
432
|
+
`)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||x0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(x0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await Y8(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let U=DX(this.config.logDirectory,Y);if(X.before)try{if((await RX(U)).mtime>=X.before)continue}catch(_){console.error(`Failed to get stats for file ${U}:`,_);continue}Z.push(U)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await U8(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function hU(X,$={}){let{maxRetries:Z=3,retryDelay:Y=1000,isRetryable:U=()=>!0,fallback:_}=$,Q=Error("Unknown error occurred");for(let L=0;L<=Z;L++)try{return await X()}catch(z){if(Q=z instanceof Error?z:Error(String(z)),L===Z||!U(Q))break;if(Y>0)await new Promise((j)=>setTimeout(j,Y))}if(_!==void 0)return _;throw Q instanceof Error?Q:Error(`Unknown error: ${String(Q)}`)}function vU(X){return X instanceof Z9}function rz(X){return X instanceof w8}function az(X){if(vU(X))return X.code==="FILE_SYSTEM_ERROR"||X.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>X.message.toLowerCase().includes($.toLowerCase()))}class zZ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(X,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(X.toLowerCase()),parse:(X)=>{let $=X.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(X,$)=>$==="number"||!Number.isNaN(Number(X))&&!Number.isNaN(Number.parseFloat(X)),parse:(X)=>{let $=Number(X);if(Number.isNaN($))throw TypeError(`Cannot parse "${X}" as number`);return $}},{name:"array",canParse:(X,$)=>$==="array"||X.startsWith("[")||X.includes(","),parse:(X)=>{try{let $=JSON.parse(X);if(Array.isArray($))return $}catch{}return X.split(",").map(($)=>$.trim())}},{name:"json",canParse:(X,$)=>$==="object"||(X.startsWith("{")&&X.endsWith("}")||X.startsWith("[")&&X.endsWith("]")),parse:(X)=>{try{return JSON.parse(X)}catch($){throw Error(`Cannot parse "${X}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(X,$,Z={}){let{prefix:Y,useCamelCase:U=!0,useBackwardCompatibility:_=!0,customParsers:Q={},verbose:L=!1,trackPerformance:z=!0}=Z,j=async()=>{if(!X)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix(X),V={...$};return this.processObject(V,[],E,{useCamelCase:U,useBackwardCompatibility:_,customParsers:Q,verbose:L,configName:X}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return x$.track("applyEnvironmentVariables",j,{configName:X});return j()}generateEnvPrefix(X){return X.toUpperCase().replace(/-/g,"_")}formatEnvKey(X,$){if(!$)return X.toUpperCase();return X.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=Q.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),z=`${Z}_${L.join("_")}`,j=Y.useBackwardCompatibility?`${Z}_${Q.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.processObject(_,Q,Z,Y);else{let E=_8.env[z]||(j?_8.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=_8.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof q8)throw V;throw u9.envVar(z,E,typeof _,Y.configName)}}}}}parseEnvironmentValue(X,$,Z,Y,U){for(let[_,Q]of Object.entries(Y))try{return Q(X)}catch{continue}for(let _ of this.defaultParsers)if(_.canParse(X,$))try{return _.parse(X)}catch{throw u9.envVar(Z,X,`${$} (via ${_.name} parser)`,U)}return X}getEnvironmentVariables(X){let $={},Z=X.toUpperCase();for(let[Y,U]of Object.entries(_8.env))if(Y.startsWith(Z)&&U!==void 0)$[Y]=U;return $}validateEnvironmentVariable(X,$,Z){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(X))Y.push(`Environment variable key "${X}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(X,$,Z,{})}catch(U){Y.push(`Cannot parse value "${$}" as ${Z}: ${U}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(X,$,Z={}){let{prefix:Y,format:U="text"}=Z,_=Y||this.generateEnvPrefix(X),Q=[];switch(this.extractEnvVarInfo($,[],_,Q),U){case"markdown":return this.formatAsMarkdown(Q,X);case"json":return JSON.stringify(Q,null,2);default:return this.formatAsText(Q,X)}}extractEnvVarInfo(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=`${Z}_${Q.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.extractEnvVarInfo(_,Q,Z,Y);else Y.push({key:L,type:Array.isArray(_)?"array":typeof _,description:`Configuration for ${Q.join(".")}`,example:this.generateExample(_)})}}generateExample(X){if(Array.isArray(X))return JSON.stringify(X);if(typeof X==="object"&&X!==null)return JSON.stringify(X);return String(X)}formatAsText(X,$){let Z=`Environment Variables for ${$}:
|
|
433
433
|
|
|
434
434
|
`;for(let Y of X)Z+=`${Y.key}
|
|
435
435
|
`,Z+=` Type: ${Y.type}
|
|
@@ -441,29 +441,29 @@ export default class ${U} extends Seeder {
|
|
|
441
441
|
`;Z+=`| Variable | Type | Description | Example |
|
|
442
442
|
`,Z+=`|----------|------|-------------|----------|
|
|
443
443
|
`;for(let Y of X)Z+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
444
|
-
`;return Z}}function az(X,$){let Z=mU("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function vU(X,$,Z={}){return bU(X,$,Z,new WeakMap)}function bU(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return fU(X,$,U,Y);if(!O9($)||!O9(X))return $;return $L(X,$,Z,Y)}function fU(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return tz(X,$);case"smart":return ez(X,$,Y);default:return $}return $}function tz(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>x1(U,Y)))Z.push(Y);return Z}function ez(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(O9($[0])&&O9(X[0]))return XL(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function XL(X,$,Z){let Y=[...$];for(let U of X){if(!O9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((z)=>O9(z)&&(L in z)&&z[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function $L(X,$,Z,Y){let U=$;if(O9(U)&&Y.has(U))return Y.get(U);let _={...X};if(O9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(O9(L)&&O9(z))_[Q]=bU(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=fU(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function Q5(X,$,Z="replace"){return vU(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function x1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!x1(X[Z],$[Z]))return!1;return!0}if(O9(X)&&O9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!x1(X[U],$[U]))return!1}return!0}return!1}function O9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class LZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=hX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!Q8(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new C$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new C$(X,Error("Configuration must export a valid object"),"unknown");let W={config:Q5($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)hX.setWithFileCheck("file",W,X,_);return W}catch(j){throw j instanceof Error?m9.configLoad(X,j):m9.configLoad(X,Error(String(j)))}};if(Q)return x$.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(uZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let Y=$===void 0?[]:Array.isArray($)?$:[$];for(let _ of Y){if(!_)continue;if(Z.push(_,`.${_}.config`,`${_}.config`,`.${_}`),X)Z.push(`${X}.${_}.config`,`.${X}.${_}.config`)}let U=new Set;return Z.filter((_)=>{if(!_||U.has(_))return!1;return U.add(_),!0})}checkFileAccess(X){return yU(async()=>{return Q8(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!Q8(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=uZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=uZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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(($)=>$.test(X))}async validateConfigFile(X){let $=[];try{if(!Q8(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class z5{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await x$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!Bz($))throw new w$($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new w$($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:nU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function ZL(X){if(!X)return"";let $=Array.isArray(X)?X.filter(Boolean):[X];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Z)=>`"${Z}"`).join(", ")}`}class B1{fileLoader=new LZ;envProcessor=new zZ;validator=new z5;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)j9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw j9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||XX.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(l0(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw m9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${ZL(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?aX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)j9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)j9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?aX(X,Z,U):Z,L=[l0(HX(),".config",X),l0(HX(),".config"),HX()];for(let z of L){if(U)j9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)j9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?aX(X,Y,_):Y;try{let z=l0(Z,"package.json");if(!S1(z))return null;let j={};try{j=JSON.parse(vz(z,"utf8"))}catch(G){if(_)j9.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let E=j[X],V=X;if(!E&&$){let G=Array.isArray($)?$:[$];for(let J of G){if(!J)continue;if(j[J]){E=j[J],V=J;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)j9.success(`Configuration loaded from package.json: ${V}`);return{config:Q5(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)j9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:aX(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw m9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return hX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);hX.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias){let Y=Array.isArray($.alias)?$.alias.join(","):$.alias;Z.push(`alias:${Y}`)}if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,l0(X,"config"),l0(X,".config"),$?l0(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(l0(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[l0(HX(),".config",X),l0(HX(),".config"),HX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function rY(X){let $=!(X.message.includes("EACCES")||X.message.includes("EPERM")||X.message.includes("permission denied"))&&(X.message.includes("syntax")||X.message.includes("Expected")||X.message.includes("Unexpected")||X.message.includes("BuildMessage")),Z=X.message.includes("Configuration must export a valid object")||X.message.includes("Configuration file is empty and exports nothing");return $||Z}async function YL(X){return k9.loadConfig({...X,__strictErrorHandling:!0})}async function L5(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await k9.loadConfig(X);else Y=await k9.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)j9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let Q=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await k9.applyEnvironmentVariables(Q.name||"",$,!0,Q.verbose||!1))?.config??$;return $}}async function UL(X={defaultConfig:{}}){if(typeof X==="string"){let{cwd:$}=await import("process");try{return(await k9.loadConfig({name:X,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&rY(Z)))return(await k9.applyEnvironmentVariables(X,{},!0,!1)).config;throw Z}}try{return(await k9.loadConfig({...X,cwd:X.cwd||XX.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&rY($)))return(await k9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function _L(X,$,Z="replace"){let Y=new LZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function aX(X,$,Z=!1){let Y=new zZ,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=XX.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}function QL(X){let $=l0(XX.cwd(),X.configDir),Z=l0(XX.cwd(),X.generatedDir),Y=l0(Z,"config-types.ts");if(!S1(sY(Y)))yz(sY(Y),{recursive:!0,mode:511});let U=S1($)?hz($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${SL}
|
|
444
|
+
`;return Z}}function tz(X,$){let Z=uU("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function bU(X,$,Z={}){return fU(X,$,Z,new WeakMap)}function fU(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return gU(X,$,U,Y);if(!O9($)||!O9(X))return $;return ZL(X,$,Z,Y)}function gU(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return ez(X,$);case"smart":return XL(X,$,Y);default:return $}return $}function ez(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>x1(U,Y)))Z.push(Y);return Z}function XL(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(O9($[0])&&O9(X[0]))return $L(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function $L(X,$,Z){let Y=[...$];for(let U of X){if(!O9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((z)=>O9(z)&&(L in z)&&z[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function ZL(X,$,Z,Y){let U=$;if(O9(U)&&Y.has(U))return Y.get(U);let _={...X};if(O9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(O9(L)&&O9(z))_[Q]=fU(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=gU(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function z5(X,$,Z="replace"){return bU(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function x1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!x1(X[Z],$[Z]))return!1;return!0}if(O9(X)&&O9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!x1(X[U],$[U]))return!1}return!0}return!1}function O9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class LZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=hX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!Q8(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new C$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new C$(X,Error("Configuration must export a valid object"),"unknown");let W={config:z5($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)hX.setWithFileCheck("file",W,X,_);return W}catch(j){throw j instanceof Error?u9.configLoad(X,j):u9.configLoad(X,Error(String(j)))}};if(Q)return x$.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(uZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let Y=$===void 0?[]:Array.isArray($)?$:[$];for(let _ of Y){if(!_)continue;if(Z.push(_,`.${_}.config`,`${_}.config`,`.${_}`),X)Z.push(`${X}.${_}.config`,`.${X}.${_}.config`)}let U=new Set;return Z.filter((_)=>{if(!_||U.has(_))return!1;return U.add(_),!0})}checkFileAccess(X){return hU(async()=>{return Q8(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!Q8(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=uZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=uZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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(($)=>$.test(X))}async validateConfigFile(X){let $=[];try{if(!Q8(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class L5{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await x$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!yz($))throw new w$($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new w$($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:iU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function YL(X){if(!X)return"";let $=Array.isArray(X)?X.filter(Boolean):[X];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Z)=>`"${Z}"`).join(", ")}`}class B1{fileLoader=new LZ;envProcessor=new zZ;validator=new L5;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)j9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw j9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||XX.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(s0(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw u9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${YL(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?aX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)j9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)j9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?aX(X,Z,U):Z,L=[s0(HX(),".config",X),s0(HX(),".config"),HX()];for(let z of L){if(U)j9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)j9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?aX(X,Y,_):Y;try{let z=s0(Z,"package.json");if(!S1(z))return null;let j={};try{j=JSON.parse(bz(z,"utf8"))}catch(G){if(_)j9.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let E=j[X],V=X;if(!E&&$){let G=Array.isArray($)?$:[$];for(let J of G){if(!J)continue;if(j[J]){E=j[J],V=J;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)j9.success(`Configuration loaded from package.json: ${V}`);return{config:z5(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)j9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:aX(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw u9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return hX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);hX.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias){let Y=Array.isArray($.alias)?$.alias.join(","):$.alias;Z.push(`alias:${Y}`)}if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,s0(X,"config"),s0(X,".config"),$?s0(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(s0(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[s0(HX(),".config",X),s0(HX(),".config"),HX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function aY(X){let $=!(X.message.includes("EACCES")||X.message.includes("EPERM")||X.message.includes("permission denied"))&&(X.message.includes("syntax")||X.message.includes("Expected")||X.message.includes("Unexpected")||X.message.includes("BuildMessage")),Z=X.message.includes("Configuration must export a valid object")||X.message.includes("Configuration file is empty and exports nothing");return $||Z}async function UL(X){return x9.loadConfig({...X,__strictErrorHandling:!0})}async function j5(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await x9.loadConfig(X);else Y=await x9.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)j9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let Q=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await x9.applyEnvironmentVariables(Q.name||"",$,!0,Q.verbose||!1))?.config??$;return $}}async function _L(X={defaultConfig:{}}){if(typeof X==="string"){let{cwd:$}=await import("process");try{return(await x9.loadConfig({name:X,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&aY(Z)))return(await x9.applyEnvironmentVariables(X,{},!0,!1)).config;throw Z}}try{return(await x9.loadConfig({...X,cwd:X.cwd||XX.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&aY($)))return(await x9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function QL(X,$,Z="replace"){let Y=new LZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function aX(X,$,Z=!1){let Y=new zZ,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=XX.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}function zL(X){let $=s0(XX.cwd(),X.configDir),Z=s0(XX.cwd(),X.generatedDir),Y=s0(Z,"config-types.ts");if(!S1(oY(Y)))hz(oY(Y),{recursive:!0,mode:511});let U=S1($)?vz($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${AL}
|
|
445
445
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
446
|
-
`;
|
|
447
|
-
${U.map((z)=>{let j=
|
|
446
|
+
`;fz(Y,_,{mode:438})}function LL(X){let $=null,Z=null,Y=()=>{if(!Z)Z=j5(X).then((_)=>{return $=_,_},(_)=>{let Q="defaultConfig"in X?X.defaultConfig:{};if($=Q,"verbose"in X&&X.verbose)j9.warn("Config loading failed, using defaults:",[_ instanceof Error?_:Error(String(_))]);return Q});return Z},U="defaultConfig"in X?X.defaultConfig:{};return $=U,Y(),new Proxy({},{get(_,Q){if($)return $[Q];let L=U[Q];return Y(),L},has(_,Q){return Q in($||U)},ownKeys(){return Object.keys($||U)},getOwnPropertyDescriptor(_,Q){return Object.getOwnPropertyDescriptor($||U,Q)},set(_,Q,L){if(!$)$={...U};return $[Q]=L,!0}})}function jL(X){let $=rY(pz.cwd(),X?.configDir||"./config");function Z(){if(!gz($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=dz($).filter((z)=>U.has(nZ(z))).map((z)=>({base:z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:z})),L=new Map;for(let{base:z,file:j}of Q){let E=nZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=nZ(V).toLowerCase();if(_.indexOf(E)<_.indexOf(G))L.set(z,j)}return Array.from(L.entries()).map(([z,j])=>({base:z,file:j})).sort((z,j)=>z.base.localeCompare(j.base))}function Y(){let U=Z(),_=U.map((z)=>z.base),Q=_.length?_.map((z)=>`'${z}'`).join(" | "):"string",L=U.length?`{
|
|
447
|
+
${U.map((z)=>{let j=rY($,z.file).replace(/\\/g,"/");return` '${z.base}': typeof import('${j}').default`}).join(`,
|
|
448
448
|
`)}
|
|
449
449
|
}`:"Record<string, any>";return`export type ConfigNames = ${Q}
|
|
450
450
|
export type ConfigByName = ${L}
|
|
451
451
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
452
452
|
export type ConfigOf = Config
|
|
453
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(_)=>{return{path:_.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}async function
|
|
454
|
-
\uD83D\uDCE6 Installing ${X} using ${Z}...`);let U={bun:{cmd:"bun",args:["add",X]},npm:{cmd:"npm",args:["install",X]},yarn:{cmd:"yarn",args:["add",X]},pnpm:{cmd:"pnpm",args:["add",X]}},{cmd:_,args:Q}=U[Z];try{let L=
|
|
455
|
-
\u26A0\uFE0F Package ${X} is already available in the workspace and cannot be installed separately due to a dependency loop.`),AX())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!Y)console.error(`\u2717 Failed to install ${X}`);return!1}}catch(L){if(!Y)console.error(`\u2717 Error installing ${X}:`,L);return!1}}function A$(X,$){let Z=[];for(let Y of $.rules)if(!Y.validator(X)){let U=Y.errorMessage||`Validation failed for value: ${X}`;if(Z.push(U),$.strict)throw Error(U)}return{isValid:Z.length===0,errors:Z}}function k$(X,$){let{items:Z}=$;if(Z.length===0)throw Error("Cannot select from empty weighted items array");let Y=Z.reduce((Q,L)=>Q+L.weight,0);if(Y<=0)throw Error("Total weight must be greater than 0");let U=X.number()*Y,_=0;for(let Q of Z)if(_+=Q.weight,U<=_)return Q.item;return Z[Z.length-1].item}function FL(X,$){return X.filter((Z)=>{if($.gender&&Z.gender&&Z.gender!==$.gender)return!1;if($.country){let Y=Array.isArray($.country)?$.country:[$.country];if(Z.country&&!Y.includes(Z.country))return!1}if($.region){let Y=Array.isArray($.region)?$.region:[$.region];if(Z.region&&!Y.includes(Z.region))return!1}if($.locale&&Z.locale&&Z.locale!==$.locale)return!1;if($.ageRange&&Z.age){let{min:Y,max:U}=$.ageRange;if(Z.age<Y||Z.age>U)return!1}for(let[Y,U]of Object.entries($))if(Y!=="gender"&&Y!=="country"&&Y!=="region"&&Y!=="locale"&&Y!=="ageRange"&&Z[Y]!==void 0){if(!(Array.isArray(U)?U:[U]).includes(Z[Y]))return!1}return!0})}function d9(X,$){let Z={...X};for(let Y of $){let{field:U,dependsOn:_,mapping:Q}=Y;if(Z[_]&&Q[Z[_]])Z[U]=Q[Z[_]]}return Z}function OL(X,$={}){let Z=X();if($.relationships)return d9(Z,$.relationships);return Z}class j5{providers=new Map;register(X){let{category:$,name:Z}=X;if(!this.providers.has($))this.providers.set($,new Map);this.providers.get($).set(Z,X)}get(X,$){return this.providers.get(X)?.get($)}getProvidersInCategory(X){let $=this.providers.get(X);return $?Array.from($.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove(X,$){let Z=this.providers.get(X);if(Z)return Z.delete($);return!1}clear(){this.providers.clear()}}class _${random;locale;constructor(X,$){this.random=X,this.locale=$}street(){let X=this.random.arrayElement(this.locale.address.street),$=this.streetSuffix();return`${X} ${$}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress(X){let $=this.buildingNumber(),Z=this.street();if(X?.useFullAddress)return`${$} ${Z}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${$} ${Z}`}buildingNumber(){let X=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols(X)}city(){return this.random.arrayElement(this.locale.address.city)}state(){return this.random.arrayElement(this.locale.address.state)}stateAbbr(){return this.random.arrayElement(this.locale.address.stateAbbr??[])}country(){return this.random.arrayElement(this.locale.address.country)}countryCode(){return this.random.arrayElement(this.locale.address.countryCode??[])}zipCode(){let X=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols(X)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude(X){let $=X?.min??-90,Z=X?.max??90,Y=X?.precision??4;return this.random.float($,Z,Y)}longitude(X){let $=X?.min??-180,Z=X?.max??180,Y=X?.precision??4;return this.random.float($,Z,Y)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced(X){let $;if(X?.constraints?.country){let Z=X.constraints.country,Y=Array.isArray(Z)?Z:[Z];$=this.city()}else $=this.city();if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({city:$,country:X?.constraints?.country},X.relationships).city||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.city()}}return $}countryAdvanced(X){let $;if(X?.constraints?.country){let Z=X.constraints.country,Y=Array.isArray(Z)?Z:[Z];$=this.random.arrayElement(Y)}else $=this.country();if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({country:$},X.relationships).country||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.country()}}return $}addressAdvanced(X){let $=this.countryAdvanced(X),Z=this.cityAdvanced(X),Y=this.state(),U=this.stateAbbr(),_=this.zipCode(),Q=this.street(),L=this.latitude(),z=this.longitude(),j={street:Q,city:Z,state:Y,stateAbbr:U,country:$,countryCode:this.countryCode(),zipCode:_,latitude:L,longitude:z};if(X?.relationships)return d9(j,X.relationships);return j}neighborhood(X){let $=X?.size||this.random.int(3,10),Z=this.cityAdvanced(X),Y=this.state(),U=this.zipCode(),_=[];for(let Q=0;Q<$;Q++)_.push({street:this.street(),city:Z,state:Y,zipCode:U,latitude:this.latitude({min:this.latitude()-0.01,max:this.latitude()+0.01}),longitude:this.longitude({min:this.longitude()-0.01,max:this.longitude()+0.01})});return _}}class Q${random;locale;constructor(X,$){this.random=X,this.locale=$}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let X=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement(X)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let X=["Golden Retriever","Labrador Retriever","German Shepherd","Bulldog","Beagle","Poodle","Rottweiler","Yorkshire Terrier","Boxer","Dachshund","Siberian Husky","Great Dane","Doberman Pinscher","Australian Shepherd","Cavalier King Charles Spaniel","Shih Tzu","Boston Terrier","Pomeranian","Havanese","Shetland Sheepdog","Bernese Mountain Dog","English Springer Spaniel","Brittany","Pug","Cocker Spaniel","Border Collie"];return this.random.arrayElement(X)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let X=["Persian","Maine Coon","Ragdoll","British Shorthair","Siamese","Scottish Fold","Sphynx","Abyssinian","Devon Rex","American Shorthair","Bengal","Russian Blue","Birman","Oriental Shorthair","Norwegian Forest Cat","Cornish Rex","Himalayan","Exotic Shorthair","Burmese","Turkish Angora","Somali","Manx","Tonkinese"];return this.random.arrayElement(X)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let X=["Eagle","Hawk","Falcon","Owl","Parrot","Macaw","Cockatoo","Parakeet","Canary","Finch","Sparrow","Robin","Blue Jay","Cardinal","Crow","Raven","Pigeon","Dove","Hummingbird","Woodpecker","Pelican","Swan","Duck","Goose","Flamingo","Penguin","Ostrich","Emu","Peacock","Turkey","Chicken","Rooster"];return this.random.arrayElement(X)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let X=["Goldfish","Betta","Guppy","Angelfish","Neon Tetra","Molly","Platy","Swordtail","Clownfish","Tang","Damselfish","Lionfish","Grouper","Snapper","Tuna","Marlin","Swordfish","Shark","Ray","Barracuda","Catfish","Bass","Pike","Trout","Carp"];return this.random.arrayElement(X)}bear(){let X=["Grizzly Bear","Black Bear","Polar Bear","Brown Bear","Panda Bear","Sun Bear","Sloth Bear","Spectacled Bear","Asian Black Bear","Kodiak Bear"];return this.random.arrayElement(X)}cetacean(){let X=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement(X)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let X=["Arabian","Thoroughbred","Quarter Horse","Morgan","Appaloosa","Paint Horse","Tennessee Walker","Standardbred","Mustang","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Shire","Haflinger","Icelandic","Shetland Pony"];return this.random.arrayElement(X)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let X=["Butterfly","Moth","Bee","Wasp","Ant","Beetle","Dragonfly","Grasshopper","Cricket","Ladybug","Firefly","Mosquito","Fly","Cockroach","Termite","Flea","Praying Mantis","Cicada","Caterpillar","Walking Stick"];return this.random.arrayElement(X)}lion(){let X=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement(X)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let X=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement(X)}snake(){let X=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement(X)}}class z${random;locale;constructor(X,$){this.random=X,this.locale=$}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let X=["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","The Chronicles of Narnia","Brave New World","The Divine Comedy","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude","The Sound and the Fury","Invisible Man","Beloved","The Grapes of Wrath","Catch-22","Slaughterhouse-Five","Fahrenheit 451","The Handmaid's Tale","The Road","Life of Pi","The Kite Runner","The Book Thief"];return this.random.arrayElement(X)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let X=["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee","Maya Angelou","Toni Morrison","Gabriel Garc\xEDa M\xE1rquez","Franz Kafka","James Joyce","Virginia Woolf","Oscar Wilde","Emily Dickinson","Walt Whitman","Robert Frost","Sylvia Plath","Kurt Vonnegut","Margaret Atwood","Haruki Murakami","Chimamanda Ngozi Adichie"];return this.random.arrayElement(X)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let X=["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Pearson","Wiley","Springer","McGraw-Hill","Bloomsbury","Vintage","Doubleday","Knopf"];return this.random.arrayElement(X)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let X=["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Poetry","Drama","Comedy","Adventure","Young Adult","Children's","Crime","Western","Dystopian","Paranormal","Contemporary","Classic","Literary Fiction"];return this.random.arrayElement(X)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let X=["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","The Maze Runner","Divergent","The Mortal Instruments","Sherlock Holmes","Discworld","Dune","Foundation","The Wheel of Time","The Witcher","Millennium","Jack Reacher"];return this.random.arrayElement(X)}isbn(){if(this.random.boolean(0.5)){let _=Array.from({length:9},()=>this.random.int(0,9)),Q=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${_.slice(0,1).join("")}-${_.slice(1,4).join("")}-${_.slice(4,9).join("")}-${Q}`}let X="978",$=this.random.int(0,9),Z=Array.from({length:3},()=>this.random.int(0,9)).join(""),Y=Array.from({length:5},()=>this.random.int(0,9)).join(""),U=this.random.int(0,9);return`${X}-${$}-${Z}-${Y}-${U}`}format(){let X=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement(X)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let X=["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","A page-turner with incredible characters.","One of the best books I've ever read.","Absolutely captivating!"];return this.random.arrayElement(X)}}class L${random;locale;constructor(X,$){this.random=X,this.locale=$}hex(X){let $=X?.prefix??"#",Z=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return $+Z}rgb(X){let $=this.random.int(0,255),Z=this.random.int(0,255),Y=this.random.int(0,255);if(X?.alpha){let U=this.random.float(0,1,2);if(X?.format==="array")return[$,Z,Y,U];return`rgba(${$}, ${Z}, ${Y}, ${U})`}if(X?.format==="array")return[$,Z,Y];return`rgb(${$}, ${Z}, ${Y})`}hsl(X){let $=this.random.int(0,360),Z=this.random.int(0,100),Y=this.random.int(0,100);if(X?.alpha){let U=this.random.float(0,1,2);if(X?.format==="array")return[$,Z,Y,U];return`hsla(${$}, ${Z}%, ${Y}%, ${U})`}if(X?.format==="array")return[$,Z,Y];return`hsl(${$}, ${Z}%, ${Y}%)`}css(X){let $=X?.format??this.random.arrayElement(["hex","rgb","hsl"]);if($==="hex")return this.hex();if($==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let X=["Red","Blue","Green","Yellow","Purple","Orange","Pink","Brown","Black","White","Gray","Cyan","Magenta","Lime","Navy","Teal","Olive","Maroon","Aqua","Silver","Fuchsia","Gold","Indigo","Violet"];return this.random.arrayElement(X)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class j${random;locale;constructor(X,$){this.random=X,this.locale=$}product(){let X=this.locale?.commerce?.productAdjective??["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable"],$=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],Z=this.locale?.commerce?.product??["Chair","Table","Lamp","Keyboard","Mouse","Computer","Shoes","Shirt","Pants","Hat","Gloves","Towel","Soap","Bike","Ball","Book","Wallet","Watch","Phone","Desk","Bottle","Plate","Cup","Bag","Pen","Notebook","Backpack","Sunglasses"];return`${this.random.arrayElement(X)} ${this.random.arrayElement($)} ${this.random.arrayElement(Z)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let X=["Books","Movies","Music","Games","Electronics","Computers","Home","Garden","Tools","Grocery","Health","Beauty","Toys","Kids","Baby","Clothing","Shoes","Jewelry","Sports","Outdoors","Automotive","Industrial"];return this.random.arrayElement(X)}price(X){let $=X?.min??1,Z=X?.max??1000,Y=X?.dec??2,U=X?.symbol??"",_=this.random.float($,Z,Y);return U+_.toFixed(Y)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let X=["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable","Innovative","Compact","Versatile","Modern","Classic","Vintage","Contemporary"];return this.random.arrayElement(X)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let X=["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum","Bronze","Copper","Brass","Titanium","Ceramic","Velvet","Linen","Wool"];return this.random.arrayElement(X)}productDescription(){let X=["The beautiful range of {adjective} {material} {product} comes with a {feature}.","Experience the {adjective} {product} that redefines {benefit}.","Our {adjective} {material} {product} is designed for {benefit}.","Discover the {adjective} {product} with {feature} for {benefit}."],$=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],Z=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement(X).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement($)).replace("{benefit}",this.random.arrayElement(Z))}review(){let X=["This product exceeded my expectations!","Absolutely love it! Worth every penny.","Great quality and fast shipping.","Not what I expected, but still decent.","Amazing! Highly recommend to everyone.","Perfect for my needs. Very satisfied.","Good value for the price.","Could be better, but it does the job.","Fantastic product! Will buy again.","Best purchase I've made this year!"];return this.random.arrayElement(X)}discountCode(){let X=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],$=this.random.int(10,99);return`${this.random.arrayElement(X)}${$}`}sku(){let X=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),$=this.random.int(1e4,99999),Z=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${X}-${$}-${Z}`}}class E${random;locale;constructor(X,$){this.random=X,this.locale=$}name(){let X=this.random.arrayElement(this.locale.company.name??["Company"]),$=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${X} ${$}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let X=this.random.arrayElement(this.locale.company.adjective??["innovative"]),$=this.random.arrayElement(this.locale.company.descriptor??["digital"]),Z=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${X} ${$} ${Z}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let X=this.buzzword(),$=this.random.arrayElement(this.locale.company.descriptor??["digital"]),Z=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${X} ${$} ${Z}`}}class u8{random;constructor(X){this.random=X}engine(){let X=["MySQL","PostgreSQL","MongoDB","SQLite","Redis","Oracle","Microsoft SQL Server","MariaDB","Cassandra","Elasticsearch","DynamoDB","CouchDB","Neo4j","Firebase","Firestore","InfluxDB","TimescaleDB","RethinkDB","ArangoDB","CockroachDB"];return this.random.arrayElement(X)}type(){let X=["VARCHAR","INTEGER","BIGINT","SMALLINT","DECIMAL","NUMERIC","FLOAT","DOUBLE","BOOLEAN","DATE","TIME","TIMESTAMP","DATETIME","TEXT","BLOB","JSON","JSONB","UUID","ENUM","ARRAY","SERIAL","BIGSERIAL"];return this.random.arrayElement(X)}collation(){let X=["utf8_general_ci","utf8_unicode_ci","utf8mb4_general_ci","utf8mb4_unicode_ci","latin1_swedish_ci","latin1_general_ci","utf8_bin","utf8mb4_bin"];return this.random.arrayElement(X)}column(){let X=["id","user_id","name","email","password","created_at","updated_at","deleted_at","first_name","last_name","phone","address","city","state","country","zip_code","status","role","permissions","description","price","quantity","total","subtotal","tax","discount","shipping","notes","metadata","settings","preferences","avatar"];return this.random.arrayElement(X)}table(){let X=["users","posts","comments","products","orders","customers","invoices","payments","categories","tags","roles","permissions","sessions","settings","notifications","messages","attachments","logs","analytics","reports","subscriptions","transactions"];return this.random.arrayElement(X)}mongodbObjectId(){let X="";for(let $=0;$<24;$++)X+="0123456789abcdef"[this.random.int(0,15)];return X}constraint(){let X=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement(X)}queryType(){let X=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement(X)}connectionString(X){let $=X?.engine??this.engine().toLowerCase().replace(/ /g,""),Z="user",Y="password",U="localhost",_=this.random.int(3000,9999),Q=this.table(),L={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[$]||"jdbc";if($==="mongodb")return`${L}://user:password@localhost:${_}/${Q}`;return`${L}://user:password@localhost:${_}/${Q}`}}class n8{random;constructor(X){this.random=X}past(X){let $=X?.years??1,Z=X?.to??new Date,Y=X?.from??new Date(Z.getTime()-$*365*24*60*60*1000);return this.between({from:Y,to:Z})}future(X){let $=X?.years??1,Z=X?.from??new Date,Y=X?.to??new Date(Z.getTime()+$*365*24*60*60*1000);return this.between({from:Z,to:Y})}between(X){let $=X.from??new Date(Date.now()-31536000000),Z=X.to??new Date,Y=$.getTime(),U=Z.getTime(),_=this.random.int(Y,U);return new Date(_)}recent(X){let $=X?.days??1,Z=new Date,Y=new Date(Z.getTime()-$*24*60*60*1000);return this.between({from:Y,to:Z})}soon(X){let $=X?.days??1,Z=new Date,Y=new Date(Z.getTime()+$*24*60*60*1000);return this.between({from:Z,to:Y})}month(){let X=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement(X)}weekday(){let X=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement(X)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween(X){return this.between(X)}birthdate(X){let $=X?.mode??"age",Z=X?.refDate??new Date;if($==="year"){let z=X?.min??1900,j=X?.max??Z.getUTCFullYear(),E=new Date(Date.UTC(z,0,1)),V=new Date(Date.UTC(j,11,31,23,59,59,999));return this.between({from:E,to:V})}let Y=Math.max(0,X?.min??18),U=Math.max(Y,X?.max??80),_=(z)=>z*365.25*24*60*60*1000,Q=new Date(Z.getTime()-_(U)),L=new Date(Z.getTime()-_(Y));return this.between({from:Q,to:L})}}class i8{random;constructor(X){this.random=X}amount(X){let $=X?.min??0,Z=X?.max??1e4,Y=X?.dec??2,U=X?.symbol??"",_=this.random.float($,Z,Y);return U+_.toFixed(Y)}account(X=8){let $="";for(let Z=0;Z<X;Z++)$+=this.random.int(0,9);return $}accountName(){let X=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement(X)} Account`}routingNumber(){return this.account(9)}creditCardNumber(X){let $=X?.formatted??!0,Z=X?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),Y="",U=16;switch(Z){case"visa":Y="4",U=16;break;case"mastercard":Y=`5${this.random.int(1,5)}`,U=16;break;case"amex":Y=`3${this.random.arrayElement(["4","7"])}`,U=15;break;case"discover":Y="6011",U=16;break}let _=Y;while(_.length<U)_+=this.random.int(0,9);if($){if(Z==="amex")return`${_.slice(0,4)}-${_.slice(4,10)}-${_.slice(10)}`;return _.match(/.{1,4}/g)?.join("-")??_}return _}cvv(){return this.account(3)}iban(X){let $=X?.countryCode??"GB",Z=X?.formatted??!1,Y=this.random.int(10,99).toString(),U="WEST",_=this.account(14),Q=$+Y+"WEST"+_;if(Z)return Q.match(/.{1,4}/g)?.join(" ")??Q;return Q}bic(){let X="";for(let $=0;$<4;$++)X+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let $=0;$<2;$++)X+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let $=0;$<2;$++)X+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(Z,Y)=>Y.toString())]);return X}bitcoin(){let X=this.random.arrayElement(["1","3"]);for(let $=0;$<33;$++)X+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return X}ethereum(){let X="0x";for(let $=0;$<40;$++)X+="0123456789abcdef"[this.random.int(0,15)];return X}currencyCode(){let X=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement(X)}currencyName(){let X=["US Dollar","Euro","British Pound","Japanese Yen","Australian Dollar","Canadian Dollar","Swiss Franc","Chinese Yuan","Swedish Krona","New Zealand Dollar","Indian Rupee","Brazilian Real","Russian Ruble","South Korean Won"];return this.random.arrayElement(X)}currencySymbol(){let X=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement(X)}transactionType(){let X=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement(X)}}class G${random;locale;constructor(X,$){this.random=X,this.locale=$}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let X=["Spaghetti Carbonara","Chicken Alfredo","Beef Tacos","Margherita Pizza","Caesar Salad","Pad Thai","Chicken Tikka Masala","Sushi Roll","Beef Burger","Fish and Chips","Ramen","Tom Yum Soup","Greek Salad","Lasagna","Paella","Pho","Falafel Wrap","Burrito Bowl","Chicken Curry","Steak Frites","Risotto","Poke Bowl","Bibimbap","Shakshuka","Eggs Benedict","Club Sandwich","Caprese Salad","Fettuccine Alfredo","Chicken Parmesan","Pulled Pork Sandwich","Gyro","Butter Chicken","Peking Duck"];return this.random.arrayElement(X)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let X=["Garlic","Onion","Tomato","Basil","Oregano","Thyme","Rosemary","Cilantro","Parsley","Salt","Pepper","Olive Oil","Butter","Flour","Sugar","Eggs","Milk","Cheese","Chicken","Beef","Pork","Fish","Shrimp","Rice","Pasta","Potatoes","Carrots","Celery","Bell Pepper","Mushrooms","Spinach","Lettuce","Cucumber","Avocado","Lemon","Lime","Ginger","Soy Sauce","Vinegar","Honey","Cinnamon","Cumin"];return this.random.arrayElement(X)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let X=["Basil","Oregano","Thyme","Rosemary","Sage","Cilantro","Parsley","Mint","Dill","Paprika","Cumin","Turmeric","Coriander","Cardamom","Cinnamon","Nutmeg","Cloves","Black Pepper","White Pepper","Cayenne","Chili Powder","Curry Powder","Garam Masala","Saffron","Vanilla","Bay Leaf","Fennel","Anise","Tarragon","Marjoram"];return this.random.arrayElement(X)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let X=["Broccoli","Carrot","Celery","Lettuce","Spinach","Kale","Cabbage","Cauliflower","Brussels Sprouts","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Tomato","Cucumber","Bell Pepper","Zucchini","Eggplant","Mushroom","Onion","Garlic","Radish","Beet","Turnip","Artichoke","Bok Choy","Arugula","Swiss Chard"];return this.random.arrayElement(X)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let X=["Apple","Banana","Orange","Grape","Strawberry","Blueberry","Raspberry","Blackberry","Mango","Pineapple","Watermelon","Cantaloupe","Honeydew","Peach","Plum","Cherry","Pear","Kiwi","Papaya","Dragon Fruit","Lychee","Passion Fruit","Pomegranate","Coconut","Avocado","Lemon","Lime","Grapefruit","Apricot","Fig","Date"];return this.random.arrayElement(X)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let X=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement(X)}seafood(){let X=["Salmon","Tuna","Cod","Halibut","Trout","Mackerel","Sardines","Anchovies","Shrimp","Crab","Lobster","Scallops","Clams","Mussels","Oysters","Squid","Octopus","Tilapia","Sea Bass","Swordfish","Snapper","Grouper","Catfish"];return this.random.arrayElement(X)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let X=["Chocolate Cake","Cheesecake","Apple Pie","Ice Cream","Brownies","Cookies","Tiramisu","Cr\xE8me Br\xFBl\xE9e","Panna Cotta","Macarons","Cupcakes","Donuts","Eclairs","Profiteroles","Cannoli","Baklava","Flan","Churros","Gelato","Sorbet","Mousse","Tart","Cobbler","Pudding","Trifle","Souffl\xE9"];return this.random.arrayElement(X)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let X=["Italian","Chinese","Japanese","Mexican","Thai","Indian","French","Greek","Spanish","Korean","Vietnamese","Lebanese","Turkish","Brazilian","Moroccan","Ethiopian","Caribbean","Peruvian","German","American","British","Irish"];return this.random.arrayElement(X)}description(){let X=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],$=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement(X)} ${this.random.arrayElement($)}`}}class l8{random;constructor(X){this.random=X}branch(){let X=["feature","bugfix","hotfix","refactor","chore","docs","test"],$=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],Z=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],Y=this.random.arrayElement(X),U=this.random.arrayElement($),_=this.random.arrayElement(Z);return`${Y}/${U}-${_}`}commitMessage(){let X=["feat","fix","docs","style","refactor","test","chore","perf"],$=["api","ui","auth","db","config","deps","core","utils"],Z=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],Y=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],U=this.random.arrayElement(X),_=this.random.boolean(0.5)?`(${this.random.arrayElement($)})`:"",Q=this.random.arrayElement(Z),L=this.random.arrayElement(Y);return`${U}${_}: ${Q} ${L}`}commitSha(X){let $=X?.short?7:40,Z="0123456789abcdef",Y="";for(let U=0;U<$;U++)Y+="0123456789abcdef"[this.random.int(0,15)];return Y}commitEntry(){let X=this.commitSha({short:!0}),$=this.commitMessage();return`${X} ${$}`}commitAuthor(X){let $=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],Z=X?.name??this.random.arrayElement($),Y=X?.email??`${Z.toLowerCase().replace(" ",".")}@example.com`;return`${Z} <${Y}>`}remote(X){let $=X?.protocol??this.random.arrayElement(["https","ssh"]),Z=X?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),Y=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),U=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),_={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if($==="ssh")return`git@${_[Z]}:${Y}/${U}.git`;return`https://${_[Z]}/${Y}/${U}.git`}tag(){let X=this.random.int(0,5),$=this.random.int(0,20),Z=this.random.int(0,50),Y=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${X}.${$}.${Z}${Y}`}}class F${random;locale;constructor(X,$){this.random=X,this.locale=$}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let X=["TCP","HTTP","SDD","RAM","GB","CSS","SSL","AGP","SQL","CLI","IB","UX","UI","FTP","AI","ADP","RSS","XML","EXE","COM","HDD","THX","MP3","GPU","API","DNS","IP","LAN","WAN","VPN","SSH","HTTPS","JSON","REST","SOAP"];return this.random.arrayElement(X)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let X=["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","haptic","multi-byte","bluetooth","wireless","mobile","neural","optical","solid state","cloud","quantum","distributed","encrypted"];return this.random.arrayElement(X)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let X=["driver","protocol","bandwidth","panel","microchip","program","port","card","array","interface","system","sensor","firewall","hard drive","pixel","alarm","feed","monitor","application","transmitter","bus","circuit","capacitor","matrix","server","database","network","router","switch","gateway","node","cluster"];return this.random.arrayElement(X)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let X=["back up","bypass","hack","override","compress","copy","navigate","index","connect","generate","quantify","calculate","synthesize","input","transmit","program","reboot","parse","compile","encode","decode","encrypt","decrypt","patch","upgrade","deploy","configure","optimize","refactor","debug"];return this.random.arrayElement(X)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let X=["backing up","bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","quantifying","calculating","synthesizing","transmitting","programming","parsing","compiling","encoding","decoding","encrypting","decrypting","patching","deploying","configuring","optimizing"];return this.random.arrayElement(X)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let X=["If we {verb} the {noun}, we can get to the {abbreviation} {noun} through the {adjective} {abbreviation} {noun}!","We need to {verb} the {adjective} {abbreviation} {noun}!","Try to {verb} the {abbreviation} {noun}, maybe it will {verb} the {adjective} {noun}!","You can't {verb} the {noun} without {ingverb} the {adjective} {abbreviation} {noun}!","Use the {adjective} {abbreviation} {noun}, then you can {verb} the {adjective} {noun}!","The {abbreviation} {noun} is down, {verb} the {adjective} {noun} so we can {verb} the {abbreviation} {noun}!","{ingverb} the {noun} won't do anything, we need to {verb} the {adjective} {abbreviation} {noun}!","I'll {verb} the {adjective} {abbreviation} {noun}, that should {verb} the {abbreviation} {noun}!"];return this.random.arrayElement(X).replace(/\{verb\}/g,()=>this.verb()).replace(/\{ingverb\}/g,()=>this.ingverb()).replace(/\{noun\}/g,()=>this.noun()).replace(/\{adjective\}/g,()=>this.adjective()).replace(/\{abbreviation\}/g,()=>this.abbreviation())}}class s8{random;constructor(X){this.random=X}randomElement(X){return this.random.arrayElement(X)}arrayElement(X){return this.random.arrayElement(X)}arrayElements(X,$){return this.random.arrayElements(X,$)}shuffle(X){return this.random.shuffle(X)}numerify(X){return X.replace(/#/g,()=>String(this.random.int(0,9)))}lexify(X){return X.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify(X){return this.numerify(this.lexify(X))}replaceSymbols(X){return this.random.replaceSymbols(X)}boolean(X=0.5){return this.random.boolean(X)}objectKey(X){let $=Object.keys(X);return this.random.arrayElement($)}objectValue(X){let $=this.objectKey(X);return X[$]}multiple(X,$=3){return Array.from({length:$},X)}maybe(X,$=0.5){return this.random.boolean($)?X():void 0}unique(X,$=50){let Z=new Set,Y=0;while(Y<$){let U=X();if(!Z.has(U))return Z.add(U),U;Y++}throw Error(`Failed to generate unique value after ${$} retries`)}replaceCreditCardSymbols(X="####-####-####-####",$="#"){return this.random.replaceCreditCardSymbols(X,$)}regexify(X){return X.replace(/\[A-Z\]/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/\[a-z\]/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split(""))).replace(/\[0-9\]/g,()=>String(this.random.int(0,9))).replace(/\{(\d+)\}/g,($,Z)=>{return""})}}class o8{random;constructor(X){this.random=X}url(X){let $=X?.width??640,Z=X?.height??480;return`https://via.placeholder.com/${$}x${Z}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr(X){let $=X?.width??640,Z=X?.height??480,Y=X?.category??"";if(Y)return`https://loremflickr.com/${$}/${Z}/${Y}`;return`https://loremflickr.com/${$}/${Z}`}urlPicsumPhotos(X){let $=X?.width??640,Z=X?.height??480,Y=`https://picsum.photos/${$}/${Z}`;if(X?.grayscale)Y+="?grayscale";if(X?.blur)Y+=X?.grayscale?`&blur=${X.blur}`:`?blur=${X.blur}`;return Y}dataUri(X){let $=X?.width??640,Z=X?.height??480,Y=X?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),U=`<svg xmlns="http://www.w3.org/2000/svg" width="${$}" height="${Z}"><rect width="${$}" height="${Z}" fill="#${Y}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(U)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let X=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement(X)}imageType(){let X=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement(X)}}class O${random;locale;domainWordsCache=null;constructor(X,$){this.random=X,this.locale=$}getDomainWords(){if(!this.domainWordsCache){let X=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=X.map(($)=>$.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(($)=>$.length>0)}return this.domainWordsCache}email(X){let $;if(X?.firstName)$=X.firstName.toLowerCase();else{let Q=this.locale.person.firstNameMale.length,L=this.locale.person.firstNameFemale.length,z=this.locale.person.firstNameNeutral?.length||0,j=Q+L+z,E=this.random.int(0,j-1);if(E<Q)$=this.locale.person.firstNameMale[E].toLowerCase();else if(E<Q+L)$=this.locale.person.firstNameFemale[E-Q].toLowerCase();else $=this.locale.person.firstNameNeutral[E-Q-L].toLowerCase()}let Z=X?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=X?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),U=this.random.arrayElement(rU),_=this.random.arrayElement(this.getDomainWords());return`${$}${U}${Z}@${_}.${Y}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let X=this.locale.person.firstNameMale.length,$=this.locale.person.firstNameFemale.length,Z=this.locale.person.firstNameNeutral?.length||0,Y=X+$+Z,U=this.random.int(0,Y-1),_;if(U<X)_=this.locale.person.firstNameMale[U].toLowerCase();else if(U<X+$)_=this.locale.person.firstNameFemale[U-X].toLowerCase();else _=this.locale.person.firstNameNeutral[U-X-$].toLowerCase();let Q=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),L=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),z=[".","_",""],j=this.random.arrayElement(z);return`${_}${j}${Q}@${L}`}username(X){let $;if(X?.firstName)$=X.firstName.toLowerCase();else{let U=this.locale.person.firstNameMale.length,_=this.locale.person.firstNameFemale.length,Q=this.locale.person.firstNameNeutral?.length||0,L=U+_+Q,z=this.random.int(0,L-1);if(z<U)$=this.locale.person.firstNameMale[z].toLowerCase();else if(z<U+_)$=this.locale.person.firstNameFemale[z-U].toLowerCase();else $=this.locale.person.firstNameNeutral[z-U-_].toLowerCase()}let Z=X?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=[`${$}${Z}`,`${$}_${Z}`,`${$}.${Z}`,`${$}${this.random.int(10,999)}`,`${$}_${Z}${this.random.int(10,99)}`];return this.random.arrayElement(Y)}password(X){let $=X?.length??12,Z=X?.memorable??!1,Y=X?.prefix??"";if(Z){let Q=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],L=[];for(let z=0;z<3;z++)L.push(this.random.arrayElement(Q));return Y+L.join("-")+this.random.int(10,999)}let U="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",_=Y;for(let Q=Y.length;Q<$;Q++)_+=U[this.random.int(0,U.length-1)];return _}url(X){let $=X?.protocol??this.random.arrayElement(["http","https"]),Z=X?.domain??this.domainName();return`${$}://${Z}`}domainName(){return`${this.domainWord()}.${this.domainSuffix()}`}domainWord(){return this.random.arrayElement(this.getDomainWords())}domainSuffix(){return this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"])}ipv4(){return`${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}`}ipv6(){let X=[];for(let $=0;$<8;$++)X.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return X.join(":")}mac(X=":"){let $=[];for(let Z=0;Z<6;Z++)$.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return $.join(X)}userAgent(){let X=["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/120.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 14.0; rv:109.0) Gecko/20100101 Firefox/120.0"];return this.random.arrayElement(X)}slug(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return $.join("-").toLowerCase()}ip(){return this.ipv4()}}class r8{random;constructor(X){this.random=X}word(){return this.random.arrayElement(aU)}words(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.word());return $.join(" ")}sentence(X){let $=X??this.random.int(3,10),Z=this.words($);return`${Z.charAt(0).toUpperCase()+Z.slice(1)}.`}sentences(X=3,$=" "){let Z=[];for(let Y=0;Y<X;Y++)Z.push(this.sentence());return Z.join($)}paragraph(X){let $=X??this.random.int(3,7);return this.sentences($)}paragraphs(X=3,$=`
|
|
453
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(_)=>{return{path:_.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}async function EL(){if(!Q1)Q1=await j5({name:"faker",alias:"mock",defaultConfig:XZ});return Q1}function SX(X){let $=X.replace(/-/g,"_").split("_"),Z=$[0].toLowerCase(),Y=$[1]?.toUpperCase(),U=Y?`${Z}-${Y.toLowerCase()}`:Z;return{full:X,language:Z,region:Y,packageName:U,normalized:Y?`${Z}_${Y}`:Z}}function GL(X){let $=SX(X);if($.region)return[$.normalized,$.language];return[$.language]}function FL(X){return`@mock-locale/${SX(X).packageName}`}function dU(X,$){let Z={...X};for(let Y in $){let U=$[Y],_=X[Y];if(U===void 0)continue;if(typeof U==="object"&&U!==null&&!Array.isArray(U)&&typeof _==="object"&&_!==null&&!Array.isArray(_))Z[Y]=dU(_,U);else Z[Y]=U}return Z}function AX(){let X=BU.cwd(),$=NX(X,"package.json");if(!TX($))return!1;try{let Z=JSON.parse(mz($,"utf-8"));return!!(Z.workspaces||Z.workspace)}catch{return!1}}function pU(){let X=BU.cwd();if(TX(NX(X,"bun.lockb"))||TX(NX(X,"bun.lock")))return"bun";if(TX(NX(X,"pnpm-lock.yaml")))return"pnpm";if(TX(NX(X,"yarn.lock")))return"yarn";if(TX(NX(X,"package-lock.json")))return"npm";return"bun"}function cU(X,$={}){let Z=pU(),{silent:Y=!1}=$;if(!Y)console.log(`
|
|
454
|
+
\uD83D\uDCE6 Installing ${X} using ${Z}...`);let U={bun:{cmd:"bun",args:["add",X]},npm:{cmd:"npm",args:["install",X]},yarn:{cmd:"yarn",args:["add",X]},pnpm:{cmd:"pnpm",args:["add",X]}},{cmd:_,args:Q}=U[Z];try{let L=cz(_,Q,{stdio:"pipe",shell:!0}),z=L.stdout?.toString()||"",j=L.stderr?.toString()||"",E=z+j;if(!Y){if(z)console.log(z);if(j)console.error(j)}if(L.status===0){if(!Y)console.log(`\u2713 Successfully installed ${X}`);return!0}else{let V=E;if(V.toLowerCase().includes("dependency loop")||V.includes("DependencyLoop")||V.includes("has a dependency loop")||V.includes("An internal error occurred (DependencyLoop)")){if(!Y){if(console.log(`
|
|
455
|
+
\u26A0\uFE0F Package ${X} is already available in the workspace and cannot be installed separately due to a dependency loop.`),AX())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!Y)console.error(`\u2717 Failed to install ${X}`);return!1}}catch(L){if(!Y)console.error(`\u2717 Error installing ${X}:`,L);return!1}}function A$(X,$){let Z=[];for(let Y of $.rules)if(!Y.validator(X)){let U=Y.errorMessage||`Validation failed for value: ${X}`;if(Z.push(U),$.strict)throw Error(U)}return{isValid:Z.length===0,errors:Z}}function k$(X,$){let{items:Z}=$;if(Z.length===0)throw Error("Cannot select from empty weighted items array");let Y=Z.reduce((Q,L)=>Q+L.weight,0);if(Y<=0)throw Error("Total weight must be greater than 0");let U=X.number()*Y,_=0;for(let Q of Z)if(_+=Q.weight,U<=_)return Q.item;return Z[Z.length-1].item}function OL(X,$){return X.filter((Z)=>{if($.gender&&Z.gender&&Z.gender!==$.gender)return!1;if($.country){let Y=Array.isArray($.country)?$.country:[$.country];if(Z.country&&!Y.includes(Z.country))return!1}if($.region){let Y=Array.isArray($.region)?$.region:[$.region];if(Z.region&&!Y.includes(Z.region))return!1}if($.locale&&Z.locale&&Z.locale!==$.locale)return!1;if($.ageRange&&Z.age){let{min:Y,max:U}=$.ageRange;if(Z.age<Y||Z.age>U)return!1}for(let[Y,U]of Object.entries($))if(Y!=="gender"&&Y!=="country"&&Y!=="region"&&Y!=="locale"&&Y!=="ageRange"&&Z[Y]!==void 0){if(!(Array.isArray(U)?U:[U]).includes(Z[Y]))return!1}return!0})}function p9(X,$){let Z={...X};for(let Y of $){let{field:U,dependsOn:_,mapping:Q}=Y;if(Z[_]&&Q[Z[_]])Z[U]=Q[Z[_]]}return Z}function JL(X,$={}){let Z=X();if($.relationships)return p9(Z,$.relationships);return Z}class E5{providers=new Map;register(X){let{category:$,name:Z}=X;if(!this.providers.has($))this.providers.set($,new Map);this.providers.get($).set(Z,X)}get(X,$){return this.providers.get(X)?.get($)}getProvidersInCategory(X){let $=this.providers.get(X);return $?Array.from($.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove(X,$){let Z=this.providers.get(X);if(Z)return Z.delete($);return!1}clear(){this.providers.clear()}}class _${random;locale;constructor(X,$){this.random=X,this.locale=$}street(){let X=this.random.arrayElement(this.locale.address.street),$=this.streetSuffix();return`${X} ${$}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress(X){let $=this.buildingNumber(),Z=this.street();if(X?.useFullAddress)return`${$} ${Z}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${$} ${Z}`}buildingNumber(){let X=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols(X)}city(){return this.random.arrayElement(this.locale.address.city)}state(){return this.random.arrayElement(this.locale.address.state)}stateAbbr(){return this.random.arrayElement(this.locale.address.stateAbbr??[])}country(){return this.random.arrayElement(this.locale.address.country)}countryCode(){return this.random.arrayElement(this.locale.address.countryCode??[])}zipCode(){let X=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols(X)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude(X){let $=X?.min??-90,Z=X?.max??90,Y=X?.precision??4;return this.random.float($,Z,Y)}longitude(X){let $=X?.min??-180,Z=X?.max??180,Y=X?.precision??4;return this.random.float($,Z,Y)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced(X){let $;if(X?.constraints?.country){let Z=X.constraints.country,Y=Array.isArray(Z)?Z:[Z];$=this.city()}else $=this.city();if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=p9({city:$,country:X?.constraints?.country},X.relationships).city||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.city()}}return $}countryAdvanced(X){let $;if(X?.constraints?.country){let Z=X.constraints.country,Y=Array.isArray(Z)?Z:[Z];$=this.random.arrayElement(Y)}else $=this.country();if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=p9({country:$},X.relationships).country||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.country()}}return $}addressAdvanced(X){let $=this.countryAdvanced(X),Z=this.cityAdvanced(X),Y=this.state(),U=this.stateAbbr(),_=this.zipCode(),Q=this.street(),L=this.latitude(),z=this.longitude(),j={street:Q,city:Z,state:Y,stateAbbr:U,country:$,countryCode:this.countryCode(),zipCode:_,latitude:L,longitude:z};if(X?.relationships)return p9(j,X.relationships);return j}neighborhood(X){let $=X?.size||this.random.int(3,10),Z=this.cityAdvanced(X),Y=this.state(),U=this.zipCode(),_=[];for(let Q=0;Q<$;Q++)_.push({street:this.street(),city:Z,state:Y,zipCode:U,latitude:this.latitude({min:this.latitude()-0.01,max:this.latitude()+0.01}),longitude:this.longitude({min:this.longitude()-0.01,max:this.longitude()+0.01})});return _}}class Q${random;locale;constructor(X,$){this.random=X,this.locale=$}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let X=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement(X)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let X=["Golden Retriever","Labrador Retriever","German Shepherd","Bulldog","Beagle","Poodle","Rottweiler","Yorkshire Terrier","Boxer","Dachshund","Siberian Husky","Great Dane","Doberman Pinscher","Australian Shepherd","Cavalier King Charles Spaniel","Shih Tzu","Boston Terrier","Pomeranian","Havanese","Shetland Sheepdog","Bernese Mountain Dog","English Springer Spaniel","Brittany","Pug","Cocker Spaniel","Border Collie"];return this.random.arrayElement(X)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let X=["Persian","Maine Coon","Ragdoll","British Shorthair","Siamese","Scottish Fold","Sphynx","Abyssinian","Devon Rex","American Shorthair","Bengal","Russian Blue","Birman","Oriental Shorthair","Norwegian Forest Cat","Cornish Rex","Himalayan","Exotic Shorthair","Burmese","Turkish Angora","Somali","Manx","Tonkinese"];return this.random.arrayElement(X)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let X=["Eagle","Hawk","Falcon","Owl","Parrot","Macaw","Cockatoo","Parakeet","Canary","Finch","Sparrow","Robin","Blue Jay","Cardinal","Crow","Raven","Pigeon","Dove","Hummingbird","Woodpecker","Pelican","Swan","Duck","Goose","Flamingo","Penguin","Ostrich","Emu","Peacock","Turkey","Chicken","Rooster"];return this.random.arrayElement(X)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let X=["Goldfish","Betta","Guppy","Angelfish","Neon Tetra","Molly","Platy","Swordtail","Clownfish","Tang","Damselfish","Lionfish","Grouper","Snapper","Tuna","Marlin","Swordfish","Shark","Ray","Barracuda","Catfish","Bass","Pike","Trout","Carp"];return this.random.arrayElement(X)}bear(){let X=["Grizzly Bear","Black Bear","Polar Bear","Brown Bear","Panda Bear","Sun Bear","Sloth Bear","Spectacled Bear","Asian Black Bear","Kodiak Bear"];return this.random.arrayElement(X)}cetacean(){let X=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement(X)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let X=["Arabian","Thoroughbred","Quarter Horse","Morgan","Appaloosa","Paint Horse","Tennessee Walker","Standardbred","Mustang","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Shire","Haflinger","Icelandic","Shetland Pony"];return this.random.arrayElement(X)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let X=["Butterfly","Moth","Bee","Wasp","Ant","Beetle","Dragonfly","Grasshopper","Cricket","Ladybug","Firefly","Mosquito","Fly","Cockroach","Termite","Flea","Praying Mantis","Cicada","Caterpillar","Walking Stick"];return this.random.arrayElement(X)}lion(){let X=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement(X)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let X=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement(X)}snake(){let X=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement(X)}}class z${random;locale;constructor(X,$){this.random=X,this.locale=$}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let X=["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","The Chronicles of Narnia","Brave New World","The Divine Comedy","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude","The Sound and the Fury","Invisible Man","Beloved","The Grapes of Wrath","Catch-22","Slaughterhouse-Five","Fahrenheit 451","The Handmaid's Tale","The Road","Life of Pi","The Kite Runner","The Book Thief"];return this.random.arrayElement(X)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let X=["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee","Maya Angelou","Toni Morrison","Gabriel Garc\xEDa M\xE1rquez","Franz Kafka","James Joyce","Virginia Woolf","Oscar Wilde","Emily Dickinson","Walt Whitman","Robert Frost","Sylvia Plath","Kurt Vonnegut","Margaret Atwood","Haruki Murakami","Chimamanda Ngozi Adichie"];return this.random.arrayElement(X)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let X=["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Pearson","Wiley","Springer","McGraw-Hill","Bloomsbury","Vintage","Doubleday","Knopf"];return this.random.arrayElement(X)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let X=["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Poetry","Drama","Comedy","Adventure","Young Adult","Children's","Crime","Western","Dystopian","Paranormal","Contemporary","Classic","Literary Fiction"];return this.random.arrayElement(X)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let X=["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","The Maze Runner","Divergent","The Mortal Instruments","Sherlock Holmes","Discworld","Dune","Foundation","The Wheel of Time","The Witcher","Millennium","Jack Reacher"];return this.random.arrayElement(X)}isbn(){if(this.random.boolean(0.5)){let _=Array.from({length:9},()=>this.random.int(0,9)),Q=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${_.slice(0,1).join("")}-${_.slice(1,4).join("")}-${_.slice(4,9).join("")}-${Q}`}let X="978",$=this.random.int(0,9),Z=Array.from({length:3},()=>this.random.int(0,9)).join(""),Y=Array.from({length:5},()=>this.random.int(0,9)).join(""),U=this.random.int(0,9);return`${X}-${$}-${Z}-${Y}-${U}`}format(){let X=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement(X)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let X=["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","A page-turner with incredible characters.","One of the best books I've ever read.","Absolutely captivating!"];return this.random.arrayElement(X)}}class L${random;locale;constructor(X,$){this.random=X,this.locale=$}hex(X){let $=X?.prefix??"#",Z=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return $+Z}rgb(X){let $=this.random.int(0,255),Z=this.random.int(0,255),Y=this.random.int(0,255);if(X?.alpha){let U=this.random.float(0,1,2);if(X?.format==="array")return[$,Z,Y,U];return`rgba(${$}, ${Z}, ${Y}, ${U})`}if(X?.format==="array")return[$,Z,Y];return`rgb(${$}, ${Z}, ${Y})`}hsl(X){let $=this.random.int(0,360),Z=this.random.int(0,100),Y=this.random.int(0,100);if(X?.alpha){let U=this.random.float(0,1,2);if(X?.format==="array")return[$,Z,Y,U];return`hsla(${$}, ${Z}%, ${Y}%, ${U})`}if(X?.format==="array")return[$,Z,Y];return`hsl(${$}, ${Z}%, ${Y}%)`}css(X){let $=X?.format??this.random.arrayElement(["hex","rgb","hsl"]);if($==="hex")return this.hex();if($==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let X=["Red","Blue","Green","Yellow","Purple","Orange","Pink","Brown","Black","White","Gray","Cyan","Magenta","Lime","Navy","Teal","Olive","Maroon","Aqua","Silver","Fuchsia","Gold","Indigo","Violet"];return this.random.arrayElement(X)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class j${random;locale;constructor(X,$){this.random=X,this.locale=$}product(){let X=this.locale?.commerce?.productAdjective??["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable"],$=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],Z=this.locale?.commerce?.product??["Chair","Table","Lamp","Keyboard","Mouse","Computer","Shoes","Shirt","Pants","Hat","Gloves","Towel","Soap","Bike","Ball","Book","Wallet","Watch","Phone","Desk","Bottle","Plate","Cup","Bag","Pen","Notebook","Backpack","Sunglasses"];return`${this.random.arrayElement(X)} ${this.random.arrayElement($)} ${this.random.arrayElement(Z)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let X=["Books","Movies","Music","Games","Electronics","Computers","Home","Garden","Tools","Grocery","Health","Beauty","Toys","Kids","Baby","Clothing","Shoes","Jewelry","Sports","Outdoors","Automotive","Industrial"];return this.random.arrayElement(X)}price(X){let $=X?.min??1,Z=X?.max??1000,Y=X?.dec??2,U=X?.symbol??"",_=this.random.float($,Z,Y);return U+_.toFixed(Y)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let X=["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable","Innovative","Compact","Versatile","Modern","Classic","Vintage","Contemporary"];return this.random.arrayElement(X)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let X=["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum","Bronze","Copper","Brass","Titanium","Ceramic","Velvet","Linen","Wool"];return this.random.arrayElement(X)}productDescription(){let X=["The beautiful range of {adjective} {material} {product} comes with a {feature}.","Experience the {adjective} {product} that redefines {benefit}.","Our {adjective} {material} {product} is designed for {benefit}.","Discover the {adjective} {product} with {feature} for {benefit}."],$=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],Z=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement(X).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement($)).replace("{benefit}",this.random.arrayElement(Z))}review(){let X=["This product exceeded my expectations!","Absolutely love it! Worth every penny.","Great quality and fast shipping.","Not what I expected, but still decent.","Amazing! Highly recommend to everyone.","Perfect for my needs. Very satisfied.","Good value for the price.","Could be better, but it does the job.","Fantastic product! Will buy again.","Best purchase I've made this year!"];return this.random.arrayElement(X)}discountCode(){let X=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],$=this.random.int(10,99);return`${this.random.arrayElement(X)}${$}`}sku(){let X=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),$=this.random.int(1e4,99999),Z=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${X}-${$}-${Z}`}}class E${random;locale;constructor(X,$){this.random=X,this.locale=$}name(){let X=this.random.arrayElement(this.locale.company.name??["Company"]),$=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${X} ${$}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let X=this.random.arrayElement(this.locale.company.adjective??["innovative"]),$=this.random.arrayElement(this.locale.company.descriptor??["digital"]),Z=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${X} ${$} ${Z}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let X=this.buzzword(),$=this.random.arrayElement(this.locale.company.descriptor??["digital"]),Z=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${X} ${$} ${Z}`}}class u8{random;constructor(X){this.random=X}engine(){let X=["MySQL","PostgreSQL","MongoDB","SQLite","Redis","Oracle","Microsoft SQL Server","MariaDB","Cassandra","Elasticsearch","DynamoDB","CouchDB","Neo4j","Firebase","Firestore","InfluxDB","TimescaleDB","RethinkDB","ArangoDB","CockroachDB"];return this.random.arrayElement(X)}type(){let X=["VARCHAR","INTEGER","BIGINT","SMALLINT","DECIMAL","NUMERIC","FLOAT","DOUBLE","BOOLEAN","DATE","TIME","TIMESTAMP","DATETIME","TEXT","BLOB","JSON","JSONB","UUID","ENUM","ARRAY","SERIAL","BIGSERIAL"];return this.random.arrayElement(X)}collation(){let X=["utf8_general_ci","utf8_unicode_ci","utf8mb4_general_ci","utf8mb4_unicode_ci","latin1_swedish_ci","latin1_general_ci","utf8_bin","utf8mb4_bin"];return this.random.arrayElement(X)}column(){let X=["id","user_id","name","email","password","created_at","updated_at","deleted_at","first_name","last_name","phone","address","city","state","country","zip_code","status","role","permissions","description","price","quantity","total","subtotal","tax","discount","shipping","notes","metadata","settings","preferences","avatar"];return this.random.arrayElement(X)}table(){let X=["users","posts","comments","products","orders","customers","invoices","payments","categories","tags","roles","permissions","sessions","settings","notifications","messages","attachments","logs","analytics","reports","subscriptions","transactions"];return this.random.arrayElement(X)}mongodbObjectId(){let X="";for(let $=0;$<24;$++)X+="0123456789abcdef"[this.random.int(0,15)];return X}constraint(){let X=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement(X)}queryType(){let X=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement(X)}connectionString(X){let $=X?.engine??this.engine().toLowerCase().replace(/ /g,""),Z="user",Y="password",U="localhost",_=this.random.int(3000,9999),Q=this.table(),L={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[$]||"jdbc";if($==="mongodb")return`${L}://user:password@localhost:${_}/${Q}`;return`${L}://user:password@localhost:${_}/${Q}`}}class n8{random;constructor(X){this.random=X}past(X){let $=X?.years??1,Z=X?.to??new Date,Y=X?.from??new Date(Z.getTime()-$*365*24*60*60*1000);return this.between({from:Y,to:Z})}future(X){let $=X?.years??1,Z=X?.from??new Date,Y=X?.to??new Date(Z.getTime()+$*365*24*60*60*1000);return this.between({from:Z,to:Y})}between(X){let $=X.from??new Date(Date.now()-31536000000),Z=X.to??new Date,Y=$.getTime(),U=Z.getTime(),_=this.random.int(Y,U);return new Date(_)}recent(X){let $=X?.days??1,Z=new Date,Y=new Date(Z.getTime()-$*24*60*60*1000);return this.between({from:Y,to:Z})}soon(X){let $=X?.days??1,Z=new Date,Y=new Date(Z.getTime()+$*24*60*60*1000);return this.between({from:Z,to:Y})}month(){let X=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement(X)}weekday(){let X=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement(X)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween(X){return this.between(X)}birthdate(X){let $=X?.mode??"age",Z=X?.refDate??new Date;if($==="year"){let z=X?.min??1900,j=X?.max??Z.getUTCFullYear(),E=new Date(Date.UTC(z,0,1)),V=new Date(Date.UTC(j,11,31,23,59,59,999));return this.between({from:E,to:V})}let Y=Math.max(0,X?.min??18),U=Math.max(Y,X?.max??80),_=(z)=>z*365.25*24*60*60*1000,Q=new Date(Z.getTime()-_(U)),L=new Date(Z.getTime()-_(Y));return this.between({from:Q,to:L})}}class i8{random;constructor(X){this.random=X}amount(X){let $=X?.min??0,Z=X?.max??1e4,Y=X?.dec??2,U=X?.symbol??"",_=this.random.float($,Z,Y);return U+_.toFixed(Y)}account(X=8){let $="";for(let Z=0;Z<X;Z++)$+=this.random.int(0,9);return $}accountName(){let X=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement(X)} Account`}routingNumber(){return this.account(9)}creditCardNumber(X){let $=X?.formatted??!0,Z=X?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),Y="",U=16;switch(Z){case"visa":Y="4",U=16;break;case"mastercard":Y=`5${this.random.int(1,5)}`,U=16;break;case"amex":Y=`3${this.random.arrayElement(["4","7"])}`,U=15;break;case"discover":Y="6011",U=16;break}let _=Y;while(_.length<U)_+=this.random.int(0,9);if($){if(Z==="amex")return`${_.slice(0,4)}-${_.slice(4,10)}-${_.slice(10)}`;return _.match(/.{1,4}/g)?.join("-")??_}return _}cvv(){return this.account(3)}iban(X){let $=X?.countryCode??"GB",Z=X?.formatted??!1,Y=this.random.int(10,99).toString(),U="WEST",_=this.account(14),Q=$+Y+"WEST"+_;if(Z)return Q.match(/.{1,4}/g)?.join(" ")??Q;return Q}bic(){let X="";for(let $=0;$<4;$++)X+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let $=0;$<2;$++)X+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let $=0;$<2;$++)X+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(Z,Y)=>Y.toString())]);return X}bitcoin(){let X=this.random.arrayElement(["1","3"]);for(let $=0;$<33;$++)X+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return X}ethereum(){let X="0x";for(let $=0;$<40;$++)X+="0123456789abcdef"[this.random.int(0,15)];return X}currencyCode(){let X=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement(X)}currencyName(){let X=["US Dollar","Euro","British Pound","Japanese Yen","Australian Dollar","Canadian Dollar","Swiss Franc","Chinese Yuan","Swedish Krona","New Zealand Dollar","Indian Rupee","Brazilian Real","Russian Ruble","South Korean Won"];return this.random.arrayElement(X)}currencySymbol(){let X=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement(X)}transactionType(){let X=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement(X)}}class G${random;locale;constructor(X,$){this.random=X,this.locale=$}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let X=["Spaghetti Carbonara","Chicken Alfredo","Beef Tacos","Margherita Pizza","Caesar Salad","Pad Thai","Chicken Tikka Masala","Sushi Roll","Beef Burger","Fish and Chips","Ramen","Tom Yum Soup","Greek Salad","Lasagna","Paella","Pho","Falafel Wrap","Burrito Bowl","Chicken Curry","Steak Frites","Risotto","Poke Bowl","Bibimbap","Shakshuka","Eggs Benedict","Club Sandwich","Caprese Salad","Fettuccine Alfredo","Chicken Parmesan","Pulled Pork Sandwich","Gyro","Butter Chicken","Peking Duck"];return this.random.arrayElement(X)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let X=["Garlic","Onion","Tomato","Basil","Oregano","Thyme","Rosemary","Cilantro","Parsley","Salt","Pepper","Olive Oil","Butter","Flour","Sugar","Eggs","Milk","Cheese","Chicken","Beef","Pork","Fish","Shrimp","Rice","Pasta","Potatoes","Carrots","Celery","Bell Pepper","Mushrooms","Spinach","Lettuce","Cucumber","Avocado","Lemon","Lime","Ginger","Soy Sauce","Vinegar","Honey","Cinnamon","Cumin"];return this.random.arrayElement(X)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let X=["Basil","Oregano","Thyme","Rosemary","Sage","Cilantro","Parsley","Mint","Dill","Paprika","Cumin","Turmeric","Coriander","Cardamom","Cinnamon","Nutmeg","Cloves","Black Pepper","White Pepper","Cayenne","Chili Powder","Curry Powder","Garam Masala","Saffron","Vanilla","Bay Leaf","Fennel","Anise","Tarragon","Marjoram"];return this.random.arrayElement(X)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let X=["Broccoli","Carrot","Celery","Lettuce","Spinach","Kale","Cabbage","Cauliflower","Brussels Sprouts","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Tomato","Cucumber","Bell Pepper","Zucchini","Eggplant","Mushroom","Onion","Garlic","Radish","Beet","Turnip","Artichoke","Bok Choy","Arugula","Swiss Chard"];return this.random.arrayElement(X)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let X=["Apple","Banana","Orange","Grape","Strawberry","Blueberry","Raspberry","Blackberry","Mango","Pineapple","Watermelon","Cantaloupe","Honeydew","Peach","Plum","Cherry","Pear","Kiwi","Papaya","Dragon Fruit","Lychee","Passion Fruit","Pomegranate","Coconut","Avocado","Lemon","Lime","Grapefruit","Apricot","Fig","Date"];return this.random.arrayElement(X)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let X=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement(X)}seafood(){let X=["Salmon","Tuna","Cod","Halibut","Trout","Mackerel","Sardines","Anchovies","Shrimp","Crab","Lobster","Scallops","Clams","Mussels","Oysters","Squid","Octopus","Tilapia","Sea Bass","Swordfish","Snapper","Grouper","Catfish"];return this.random.arrayElement(X)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let X=["Chocolate Cake","Cheesecake","Apple Pie","Ice Cream","Brownies","Cookies","Tiramisu","Cr\xE8me Br\xFBl\xE9e","Panna Cotta","Macarons","Cupcakes","Donuts","Eclairs","Profiteroles","Cannoli","Baklava","Flan","Churros","Gelato","Sorbet","Mousse","Tart","Cobbler","Pudding","Trifle","Souffl\xE9"];return this.random.arrayElement(X)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let X=["Italian","Chinese","Japanese","Mexican","Thai","Indian","French","Greek","Spanish","Korean","Vietnamese","Lebanese","Turkish","Brazilian","Moroccan","Ethiopian","Caribbean","Peruvian","German","American","British","Irish"];return this.random.arrayElement(X)}description(){let X=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],$=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement(X)} ${this.random.arrayElement($)}`}}class l8{random;constructor(X){this.random=X}branch(){let X=["feature","bugfix","hotfix","refactor","chore","docs","test"],$=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],Z=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],Y=this.random.arrayElement(X),U=this.random.arrayElement($),_=this.random.arrayElement(Z);return`${Y}/${U}-${_}`}commitMessage(){let X=["feat","fix","docs","style","refactor","test","chore","perf"],$=["api","ui","auth","db","config","deps","core","utils"],Z=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],Y=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],U=this.random.arrayElement(X),_=this.random.boolean(0.5)?`(${this.random.arrayElement($)})`:"",Q=this.random.arrayElement(Z),L=this.random.arrayElement(Y);return`${U}${_}: ${Q} ${L}`}commitSha(X){let $=X?.short?7:40,Z="0123456789abcdef",Y="";for(let U=0;U<$;U++)Y+="0123456789abcdef"[this.random.int(0,15)];return Y}commitEntry(){let X=this.commitSha({short:!0}),$=this.commitMessage();return`${X} ${$}`}commitAuthor(X){let $=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],Z=X?.name??this.random.arrayElement($),Y=X?.email??`${Z.toLowerCase().replace(" ",".")}@example.com`;return`${Z} <${Y}>`}remote(X){let $=X?.protocol??this.random.arrayElement(["https","ssh"]),Z=X?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),Y=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),U=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),_={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if($==="ssh")return`git@${_[Z]}:${Y}/${U}.git`;return`https://${_[Z]}/${Y}/${U}.git`}tag(){let X=this.random.int(0,5),$=this.random.int(0,20),Z=this.random.int(0,50),Y=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${X}.${$}.${Z}${Y}`}}class F${random;locale;constructor(X,$){this.random=X,this.locale=$}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let X=["TCP","HTTP","SDD","RAM","GB","CSS","SSL","AGP","SQL","CLI","IB","UX","UI","FTP","AI","ADP","RSS","XML","EXE","COM","HDD","THX","MP3","GPU","API","DNS","IP","LAN","WAN","VPN","SSH","HTTPS","JSON","REST","SOAP"];return this.random.arrayElement(X)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let X=["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","haptic","multi-byte","bluetooth","wireless","mobile","neural","optical","solid state","cloud","quantum","distributed","encrypted"];return this.random.arrayElement(X)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let X=["driver","protocol","bandwidth","panel","microchip","program","port","card","array","interface","system","sensor","firewall","hard drive","pixel","alarm","feed","monitor","application","transmitter","bus","circuit","capacitor","matrix","server","database","network","router","switch","gateway","node","cluster"];return this.random.arrayElement(X)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let X=["back up","bypass","hack","override","compress","copy","navigate","index","connect","generate","quantify","calculate","synthesize","input","transmit","program","reboot","parse","compile","encode","decode","encrypt","decrypt","patch","upgrade","deploy","configure","optimize","refactor","debug"];return this.random.arrayElement(X)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let X=["backing up","bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","quantifying","calculating","synthesizing","transmitting","programming","parsing","compiling","encoding","decoding","encrypting","decrypting","patching","deploying","configuring","optimizing"];return this.random.arrayElement(X)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let X=["If we {verb} the {noun}, we can get to the {abbreviation} {noun} through the {adjective} {abbreviation} {noun}!","We need to {verb} the {adjective} {abbreviation} {noun}!","Try to {verb} the {abbreviation} {noun}, maybe it will {verb} the {adjective} {noun}!","You can't {verb} the {noun} without {ingverb} the {adjective} {abbreviation} {noun}!","Use the {adjective} {abbreviation} {noun}, then you can {verb} the {adjective} {noun}!","The {abbreviation} {noun} is down, {verb} the {adjective} {noun} so we can {verb} the {abbreviation} {noun}!","{ingverb} the {noun} won't do anything, we need to {verb} the {adjective} {abbreviation} {noun}!","I'll {verb} the {adjective} {abbreviation} {noun}, that should {verb} the {abbreviation} {noun}!"];return this.random.arrayElement(X).replace(/\{verb\}/g,()=>this.verb()).replace(/\{ingverb\}/g,()=>this.ingverb()).replace(/\{noun\}/g,()=>this.noun()).replace(/\{adjective\}/g,()=>this.adjective()).replace(/\{abbreviation\}/g,()=>this.abbreviation())}}class s8{random;constructor(X){this.random=X}randomElement(X){return this.random.arrayElement(X)}arrayElement(X){return this.random.arrayElement(X)}arrayElements(X,$){return this.random.arrayElements(X,$)}shuffle(X){return this.random.shuffle(X)}numerify(X){return X.replace(/#/g,()=>String(this.random.int(0,9)))}lexify(X){return X.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify(X){return this.numerify(this.lexify(X))}replaceSymbols(X){return this.random.replaceSymbols(X)}boolean(X=0.5){return this.random.boolean(X)}objectKey(X){let $=Object.keys(X);return this.random.arrayElement($)}objectValue(X){let $=this.objectKey(X);return X[$]}multiple(X,$=3){return Array.from({length:$},X)}maybe(X,$=0.5){return this.random.boolean($)?X():void 0}unique(X,$=50){let Z=new Set,Y=0;while(Y<$){let U=X();if(!Z.has(U))return Z.add(U),U;Y++}throw Error(`Failed to generate unique value after ${$} retries`)}replaceCreditCardSymbols(X="####-####-####-####",$="#"){return this.random.replaceCreditCardSymbols(X,$)}regexify(X){return X.replace(/\[A-Z\]/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/\[a-z\]/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split(""))).replace(/\[0-9\]/g,()=>String(this.random.int(0,9))).replace(/\{(\d+)\}/g,($,Z)=>{return""})}}class o8{random;constructor(X){this.random=X}url(X){let $=X?.width??640,Z=X?.height??480;return`https://via.placeholder.com/${$}x${Z}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr(X){let $=X?.width??640,Z=X?.height??480,Y=X?.category??"";if(Y)return`https://loremflickr.com/${$}/${Z}/${Y}`;return`https://loremflickr.com/${$}/${Z}`}urlPicsumPhotos(X){let $=X?.width??640,Z=X?.height??480,Y=`https://picsum.photos/${$}/${Z}`;if(X?.grayscale)Y+="?grayscale";if(X?.blur)Y+=X?.grayscale?`&blur=${X.blur}`:`?blur=${X.blur}`;return Y}dataUri(X){let $=X?.width??640,Z=X?.height??480,Y=X?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),U=`<svg xmlns="http://www.w3.org/2000/svg" width="${$}" height="${Z}"><rect width="${$}" height="${Z}" fill="#${Y}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(U)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let X=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement(X)}imageType(){let X=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement(X)}}class O${random;locale;domainWordsCache=null;constructor(X,$){this.random=X,this.locale=$}getDomainWords(){if(!this.domainWordsCache){let X=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=X.map(($)=>$.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(($)=>$.length>0)}return this.domainWordsCache}email(X){let $;if(X?.firstName)$=X.firstName.toLowerCase();else{let Q=this.locale.person.firstNameMale.length,L=this.locale.person.firstNameFemale.length,z=this.locale.person.firstNameNeutral?.length||0,j=Q+L+z,E=this.random.int(0,j-1);if(E<Q)$=this.locale.person.firstNameMale[E].toLowerCase();else if(E<Q+L)$=this.locale.person.firstNameFemale[E-Q].toLowerCase();else $=this.locale.person.firstNameNeutral[E-Q-L].toLowerCase()}let Z=X?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=X?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),U=this.random.arrayElement(aU),_=this.random.arrayElement(this.getDomainWords());return`${$}${U}${Z}@${_}.${Y}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let X=this.locale.person.firstNameMale.length,$=this.locale.person.firstNameFemale.length,Z=this.locale.person.firstNameNeutral?.length||0,Y=X+$+Z,U=this.random.int(0,Y-1),_;if(U<X)_=this.locale.person.firstNameMale[U].toLowerCase();else if(U<X+$)_=this.locale.person.firstNameFemale[U-X].toLowerCase();else _=this.locale.person.firstNameNeutral[U-X-$].toLowerCase();let Q=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),L=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),z=[".","_",""],j=this.random.arrayElement(z);return`${_}${j}${Q}@${L}`}username(X){let $;if(X?.firstName)$=X.firstName.toLowerCase();else{let U=this.locale.person.firstNameMale.length,_=this.locale.person.firstNameFemale.length,Q=this.locale.person.firstNameNeutral?.length||0,L=U+_+Q,z=this.random.int(0,L-1);if(z<U)$=this.locale.person.firstNameMale[z].toLowerCase();else if(z<U+_)$=this.locale.person.firstNameFemale[z-U].toLowerCase();else $=this.locale.person.firstNameNeutral[z-U-_].toLowerCase()}let Z=X?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=[`${$}${Z}`,`${$}_${Z}`,`${$}.${Z}`,`${$}${this.random.int(10,999)}`,`${$}_${Z}${this.random.int(10,99)}`];return this.random.arrayElement(Y)}password(X){let $=X?.length??12,Z=X?.memorable??!1,Y=X?.prefix??"";if(Z){let Q=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],L=[];for(let z=0;z<3;z++)L.push(this.random.arrayElement(Q));return Y+L.join("-")+this.random.int(10,999)}let U="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",_=Y;for(let Q=Y.length;Q<$;Q++)_+=U[this.random.int(0,U.length-1)];return _}url(X){let $=X?.protocol??this.random.arrayElement(["http","https"]),Z=X?.domain??this.domainName();return`${$}://${Z}`}domainName(){return`${this.domainWord()}.${this.domainSuffix()}`}domainWord(){return this.random.arrayElement(this.getDomainWords())}domainSuffix(){return this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"])}ipv4(){return`${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}`}ipv6(){let X=[];for(let $=0;$<8;$++)X.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return X.join(":")}mac(X=":"){let $=[];for(let Z=0;Z<6;Z++)$.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return $.join(X)}userAgent(){let X=["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/120.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 14.0; rv:109.0) Gecko/20100101 Firefox/120.0"];return this.random.arrayElement(X)}slug(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return $.join("-").toLowerCase()}ip(){return this.ipv4()}}class r8{random;constructor(X){this.random=X}word(){return this.random.arrayElement(tU)}words(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.word());return $.join(" ")}sentence(X){let $=X??this.random.int(3,10),Z=this.words($);return`${Z.charAt(0).toUpperCase()+Z.slice(1)}.`}sentences(X=3,$=" "){let Z=[];for(let Y=0;Y<X;Y++)Z.push(this.sentence());return Z.join($)}paragraph(X){let $=X??this.random.int(3,7);return this.sentences($)}paragraphs(X=3,$=`
|
|
456
456
|
|
|
457
457
|
`){let Z=[];for(let Y=0;Y<X;Y++)Z.push(this.paragraph());return Z.join($)}text(X){let $=X??200,Z="";while(Z.length<$)Z+=`${this.paragraph()} `;return Z.trim().slice(0,$)}slug(X=3){return this.words(X).replace(/ /g,"-")}lines(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.sentence());return $.join(`
|
|
458
|
-
`)}}class J${random;locale;constructor(X,$){this.random=X,this.locale=$}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let X=["Rock","Pop","Jazz","Blues","Classical","Hip Hop","R&B","Country","Electronic","Dance","Metal","Punk","Reggae","Soul","Funk","Disco","House","Techno","Dubstep","Indie","Alternative","Folk","Gospel","Latin","K-Pop","EDM","Trap","Lo-Fi","Ambient","Ska"];return this.random.arrayElement(X)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let X=["Dancing in the Moonlight","Bohemian Rhapsody","Stairway to Heaven","Hotel California","Imagine","Yesterday","Hey Jude","Sweet Child O' Mine","Smells Like Teen Spirit","Billie Jean","Thriller","Purple Rain","Born to Run","Like a Rolling Stone","What's Going On","Respect","Good Vibrations","Johnny B. Goode","I Want to Hold Your Hand","Satisfaction","My Generation","Brown Sugar","Layla","Crossroads","The End","Light My Fire","All Along the Watchtower","While My Guitar Gently Weeps","A Day in the Life"];return this.random.arrayElement(X)}albumName(){let X=["Abbey Road","The Dark Side of the Moon","Thriller","Back in Black","The Wall","Rumours","Nevermind","Led Zeppelin IV","Born in the U.S.A.","Sgt. Pepper's Lonely Hearts Club Band","OK Computer","The Beatles (White Album)","Purple Rain","Hotel California","21","Appetite for Destruction","Lemonade","To Pimp a Butterfly","Random Access Memories"];return this.random.arrayElement(X)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let X=["The Beatles","Led Zeppelin","Pink Floyd","Queen","The Rolling Stones","Elvis Presley","Michael Jackson","Madonna","David Bowie","Nirvana","Radiohead","U2","AC/DC","Metallica","Bob Dylan","Jimi Hendrix","Prince","Stevie Wonder","Aretha Franklin","The Who","The Doors","Fleetwood Mac","Eagles","Guns N' Roses","Red Hot Chili Peppers","Coldplay","Beyonc\xE9","Taylor Swift","Drake","Kendrick Lamar","Adele","Ed Sheeran"];return this.random.arrayElement(X)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let X=["Guitar","Piano","Drums","Bass","Violin","Saxophone","Trumpet","Flute","Clarinet","Cello","Harp","Keyboard","Harmonica","Accordion","Ukulele","Banjo","Mandolin","Trombone","French Horn","Tuba","Oboe","Bassoon","Xylophone","Marimba","Tambourine","Synthesizer","Didgeridoo","Sitar","Tabla","Djembe"];return this.random.arrayElement(X)}note(){let X=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement(X)}chord(){let X=this.note(),$=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${X}${$}`}tempo(){return this.random.int(60,200)}key(){let X=this.note(),$=this.random.arrayElement(["Major","Minor"]);return`${X} ${$}`}timeSignature(){let X=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement(X)}}class a8{random;constructor(X){this.random=X}int(X){let $=X?.min??0,Z=X?.max??100;return this.random.int($,Z)}float(X){let $=X?.min??0,Z=X?.max??1,Y=X?.precision??2;return this.random.float($,Z,Y)}bigInt(X){let $=X?.min??0n,Z=(X?.max??1000000n)-$+1n,Y=BigInt(Math.floor(this.random.number()*Number(Z)));return $+Y}binary(X){let $=X?.length??8,Z="";for(let Y=0;Y<$;Y++)Z+=this.random.int(0,1);return Z}octal(X){let $=X?.length??3,Z="";for(let Y=0;Y<$;Y++)Z+=this.random.int(0,7);return Z}hex(X){let $=X?.length??6,Z="0123456789ABCDEF",Y="";for(let U=0;U<$;U++)Y+="0123456789ABCDEF"[this.random.int(0,15)];return Y}randomNumber(X){return this.int(X)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class W${random;locale;constructor(X,$){this.random=X,this.locale=$}firstName(X){if(X?.gender==="male")return this.firstNameMale();if(X?.gender==="female")return this.firstNameFemale();if(X?.gender==="neutral")return this.firstNameNeutral();let $=this.locale.person.firstNameMale.length,Z=this.locale.person.firstNameFemale.length,Y=this.locale.person.firstNameNeutral?.length||0,U=$+Z+Y,_=this.random.int(0,U-1);if(_<$)return this.locale.person.firstNameMale[_];if(_<$+Z)return this.locale.person.firstNameFemale[_-$];return this.locale.person.firstNameNeutral[_-$-Z]}firstNameMale(){return this.random.arrayElement(this.locale.person.firstNameMale)}firstNameFemale(){return this.random.arrayElement(this.locale.person.firstNameFemale)}firstNameNeutral(){if(!this.locale.person.firstNameNeutral||this.locale.person.firstNameNeutral.length===0){let X=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement(X)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName(X){if(!X)return`${this.firstName()} ${this.lastName()}`;let $=this.firstName({gender:X.gender}),Z=this.lastName();if(X.prefix&&X.suffix)return`${this.prefix()} ${$} ${Z} ${this.suffix()}`;if(X.prefix)return`${this.prefix()} ${$} ${Z}`;if(X.suffix)return`${$} ${Z} ${this.suffix()}`;return`${$} ${Z}`}prefix(){return this.random.arrayElement(this.locale.person.prefix)}suffix(){return this.random.arrayElement(this.locale.person.suffix)}gender(){return this.random.arrayElement(this.locale.person.gender)}jobTitle(){return this.random.arrayElement(this.locale.person.jobTitle)}name(){return this.fullName()}firstNameAdvanced(X){let $;if(X?.constraints)$=this.firstName({gender:X.constraints.gender});else $=this.firstName({gender:X?.gender});if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({firstName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).firstName||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.firstName({gender:X?.gender||X?.constraints?.gender})}}return $}fullNameAdvanced(X){let $;if(X?.constraints)$=this.fullName({gender:X.constraints.gender,prefix:X.prefix,suffix:X.suffix});else $=this.fullName(X);if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({fullName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).fullName||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.fullName({gender:X?.gender||X?.constraints?.gender,prefix:X?.prefix,suffix:X?.suffix})}}return $}profile(X){let $=X?.constraints?.gender||X?.gender||this.gender(),Z=this.firstNameAdvanced({...X,gender:$}),Y=this.lastName(),U=`${Z} ${Y}`,_={firstName:Z,lastName:Y,fullName:U,gender:$,jobTitle:this.jobTitle(),age:X?.constraints?.ageRange?this.random.int(X.constraints.ageRange.min,X.constraints.ageRange.max):this.random.int(18,80)};if(X?.relationships)return d9(_,X.relationships);return _}family(X){let $=X?.size||this.random.int(2,6),Z=this.lastName(),Y=["parent","parent","child","child","child","grandparent"],U=[];for(let _=0;_<$;_++){let Q=Y[_]||"relative",L=Q==="parent"||Q==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",z=this.firstNameAdvanced({...X,gender:L,constraints:{...X?.constraints,gender:L}});U.push({firstName:z,lastName:Z,fullName:`${z} ${Z}`,gender:L,relationship:Q})}return{members:U,lastName:Z}}}class V${random;locale;constructor(X,$){this.random=X,this.locale=$}number(X){let $=X??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols($)}phoneNumber(X){return this.number(X)}}class I${random;locale;constructor(X,$){this.random=X,this.locale=$}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let X=["Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Argon","Potassium","Calcium","Iron","Copper","Zinc","Silver","Gold","Mercury","Lead","Uranium","Platinum","Titanium"];return this.random.arrayElement(X)}chemicalElementSymbol(){let X=["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Fe","Cu","Zn","Ag","Au","Hg","Pb","U","Pt","Ti"];return this.random.arrayElement(X)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let X=["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","coulomb","volt","ohm","farad","weber","tesla","henry","celsius","lumen","lux","becquerel","gray","sievert","katal","hertz","radian","steradian"];return this.random.arrayElement(X)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let X=["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Magnetic Constant","Electric Constant","Fine Structure Constant","Rydberg Constant","Gas Constant","Stefan-Boltzmann Constant"];return this.random.arrayElement(X)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let X=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement(X)}dnaSequence(X=12){let $=["A","T","C","G"],Z="";for(let Y=0;Y<X;Y++)Z+=this.random.arrayElement($);return Z}rnaSequence(X=12){let $=["A","U","C","G"],Z="";for(let Y=0;Y<X;Y++)Z+=this.random.arrayElement($);return Z}hypothesis(){let X=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],$=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement(X)}, then ${this.random.arrayElement($)}`}}class K${random;locale;constructor(X,$){this.random=X,this.locale=$}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let X=["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding","Cycling","Running","Marathon","Triathlon","Gymnastics","Fencing","Archery","Martial Arts","Karate","Judo","Taekwondo","MMA","Formula 1","NASCAR","Sailing"];return this.random.arrayElement(X)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let X=["Lakers","Warriors","Bulls","Celtics","Knicks","Heat","Spurs","Mavericks","Yankees","Red Sox","Dodgers","Cubs","Giants","Astros","Braves","Phillies","Patriots","49ers","Cowboys","Packers","Steelers","Eagles","Seahawks","Chiefs","Manchester United","Real Madrid","Barcelona","Liverpool","Bayern Munich","PSG","Maple Leafs","Bruins","Canadiens","Blackhawks","Penguins","Lightning"];return this.random.arrayElement(X)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let X=["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Pel\xE9","Cristiano Ronaldo","Lionel Messi","Roger Federer","Usain Bolt","Simone Biles","Michael Phelps","Kobe Bryant","Derek Jeter","Joe Montana","Magic Johnson","Larry Bird"];return this.random.arrayElement(X)}position(){let X=["Quarterback","Running Back","Wide Receiver","Linebacker","Defensive Back","Point Guard","Shooting Guard","Small Forward","Power Forward","Center","Pitcher","Catcher","First Base","Shortstop","Outfielder","Forward","Midfielder","Defender","Goalkeeper","Striker","Winger"];return this.random.arrayElement(X)}event(){let X=["Super Bowl","World Series","NBA Finals","Stanley Cup","FIFA World Cup","Olympics","Wimbledon","Masters Tournament","Kentucky Derby","Indianapolis 500","Tour de France","Boston Marathon","UEFA Champions League","World Cup","The Open Championship","US Open","French Open","Australian Open"];return this.random.arrayElement(X)}league(){let X=["NFL","NBA","MLB","NHL","MLS","Premier League","La Liga","Serie A","Bundesliga","Ligue 1","UEFA","FIFA","NCAA","PGA","ATP","WTA","F1","NASCAR","IndyCar"];return this.random.arrayElement(X)}quote(){let X=["Just do it!","Winners never quit and quitters never win.","Hard work beats talent when talent doesn't work hard.","The only way to prove you're a good sport is to lose.","Champions keep playing until they get it right.","It's not whether you get knocked down, it's whether you get up.","You miss 100% of the shots you don't take.","The difference between the impossible and the possible lies in determination."];return this.random.arrayElement(X)}equipment(){let X=["Ball","Bat","Glove","Helmet","Racket","Puck","Skates","Cleats","Pads","Jersey","Goggles","Swimsuit","Bicycle","Surfboard","Skateboard","Snowboard","Skis","Golf Clubs","Tennis Racket","Boxing Gloves","Mouthguard"];return this.random.arrayElement(X)}}class t8{random;constructor(X){this.random=X}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let X="0123456789abcdef",$="";for(let Z=0;Z<36;Z++)if(Z===8||Z===13||Z===18||Z===23)$+="-";else if(Z===14)$+="4";else if(Z===19){let Y=this.random.int(0,15);$+=X[Y&3|8]}else $+=X[this.random.int(0,15)];return $}nanoid(X=21){let $="";for(let Z=0;Z<X;Z++)$+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return $}alpha(X){let $=X?.length??10,Z=X?.casing??"mixed",Y="abcdefghijklmnopqrstuvwxyz",U="ABCDEFGHIJKLMNOPQRSTUVWXYZ",_="";if(Z==="lower")_="abcdefghijklmnopqrstuvwxyz";else if(Z==="upper")_="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else _="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let Q="";for(let L=0;L<$;L++)Q+=_[this.random.int(0,_.length-1)];return Q}alphanumeric(X){let $=X?.length??10,Z=X?.casing??"mixed",Y="abcdefghijklmnopqrstuvwxyz",U="ABCDEFGHIJKLMNOPQRSTUVWXYZ",_="0123456789",Q="0123456789";if(Z==="lower")Q+="abcdefghijklmnopqrstuvwxyz";else if(Z==="upper")Q+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else Q+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let L="";for(let z=0;z<$;z++)L+=Q[this.random.int(0,Q.length-1)];return L}numeric(X=10){if(!this.random.isSeeded()){let Z="";for(let Y=0;Y<X;Y++)Z+=Math.floor(Math.random()*10);return Z}let $="";for(let Z=0;Z<X;Z++)$+=this.random.int(0,9);return $}sample(X=10){return this.alphanumeric({length:X})}symbol(X=5){let $="";for(let Z=0;Z<X;Z++)$+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return $}hexadecimal(X){let $=X?.length??6,Z=X?.prefix??"",Y="0123456789abcdef",U=Z;for(let _=0;_<$;_++)U+="0123456789abcdef"[this.random.int(0,15)];return U}}class R${random;locale;constructor(X,$){this.random=X,this.locale=$}fileName(X){let $;if(this.locale?.system?.fileName)$=this.locale.system.fileName;else $=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let Z=this.random.arrayElement($),Y=X?.extension??this.fileExtension();return`${Z}.${Y}`}fileExtension(){let X=["pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","json","xml","jpg","jpeg","png","gif","bmp","svg","webp","ico","mp3","wav","ogg","flac","aac","m4a","mp4","avi","mov","wmv","flv","webm","mkv","zip","rar","tar","gz","7z","bz2","html","css","js","ts","jsx","tsx","vue","py","java","cpp","c","go","rs"];return this.random.arrayElement(X)}commonFileName(){let X=["README.md","package.json","tsconfig.json",".gitignore",".env","docker-compose.yml","Dockerfile","index.html","index.js","app.js","main.py","requirements.txt","Makefile","LICENSE","CHANGELOG.md","yarn.lock","package-lock.json","pom.xml"];return this.random.arrayElement(X)}mimeType(){let X=["application/json","application/xml","application/pdf","application/zip","text/html","text/css","text/javascript","text/plain","text/csv","image/jpeg","image/png","image/gif","image/svg+xml","image/webp","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg","video/avi","application/octet-stream","multipart/form-data","application/x-www-form-urlencoded"];return this.random.arrayElement(X)}commonMimeType(){let X=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement(X)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let X=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement(X)}directoryPath(){let X=["/usr/local/bin","/usr/bin","/etc","/var/log","/tmp","/home","/root","/opt","/srv","/mnt","/media","/dev","/proc","/sys","C:\\Program Files","C:\\Users","C:\\Windows","C:\\Temp","/Applications","/Library","/System","/Users","/Documents","/Downloads"];return this.random.arrayElement(X)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let X=this.random.int(0,10),$=this.random.int(0,20),Z=this.random.int(0,50);return`${X}.${$}.${Z}`}networkInterface(){let X=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement(X)}cron(){let X=this.random.boolean(0.5)?"*":this.random.int(0,59),$=this.random.boolean(0.5)?"*":this.random.int(0,23),Z=this.random.boolean(0.5)?"*":this.random.int(1,31),Y=this.random.boolean(0.5)?"*":this.random.int(1,12),U=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${X} ${$} ${Z} ${Y} ${U}`}}class D${random;locale;constructor(X,$){this.random=X,this.locale=$}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(tU)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(eU)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(X7)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement($7)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(Z7)}vin(){let X="";for(let $=0;$<17;$++)X+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return X}registration(){let X=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement(X).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let X=this.random.int(2000,2024),$=this.manufacturer(),Z=this.model();return`${X} ${$} ${Z}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let X=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement(X)}}class M${random;locale;constructor(X,$){this.random=X,this.locale=$}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let X=["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold","warm","cool","bright","dark","loud","quiet","strong","weak","clean","dirty","new","old","young","fresh","dry","wet","smooth","rough","sharp","dull","simple","complex","easy","difficult","good","bad","right","wrong","true","false"];return this.random.arrayElement(X)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let X=["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well","almost","always","never","often","rarely","sometimes","usually","frequently","occasionally","immediately","instantly","eventually","probably","possibly"];return this.random.arrayElement(X)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let X=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement(X)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let X=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement(X)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let X=["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","air","fire","earth","mountain","river","ocean","sky","sun","moon","star","cloud","rain","snow","person","man","woman","child","friend","family","food","music","art","book","school","work","time","day","night","morning","evening","world","life","love"];return this.random.arrayElement(X)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let X=["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through","during","before","after","against","among","into","onto","upon","within","without","toward","near","beside","behind"];return this.random.arrayElement(X)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let X=["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","look","see","hear","think","know","want","like","love","hate","need","make","take","give","get","put","come","go","say","tell","ask","answer","help","start","stop","begin","end","open","close","show","hide","find","lose","buy","sell","learn"];return this.random.arrayElement(X)}sample(){let X=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],$=this.random.arrayElement(X);return this[$]()}words(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.sample());return $.join(" ")}}class e8{seed;constructor(X){this.seed=X}isSeeded(){return this.seed!==void 0}number(){if(this.seed!==void 0)return this.seed=(this.seed*9301+49297)%233280,this.seed/233280;return Math.random()}int(X=0,$=100){return Math.floor(this.number()*($-X+1))+X}float(X=0,$=1,Z=2){let Y=this.number()*($-X)+X;return Number.parseFloat(Y.toFixed(Z))}arrayElement(X){if(X.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return X[Math.floor(Math.random()*X.length)];return X[this.int(0,X.length-1)]}arrayElements(X,$){if(X.length===0)return[];let Z=$??this.int(1,X.length);return[...X].sort(()=>this.number()-0.5).slice(0,Math.min(Z,X.length))}shuffle(X){let $=[...X];for(let Z=$.length-1;Z>0;Z--){let Y=this.int(0,Z);[$[Z],$[Y]]=[$[Y],$[Z]]}return $}boolean(X=0.5){return this.number()<X}replaceSymbols(X){if(this.seed===void 0){let $="";for(let Z=0;Z<X.length;Z++){let Y=X[Z];if(Y==="#")$+="0123456789"[Math.floor(Math.random()*10)];else if(Y==="?")$+=h1[Math.floor(Math.random()*26)];else $+=Y}return $}return X.replace(/[#?]/g,($)=>{if($==="#")return String(this.int(0,9));return this.arrayElement(h1)})}replaceCreditCardSymbols(X="####-####-####-####",$="#"){return X.replace(new RegExp($,"g"),()=>String(this.int(0,9)))}weightedArrayElement(X){if(X.length===0)throw Error("Cannot pick from empty weighted items array");let $=X.reduce((U,_)=>U+_.weight,0);if($<=0)throw Error("Total weight must be greater than 0");let Z=this.number()*$,Y=0;for(let U of X)if(Y+=U.weight,Z<=Y)return U.item;return X[X.length-1].item}weightedArrayElements(X,$,Z=!1){if(X.length===0)return[];let Y=$??this.int(1,X.length),U=[],_=[...X];for(let Q=0;Q<Y&&_.length>0;Q++){let L=this.weightedArrayElement(_);if(U.push(L),!Z){let z=_.findIndex((j)=>j.item===L);if(z!==-1)_.splice(z,1)}}return U}weightedBoolean(X=0.5){return this.number()<X}weightedInt(X,$,Z){let Y=$-X+1;if(Z){if(Z.length!==Y)throw Error("Weights array length must match the range size");let U=Z.map((_,Q)=>({item:X+Q,weight:_}));return this.weightedArrayElement(U)}return this.int(X,$)}}class jZ{random;_locale;_autoInstallLocales;person;address;internet;phone;company;lorem;date;number;string;color;finance;helpers;vehicle;image;git;science;music;database;food;commerce;book;animal;sport;hacker;system;word;constructor(X){let $=X?.locale??"en",Z=X?.seed;if(this._autoInstallLocales=X?.autoInstallLocales??!1,$!=="en"&&!Y9.isCached($))console.warn(`[ts-mocker] Locale '${$}' requires async loading. Use 'await Faker.create({ locale: "${$}" })' for better performance. Falling back to English.`),this._locale=Y9.loadSync("en");else this._locale=Y9.loadSync($);this.random=new e8(Z),this.person=new W$(this.random,this._locale),this.address=new _$(this.random,this._locale),this.internet=new O$(this.random,this._locale),this.phone=new V$(this.random,this._locale),this.company=new E$(this.random,this._locale),this.lorem=new r8(this.random),this.date=new n8(this.random),this.number=new a8(this.random),this.string=new t8(this.random),this.color=new L$(this.random,this._locale),this.finance=new i8(this.random),this.helpers=new s8(this.random),this.image=new o8(this.random),this.git=new l8(this.random),this.science=new I$(this.random,this._locale),this.music=new J$(this.random,this._locale),this.database=new u8(this.random),this.food=new G$(this.random,this._locale),this.commerce=new j$(this.random,this._locale),this.book=new z$(this.random,this._locale),this.animal=new Q$(this.random,this._locale),this.sport=new K$(this.random,this._locale),this.hacker=new F$(this.random,this._locale),this.system=new R$(this.random,this._locale),this.word=new M$(this.random,this._locale),this.vehicle=new D$(this.random,this._locale)}static async create(X){let $=X?.locale??"en";return await Y9.load($),new jZ(X)}seed(X){return this.random=new e8(X),Object.assign(this.person,new W$(this.random,this._locale)),Object.assign(this.address,new _$(this.random,this._locale)),Object.assign(this.internet,new O$(this.random,this._locale)),Object.assign(this.phone,new V$(this.random,this._locale)),Object.assign(this.company,new E$(this.random,this._locale)),Object.assign(this.lorem,new r8(this.random)),Object.assign(this.date,new n8(this.random)),Object.assign(this.number,new a8(this.random)),Object.assign(this.string,new t8(this.random)),Object.assign(this.color,new L$(this.random,this._locale)),Object.assign(this.finance,new i8(this.random)),Object.assign(this.helpers,new s8(this.random)),Object.assign(this.image,new o8(this.random)),Object.assign(this.git,new l8(this.random)),Object.assign(this.science,new I$(this.random,this._locale)),Object.assign(this.music,new J$(this.random,this._locale)),Object.assign(this.database,new u8(this.random)),Object.assign(this.food,new G$(this.random,this._locale)),Object.assign(this.commerce,new j$(this.random,this._locale)),Object.assign(this.book,new z$(this.random,this._locale)),Object.assign(this.animal,new Q$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.hacker,new F$(this.random,this._locale)),Object.assign(this.system,new R$(this.random,this._locale)),Object.assign(this.word,new M$(this.random,this._locale)),Object.assign(this.vehicle,new D$(this.random,this._locale)),this}async setLocale(X){return this._locale=await Y9.load(X),this.reinitializeLocaleModules(),this}setLocaleSync(X){if(!Y9.isCached(X)&&X!=="en")return console.warn(`[ts-mocker] Locale '${X}' is not loaded. Use 'await faker.setLocale("${X}")' or preload it first.`),this;return this._locale=Y9.loadSync(X),this.reinitializeLocaleModules(),this}async preloadLocales(X){return await Y9.preload(X),this}reinitializeLocaleModules(){Object.assign(this.person,new W$(this.random,this._locale)),Object.assign(this.address,new _$(this.random,this._locale)),Object.assign(this.internet,new O$(this.random,this._locale)),Object.assign(this.phone,new V$(this.random,this._locale)),Object.assign(this.company,new E$(this.random,this._locale)),Object.assign(this.food,new G$(this.random,this._locale)),Object.assign(this.animal,new Q$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.music,new J$(this.random,this._locale)),Object.assign(this.commerce,new j$(this.random,this._locale)),Object.assign(this.book,new z$(this.random,this._locale)),Object.assign(this.vehicle,new D$(this.random,this._locale)),Object.assign(this.word,new M$(this.random,this._locale)),Object.assign(this.hacker,new F$(this.random,this._locale)),Object.assign(this.system,new R$(this.random,this._locale)),Object.assign(this.color,new L$(this.random,this._locale)),Object.assign(this.science,new I$(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return Y9.getAvailableLocales()}static isLocaleLoaded(X){return Y9.isCached(X)}static async preloadLocales(X){await Y9.preload(X)}name(){return this.person.name()}email(){return this.internet.email()}}var cU,JL=(X)=>X,WL=(X,$)=>{for(var Z in $)cU(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:mz.bind($,Z)})},H9=(X,$)=>()=>(X&&($=X(X=0)),$),mU,hX,x$,aY,CX,tY,iZ,H$,VL,B0,G0,IL,eY,KL,X6,RL,DL,lZ,ML,$6,Z6,HL,sZ,CL,wL,qL,PL,TL,C8,uU,NL,Y6,SL="0.15.9",AL=()=>{},Z9,w8,C$,oZ,rZ,q8,aZ,tZ,w$,eZ,X1,m9,n9,$1,U6,z8,Z1,nU,Y1,j9,k9,_6,Q6,z6,kL=()=>{},U1,_1,XZ,Q1=null,y1,nX,z9,wX,Y9,iU,lU,sU,oU,rU,aU,tU,eU,X7,$7,Z7,h1,v1,Y7,xL=e(()=>{cU=Object.defineProperty,mU=import.meta.require,CX=H9(()=>{hX=new A1,x$=new k1,aY={createKey:uz,isEquivalent:nz,estimateMemoryUsage:iz}}),Y6=H9(()=>{tY=c8.env.CLARITY_LOG_DIR||Hz(lz(),"logs"),iZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},H$={...iZ},VL=(async()=>{try{let{loadConfig:X}=await Promise.resolve().then(()=>(_1(),U1)),$=await X({name:"clarity",alias:"logging",defaultConfig:iZ,cwd:c8.cwd()});if($)Object.assign(H$,$)}catch{}return H$})(),B0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},G0=B0,IL=B0.red,eY=B0.green,KL=B0.yellow,X6=B0.blue,RL=B0.magenta,DL=B0.cyan,lZ=B0.white,ML=B0.gray,$6=B0.bgRed,Z6=B0.bgYellow,HL=B0.bgGray,sZ=B0.bold,CL=B0.dim,wL=B0.italic,qL=B0.underline,PL=B0.strikethrough,TL=B0.reset,C8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uU={debug:"\uD83D\uDD0D",info:X6("\u2139"),success:eY("\u2713"),warning:Z6(lZ(sZ(" WARN "))),error:$6(lZ(sZ(" ERROR ")))},NL=new m8("stacks")}),n9=H9(()=>{Z9=class extends Error{timestamp;context;constructor(X,$={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Z])=>`${$}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},w8=class extends Z9{code="CONFIG_NOT_FOUND";constructor(X,$,Z){let Y=Z===void 0?[]:Array.isArray(Z)?Z.filter(Boolean):[Z],U="";if(Y.length===1)U=` or alias "${Y[0]}"`;else if(Y.length>1)U=` or aliases ${Y.map((_)=>`"${_}"`).join(", ")}`;super(`Configuration "${X}"${U} not found`,{configName:X,alias:Z,searchPaths:$,searchPathCount:$.length})}},C$=class extends Z9{code="CONFIG_LOAD_ERROR";constructor(X,$,Z){super(`Failed to load configuration from "${X}": ${$.message}`,{configPath:X,configName:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},oZ=class extends Z9{code="CONFIG_VALIDATION_ERROR";constructor(X,$,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},rZ=class extends Z9{code="CONFIG_MERGE_ERROR";constructor(X,$,Z,Y){super(`Failed to merge configuration from "${X}" with "${$}": ${Z.message}`,{sourcePath:X,targetPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},q8=class extends Z9{code="ENV_VAR_ERROR";constructor(X,$,Z,Y){super(`Failed to parse environment variable "${X}" with value "${$}" as ${Z}`,{envKey:X,envValue:$,expectedType:Z,configName:Y})}},aZ=class extends Z9{code="FILE_SYSTEM_ERROR";constructor(X,$,Z){super(`File system ${X} failed for "${$}": ${Z.message}`,{operation:X,path:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},tZ=class extends Z9{code="TYPE_GENERATION_ERROR";constructor(X,$,Z){super(`Failed to generate types from "${X}" to "${$}": ${Z.message}`,{configDir:X,outputPath:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},w$=class extends Z9{code="SCHEMA_VALIDATION_ERROR";constructor(X,$,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},eZ=class extends Z9{code="BROWSER_CONFIG_ERROR";constructor(X,$,Z,Y){super(`Failed to fetch configuration from "${X}": ${$} ${Z}`,{endpoint:X,status:$,statusText:Z,configName:Y})}},X1=class extends Z9{code="PLUGIN_ERROR";constructor(X,$,Z){super(`Plugin "${X}" failed during ${$}: ${Z.message}`,{pluginName:X,operation:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},m9={configNotFound(X,$,Z){return new w8(X,$,Z)},configLoad(X,$,Z){return new C$(X,$,Z)},configValidation(X,$,Z){return new oZ(X,$,Z)},configMerge(X,$,Z,Y){return new rZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new q8(X,$,Z,Y)},fileSystem(X,$,Z){return new aZ(X,$,Z)},typeGeneration(X,$,Z){return new tZ(X,$,Z)},schemaValidation(X,$,Z){return new w$(X,$,Z)},browserConfig(X,$,Z,Y){return new eZ(X,$,Z,Y)},plugin(X,$,Z){return new X1(X,$,Z)}}}),$1=H9(()=>{CX(),n9()}),z8=H9(()=>{U6={replace:"replace",concat:"concat",smart:"smart"}}),Z1=H9(()=>{CX(),n9(),z8()}),Y1=H9(()=>{CX(),n9(),nU=/^https?:\/\//}),z6=H9(()=>{Y6(),AL(),CX(),n9(),$1(),Z1(),Y1(),z8(),j9=new m8("bunfig",{showTags:!0}),k9=new B1,_6=l0(XX.cwd(),"config"),Q6=l0(XX.cwd(),"src/generated")}),U1={},WL(U1,{withErrorRecovery:()=>yU,tryLoadConfig:()=>_L,loadConfigWithResult:()=>YL,loadConfig:()=>L5,isRetryableError:()=>rz,isConfigNotFoundError:()=>oz,isBunfigError:()=>hU,globalPerformanceMonitor:()=>x$,globalCache:()=>hX,getEnvOrDefault:()=>az,generateConfigTypes:()=>QL,defaultGeneratedDir:()=>Q6,defaultConfigDir:()=>_6,deepMergeWithArrayStrategy:()=>Q5,deepMerge:()=>vU,createLibraryConfig:()=>zL,config:()=>UL,bunfigPlugin:()=>LL,applyEnvVarsToConfig:()=>aX,TypeGenerationError:()=>tZ,SchemaValidationError:()=>w$,PluginError:()=>X1,PerformanceMonitor:()=>k1,FileSystemError:()=>aZ,ErrorFactory:()=>m9,EnvVarError:()=>q8,EnvProcessor:()=>zZ,ConfigValidator:()=>z5,ConfigValidationError:()=>oZ,ConfigNotFoundError:()=>w8,ConfigMergeError:()=>rZ,ConfigLoader:()=>B1,ConfigLoadError:()=>C$,ConfigFileLoader:()=>LZ,ConfigCache:()=>A1,CacheUtils:()=>aY,BunfigError:()=>Z9,BrowserConfigError:()=>eZ,ArrayMergeStrategies:()=>U6}),_1=H9(()=>{z6(),n9(),CX(),n9(),kL(),$1(),Z1(),Y1(),z8()}),_1(),XZ={verbose:!1,locale:"en",autoInstallLocales:!1},y1=XZ,nX={title:"English",person:{firstNameMale:["James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Mark","Donald","Steven","Paul","Andrew","Joshua","Kenneth","Kevin","Brian","George","Timothy","Ronald","Edward","Jason","Jeffrey","Ryan","Jacob","Gary","Nicholas","Eric","Jonathan","Stephen","Larry","Justin","Scott","Brandon","Benjamin","Samuel","Raymond","Gregory","Frank","Alexander","Patrick","Jack","Dennis","Jerry","Liam","Noah","Oliver","Elijah","Lucas","Mason","Logan","Ethan","Henry","Jackson","Sebastian","Aiden","Carter","Owen","Wyatt","Luke","Jayden","Dylan","Grayson","Levi","Isaac","Gabriel","Julian","Mateo","Jaxon","Lincoln"],firstNameFemale:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen","Lisa","Nancy","Betty","Margaret","Sandra","Ashley","Kimberly","Emily","Donna","Michelle","Dorothy","Carol","Amanda","Melissa","Deborah","Stephanie","Rebecca","Sharon","Laura","Cynthia","Kathleen","Amy","Angela","Shirley","Anna","Brenda","Pamela","Emma","Nicole","Helen","Olivia","Ava","Isabella","Sophia","Mia","Charlotte","Amelia","Harper","Evelyn","Abigail","Sofia","Ella","Scarlett","Grace","Chloe","Victoria","Aria","Lily","Aubrey","Zoey","Penelope","Lillian","Addison","Layla","Natalie","Camila"],firstNameNeutral:["Taylor","Jordan","Alex","Riley","Casey","Morgan","Avery","Quinn","Blake","Cameron","Sage","River","Phoenix","Rowan","Skyler","Charlie","Finley","Peyton","Reese","Kai"],lastName:["Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Rodriguez","Martinez","Hernandez","Lopez","Gonzalez","Wilson","Anderson","Thomas","Taylor","Moore","Jackson","Martin","Lee","Perez","Thompson","White","Harris","Sanchez","Clark","Ramirez","Lewis","Robinson","Walker","Young","Allen","King","Wright","Scott","Torres","Nguyen","Hill","Flores","Green","Adams","Nelson","Baker","Hall","Rivera","Campbell","Mitchell","Carter","Roberts","Gomez","Phillips","Evans","Turner","Diaz","Parker","Cruz","Edwards","Collins","Reyes","Stewart","Morris","Morales","Murphy","Cook","Rogers","Gutierrez","Ortiz","Morgan","Cooper","Peterson","Bailey","Reed","Kelly","Howard","Ramos","Kim","Cox","Ward","Richardson","Watson","Brooks","Chavez","Wood","James","Bennett","Gray","Mendoza","Ruiz","Hughes","Price","Alvarez","Castillo","Sanders","Patel","Myers","Long","Ross","Foster","Jimenez"],prefix:["Mr.","Mrs.","Ms.","Miss","Dr.","Prof."],suffix:["Jr.","Sr.","I","II","III","IV","V","MD","PhD","DDS"],gender:["Male","Female","Non-binary","Agender","Bigender","Genderfluid","Genderqueer"],jobTitle:["Software Engineer","Product Manager","Designer","Data Scientist","DevOps Engineer","Marketing Manager","Sales Representative","Accountant","Human Resources Manager","CEO","CTO","CFO","COO","Director","Manager","Analyst","Consultant","Administrator","Coordinator","Specialist","Developer","Architect","Engineer","Technician","Assistant","Project Manager","Business Analyst","Quality Assurance Engineer","UX Designer","UI Designer","Backend Developer","Frontend Developer","Full Stack Developer","Mobile Developer","Cloud Architect","Security Engineer","Network Engineer","Database Administrator","Systems Administrator","Technical Writer","Scrum Master","Product Owner","Release Manager","Content Manager","Social Media Manager","SEO Specialist","Digital Marketing Specialist","Growth Hacker","Brand Manager","Creative Director","Financial Analyst","Investment Banker","Risk Analyst","Compliance Officer","Tax Consultant","Legal Counsel","Paralegal","Executive Assistant","Operations Manager","Supply Chain Manager","Logistics Coordinator","Customer Success Manager","Account Executive","Sales Engineer","Technical Support"]},address:{street:["Main","Oak","Maple","Cedar","Elm","Washington","Lake","Hill","Park","River","Sunset","Pine","Walnut","Highland","Madison","Lincoln","Jackson","Franklin"],city:["New York","Los Angeles","Chicago","Playa Vista","Houston","Phoenix","Philadelphia","San Antonio","San Diego","Dallas","San Jose","Austin","Jacksonville","Fort Worth","Columbus","Charlotte","San Francisco","Indianapolis","Seattle","Denver","Boston","Nashville","Detroit","Memphis","Portland","Oklahoma City","Las Vegas","Louisville","Baltimore","Milwaukee","Albuquerque","Tucson","Fresno","Sacramento","Mesa","Kansas City","Atlanta","Long Beach","Colorado Springs","Raleigh","Miami","Virginia Beach","Omaha","Oakland","Minneapolis","Tulsa","Arlington","Tampa","New Orleans","Wichita","Cleveland","Bakersfield","Aurora","Anaheim","Honolulu","Santa Ana","Riverside","Corpus Christi","Lexington","Stockton","Henderson","Saint Paul","Cincinnati","Pittsburgh","Greensboro","Anchorage","Plano","Lincoln","Orlando","Irvine","Newark","Durham","Chula Vista","Toledo","Fort Wayne","St. Petersburg","Laredo","Jersey City"],state:["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],stateAbbr:["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],country:["United States","Canada","United Kingdom","Australia","Germany","France","Spain","Italy","Japan","China","India","Brazil","Mexico","Russia","South Korea"],countryCode:["US","CA","GB","AU","DE","FR","ES","IT","JP","CN","IN","BR","MX","RU","KR"],zipCode:["#####","#####-####"],buildingNumber:["###","####","#","##"],direction:["North","East","South","West","Northeast","Northwest","Southeast","Southwest"],streetSuffix:["Street","Avenue","Road","Boulevard","Drive","Court","Circle","Lane","Way","Place","Terrace","Parkway","Commons","Trail","Square","Run","Crossing"]},company:{name:["TechCorp","GlobalSoft","DataSystems","CloudNet","Innovate Inc","Digital Solutions","NextGen Tech","FutureTech","SmartSystems","CoreTech","PrimeSoft","AlphaTech"],suffix:["Inc","LLC","Corp","Group","Ltd","Co","Technologies","Solutions","Systems"],industry:["Technology","Finance","Healthcare","Education","Retail","Manufacturing","Telecommunications","Energy","Real Estate","Transportation","Media","Hospitality"],buzzwords:["synergize","leverage","innovate","disrupt","optimize","streamline","transform","revolutionize","empower","enable","facilitate","orchestrate","integrate"],adjective:["revolutionary","cutting-edge","innovative","next-generation","advanced","leading","premier","world-class","enterprise","scalable","robust","seamless"],descriptor:["global","digital","cloud-based","AI-powered","data-driven","user-centric","agile","secure","efficient","intelligent","automated","integrated"],noun:["solution","platform","system","service","technology","framework","infrastructure","application","network","portal","ecosystem","architecture","engine"]},internet:{domainSuffix:["com","net","org","io","co","app","dev","tech","ai","cloud"],freeEmail:["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","proton.me"]},phone:{formats:["###-###-####","(###) ###-####","1-###-###-####","+1-###-###-####","###.###.####"]},food:{dish:["Hamburger","Cheeseburger","Pizza","Hot Dog","Fried Chicken","BBQ Ribs","Mac and Cheese","Grilled Cheese","BLT Sandwich","Caesar Salad","Cobb Salad","Chicken Wings","Nachos","Tacos","Burrito","Quesadilla","Fish and Chips","Clam Chowder","Lobster Roll","Cheesesteak","Pulled Pork Sandwich","Buffalo Wings","Meatloaf","Pot Roast","Fried Catfish","Jambalaya","Gumbo","Po' Boy","Corn Dog","Chili","Baked Beans","Cornbread","Biscuits and Gravy"],ingredient:["Flour","Sugar","Salt","Pepper","Butter","Eggs","Milk","Cheese","Tomato","Onion","Garlic","Olive Oil","Chicken","Beef","Pork","Fish","Rice","Pasta","Bread","Potato","Carrot","Celery","Bell Pepper","Mushroom","Spinach","Broccoli","Lettuce","Avocado","Lemon","Lime","Basil","Oregano","Thyme","Rosemary","Parsley","Cilantro"],cuisine:["American","Italian","Mexican","Chinese","Japanese","Thai","Indian","French","Greek","Spanish","Mediterranean","Vietnamese","Korean","Turkish","Lebanese","Brazilian","Argentinian","Peruvian","Caribbean","Moroccan","Ethiopian"],dessert:["Apple Pie","Chocolate Cake","Ice Cream","Brownies","Cookies","Cheesecake","Donuts","Cupcakes","Tiramisu","Panna Cotta","Cr\xE8me Br\xFBl\xE9e","Macarons","Churros","Flan","Bread Pudding","Pecan Pie","Key Lime Pie","Banana Split","Sundae","Milkshake"],fruit:["Apple","Banana","Orange","Strawberry","Grape","Watermelon","Pineapple","Mango","Peach","Pear","Cherry","Blueberry","Raspberry","Blackberry","Kiwi","Plum","Apricot","Cantaloupe","Honeydew","Papaya","Guava","Lychee","Dragon Fruit"],vegetable:["Carrot","Broccoli","Cauliflower","Spinach","Kale","Lettuce","Cabbage","Cucumber","Tomato","Bell Pepper","Zucchini","Eggplant","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Onion","Garlic","Celery","Radish","Beet"],meat:["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Bacon","Sausage","Ham","Salami","Prosciutto","Ribeye","Sirloin","Tenderloin"],spice:["Black Pepper","Cumin","Paprika","Cinnamon","Nutmeg","Ginger","Turmeric","Curry","Chili Powder","Cayenne","Oregano","Basil","Thyme","Rosemary","Sage","Coriander","Cardamom","Cloves","Allspice","Bay Leaf","Mustard Seed","Fennel","Star Anise"]},animal:{dog:["Labrador Retriever","German Shepherd","Golden Retriever","French Bulldog","Bulldog","Poodle","Beagle","Rottweiler","German Shorthaired Pointer","Dachshund","Pembroke Welsh Corgi","Australian Shepherd","Yorkshire Terrier","Cavalier King Charles Spaniel","Doberman Pinscher","Boxer","Miniature Schnauzer","Great Dane","Siberian Husky","Bernese Mountain Dog","Pomeranian","Boston Terrier","Havanese","Shetland Sheepdog","Brittany","Cocker Spaniel"],cat:["Persian","Maine Coon","Ragdoll","Bengal","Siamese","British Shorthair","Abyssinian","Birman","Oriental Shorthair","Sphynx","Devon Rex","American Shorthair","Scottish Fold","Exotic Shorthair","Russian Blue","Norwegian Forest Cat","Siberian","Burmese","Manx","Cornish Rex","Himalayan","Turkish Angora","Balinese","Tonkinese"],bird:["Parakeet","Cockatiel","Lovebird","Canary","Finch","Parrot","Macaw","Cockatoo","African Grey","Conure","Budgie","Dove","Pigeon","Robin","Cardinal","Blue Jay","Sparrow","Crow","Raven","Hawk","Eagle","Owl","Hummingbird","Woodpecker"],fish:["Goldfish","Betta","Guppy","Molly","Platy","Swordtail","Tetra","Angelfish","Discus","Gourami","Barb","Danio","Koi","Oscar","Cichlid","Clownfish","Tang","Damselfish","Wrasse","Goby","Blenny","Pufferfish","Lionfish"],horse:["Arabian","Thoroughbred","Quarter Horse","Appaloosa","Paint","Tennessee Walker","Morgan","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Mustang","Shetland Pony","Welsh Pony","Palomino","Buckskin","Pinto","Warmblood"],rabbit:["Holland Lop","Netherland Dwarf","Mini Rex","Flemish Giant","English Lop","French Lop","Angora","Dutch","Lionhead","Rex","Polish","Himalayan"],insect:["Butterfly","Bee","Ant","Beetle","Ladybug","Dragonfly","Grasshopper","Cricket","Moth","Firefly","Praying Mantis","Walking Stick","Caterpillar","Wasp"],type:["Dog","Cat","Bird","Fish","Rabbit","Hamster","Guinea Pig","Mouse","Rat","Ferret","Chinchilla","Hedgehog","Turtle","Lizard","Snake","Frog"]},sport:{sport:["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding"],team:["Lakers","Warriors","Bulls","Celtics","Yankees","Red Sox","Cowboys","Patriots","49ers","Packers","Steelers","Maple Leafs","Bruins","Canadiens","Blackhawks"],athlete:["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Usain Bolt","Michael Phelps"]},music:{genre:["Rock","Pop","Hip Hop","Jazz","Blues","Country","Electronic","Classical","R&B","Soul","Funk","Reggae","Metal","Punk","Indie","Alternative","Folk","Disco","House","Techno","Dubstep","Trap","Gospel","Opera"],artist:["The Beatles","Elvis Presley","Michael Jackson","Madonna","Prince","Bob Dylan","Led Zeppelin","Pink Floyd","Queen","David Bowie","The Rolling Stones","Nirvana","Bruce Springsteen","Stevie Wonder","Aretha Franklin","Ray Charles","Johnny Cash"],song:["Bohemian Rhapsody","Imagine","Hey Jude","Billie Jean","Like a Rolling Stone","Smells Like Teen Spirit","Hotel California","Sweet Child O' Mine","Stairway to Heaven","Purple Haze","What's Going On","Respect","I Want to Hold Your Hand"],instrument:["Guitar","Piano","Drums","Bass","Violin","Cello","Saxophone","Trumpet","Flute","Clarinet","Trombone","Harp","Banjo","Mandolin","Ukulele","Harmonica","Accordion","Xylophone","Synthesizer","Keyboard"]},commerce:{product:["Chair","Table","Lamp","Sofa","Bed","Desk","Computer","Phone","Tablet","Watch","Shoes","Shirt","Pants","Jacket","Hat","Gloves","Bag","Wallet","Sunglasses","Bicycle","Car","Motorcycle","Camera","Headphones","Speaker"],productAdjective:["Small","Medium","Large","Ergonomic","Rustic","Modern","Sleek","Lightweight","Durable","Handmade","Recycled","Refined","Gorgeous","Incredible","Practical","Fantastic","Awesome","Generic","Unbranded","Licensed","Intelligent","Tasty"],productMaterial:["Steel","Wood","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Aluminum","Leather","Silk","Wool","Linen"],department:["Electronics","Clothing","Home & Garden","Sports","Automotive","Books","Toys","Health & Beauty","Grocery","Jewelry","Tools","Music","Movies","Baby","Pet Supplies"],color:["Red","Blue","Green","Yellow","Black","White","Gray","Silver","Gold","Purple","Pink","Orange","Brown","Navy","Teal","Maroon","Olive"]},book:{title:["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","Brave New World","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude"],author:["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee"],publisher:["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Bloomsbury","Vintage"],genre:["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Self-Help","Poetry","Drama","Adventure","Young Adult"],series:["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","Discworld","Dune","Foundation"],review:["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","One of the best books I've ever read."]},vehicle:{manufacturer:["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Tesla","Volvo","Porsche","Jeep","Mazda","Subaru"],model:["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Model 3","Model Y","3 Series","C-Class","A4","Golf","Mustang","Wrangler"],type:["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Electric","Hybrid"],fuel:["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel"],bicycle:["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Gravel Bike"]},word:{adjective:["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold"],adverb:["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well"],conjunction:["and","but","or","nor","for","yet","so","although","because","since","unless","while","when","if"],interjection:["wow","oh","ah","hey","oops","ouch","yay","hooray","hello","goodbye","yes","no"],noun:["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","fire","sun","moon"],preposition:["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through"],verb:["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","think","know","make","take","give"]},hacker:{abbreviation:["TCP","HTTP","RAM","GB","CSS","SSL","SQL","CLI","UI","UX","FTP","API","DNS","IP","LAN","WAN","VPN","SSH","JSON","REST"],adjective:["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","wireless","mobile","neural","optical","cloud","quantum"],noun:["driver","protocol","bandwidth","panel","microchip","program","port","card","interface","system","sensor","firewall","pixel","application","server","database","network"],verb:["bypass","hack","override","compress","copy","navigate","index","connect","generate","calculate","synthesize","transmit","program","parse","compile","encrypt","decrypt"],ingverb:["bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","calculating","synthesizing","transmitting","programming","parsing","compiling","encrypting"],phrase:["We need to bypass the digital firewall!","Try to hack the TCP protocol!","The SSL port is down, override the wireless system!","You can't compress the bandwidth without indexing the neural network!"]},system:{fileName:["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache"],fileType:["audio","image","text","video","application","document","spreadsheet","presentation","archive","code"]},science:{chemicalElement:["Hydrogen","Helium","Lithium","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Iron","Copper","Zinc","Silver","Gold"],unit:["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","volt","ohm","hertz","celsius"],constant:["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Gas Constant"],field:["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Biochemistry","Microbiology","Botany","Zoology"]}},z9=new Map,wX=new Map,Y9=class{static AVAILABLE_BASE_LOCALES=["af","ar","az","cs","da","de","en","eo","es","fa","fi","fr","he","hi","it","ja","ko","nl","no","pl","pt","sv","tl","tr","uk","zh","zu"];static AVAILABLE_LOCALE_VARIANTS=["af_ZA","de_AT","de_CH","de_DE","en_AU","en_CA","en_GB","en_GH","en_HK","en_IE","en_IN","en_NG","en_US","en_ZA","es_ES","es_MX","fr_BE","fr_CA","fr_CH","fr_FR","fr_LU","fr_SN","pt_BR","pt_MZ","pt_PT","zh_CN","zh_TW","zu_ZA"];static getAvailableLocales(){return[...this.AVAILABLE_BASE_LOCALES,...this.AVAILABLE_LOCALE_VARIANTS]}static getAvailableBaseLocales(){return this.AVAILABLE_BASE_LOCALES}static getAvailableLocaleVariants(){return this.AVAILABLE_LOCALE_VARIANTS}static async load($){let Z=SX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",nX);return nX}if(z9.has(Z))return z9.get(Z);if(wX.has(Z))return wX.get(Z);let Y=this.loadLocaleWithFallback(Z);wX.set(Z,Y);try{let U=await Y;return z9.set(Z,U),U}finally{wX.delete(Z)}}static loadSync($){let Z=SX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",nX);return nX}if(z9.has(Z))return z9.get(Z);throw Error(`Locale '${$}' is not loaded. Please use async loading with faker.setLocale('${$}') or preload it.`)}static isCached($){let Z=SX($).normalized;return z9.has(Z)}static async preload($){await Promise.all($.map((Z)=>this.load(Z)))}static clearCache(){z9.clear(),wX.clear()}static async loadLocaleWithFallback($){let Z=EL($);for(let Y=0;Y<Z.length;Y++){let U=Z[Y],_=Y===0&&Z.length>1,Q=!_;try{if(_){let L=await this.loadLocaleModule(U),z=Z[1];try{let j=await this.loadLocaleModule(z);return gU(j,L)}catch{return L}}else return await this.loadLocaleModule(U)}catch(L){if(Y===Z.length-1)throw L;continue}}throw Error(`Failed to load locale '${$}' with fallback chain: ${Z.join(" \u2192 ")}`)}static async tryWorkspaceImport($,Z){if(!AX())return null;try{let Y=await import(`../../${Z.packageName}/dist/index.js`);return Y[Z.normalized]||Y[Z.language]||Y.default}catch{try{let Y=Mz.cwd(),U=Dz(Y,"packages",Z.packageName,"dist","index.js");if(!Rz(U))return null;let _=await import(`file://${U}`);return _[Z.normalized]||_[Z.language]||_.default}catch{return null}}}static async loadLocaleModule($){let Z=GL($),Y=SX($);try{let U=await import(Z);return U[Y.normalized]||U[Y.language]||U.default}catch(U){let _=U instanceof Error?U.message:String(U);if(_.includes("Cannot find")||_.includes("not found")||_.includes("ModuleNotFound")){if(AX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}if(y1.autoInstallLocales)if(console.log(`
|
|
459
|
-
\uD83D\uDD0D Locale '${$}' not found. Auto-installing ${Z}...`),
|
|
458
|
+
`)}}class J${random;locale;constructor(X,$){this.random=X,this.locale=$}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let X=["Rock","Pop","Jazz","Blues","Classical","Hip Hop","R&B","Country","Electronic","Dance","Metal","Punk","Reggae","Soul","Funk","Disco","House","Techno","Dubstep","Indie","Alternative","Folk","Gospel","Latin","K-Pop","EDM","Trap","Lo-Fi","Ambient","Ska"];return this.random.arrayElement(X)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let X=["Dancing in the Moonlight","Bohemian Rhapsody","Stairway to Heaven","Hotel California","Imagine","Yesterday","Hey Jude","Sweet Child O' Mine","Smells Like Teen Spirit","Billie Jean","Thriller","Purple Rain","Born to Run","Like a Rolling Stone","What's Going On","Respect","Good Vibrations","Johnny B. Goode","I Want to Hold Your Hand","Satisfaction","My Generation","Brown Sugar","Layla","Crossroads","The End","Light My Fire","All Along the Watchtower","While My Guitar Gently Weeps","A Day in the Life"];return this.random.arrayElement(X)}albumName(){let X=["Abbey Road","The Dark Side of the Moon","Thriller","Back in Black","The Wall","Rumours","Nevermind","Led Zeppelin IV","Born in the U.S.A.","Sgt. Pepper's Lonely Hearts Club Band","OK Computer","The Beatles (White Album)","Purple Rain","Hotel California","21","Appetite for Destruction","Lemonade","To Pimp a Butterfly","Random Access Memories"];return this.random.arrayElement(X)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let X=["The Beatles","Led Zeppelin","Pink Floyd","Queen","The Rolling Stones","Elvis Presley","Michael Jackson","Madonna","David Bowie","Nirvana","Radiohead","U2","AC/DC","Metallica","Bob Dylan","Jimi Hendrix","Prince","Stevie Wonder","Aretha Franklin","The Who","The Doors","Fleetwood Mac","Eagles","Guns N' Roses","Red Hot Chili Peppers","Coldplay","Beyonc\xE9","Taylor Swift","Drake","Kendrick Lamar","Adele","Ed Sheeran"];return this.random.arrayElement(X)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let X=["Guitar","Piano","Drums","Bass","Violin","Saxophone","Trumpet","Flute","Clarinet","Cello","Harp","Keyboard","Harmonica","Accordion","Ukulele","Banjo","Mandolin","Trombone","French Horn","Tuba","Oboe","Bassoon","Xylophone","Marimba","Tambourine","Synthesizer","Didgeridoo","Sitar","Tabla","Djembe"];return this.random.arrayElement(X)}note(){let X=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement(X)}chord(){let X=this.note(),$=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${X}${$}`}tempo(){return this.random.int(60,200)}key(){let X=this.note(),$=this.random.arrayElement(["Major","Minor"]);return`${X} ${$}`}timeSignature(){let X=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement(X)}}class a8{random;constructor(X){this.random=X}int(X){let $=X?.min??0,Z=X?.max??100;return this.random.int($,Z)}float(X){let $=X?.min??0,Z=X?.max??1,Y=X?.precision??2;return this.random.float($,Z,Y)}bigInt(X){let $=X?.min??0n,Z=(X?.max??1000000n)-$+1n,Y=BigInt(Math.floor(this.random.number()*Number(Z)));return $+Y}binary(X){let $=X?.length??8,Z="";for(let Y=0;Y<$;Y++)Z+=this.random.int(0,1);return Z}octal(X){let $=X?.length??3,Z="";for(let Y=0;Y<$;Y++)Z+=this.random.int(0,7);return Z}hex(X){let $=X?.length??6,Z="0123456789ABCDEF",Y="";for(let U=0;U<$;U++)Y+="0123456789ABCDEF"[this.random.int(0,15)];return Y}randomNumber(X){return this.int(X)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class W${random;locale;constructor(X,$){this.random=X,this.locale=$}firstName(X){if(X?.gender==="male")return this.firstNameMale();if(X?.gender==="female")return this.firstNameFemale();if(X?.gender==="neutral")return this.firstNameNeutral();let $=this.locale.person.firstNameMale.length,Z=this.locale.person.firstNameFemale.length,Y=this.locale.person.firstNameNeutral?.length||0,U=$+Z+Y,_=this.random.int(0,U-1);if(_<$)return this.locale.person.firstNameMale[_];if(_<$+Z)return this.locale.person.firstNameFemale[_-$];return this.locale.person.firstNameNeutral[_-$-Z]}firstNameMale(){return this.random.arrayElement(this.locale.person.firstNameMale)}firstNameFemale(){return this.random.arrayElement(this.locale.person.firstNameFemale)}firstNameNeutral(){if(!this.locale.person.firstNameNeutral||this.locale.person.firstNameNeutral.length===0){let X=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement(X)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName(X){if(!X)return`${this.firstName()} ${this.lastName()}`;let $=this.firstName({gender:X.gender}),Z=this.lastName();if(X.prefix&&X.suffix)return`${this.prefix()} ${$} ${Z} ${this.suffix()}`;if(X.prefix)return`${this.prefix()} ${$} ${Z}`;if(X.suffix)return`${$} ${Z} ${this.suffix()}`;return`${$} ${Z}`}prefix(){return this.random.arrayElement(this.locale.person.prefix)}suffix(){return this.random.arrayElement(this.locale.person.suffix)}gender(){return this.random.arrayElement(this.locale.person.gender)}jobTitle(){return this.random.arrayElement(this.locale.person.jobTitle)}name(){return this.fullName()}firstNameAdvanced(X){let $;if(X?.constraints)$=this.firstName({gender:X.constraints.gender});else $=this.firstName({gender:X?.gender});if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=p9({firstName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).firstName||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.firstName({gender:X?.gender||X?.constraints?.gender})}}return $}fullNameAdvanced(X){let $;if(X?.constraints)$=this.fullName({gender:X.constraints.gender,prefix:X.prefix,suffix:X.suffix});else $=this.fullName(X);if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=p9({fullName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).fullName||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.fullName({gender:X?.gender||X?.constraints?.gender,prefix:X?.prefix,suffix:X?.suffix})}}return $}profile(X){let $=X?.constraints?.gender||X?.gender||this.gender(),Z=this.firstNameAdvanced({...X,gender:$}),Y=this.lastName(),U=`${Z} ${Y}`,_={firstName:Z,lastName:Y,fullName:U,gender:$,jobTitle:this.jobTitle(),age:X?.constraints?.ageRange?this.random.int(X.constraints.ageRange.min,X.constraints.ageRange.max):this.random.int(18,80)};if(X?.relationships)return p9(_,X.relationships);return _}family(X){let $=X?.size||this.random.int(2,6),Z=this.lastName(),Y=["parent","parent","child","child","child","grandparent"],U=[];for(let _=0;_<$;_++){let Q=Y[_]||"relative",L=Q==="parent"||Q==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",z=this.firstNameAdvanced({...X,gender:L,constraints:{...X?.constraints,gender:L}});U.push({firstName:z,lastName:Z,fullName:`${z} ${Z}`,gender:L,relationship:Q})}return{members:U,lastName:Z}}}class V${random;locale;constructor(X,$){this.random=X,this.locale=$}number(X){let $=X??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols($)}phoneNumber(X){return this.number(X)}}class I${random;locale;constructor(X,$){this.random=X,this.locale=$}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let X=["Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Argon","Potassium","Calcium","Iron","Copper","Zinc","Silver","Gold","Mercury","Lead","Uranium","Platinum","Titanium"];return this.random.arrayElement(X)}chemicalElementSymbol(){let X=["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Fe","Cu","Zn","Ag","Au","Hg","Pb","U","Pt","Ti"];return this.random.arrayElement(X)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let X=["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","coulomb","volt","ohm","farad","weber","tesla","henry","celsius","lumen","lux","becquerel","gray","sievert","katal","hertz","radian","steradian"];return this.random.arrayElement(X)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let X=["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Magnetic Constant","Electric Constant","Fine Structure Constant","Rydberg Constant","Gas Constant","Stefan-Boltzmann Constant"];return this.random.arrayElement(X)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let X=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement(X)}dnaSequence(X=12){let $=["A","T","C","G"],Z="";for(let Y=0;Y<X;Y++)Z+=this.random.arrayElement($);return Z}rnaSequence(X=12){let $=["A","U","C","G"],Z="";for(let Y=0;Y<X;Y++)Z+=this.random.arrayElement($);return Z}hypothesis(){let X=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],$=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement(X)}, then ${this.random.arrayElement($)}`}}class K${random;locale;constructor(X,$){this.random=X,this.locale=$}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let X=["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding","Cycling","Running","Marathon","Triathlon","Gymnastics","Fencing","Archery","Martial Arts","Karate","Judo","Taekwondo","MMA","Formula 1","NASCAR","Sailing"];return this.random.arrayElement(X)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let X=["Lakers","Warriors","Bulls","Celtics","Knicks","Heat","Spurs","Mavericks","Yankees","Red Sox","Dodgers","Cubs","Giants","Astros","Braves","Phillies","Patriots","49ers","Cowboys","Packers","Steelers","Eagles","Seahawks","Chiefs","Manchester United","Real Madrid","Barcelona","Liverpool","Bayern Munich","PSG","Maple Leafs","Bruins","Canadiens","Blackhawks","Penguins","Lightning"];return this.random.arrayElement(X)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let X=["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Pel\xE9","Cristiano Ronaldo","Lionel Messi","Roger Federer","Usain Bolt","Simone Biles","Michael Phelps","Kobe Bryant","Derek Jeter","Joe Montana","Magic Johnson","Larry Bird"];return this.random.arrayElement(X)}position(){let X=["Quarterback","Running Back","Wide Receiver","Linebacker","Defensive Back","Point Guard","Shooting Guard","Small Forward","Power Forward","Center","Pitcher","Catcher","First Base","Shortstop","Outfielder","Forward","Midfielder","Defender","Goalkeeper","Striker","Winger"];return this.random.arrayElement(X)}event(){let X=["Super Bowl","World Series","NBA Finals","Stanley Cup","FIFA World Cup","Olympics","Wimbledon","Masters Tournament","Kentucky Derby","Indianapolis 500","Tour de France","Boston Marathon","UEFA Champions League","World Cup","The Open Championship","US Open","French Open","Australian Open"];return this.random.arrayElement(X)}league(){let X=["NFL","NBA","MLB","NHL","MLS","Premier League","La Liga","Serie A","Bundesliga","Ligue 1","UEFA","FIFA","NCAA","PGA","ATP","WTA","F1","NASCAR","IndyCar"];return this.random.arrayElement(X)}quote(){let X=["Just do it!","Winners never quit and quitters never win.","Hard work beats talent when talent doesn't work hard.","The only way to prove you're a good sport is to lose.","Champions keep playing until they get it right.","It's not whether you get knocked down, it's whether you get up.","You miss 100% of the shots you don't take.","The difference between the impossible and the possible lies in determination."];return this.random.arrayElement(X)}equipment(){let X=["Ball","Bat","Glove","Helmet","Racket","Puck","Skates","Cleats","Pads","Jersey","Goggles","Swimsuit","Bicycle","Surfboard","Skateboard","Snowboard","Skis","Golf Clubs","Tennis Racket","Boxing Gloves","Mouthguard"];return this.random.arrayElement(X)}}class t8{random;constructor(X){this.random=X}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let X="0123456789abcdef",$="";for(let Z=0;Z<36;Z++)if(Z===8||Z===13||Z===18||Z===23)$+="-";else if(Z===14)$+="4";else if(Z===19){let Y=this.random.int(0,15);$+=X[Y&3|8]}else $+=X[this.random.int(0,15)];return $}nanoid(X=21){let $="";for(let Z=0;Z<X;Z++)$+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return $}alpha(X){let $=X?.length??10,Z=X?.casing??"mixed",Y="abcdefghijklmnopqrstuvwxyz",U="ABCDEFGHIJKLMNOPQRSTUVWXYZ",_="";if(Z==="lower")_="abcdefghijklmnopqrstuvwxyz";else if(Z==="upper")_="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else _="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let Q="";for(let L=0;L<$;L++)Q+=_[this.random.int(0,_.length-1)];return Q}alphanumeric(X){let $=X?.length??10,Z=X?.casing??"mixed",Y="abcdefghijklmnopqrstuvwxyz",U="ABCDEFGHIJKLMNOPQRSTUVWXYZ",_="0123456789",Q="0123456789";if(Z==="lower")Q+="abcdefghijklmnopqrstuvwxyz";else if(Z==="upper")Q+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else Q+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let L="";for(let z=0;z<$;z++)L+=Q[this.random.int(0,Q.length-1)];return L}numeric(X=10){if(!this.random.isSeeded()){let Z="";for(let Y=0;Y<X;Y++)Z+=Math.floor(Math.random()*10);return Z}let $="";for(let Z=0;Z<X;Z++)$+=this.random.int(0,9);return $}sample(X=10){return this.alphanumeric({length:X})}symbol(X=5){let $="";for(let Z=0;Z<X;Z++)$+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return $}hexadecimal(X){let $=X?.length??6,Z=X?.prefix??"",Y="0123456789abcdef",U=Z;for(let _=0;_<$;_++)U+="0123456789abcdef"[this.random.int(0,15)];return U}}class R${random;locale;constructor(X,$){this.random=X,this.locale=$}fileName(X){let $;if(this.locale?.system?.fileName)$=this.locale.system.fileName;else $=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let Z=this.random.arrayElement($),Y=X?.extension??this.fileExtension();return`${Z}.${Y}`}fileExtension(){let X=["pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","json","xml","jpg","jpeg","png","gif","bmp","svg","webp","ico","mp3","wav","ogg","flac","aac","m4a","mp4","avi","mov","wmv","flv","webm","mkv","zip","rar","tar","gz","7z","bz2","html","css","js","ts","jsx","tsx","vue","py","java","cpp","c","go","rs"];return this.random.arrayElement(X)}commonFileName(){let X=["README.md","package.json","tsconfig.json",".gitignore",".env","docker-compose.yml","Dockerfile","index.html","index.js","app.js","main.py","requirements.txt","Makefile","LICENSE","CHANGELOG.md","yarn.lock","package-lock.json","pom.xml"];return this.random.arrayElement(X)}mimeType(){let X=["application/json","application/xml","application/pdf","application/zip","text/html","text/css","text/javascript","text/plain","text/csv","image/jpeg","image/png","image/gif","image/svg+xml","image/webp","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg","video/avi","application/octet-stream","multipart/form-data","application/x-www-form-urlencoded"];return this.random.arrayElement(X)}commonMimeType(){let X=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement(X)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let X=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement(X)}directoryPath(){let X=["/usr/local/bin","/usr/bin","/etc","/var/log","/tmp","/home","/root","/opt","/srv","/mnt","/media","/dev","/proc","/sys","C:\\Program Files","C:\\Users","C:\\Windows","C:\\Temp","/Applications","/Library","/System","/Users","/Documents","/Downloads"];return this.random.arrayElement(X)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let X=this.random.int(0,10),$=this.random.int(0,20),Z=this.random.int(0,50);return`${X}.${$}.${Z}`}networkInterface(){let X=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement(X)}cron(){let X=this.random.boolean(0.5)?"*":this.random.int(0,59),$=this.random.boolean(0.5)?"*":this.random.int(0,23),Z=this.random.boolean(0.5)?"*":this.random.int(1,31),Y=this.random.boolean(0.5)?"*":this.random.int(1,12),U=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${X} ${$} ${Z} ${Y} ${U}`}}class D${random;locale;constructor(X,$){this.random=X,this.locale=$}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(eU)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(X7)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement($7)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(Z7)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(Y7)}vin(){let X="";for(let $=0;$<17;$++)X+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return X}registration(){let X=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement(X).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let X=this.random.int(2000,2024),$=this.manufacturer(),Z=this.model();return`${X} ${$} ${Z}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let X=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement(X)}}class M${random;locale;constructor(X,$){this.random=X,this.locale=$}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let X=["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold","warm","cool","bright","dark","loud","quiet","strong","weak","clean","dirty","new","old","young","fresh","dry","wet","smooth","rough","sharp","dull","simple","complex","easy","difficult","good","bad","right","wrong","true","false"];return this.random.arrayElement(X)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let X=["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well","almost","always","never","often","rarely","sometimes","usually","frequently","occasionally","immediately","instantly","eventually","probably","possibly"];return this.random.arrayElement(X)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let X=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement(X)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let X=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement(X)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let X=["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","air","fire","earth","mountain","river","ocean","sky","sun","moon","star","cloud","rain","snow","person","man","woman","child","friend","family","food","music","art","book","school","work","time","day","night","morning","evening","world","life","love"];return this.random.arrayElement(X)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let X=["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through","during","before","after","against","among","into","onto","upon","within","without","toward","near","beside","behind"];return this.random.arrayElement(X)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let X=["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","look","see","hear","think","know","want","like","love","hate","need","make","take","give","get","put","come","go","say","tell","ask","answer","help","start","stop","begin","end","open","close","show","hide","find","lose","buy","sell","learn"];return this.random.arrayElement(X)}sample(){let X=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],$=this.random.arrayElement(X);return this[$]()}words(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.sample());return $.join(" ")}}class e8{seed;constructor(X){this.seed=X}isSeeded(){return this.seed!==void 0}number(){if(this.seed!==void 0)return this.seed=(this.seed*9301+49297)%233280,this.seed/233280;return Math.random()}int(X=0,$=100){return Math.floor(this.number()*($-X+1))+X}float(X=0,$=1,Z=2){let Y=this.number()*($-X)+X;return Number.parseFloat(Y.toFixed(Z))}arrayElement(X){if(X.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return X[Math.floor(Math.random()*X.length)];return X[this.int(0,X.length-1)]}arrayElements(X,$){if(X.length===0)return[];let Z=$??this.int(1,X.length);return[...X].sort(()=>this.number()-0.5).slice(0,Math.min(Z,X.length))}shuffle(X){let $=[...X];for(let Z=$.length-1;Z>0;Z--){let Y=this.int(0,Z);[$[Z],$[Y]]=[$[Y],$[Z]]}return $}boolean(X=0.5){return this.number()<X}replaceSymbols(X){if(this.seed===void 0){let $="";for(let Z=0;Z<X.length;Z++){let Y=X[Z];if(Y==="#")$+="0123456789"[Math.floor(Math.random()*10)];else if(Y==="?")$+=h1[Math.floor(Math.random()*26)];else $+=Y}return $}return X.replace(/[#?]/g,($)=>{if($==="#")return String(this.int(0,9));return this.arrayElement(h1)})}replaceCreditCardSymbols(X="####-####-####-####",$="#"){return X.replace(new RegExp($,"g"),()=>String(this.int(0,9)))}weightedArrayElement(X){if(X.length===0)throw Error("Cannot pick from empty weighted items array");let $=X.reduce((U,_)=>U+_.weight,0);if($<=0)throw Error("Total weight must be greater than 0");let Z=this.number()*$,Y=0;for(let U of X)if(Y+=U.weight,Z<=Y)return U.item;return X[X.length-1].item}weightedArrayElements(X,$,Z=!1){if(X.length===0)return[];let Y=$??this.int(1,X.length),U=[],_=[...X];for(let Q=0;Q<Y&&_.length>0;Q++){let L=this.weightedArrayElement(_);if(U.push(L),!Z){let z=_.findIndex((j)=>j.item===L);if(z!==-1)_.splice(z,1)}}return U}weightedBoolean(X=0.5){return this.number()<X}weightedInt(X,$,Z){let Y=$-X+1;if(Z){if(Z.length!==Y)throw Error("Weights array length must match the range size");let U=Z.map((_,Q)=>({item:X+Q,weight:_}));return this.weightedArrayElement(U)}return this.int(X,$)}}class jZ{random;_locale;_autoInstallLocales;person;address;internet;phone;company;lorem;date;number;string;color;finance;helpers;vehicle;image;git;science;music;database;food;commerce;book;animal;sport;hacker;system;word;constructor(X){let $=X?.locale??"en",Z=X?.seed;if(this._autoInstallLocales=X?.autoInstallLocales??!1,$!=="en"&&!Y9.isCached($))console.warn(`[ts-mocker] Locale '${$}' requires async loading. Use 'await Faker.create({ locale: "${$}" })' for better performance. Falling back to English.`),this._locale=Y9.loadSync("en");else this._locale=Y9.loadSync($);this.random=new e8(Z),this.person=new W$(this.random,this._locale),this.address=new _$(this.random,this._locale),this.internet=new O$(this.random,this._locale),this.phone=new V$(this.random,this._locale),this.company=new E$(this.random,this._locale),this.lorem=new r8(this.random),this.date=new n8(this.random),this.number=new a8(this.random),this.string=new t8(this.random),this.color=new L$(this.random,this._locale),this.finance=new i8(this.random),this.helpers=new s8(this.random),this.image=new o8(this.random),this.git=new l8(this.random),this.science=new I$(this.random,this._locale),this.music=new J$(this.random,this._locale),this.database=new u8(this.random),this.food=new G$(this.random,this._locale),this.commerce=new j$(this.random,this._locale),this.book=new z$(this.random,this._locale),this.animal=new Q$(this.random,this._locale),this.sport=new K$(this.random,this._locale),this.hacker=new F$(this.random,this._locale),this.system=new R$(this.random,this._locale),this.word=new M$(this.random,this._locale),this.vehicle=new D$(this.random,this._locale)}static async create(X){let $=X?.locale??"en";return await Y9.load($),new jZ(X)}seed(X){return this.random=new e8(X),Object.assign(this.person,new W$(this.random,this._locale)),Object.assign(this.address,new _$(this.random,this._locale)),Object.assign(this.internet,new O$(this.random,this._locale)),Object.assign(this.phone,new V$(this.random,this._locale)),Object.assign(this.company,new E$(this.random,this._locale)),Object.assign(this.lorem,new r8(this.random)),Object.assign(this.date,new n8(this.random)),Object.assign(this.number,new a8(this.random)),Object.assign(this.string,new t8(this.random)),Object.assign(this.color,new L$(this.random,this._locale)),Object.assign(this.finance,new i8(this.random)),Object.assign(this.helpers,new s8(this.random)),Object.assign(this.image,new o8(this.random)),Object.assign(this.git,new l8(this.random)),Object.assign(this.science,new I$(this.random,this._locale)),Object.assign(this.music,new J$(this.random,this._locale)),Object.assign(this.database,new u8(this.random)),Object.assign(this.food,new G$(this.random,this._locale)),Object.assign(this.commerce,new j$(this.random,this._locale)),Object.assign(this.book,new z$(this.random,this._locale)),Object.assign(this.animal,new Q$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.hacker,new F$(this.random,this._locale)),Object.assign(this.system,new R$(this.random,this._locale)),Object.assign(this.word,new M$(this.random,this._locale)),Object.assign(this.vehicle,new D$(this.random,this._locale)),this}async setLocale(X){return this._locale=await Y9.load(X),this.reinitializeLocaleModules(),this}setLocaleSync(X){if(!Y9.isCached(X)&&X!=="en")return console.warn(`[ts-mocker] Locale '${X}' is not loaded. Use 'await faker.setLocale("${X}")' or preload it first.`),this;return this._locale=Y9.loadSync(X),this.reinitializeLocaleModules(),this}async preloadLocales(X){return await Y9.preload(X),this}reinitializeLocaleModules(){Object.assign(this.person,new W$(this.random,this._locale)),Object.assign(this.address,new _$(this.random,this._locale)),Object.assign(this.internet,new O$(this.random,this._locale)),Object.assign(this.phone,new V$(this.random,this._locale)),Object.assign(this.company,new E$(this.random,this._locale)),Object.assign(this.food,new G$(this.random,this._locale)),Object.assign(this.animal,new Q$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.music,new J$(this.random,this._locale)),Object.assign(this.commerce,new j$(this.random,this._locale)),Object.assign(this.book,new z$(this.random,this._locale)),Object.assign(this.vehicle,new D$(this.random,this._locale)),Object.assign(this.word,new M$(this.random,this._locale)),Object.assign(this.hacker,new F$(this.random,this._locale)),Object.assign(this.system,new R$(this.random,this._locale)),Object.assign(this.color,new L$(this.random,this._locale)),Object.assign(this.science,new I$(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return Y9.getAvailableLocales()}static isLocaleLoaded(X){return Y9.isCached(X)}static async preloadLocales(X){await Y9.preload(X)}name(){return this.person.name()}email(){return this.internet.email()}}var mU,WL=(X)=>X,VL=(X,$)=>{for(var Z in $)mU(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:uz.bind($,Z)})},C9=(X,$)=>()=>(X&&($=X(X=0)),$),uU,hX,x$,tY,CX,eY,iZ,H$,IL,B0,F0,KL,X6,RL,$6,DL,ML,lZ,HL,Z6,Y6,CL,sZ,wL,qL,PL,TL,NL,C8,nU,SL,U6,AL="0.15.9",kL=()=>{},Z9,w8,C$,oZ,rZ,q8,aZ,tZ,w$,eZ,X1,u9,n9,$1,_6,z8,Z1,iU,Y1,j9,x9,Q6,z6,L6,xL=()=>{},U1,_1,XZ,Q1=null,y1,nX,z9,wX,Y9,lU,sU,oU,rU,aU,tU,eU,X7,$7,Z7,Y7,h1,v1,U7,BL=t(()=>{mU=Object.defineProperty,uU=import.meta.require,CX=C9(()=>{hX=new A1,x$=new k1,tY={createKey:nz,isEquivalent:iz,estimateMemoryUsage:lz}}),U6=C9(()=>{eY=c8.env.CLARITY_LOG_DIR||Cz(sz(),"logs"),iZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},H$={...iZ},IL=(async()=>{try{let{loadConfig:X}=await Promise.resolve().then(()=>(_1(),U1)),$=await X({name:"clarity",alias:"logging",defaultConfig:iZ,cwd:c8.cwd()});if($)Object.assign(H$,$)}catch{}return H$})(),B0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},F0=B0,KL=B0.red,X6=B0.green,RL=B0.yellow,$6=B0.blue,DL=B0.magenta,ML=B0.cyan,lZ=B0.white,HL=B0.gray,Z6=B0.bgRed,Y6=B0.bgYellow,CL=B0.bgGray,sZ=B0.bold,wL=B0.dim,qL=B0.italic,PL=B0.underline,TL=B0.strikethrough,NL=B0.reset,C8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nU={debug:"\uD83D\uDD0D",info:$6("\u2139"),success:X6("\u2713"),warning:Y6(lZ(sZ(" WARN "))),error:Z6(lZ(sZ(" ERROR ")))},SL=new m8("stacks")}),n9=C9(()=>{Z9=class extends Error{timestamp;context;constructor(X,$={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Z])=>`${$}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},w8=class extends Z9{code="CONFIG_NOT_FOUND";constructor(X,$,Z){let Y=Z===void 0?[]:Array.isArray(Z)?Z.filter(Boolean):[Z],U="";if(Y.length===1)U=` or alias "${Y[0]}"`;else if(Y.length>1)U=` or aliases ${Y.map((_)=>`"${_}"`).join(", ")}`;super(`Configuration "${X}"${U} not found`,{configName:X,alias:Z,searchPaths:$,searchPathCount:$.length})}},C$=class extends Z9{code="CONFIG_LOAD_ERROR";constructor(X,$,Z){super(`Failed to load configuration from "${X}": ${$.message}`,{configPath:X,configName:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},oZ=class extends Z9{code="CONFIG_VALIDATION_ERROR";constructor(X,$,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},rZ=class extends Z9{code="CONFIG_MERGE_ERROR";constructor(X,$,Z,Y){super(`Failed to merge configuration from "${X}" with "${$}": ${Z.message}`,{sourcePath:X,targetPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},q8=class extends Z9{code="ENV_VAR_ERROR";constructor(X,$,Z,Y){super(`Failed to parse environment variable "${X}" with value "${$}" as ${Z}`,{envKey:X,envValue:$,expectedType:Z,configName:Y})}},aZ=class extends Z9{code="FILE_SYSTEM_ERROR";constructor(X,$,Z){super(`File system ${X} failed for "${$}": ${Z.message}`,{operation:X,path:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},tZ=class extends Z9{code="TYPE_GENERATION_ERROR";constructor(X,$,Z){super(`Failed to generate types from "${X}" to "${$}": ${Z.message}`,{configDir:X,outputPath:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},w$=class extends Z9{code="SCHEMA_VALIDATION_ERROR";constructor(X,$,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},eZ=class extends Z9{code="BROWSER_CONFIG_ERROR";constructor(X,$,Z,Y){super(`Failed to fetch configuration from "${X}": ${$} ${Z}`,{endpoint:X,status:$,statusText:Z,configName:Y})}},X1=class extends Z9{code="PLUGIN_ERROR";constructor(X,$,Z){super(`Plugin "${X}" failed during ${$}: ${Z.message}`,{pluginName:X,operation:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},u9={configNotFound(X,$,Z){return new w8(X,$,Z)},configLoad(X,$,Z){return new C$(X,$,Z)},configValidation(X,$,Z){return new oZ(X,$,Z)},configMerge(X,$,Z,Y){return new rZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new q8(X,$,Z,Y)},fileSystem(X,$,Z){return new aZ(X,$,Z)},typeGeneration(X,$,Z){return new tZ(X,$,Z)},schemaValidation(X,$,Z){return new w$(X,$,Z)},browserConfig(X,$,Z,Y){return new eZ(X,$,Z,Y)},plugin(X,$,Z){return new X1(X,$,Z)}}}),$1=C9(()=>{CX(),n9()}),z8=C9(()=>{_6={replace:"replace",concat:"concat",smart:"smart"}}),Z1=C9(()=>{CX(),n9(),z8()}),Y1=C9(()=>{CX(),n9(),iU=/^https?:\/\//}),L6=C9(()=>{U6(),kL(),CX(),n9(),$1(),Z1(),Y1(),z8(),j9=new m8("bunfig",{showTags:!0}),x9=new B1,Q6=s0(XX.cwd(),"config"),z6=s0(XX.cwd(),"src/generated")}),U1={},VL(U1,{withErrorRecovery:()=>hU,tryLoadConfig:()=>QL,loadConfigWithResult:()=>UL,loadConfig:()=>j5,isRetryableError:()=>az,isConfigNotFoundError:()=>rz,isBunfigError:()=>vU,globalPerformanceMonitor:()=>x$,globalCache:()=>hX,getEnvOrDefault:()=>tz,generateConfigTypes:()=>zL,defaultGeneratedDir:()=>z6,defaultConfigDir:()=>Q6,deepMergeWithArrayStrategy:()=>z5,deepMerge:()=>bU,createLibraryConfig:()=>LL,config:()=>_L,bunfigPlugin:()=>jL,applyEnvVarsToConfig:()=>aX,TypeGenerationError:()=>tZ,SchemaValidationError:()=>w$,PluginError:()=>X1,PerformanceMonitor:()=>k1,FileSystemError:()=>aZ,ErrorFactory:()=>u9,EnvVarError:()=>q8,EnvProcessor:()=>zZ,ConfigValidator:()=>L5,ConfigValidationError:()=>oZ,ConfigNotFoundError:()=>w8,ConfigMergeError:()=>rZ,ConfigLoader:()=>B1,ConfigLoadError:()=>C$,ConfigFileLoader:()=>LZ,ConfigCache:()=>A1,CacheUtils:()=>tY,BunfigError:()=>Z9,BrowserConfigError:()=>eZ,ArrayMergeStrategies:()=>_6}),_1=C9(()=>{L6(),n9(),CX(),n9(),xL(),$1(),Z1(),Y1(),z8()}),_1(),XZ={verbose:!1,locale:"en",autoInstallLocales:!1},y1=XZ,nX={title:"English",person:{firstNameMale:["James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Mark","Donald","Steven","Paul","Andrew","Joshua","Kenneth","Kevin","Brian","George","Timothy","Ronald","Edward","Jason","Jeffrey","Ryan","Jacob","Gary","Nicholas","Eric","Jonathan","Stephen","Larry","Justin","Scott","Brandon","Benjamin","Samuel","Raymond","Gregory","Frank","Alexander","Patrick","Jack","Dennis","Jerry","Liam","Noah","Oliver","Elijah","Lucas","Mason","Logan","Ethan","Henry","Jackson","Sebastian","Aiden","Carter","Owen","Wyatt","Luke","Jayden","Dylan","Grayson","Levi","Isaac","Gabriel","Julian","Mateo","Jaxon","Lincoln"],firstNameFemale:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen","Lisa","Nancy","Betty","Margaret","Sandra","Ashley","Kimberly","Emily","Donna","Michelle","Dorothy","Carol","Amanda","Melissa","Deborah","Stephanie","Rebecca","Sharon","Laura","Cynthia","Kathleen","Amy","Angela","Shirley","Anna","Brenda","Pamela","Emma","Nicole","Helen","Olivia","Ava","Isabella","Sophia","Mia","Charlotte","Amelia","Harper","Evelyn","Abigail","Sofia","Ella","Scarlett","Grace","Chloe","Victoria","Aria","Lily","Aubrey","Zoey","Penelope","Lillian","Addison","Layla","Natalie","Camila"],firstNameNeutral:["Taylor","Jordan","Alex","Riley","Casey","Morgan","Avery","Quinn","Blake","Cameron","Sage","River","Phoenix","Rowan","Skyler","Charlie","Finley","Peyton","Reese","Kai"],lastName:["Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Rodriguez","Martinez","Hernandez","Lopez","Gonzalez","Wilson","Anderson","Thomas","Taylor","Moore","Jackson","Martin","Lee","Perez","Thompson","White","Harris","Sanchez","Clark","Ramirez","Lewis","Robinson","Walker","Young","Allen","King","Wright","Scott","Torres","Nguyen","Hill","Flores","Green","Adams","Nelson","Baker","Hall","Rivera","Campbell","Mitchell","Carter","Roberts","Gomez","Phillips","Evans","Turner","Diaz","Parker","Cruz","Edwards","Collins","Reyes","Stewart","Morris","Morales","Murphy","Cook","Rogers","Gutierrez","Ortiz","Morgan","Cooper","Peterson","Bailey","Reed","Kelly","Howard","Ramos","Kim","Cox","Ward","Richardson","Watson","Brooks","Chavez","Wood","James","Bennett","Gray","Mendoza","Ruiz","Hughes","Price","Alvarez","Castillo","Sanders","Patel","Myers","Long","Ross","Foster","Jimenez"],prefix:["Mr.","Mrs.","Ms.","Miss","Dr.","Prof."],suffix:["Jr.","Sr.","I","II","III","IV","V","MD","PhD","DDS"],gender:["Male","Female","Non-binary","Agender","Bigender","Genderfluid","Genderqueer"],jobTitle:["Software Engineer","Product Manager","Designer","Data Scientist","DevOps Engineer","Marketing Manager","Sales Representative","Accountant","Human Resources Manager","CEO","CTO","CFO","COO","Director","Manager","Analyst","Consultant","Administrator","Coordinator","Specialist","Developer","Architect","Engineer","Technician","Assistant","Project Manager","Business Analyst","Quality Assurance Engineer","UX Designer","UI Designer","Backend Developer","Frontend Developer","Full Stack Developer","Mobile Developer","Cloud Architect","Security Engineer","Network Engineer","Database Administrator","Systems Administrator","Technical Writer","Scrum Master","Product Owner","Release Manager","Content Manager","Social Media Manager","SEO Specialist","Digital Marketing Specialist","Growth Hacker","Brand Manager","Creative Director","Financial Analyst","Investment Banker","Risk Analyst","Compliance Officer","Tax Consultant","Legal Counsel","Paralegal","Executive Assistant","Operations Manager","Supply Chain Manager","Logistics Coordinator","Customer Success Manager","Account Executive","Sales Engineer","Technical Support"]},address:{street:["Main","Oak","Maple","Cedar","Elm","Washington","Lake","Hill","Park","River","Sunset","Pine","Walnut","Highland","Madison","Lincoln","Jackson","Franklin"],city:["New York","Los Angeles","Chicago","Playa Vista","Houston","Phoenix","Philadelphia","San Antonio","San Diego","Dallas","San Jose","Austin","Jacksonville","Fort Worth","Columbus","Charlotte","San Francisco","Indianapolis","Seattle","Denver","Boston","Nashville","Detroit","Memphis","Portland","Oklahoma City","Las Vegas","Louisville","Baltimore","Milwaukee","Albuquerque","Tucson","Fresno","Sacramento","Mesa","Kansas City","Atlanta","Long Beach","Colorado Springs","Raleigh","Miami","Virginia Beach","Omaha","Oakland","Minneapolis","Tulsa","Arlington","Tampa","New Orleans","Wichita","Cleveland","Bakersfield","Aurora","Anaheim","Honolulu","Santa Ana","Riverside","Corpus Christi","Lexington","Stockton","Henderson","Saint Paul","Cincinnati","Pittsburgh","Greensboro","Anchorage","Plano","Lincoln","Orlando","Irvine","Newark","Durham","Chula Vista","Toledo","Fort Wayne","St. Petersburg","Laredo","Jersey City"],state:["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],stateAbbr:["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],country:["United States","Canada","United Kingdom","Australia","Germany","France","Spain","Italy","Japan","China","India","Brazil","Mexico","Russia","South Korea"],countryCode:["US","CA","GB","AU","DE","FR","ES","IT","JP","CN","IN","BR","MX","RU","KR"],zipCode:["#####","#####-####"],buildingNumber:["###","####","#","##"],direction:["North","East","South","West","Northeast","Northwest","Southeast","Southwest"],streetSuffix:["Street","Avenue","Road","Boulevard","Drive","Court","Circle","Lane","Way","Place","Terrace","Parkway","Commons","Trail","Square","Run","Crossing"]},company:{name:["TechCorp","GlobalSoft","DataSystems","CloudNet","Innovate Inc","Digital Solutions","NextGen Tech","FutureTech","SmartSystems","CoreTech","PrimeSoft","AlphaTech"],suffix:["Inc","LLC","Corp","Group","Ltd","Co","Technologies","Solutions","Systems"],industry:["Technology","Finance","Healthcare","Education","Retail","Manufacturing","Telecommunications","Energy","Real Estate","Transportation","Media","Hospitality"],buzzwords:["synergize","leverage","innovate","disrupt","optimize","streamline","transform","revolutionize","empower","enable","facilitate","orchestrate","integrate"],adjective:["revolutionary","cutting-edge","innovative","next-generation","advanced","leading","premier","world-class","enterprise","scalable","robust","seamless"],descriptor:["global","digital","cloud-based","AI-powered","data-driven","user-centric","agile","secure","efficient","intelligent","automated","integrated"],noun:["solution","platform","system","service","technology","framework","infrastructure","application","network","portal","ecosystem","architecture","engine"]},internet:{domainSuffix:["com","net","org","io","co","app","dev","tech","ai","cloud"],freeEmail:["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","proton.me"]},phone:{formats:["###-###-####","(###) ###-####","1-###-###-####","+1-###-###-####","###.###.####"]},food:{dish:["Hamburger","Cheeseburger","Pizza","Hot Dog","Fried Chicken","BBQ Ribs","Mac and Cheese","Grilled Cheese","BLT Sandwich","Caesar Salad","Cobb Salad","Chicken Wings","Nachos","Tacos","Burrito","Quesadilla","Fish and Chips","Clam Chowder","Lobster Roll","Cheesesteak","Pulled Pork Sandwich","Buffalo Wings","Meatloaf","Pot Roast","Fried Catfish","Jambalaya","Gumbo","Po' Boy","Corn Dog","Chili","Baked Beans","Cornbread","Biscuits and Gravy"],ingredient:["Flour","Sugar","Salt","Pepper","Butter","Eggs","Milk","Cheese","Tomato","Onion","Garlic","Olive Oil","Chicken","Beef","Pork","Fish","Rice","Pasta","Bread","Potato","Carrot","Celery","Bell Pepper","Mushroom","Spinach","Broccoli","Lettuce","Avocado","Lemon","Lime","Basil","Oregano","Thyme","Rosemary","Parsley","Cilantro"],cuisine:["American","Italian","Mexican","Chinese","Japanese","Thai","Indian","French","Greek","Spanish","Mediterranean","Vietnamese","Korean","Turkish","Lebanese","Brazilian","Argentinian","Peruvian","Caribbean","Moroccan","Ethiopian"],dessert:["Apple Pie","Chocolate Cake","Ice Cream","Brownies","Cookies","Cheesecake","Donuts","Cupcakes","Tiramisu","Panna Cotta","Cr\xE8me Br\xFBl\xE9e","Macarons","Churros","Flan","Bread Pudding","Pecan Pie","Key Lime Pie","Banana Split","Sundae","Milkshake"],fruit:["Apple","Banana","Orange","Strawberry","Grape","Watermelon","Pineapple","Mango","Peach","Pear","Cherry","Blueberry","Raspberry","Blackberry","Kiwi","Plum","Apricot","Cantaloupe","Honeydew","Papaya","Guava","Lychee","Dragon Fruit"],vegetable:["Carrot","Broccoli","Cauliflower","Spinach","Kale","Lettuce","Cabbage","Cucumber","Tomato","Bell Pepper","Zucchini","Eggplant","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Onion","Garlic","Celery","Radish","Beet"],meat:["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Bacon","Sausage","Ham","Salami","Prosciutto","Ribeye","Sirloin","Tenderloin"],spice:["Black Pepper","Cumin","Paprika","Cinnamon","Nutmeg","Ginger","Turmeric","Curry","Chili Powder","Cayenne","Oregano","Basil","Thyme","Rosemary","Sage","Coriander","Cardamom","Cloves","Allspice","Bay Leaf","Mustard Seed","Fennel","Star Anise"]},animal:{dog:["Labrador Retriever","German Shepherd","Golden Retriever","French Bulldog","Bulldog","Poodle","Beagle","Rottweiler","German Shorthaired Pointer","Dachshund","Pembroke Welsh Corgi","Australian Shepherd","Yorkshire Terrier","Cavalier King Charles Spaniel","Doberman Pinscher","Boxer","Miniature Schnauzer","Great Dane","Siberian Husky","Bernese Mountain Dog","Pomeranian","Boston Terrier","Havanese","Shetland Sheepdog","Brittany","Cocker Spaniel"],cat:["Persian","Maine Coon","Ragdoll","Bengal","Siamese","British Shorthair","Abyssinian","Birman","Oriental Shorthair","Sphynx","Devon Rex","American Shorthair","Scottish Fold","Exotic Shorthair","Russian Blue","Norwegian Forest Cat","Siberian","Burmese","Manx","Cornish Rex","Himalayan","Turkish Angora","Balinese","Tonkinese"],bird:["Parakeet","Cockatiel","Lovebird","Canary","Finch","Parrot","Macaw","Cockatoo","African Grey","Conure","Budgie","Dove","Pigeon","Robin","Cardinal","Blue Jay","Sparrow","Crow","Raven","Hawk","Eagle","Owl","Hummingbird","Woodpecker"],fish:["Goldfish","Betta","Guppy","Molly","Platy","Swordtail","Tetra","Angelfish","Discus","Gourami","Barb","Danio","Koi","Oscar","Cichlid","Clownfish","Tang","Damselfish","Wrasse","Goby","Blenny","Pufferfish","Lionfish"],horse:["Arabian","Thoroughbred","Quarter Horse","Appaloosa","Paint","Tennessee Walker","Morgan","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Mustang","Shetland Pony","Welsh Pony","Palomino","Buckskin","Pinto","Warmblood"],rabbit:["Holland Lop","Netherland Dwarf","Mini Rex","Flemish Giant","English Lop","French Lop","Angora","Dutch","Lionhead","Rex","Polish","Himalayan"],insect:["Butterfly","Bee","Ant","Beetle","Ladybug","Dragonfly","Grasshopper","Cricket","Moth","Firefly","Praying Mantis","Walking Stick","Caterpillar","Wasp"],type:["Dog","Cat","Bird","Fish","Rabbit","Hamster","Guinea Pig","Mouse","Rat","Ferret","Chinchilla","Hedgehog","Turtle","Lizard","Snake","Frog"]},sport:{sport:["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding"],team:["Lakers","Warriors","Bulls","Celtics","Yankees","Red Sox","Cowboys","Patriots","49ers","Packers","Steelers","Maple Leafs","Bruins","Canadiens","Blackhawks"],athlete:["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Usain Bolt","Michael Phelps"]},music:{genre:["Rock","Pop","Hip Hop","Jazz","Blues","Country","Electronic","Classical","R&B","Soul","Funk","Reggae","Metal","Punk","Indie","Alternative","Folk","Disco","House","Techno","Dubstep","Trap","Gospel","Opera"],artist:["The Beatles","Elvis Presley","Michael Jackson","Madonna","Prince","Bob Dylan","Led Zeppelin","Pink Floyd","Queen","David Bowie","The Rolling Stones","Nirvana","Bruce Springsteen","Stevie Wonder","Aretha Franklin","Ray Charles","Johnny Cash"],song:["Bohemian Rhapsody","Imagine","Hey Jude","Billie Jean","Like a Rolling Stone","Smells Like Teen Spirit","Hotel California","Sweet Child O' Mine","Stairway to Heaven","Purple Haze","What's Going On","Respect","I Want to Hold Your Hand"],instrument:["Guitar","Piano","Drums","Bass","Violin","Cello","Saxophone","Trumpet","Flute","Clarinet","Trombone","Harp","Banjo","Mandolin","Ukulele","Harmonica","Accordion","Xylophone","Synthesizer","Keyboard"]},commerce:{product:["Chair","Table","Lamp","Sofa","Bed","Desk","Computer","Phone","Tablet","Watch","Shoes","Shirt","Pants","Jacket","Hat","Gloves","Bag","Wallet","Sunglasses","Bicycle","Car","Motorcycle","Camera","Headphones","Speaker"],productAdjective:["Small","Medium","Large","Ergonomic","Rustic","Modern","Sleek","Lightweight","Durable","Handmade","Recycled","Refined","Gorgeous","Incredible","Practical","Fantastic","Awesome","Generic","Unbranded","Licensed","Intelligent","Tasty"],productMaterial:["Steel","Wood","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Aluminum","Leather","Silk","Wool","Linen"],department:["Electronics","Clothing","Home & Garden","Sports","Automotive","Books","Toys","Health & Beauty","Grocery","Jewelry","Tools","Music","Movies","Baby","Pet Supplies"],color:["Red","Blue","Green","Yellow","Black","White","Gray","Silver","Gold","Purple","Pink","Orange","Brown","Navy","Teal","Maroon","Olive"]},book:{title:["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","Brave New World","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude"],author:["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee"],publisher:["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Bloomsbury","Vintage"],genre:["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Self-Help","Poetry","Drama","Adventure","Young Adult"],series:["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","Discworld","Dune","Foundation"],review:["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","One of the best books I've ever read."]},vehicle:{manufacturer:["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Tesla","Volvo","Porsche","Jeep","Mazda","Subaru"],model:["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Model 3","Model Y","3 Series","C-Class","A4","Golf","Mustang","Wrangler"],type:["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Electric","Hybrid"],fuel:["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel"],bicycle:["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Gravel Bike"]},word:{adjective:["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold"],adverb:["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well"],conjunction:["and","but","or","nor","for","yet","so","although","because","since","unless","while","when","if"],interjection:["wow","oh","ah","hey","oops","ouch","yay","hooray","hello","goodbye","yes","no"],noun:["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","fire","sun","moon"],preposition:["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through"],verb:["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","think","know","make","take","give"]},hacker:{abbreviation:["TCP","HTTP","RAM","GB","CSS","SSL","SQL","CLI","UI","UX","FTP","API","DNS","IP","LAN","WAN","VPN","SSH","JSON","REST"],adjective:["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","wireless","mobile","neural","optical","cloud","quantum"],noun:["driver","protocol","bandwidth","panel","microchip","program","port","card","interface","system","sensor","firewall","pixel","application","server","database","network"],verb:["bypass","hack","override","compress","copy","navigate","index","connect","generate","calculate","synthesize","transmit","program","parse","compile","encrypt","decrypt"],ingverb:["bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","calculating","synthesizing","transmitting","programming","parsing","compiling","encrypting"],phrase:["We need to bypass the digital firewall!","Try to hack the TCP protocol!","The SSL port is down, override the wireless system!","You can't compress the bandwidth without indexing the neural network!"]},system:{fileName:["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache"],fileType:["audio","image","text","video","application","document","spreadsheet","presentation","archive","code"]},science:{chemicalElement:["Hydrogen","Helium","Lithium","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Iron","Copper","Zinc","Silver","Gold"],unit:["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","volt","ohm","hertz","celsius"],constant:["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Gas Constant"],field:["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Biochemistry","Microbiology","Botany","Zoology"]}},z9=new Map,wX=new Map,Y9=class{static AVAILABLE_BASE_LOCALES=["af","ar","az","cs","da","de","en","eo","es","fa","fi","fr","he","hi","it","ja","ko","nl","no","pl","pt","sv","tl","tr","uk","zh","zu"];static AVAILABLE_LOCALE_VARIANTS=["af_ZA","de_AT","de_CH","de_DE","en_AU","en_CA","en_GB","en_GH","en_HK","en_IE","en_IN","en_NG","en_US","en_ZA","es_ES","es_MX","fr_BE","fr_CA","fr_CH","fr_FR","fr_LU","fr_SN","pt_BR","pt_MZ","pt_PT","zh_CN","zh_TW","zu_ZA"];static getAvailableLocales(){return[...this.AVAILABLE_BASE_LOCALES,...this.AVAILABLE_LOCALE_VARIANTS]}static getAvailableBaseLocales(){return this.AVAILABLE_BASE_LOCALES}static getAvailableLocaleVariants(){return this.AVAILABLE_LOCALE_VARIANTS}static async load($){let Z=SX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",nX);return nX}if(z9.has(Z))return z9.get(Z);if(wX.has(Z))return wX.get(Z);let Y=this.loadLocaleWithFallback(Z);wX.set(Z,Y);try{let U=await Y;return z9.set(Z,U),U}finally{wX.delete(Z)}}static loadSync($){let Z=SX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",nX);return nX}if(z9.has(Z))return z9.get(Z);throw Error(`Locale '${$}' is not loaded. Please use async loading with faker.setLocale('${$}') or preload it.`)}static isCached($){let Z=SX($).normalized;return z9.has(Z)}static async preload($){await Promise.all($.map((Z)=>this.load(Z)))}static clearCache(){z9.clear(),wX.clear()}static async loadLocaleWithFallback($){let Z=GL($);for(let Y=0;Y<Z.length;Y++){let U=Z[Y],_=Y===0&&Z.length>1,Q=!_;try{if(_){let L=await this.loadLocaleModule(U),z=Z[1];try{let j=await this.loadLocaleModule(z);return dU(j,L)}catch{return L}}else return await this.loadLocaleModule(U)}catch(L){if(Y===Z.length-1)throw L;continue}}throw Error(`Failed to load locale '${$}' with fallback chain: ${Z.join(" \u2192 ")}`)}static async tryWorkspaceImport($,Z){if(!AX())return null;try{let Y=await import(`../../${Z.packageName}/dist/index.js`);return Y[Z.normalized]||Y[Z.language]||Y.default}catch{try{let Y=Hz.cwd(),U=Mz(Y,"packages",Z.packageName,"dist","index.js");if(!Dz(U))return null;let _=await import(`file://${U}`);return _[Z.normalized]||_[Z.language]||_.default}catch{return null}}}static async loadLocaleModule($){let Z=FL($),Y=SX($);try{let U=await import(Z);return U[Y.normalized]||U[Y.language]||U.default}catch(U){let _=U instanceof Error?U.message:String(U);if(_.includes("Cannot find")||_.includes("not found")||_.includes("ModuleNotFound")){if(AX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}if(y1.autoInstallLocales)if(console.log(`
|
|
459
|
+
\uD83D\uDD0D Locale '${$}' not found. Auto-installing ${Z}...`),cU(Z)){if(AX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}try{let Q=await import(Z);return Q[Y.normalized]||Q[Y.language]||Q.default}catch(Q){if(AX()&&Z.startsWith("@mock-locale/")){let L=await this.tryWorkspaceImport($,Y);if(L)return L;throw Error(`Locale '${$}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${Z.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${$}' after installation: ${Q instanceof Error?Q.message:String(Q)}`)}}else throw Error(`Failed to auto-install locale '${$}'. Please install manually with: bun add ${Z}`);throw Error(`Locale '${$}' is not installed. Install it with: bun add ${Z}
|
|
460
460
|
Or install all locales with: bun add @mock-locale/{af,ar,az,cs,da,de,en,eo,es,fa,fi,fr,he,hi,it,ja,ko,nl,no,pl,pt,sv,tl,tr,uk,zh,zu}
|
|
461
|
-
Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${$}': ${_}`)}}},iU=new j5,lU={email:(X)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(X)},phone:(X)=>{let $=/^\+?[1-9]\d{0,15}$/,Z=X.replace(/[\s\-()]/g,"");return Z.length>=7&&$.test(Z)},name:(X)=>{return/^[a-z\s\-']+$/i.test(X)&&X.length>=2&&X.length<=50},age:(X)=>{return Number.isInteger(X)&&X>=0&&X<=150},url:(X)=>{try{let $=new URL(X);return X.startsWith("http://")||X.startsWith("https://")}catch{return!1}},regex:(X)=>($)=>{return X.test($)},length:(X,$)=>(Z)=>{return Z.length>=X&&Z.length<=$},range:(X,$)=>(Z)=>{return Z>=X&&Z<=$}},sU={phoneByCountry:{field:"phone",dependsOn:"country",mapping:{"United States":"+1-###-###-####","United Kingdom":"+44 #### ### ###",Germany:"+49 ### ########",France:"+33 # ## ## ## ##",Spain:"+34 ### ## ## ##",Italy:"+39 ### ### ###",Japan:"+81 ##-####-####",China:"+86 ### #### ####",Australia:"+61 ### ### ###",Canada:"+1-###-###-####"}},postalCodeByCountry:{field:"postalCode",dependsOn:"country",mapping:{"United States":"#####","United Kingdom":"AA## #AA",Germany:"#####",France:"#####",Spain:"#####",Italy:"#####",Japan:"###-####",China:"######",Australia:"####",Canada:"A#A #A#"}},firstNameByGender:{field:"firstName",dependsOn:"gender",mapping:{male:["John","Michael","David","James","Robert","William","Richard","Thomas","Christopher","Daniel"],female:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen"]}}},oU={commonFirstNames:{items:[{item:"John",weight:100},{item:"Michael",weight:85},{item:"David",weight:80},{item:"James",weight:75},{item:"Robert",weight:70},{item:"William",weight:65},{item:"Richard",weight:60},{item:"Thomas",weight:55},{item:"Christopher",weight:50},{item:"Daniel",weight:45}]},ageDistribution:{items:[{item:25,weight:80},{item:30,weight:90},{item:35,weight:95},{item:40,weight:100},{item:45,weight:85},{item:50,weight:70},{item:55,weight:55},{item:60,weight:40},{item:65,weight:25},{item:70,weight:15}]},countryDistribution:{items:[{item:"United States",weight:100},{item:"China",weight:95},{item:"India",weight:90},{item:"Brazil",weight:60},{item:"Russia",weight:55},{item:"Japan",weight:50},{item:"Germany",weight:45},{item:"United Kingdom",weight:40},{item:"France",weight:35},{item:"Italy",weight:30}]}},rU=[".","_","-",""],aU=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","fugiat","nulla","pariatur","excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"],tU=["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Hyundai","Kia","Mazda","Subaru","Lexus","Tesla","Volvo","Porsche","Jeep","Ram","GMC","Dodge","Chrysler","Buick","Cadillac","Acura","Infiniti","Genesis","Land Rover","Jaguar","Mini"],eU=["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Silverado","Tacoma","Altima","Sentra","Rogue","Model 3","Model Y","Model S","X5","X3","3 Series","5 Series","C-Class","E-Class","A4","Q5","Golf","Jetta","Passat","Tiguan","Escape","Explorer","Mustang","Ranger","Malibu","Equinox","Traverse","Wrangler","Grand Cherokee","Cherokee","Compass"],X7=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],$7=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],Z7=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],h1="abcdefghijklmnopqrstuvwxyz".split(""),v1=new jZ,Y7=v1}),U7={};n1(U7,{validateData:()=>A$,selectWeightedItem:()=>k$,isInWorkspace:()=>AX,installPackage:()=>pU,globalProviderRegistry:()=>iU,getConfig:()=>jL,generateRealisticData:()=>OL,faker:()=>v1,detectPackageManager:()=>dU,defaultConfig:()=>XZ,default:()=>Y7,config:()=>y1,applyRelationships:()=>d9,applyConstraints:()=>FL,WordModule:()=>M$,WeightedSelections:()=>oU,VehicleModule:()=>D$,ValidationRules:()=>lU,SystemModule:()=>R$,StringModule:()=>t8,SportModule:()=>K$,ScienceModule:()=>I$,Random:()=>e8,PhoneModule:()=>V$,PersonModule:()=>W$,NumberModule:()=>a8,MusicModule:()=>J$,LoremModule:()=>r8,LocaleLoader:()=>Y9,InternetModule:()=>O$,ImageModule:()=>o8,HelpersModule:()=>s8,HackerModule:()=>F$,GitModule:()=>l8,FoodModule:()=>G$,FinanceModule:()=>i8,Faker:()=>jZ,DateModule:()=>n8,DatabaseModule:()=>u8,DataRelationships:()=>sU,DataProviderRegistry:()=>j5,CompanyModule:()=>E$,CommerceModule:()=>j$,ColorModule:()=>L$,BookModule:()=>z$,AnimalModule:()=>Q$,AddressModule:()=>_$});var BL=e(()=>{xL()});function r9(){let X=new Date().toISOString();return J0(f.dialect)?X.slice(0,19).replace("T"," "):X}function C9(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);if(X.length>64)throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' exceeds 64 chars`);if(!E5.test(X))throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function _7(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);let Z=X.split(".");if(Z.length>2||Z.some((Y)=>Y.length===0||Y.length>64||!E5.test(Y)))throw TypeError(`[bun-query-builder] ${$}: invalid ORDER BY column '${X}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function U9(X){if(!L8)try{L8=(P8(),p7(F7)).getModel}catch{L8=()=>{return}}return L8(X)}function L6(X){let $=tX.get(X);if($!==void 0)return $;let Z=0,Y=X.replace(/\?/g,()=>`$${++Z}`);if(tX.size>=dL)tX.clear();return tX.set(X,Y),Y}function j6(X){if(X==null)return 0;if(typeof X.affectedRows==="number")return X.affectedRows;if(typeof X.count==="number")return X.count;if(Array.isArray(X))return X.length;return 0}function E6(X){if(X==null||typeof X!=="object")return null;if("insertId"in X&&X.insertId!=null)return X.insertId;if("lastInsertRowid"in X&&X.lastInsertRowid!=null)return X.lastInsertRowid;return null}class f1{sqliteDb;dialect="sqlite";constructor(X){this.sqliteDb=X}all(X,$){return Promise.resolve(this.sqliteDb.query(X).all(...$))}get(X,$){return Promise.resolve(this.sqliteDb.query(X).get(...$)??void 0)}run(X,$){let Z=this.sqliteDb.run(X,$);return Promise.resolve({changes:Z.changes,lastInsertId:Z.lastInsertRowid})}insert(X,$){return this.run(X,$)}}class Q7{dialect;constructor(X){this.dialect=X}conn(){return BX()}text(X){return this.dialect==="postgres"?L6(X):X}async all(X,$){let Z=await this.conn().unsafe(this.text(X),$);return Array.isArray(Z)?Z:[]}async get(X,$){let Z=await this.conn().unsafe(this.text(X),$);if(Array.isArray(Z))return Z[0]??void 0;return Z??void 0}async run(X,$){let Z=await this.conn().unsafe(this.text(X),$);return{changes:j6(Z),lastInsertId:E6(Z)}}async insert(X,$,Z){if(this.dialect==="postgres"){let _=await this.conn().unsafe(`${L6(X)} RETURNING ${Z}`,$),Q=Array.isArray(_)?_[0]:_;return{changes:1,lastInsertId:Q?Q[Z]??null:null}}let Y=await this.conn().unsafe(X,$),U=E6(Y);if(U==null){let _=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);U=(Array.isArray(_)?_[0]:_)?.id??null}return{changes:j6(Y)||1,lastInsertId:U}}}function z7(X){if(X.database instanceof b1)o9=X.database;else o9=new b1(X.database||":memory:",{create:!0}),t1(o9);q9=null,eX=null}function I0(){if(o9){if(!q9||eX!==o9)q9=new f1(o9),eX=o9,z1="sqlite",L1=null;return q9}let X=f.dialect,$=f.database?.database??null;if(q9&&eX===null&&z1===X&&L1===$)return q9;if(eX=null,z1=X,L1=$,X==="sqlite"){let Z=new b1($||":memory:",{create:!0});t1(Z),q9=new f1(Z)}else q9=new Q7(X);return q9}function L7(){let X=I0();if(X.sqliteDb)return X.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${X.dialect}'. Use the async model API instead.`)}function vX(X){let $=X.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function a9(X){let $=X.traits;return Boolean($?.useTimestamps||$?.timestampable)}function yL(X){let $=g1.get(X);if($)return $;let Z=new Set,Y=X.belongsToMany;if(Y){if(Array.isArray(Y)){for(let U of Y)if(typeof U==="string")Z.add(U.toLowerCase());else if(U&&typeof U==="object"&&U.model)Z.add(U.model.toLowerCase())}else if(typeof Y==="object")for(let U of Object.keys(Y))Z.add(U)}return g1.set(X,Z),Z}function G6(X){let $={};for(let[Z,Y]of Object.entries(X))$[s0(Z)]=Y;return $}function hL(X,$){if(X[$])return X[$];let Z=s0($);if(X[Z])return X[Z];for(let Y of Object.keys(X))if(s0(Y)===Z)return X[Y];return}class t0{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor(X,$={}){this._definition=X,this._attributes=G6({...$}),this._original=null;let Z=yL(X);if(Z.size===0)return;let Y=this;return new Proxy(this,{get(U,_,Q){if(typeof _==="string"&&Z.has(_)&&!(_ in U))return()=>{let L=j7(X,_);if(!L||L.type!=="belongsToMany")throw Error(`[orm] relation '${_}' did not resolve to a belongsToMany on '${X.name}'`);let z=U9(L.relatedModelName),j=z?.getDefinition?.()||z?.definition;if(!j)throw Error(`[orm] related model '${L.relatedModelName}' is not registered`);return new E7(Y,X,L,j)};return Reflect.get(U,_,Q)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(X){let $=this._definition.get?.[X];if($)try{let Z=$(this._attributes);if(Z!==void 0)return Z}catch{}return this._attributes[s0(X)]}getAttribute(X){return this._attributes[s0(X)]}getAttributes(){return{...this._attributes}}set(X,$){if(this._original===null)this._original={...this._attributes};this._attributes[s0(X)]=$}only(X){let $={};for(let Z of X)$[Z]=this._attributes[Z];return $}except(X){let $=new Set(X.map((Y)=>Y)),Z={};for(let Y of Object.keys(this._attributes))if(!$.has(Y))Z[Y]=this._attributes[Y];return Z}getRelation(X){return this._relations[X]}setRelation(X,$){this._relations[X]=$}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let X=this._definition.primaryKey||"id";return this._attributes[X]}isDirty(X){if(this._original===null)return!1;if(X)return this._attributes[X]!==this._original[X];return Object.keys(this._attributes).some(($)=>this._attributes[$]!==this._original[$])}isClean(X){return!this.isDirty(X)}getOriginal(X){return this.getOriginalAttributes()[X]}getChanges(){if(this._original===null)return{};let X={};for(let $ of Object.keys(this._attributes))if(this._attributes[$]!==this._original[$])X[$]=this._attributes[$];return X}fill(X){let $=this._definition.attributes;for(let[Z,Y]of Object.entries(X)){let U=hL($,Z),_=!U&&s0(Z).endsWith("_id");if(U?.fillable&&!U?.guarded||_){if(this._original===null)this._original={...this._attributes};this._attributes[s0(Z)]=Y}}return this}forceFill(X){if(this._original===null)this._original={...this._attributes};return Object.assign(this._attributes,G6(X)),this}async save(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._definition.hooks,Y=this._definition.set||{};for(let[U,_]of Object.entries(Y))if(this.isDirty(U))this._attributes[U]=_(this._attributes);if(this._attributes[$]){await Z?.beforeUpdate?.(this,this.getChanges());let U=this.getChanges(),_=Object.keys(U);if(_.length>0){let Q=_.map((z)=>`${z} = ?`).join(", "),L=[...Object.values(U),this._attributes[$]];if(a9(this._definition)){let z=r9();await X.run(`UPDATE ${this._definition.table} SET ${Q}, updated_at = ? WHERE ${$} = ?`,[...Object.values(U),z,this._attributes[$]])}else await X.run(`UPDATE ${this._definition.table} SET ${Q} WHERE ${$} = ?`,L)}await Z?.afterUpdate?.(this)}else{let U=this._definition.attributes,_={};for(let[j,E]of Object.entries(U)){if(E.guarded)continue;let V=s0(j);if(this._attributes[V]!==void 0)_[V]=this._attributes[V]}for(let j of Object.keys(this._attributes))if(j.endsWith("_id")&&j!==$&&!(j in _))_[j]=this._attributes[j];if(a9(this._definition)){let j=r9();_.created_at=j,_.updated_at=j}if(this._definition.traits?.useUuid&&!_.uuid)_.uuid=crypto.randomUUID();await Z?.beforeCreate?.(_);let Q=Object.keys(_),L=Q.map(()=>"?").join(", "),z=await X.insert(`INSERT INTO ${this._definition.table} (${Q.join(", ")}) VALUES (${L})`,Object.values(_),$);for(let[j,E]of Object.entries(_))this._attributes[j]=E;if(z.lastInsertId!=null)this._attributes[$]=z.lastInsertId;await Z?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(X){return this.fill(X),this.save()}async fresh(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._attributes[$];if(Z==null)return null;let Y=await X.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);if(!Y)return null;return new t0(this._definition,Y)}async delete(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._attributes[$],Y=this._definition.hooks;if(!Z)throw Error("Cannot delete a model without a primary key");if(await Y?.beforeDelete?.(this),vX(this._definition)){let U=r9();await X.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${$} = ?`,[U,Z]),this._attributes[v9]=U}else await X.run(`DELETE FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);return await Y?.afterDelete?.(this),!0}async restore(){if(!vX(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let X=this._definition.primaryKey||"id",$=this._attributes[X];if(!$)throw Error("Cannot restore a model without a primary key");return await I0().run(`UPDATE ${this._definition.table} SET ${v9} = ? WHERE ${X} = ?`,[null,$]),this._attributes[v9]=null,this._original=null,this}trashed(){return this._attributes[v9]!=null}async refresh(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._attributes[$];if(!Z)throw Error("Cannot refresh a model without a primary key");let Y=await X.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);if(!Y)return null;return this._attributes=Y,this._original=null,this}replicate(){let X=this._definition.primaryKey||"id",$={...this._attributes};return delete $[X],delete $.uuid,delete $.created_at,delete $.updated_at,new t0(this._definition,$)}toArray(){let X={...this._attributes};for(let[$,Z]of Object.entries(this._relations))if(Array.isArray(Z))X[$]=Z.map((Y)=>Y.toArray());else if(Z)X[$]=Z.toArray();else X[$]=null;return X}toJSON(){let X=new Set;for(let[Z,Y]of Object.entries(this._definition.attributes))if(Y.hidden)X.add(Z);let $={};for(let[Z,Y]of Object.entries(this._attributes))if(!X.has(Z))$[Z]=Y;for(let[Z,Y]of Object.entries(this._relations))if(Array.isArray(Y))$[Z]=Y.map((U)=>U.toJSON());else if(Y)$[Z]=Y.toJSON();else $[Z]=null;return $}}function s0(X){let $=d1.get(X);if($!==void 0)return $;return $=X.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),d1.set(X,$),$}function i9(X){let $=p1.get(X);if($!==void 0)return $;let Z=s0(X);if(Z.endsWith("y")&&!Z.endsWith("ay")&&!Z.endsWith("ey")&&!Z.endsWith("oy")&&!Z.endsWith("uy"))$=Z.slice(0,-1)+"ies";else if(Z.endsWith("s")||Z.endsWith("x")||Z.endsWith("ch")||Z.endsWith("sh"))$=`${Z}es`;else $=`${Z}s`;return p1.set(X,$),$}function j7(X,$){let{name:Z,table:Y}=X,U=X.primaryKey||"id";function _(W){if(!W)return null;if(Array.isArray(W)){for(let F of W){let K=typeof F==="string"?F:F?.model||"";if(K&&K.toLowerCase()===$.toLowerCase())return K}return null}if(typeof W==="object"){for(let[F,K]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||F}return null}function Q(){let W=X.belongsToMany;if(!W)return null;if(Array.isArray(W)){for(let F of W)if(typeof F==="string"){if(F.toLowerCase()===$.toLowerCase())return{entry:F}}else if(F&&typeof F==="object"&&F.model){if(F.model.toLowerCase()===$.toLowerCase())return{entry:F}}return null}if(typeof W==="object"){for(let[F,K]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:K}}return null}let L=_(X.hasMany);if(L){let F=U9(L)?.getTable?.()||i9(L),K=s0(Z)+"_id";return{type:"hasMany",relatedModelName:L,relatedTable:F,foreignKey:K,localKey:U}}let z=_(X.hasOne);if(z){let F=U9(z)?.getTable?.()||i9(z),K=s0(Z)+"_id";return{type:"hasOne",relatedModelName:z,relatedTable:F,foreignKey:K,localKey:U}}let j=_(X.belongsTo);if(j){let W=U9(j),F=W?.getTable?.()||i9(j),K=W?.getDefinition?.()?.primaryKey||"id",D=s0(j)+"_id";return{type:"belongsTo",relatedModelName:j,relatedTable:F,foreignKey:D,localKey:K}}let E=Q();if(E){let W=typeof E.entry==="object",F=W?E.entry.model:E.entry,D=U9(F)?.getTable?.()||i9(F),w=W?E.entry:null,T,N;if(w?.table)T=w.table;else if(w?.through){N=w.through;let h=U9(w.through);if(!h)throw Error(`[orm] belongsToMany relation '${$}' on '${Z}' references unknown through model '${w.through}'. Make sure '${w.through}' is registered.`);T=h.getTable?.()||h.getDefinition?.()?.table||i9(w.through)}else{let h=Y.endsWith("s")?Y.slice(0,-1):Y,c=D.endsWith("s")?D.slice(0,-1):D;T=[h,c].sort().join("_")}let q=w?.foreignKey||`${Y.endsWith("s")?Y.slice(0,-1):Y}_id`,H=w?.relatedKey||`${D.endsWith("s")?D.slice(0,-1):D}_id`,x=[];if(w?.pivot?.columns)for(let h of Object.keys(w.pivot.columns))x.push(h);if(N){let h=U9(N),c=h?.getDefinition?.()||h?.definition,y=c?.attributes??{},g=c?.primaryKey??"id";for(let v of Object.keys(y)){if(v===q||v===H||v===g)continue;if(!x.includes(v))x.push(v)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:D,foreignKey:q,localKey:U,pivotTable:T,pivotFkParent:q,pivotFkRelated:H,pivotColumns:x,pivotModelName:N,pivotTimestamps:Boolean(w?.pivot?.timestamps)}}let V=(W,F)=>{if(!W||typeof W!=="object"||Array.isArray(W))return null;let K=W[$]??W[Object.keys(W).find((c)=>c.toLowerCase()===$.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:D,target:w}=K;if(!D||!w)return null;let T=U9(D),N=T?.getDefinition?.()||T?.definition,q=T?.getTable?.()||N?.table||i9(D),H=N?.primaryKey||"id",h=U9(w)?.getTable?.()||i9(w);return{type:F,relatedModelName:w,relatedTable:h,foreignKey:`${s0(Z)}_id`,localKey:U,throughTable:q,throughForeignKey:`${s0(Z)}_id`,throughLocalKey:H,targetForeignKey:`${vL(q)}_id`}},G=V(X.hasManyThrough,"hasManyThrough");if(G)return G;let J=V(X.hasOneThrough,"hasOneThrough");if(J)return J;return null}function vL(X){return X.endsWith("s")?X.slice(0,-1):X}class E7{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(X,$,Z,Y){this._parent=X,this._parentDef=$,this._resolved=Z,this._relatedDef=Y}get parentId(){let X=this._parentDef.primaryKey||"id";return this._parent.get(X)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(X,$,Z){if(Z===void 0)this._wheres.push({sql:`${this.relatedTable}.${X} = ?`,params:[$]});else this._wheres.push({sql:`${this.relatedTable}.${X} ${String($)} ?`,params:[Z]});return this}wherePivot(X,$,Z){if(Z===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${X} = ?`,params:[$]});else this._pivotWheres.push({sql:`${this.pivotTable}.${X} ${String($)} ?`,params:[Z]});return this}wherePivotIn(X,$){if(!$.length)return this;let Z=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IN (${Z})`,params:[...$]}),this}wherePivotNotIn(X,$){if(!$.length)return this;let Z=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${X} NOT IN (${Z})`,params:[...$]}),this}wherePivotNull(X){return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IS NULL`,params:[]}),this}wherePivotNotNull(X){return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IS NOT NULL`,params:[]}),this}orderBy(X,$="asc"){if(_7(X,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push(`${X} ${$.toUpperCase()}`),this}limit(X){if(!Number.isFinite(X)||X<0||!Number.isInteger(X))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${X}`);return this._limit=X,this}offset(X){if(!Number.isFinite(X)||X<0||!Number.isInteger(X))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${X}`);return this._offset=X,this}relatedSelectColumns(){let X=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),$=this._relatedDef.traits;if($?.useTimestamps||$?.timestampable)X.add("created_at"),X.add("updated_at");if($?.useSoftDeletes||$?.softDeletable)X.add("deleted_at");if($?.useUuid)X.add("uuid");return[...X]}buildSelect(){let X=[],Z=`SELECT ${this.relatedSelectColumns().map((Y)=>`${this.relatedTable}.${Y} AS ${j1}${Y}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;Z+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,Z+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,X.push(this.parentId);for(let Y of this._pivotWheres)Z+=` AND ${Y.sql}`,X.push(...Y.params);for(let Y of this._wheres)Z+=` AND ${Y.sql}`,X.push(...Y.params);if(this._orderBy.length>0)Z+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)Z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Z+=` OFFSET ${this._offset}`;return{sql:Z,params:X}}hydrateRows(X){let $=this.fkParent,Z=this.fkRelated;return X.map((Y)=>{let U={},_={};for(let[L,z]of Object.entries(Y))if(L.startsWith(j1))U[L.slice(j1.length)]=z;else if(L!==$&&L!==Z)_[L]=z;let Q=new t0(this._relatedDef,U);return Q.pivot=_,Q})}async get(){let X=I0(),{sql:$,params:Z}=this.buildSelect(),Y=await X.all($,Z);return this.hydrateRows(Y)}async first(){return this._limit=1,(await this.get())[0]}async count(){let X=I0(),$=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Z=[this.parentId];for(let U of this._pivotWheres)$+=` AND ${U.sql}`,Z.push(...U.params);let Y=await X.get($,Z);return Number(Y?.count??0)}async exists(){return await this.count()>0}now(){return r9()}async attach(X,$={}){let Z=I0(),Y=Array.isArray(X)?X:[X];if(Y.length===0)return 0;let U=this._resolved.pivotTimestamps?this.now():null,_=0;for(let Q of Y){let L={[this.fkParent]:this.parentId,[this.fkRelated]:Q,...$};if(U){if(L.created_at===void 0)L.created_at=U;if(L.updated_at===void 0)L.updated_at=U}let z=Object.keys(L),j=z.map(()=>"?").join(", "),E=`INSERT INTO ${this.pivotTable} (${z.join(", ")}) VALUES (${j})`,V=z.map((G)=>L[G]);await Z.run(E,V),_++}return _}async detach(X){let $=I0(),Z=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Y=[this.parentId];if(X!==void 0&&X!==null){let U=Array.isArray(X)?X:[X];if(U.length===0)return 0;let _=U.map(()=>"?").join(", ");Z+=` AND ${this.fkRelated} IN (${_})`,Y.push(...U)}return(await $.run(Z,Y)).changes}async updateExistingPivot(X,$){let Z=I0(),Y={...$};if(this._resolved.pivotTimestamps&&Y.updated_at===void 0)Y.updated_at=this.now();let U=Object.keys(Y);if(U.length===0)return 0;let _=U.map((z)=>`${z} = ?`).join(", "),Q=`UPDATE ${this.pivotTable} SET ${_} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,L=[...U.map((z)=>Y[z]),this.parentId,X];return(await Z.run(Q,L)).changes}async sync(X){let $=I0(),Z=new Map;for(let j of X)if(j!=null&&typeof j==="object"&&"id"in j){let{id:E,...V}=j;Z.set(E,V)}else Z.set(j,{});let Y=await $.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),U=new Set(Y.map((j)=>j[this.fkRelated])),_=[],Q=[],L=[],z=[...U].filter((j)=>!Z.has(j));if(z.length>0)await this.detach(z),Q.push(...z);for(let[j,E]of Z)if(!U.has(j))await this.attach(j,E),_.push(j);else if(Object.keys(E).length>0)await this.updateExistingPivot(j,E),L.push(j);return{attached:_,detached:Q,updated:L}}async toggle(X){let $=I0(),Z=Array.isArray(X)?X:[X];if(Z.length===0)return{attached:[],detached:[]};let Y=Z.map(()=>"?").join(", "),U=await $.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${Y})`,[this.parentId,...Z]),_=new Set(U.map((z)=>z[this.fkRelated])),Q=Z.filter((z)=>!_.has(z)),L=Z.filter((z)=>_.has(z));if(Q.length>0)await this.attach(Q);if(L.length>0)await this.detach(L);return{attached:Q,detached:L}}}class Y0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(X){this._definition=X}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}whereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"and"}),this}orWhereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"or"}),this}whereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"and"}),this}orWhereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"or"}),this}whereNull(X){return C9(X,"whereNull(column)"),this._wheres.push({column:X,operator:"=",value:null,boolean:"and"}),this}orWhereNull(X){return C9(X,"orWhereNull(column)"),this._wheres.push({column:X,operator:"=",value:null,boolean:"or"}),this}whereNotNull(X){return C9(X,"whereNotNull(column)"),this._wheres.push({column:X,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(X){return C9(X,"orWhereNotNull(column)"),this._wheres.push({column:X,operator:"!=",value:null,boolean:"or"}),this}whereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"and"}),this}orWhereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"or"}),this}whereNotLike(X,$){return this._wheres.push({column:X,operator:"not like",value:$,boolean:"and"}),this}orWhereNotLike(X,$){return this._wheres.push({column:X,operator:"not like",value:$,boolean:"or"}),this}whereRaw(X,...$){return this._wheres.push({raw:X,rawParams:$,boolean:"and"}),this}orWhereRaw(X,...$){return this._wheres.push({raw:X,rawParams:$,boolean:"or"}),this}whereGroup(X){return this._addGroup("and",X)}orWhereGroup(X){return this._addGroup("or",X)}_addGroup(X,$){let Z=new Y0(this._definition);if($(Z),Z._wheres.length===0)return this;let Y=[],U=Z.buildWhereClauses(Y);if(!U)return this;return this._wheres.push({raw:`(${U})`,rawParams:Y,boolean:X}),this}whereBetween(X,$){return C9(X,"whereBetween(column)"),this._wheres.push({column:X,operator:">=",value:$[0],boolean:"and"}),this._wheres.push({column:X,operator:"<=",value:$[1],boolean:"and"}),this}whereNotBetween(X,$){C9(X,"whereNotBetween(column)");let Z=X;return this._wheres.push({raw:`(${Z} < ? OR ${Z} > ?)`,rawParams:[$[0],$[1]],boolean:"and"}),this}when(X,$){if(X)return $(this);return this}orderBy(X,$="asc"){if(_7(X,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}orderByAsc(X){return this.orderBy(X,"asc")}limit(X){return this._limit=X,this}take(X){return this.limit(X)}offset(X){return this._offset=X,this}skip(X){return this.offset(X)}select(...X){return this._select=X,this}with(...X){return this._withRelations=X,this}getWithRelations(){return this._withRelations}buildWhereClauses(X){let $=[];for(let Z=0;Z<this._wheres.length;Z++){let Y=this._wheres[Z],U;if(Y.raw){if(U=Y.raw,Y.rawParams&&Y.rawParams.length>0)X.push(...Y.rawParams)}else if(Y.value===null)U=Y.operator==="="?`${Y.column} IS NULL`:`${Y.column} IS NOT NULL`;else if(Y.operator==="in"||Y.operator==="not in"){let _=Y.value;U=`${Y.column} ${Y.operator.toUpperCase()} (${_.map(()=>"?").join(", ")})`,X.push(..._)}else U=`${Y.column} ${Y.operator} ?`,X.push(Y.value);$.push(Z===0?U:`${Y.boolean.toUpperCase()} ${U}`)}return $.join(" ")}softDeleteClause(){if(this._trashed==="include"||!vX(this._definition))return"";return this._trashed==="only"?`${v9} IS NOT NULL`:`${v9} IS NULL`}composeWhere(X){let $=this._wheres.length>0?this.buildWhereClauses(X):"",Z=this.softDeleteClause();if($&&Z)return`(${$}) AND ${Z}`;return $||Z}buildQuery(){let X=[],$=`SELECT ${this._select.join(", ")} FROM ${this._definition.table}`,Z=this.composeWhere(X);if(Z)$+=` WHERE ${Z}`;if(this._orderBy.length>0)$+=` ORDER BY ${this._orderBy.map((Y)=>`${Y.column} ${Y.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)$+=` LIMIT ${this._limit}`;if(this._offset!==void 0)$+=` OFFSET ${this._offset}`;return{sql:$,params:X}}toSql(){return this.buildQuery()}async eagerLoadRelations(X){if(X.length===0||this._withRelations.length===0)return;let $=I0(),Z=this._definition.primaryKey||"id";for(let Y of this._withRelations){let U=`${this._definition.name}:${Y}`,_=X$.get(U);if(_===void 0){if(_=j7(this._definition,Y),X$.size>=pL)X$.clear();X$.set(U,_)}if(!_)continue;if(_.type==="hasMany"||_.type==="hasOne"){let Q=X.map((V)=>V.get(Z)).filter((V)=>V!=null);if(Q.length===0)continue;let L=Q.map(()=>"?").join(", "),z=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.foreignKey} IN (${L})`,Q),j=U9(_.relatedModelName),E=j?.getDefinition?.()||j?.definition||this._definition;if(_.type==="hasMany"){let V=new Map;for(let G of z){let J=G[_.foreignKey];if(!V.has(J))V.set(J,[]);V.get(J).push(G)}for(let G of X){let J=V.get(G.get(Z))||[];G.setRelation(Y,J.map((W)=>new t0(E,W)))}}else{let V=new Map;for(let G of z)V.set(G[_.foreignKey],G);for(let G of X){let J=V.get(G.get(Z));G.setRelation(Y,J?new t0(E,J):null)}}}if(_.type==="belongsTo"){let Q=new Set;for(let J of X){let W=J._attributes[_.foreignKey];if(W!=null)Q.add(W)}let L=[...Q];if(L.length===0)continue;let z=L.map(()=>"?").join(", "),j=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.localKey} IN (${z})`,L),E=U9(_.relatedModelName),V=E?.getDefinition?.()||E?.definition||this._definition,G=new Map;for(let J of j)G.set(J[_.localKey],J);for(let J of X){let W=J._attributes[_.foreignKey],F=G.get(W);J.setRelation(Y,F?new t0(V,F):null)}}if(_.type==="belongsToMany"){let Q=X.map((w)=>w.get(Z)).filter((w)=>w!=null);if(Q.length===0)continue;if(!_.pivotTable||!_.pivotFkParent||!_.pivotFkRelated)continue;let L=Q.map(()=>"?").join(", "),z=await $.all(`SELECT * FROM ${_.pivotTable} WHERE ${_.pivotFkParent} IN (${L})`,Q);if(z.length===0){for(let w of X)w.setRelation(Y,[]);continue}let j=new Set;for(let w of z){let T=w[_.pivotFkRelated];if(T!=null)j.add(T)}let E=[...j],V=U9(_.relatedModelName),G=V?.getDefinition?.()||V?.definition||this._definition,J=G?.primaryKey||"id",W=[];if(E.length>0){let w=E.map(()=>"?").join(", ");W=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${J} IN (${w})`,E)}let F=new Map;for(let w of W)F.set(w[J],w);let K=new Map;for(let w of z){let T=w[_.pivotFkParent];if(!K.has(T))K.set(T,[]);K.get(T).push(w)}let D=new Set([_.pivotFkParent,_.pivotFkRelated]);for(let w of X){let T=w.get(Z),q=(K.get(T)||[]).map((H)=>{let x=F.get(H[_.pivotFkRelated]);if(!x)return null;let h=new t0(G,x),c={};for(let[y,g]of Object.entries(H))if(!D.has(y))c[y]=g;return h.pivot=c,h}).filter((H)=>H!==null);w.setRelation(Y,q)}}if(_.type==="hasManyThrough"||_.type==="hasOneThrough"){let Q=X.map((D)=>D.get(Z)).filter((D)=>D!=null);if(Q.length===0)continue;let L=_.throughLocalKey||"id",z=Q.map(()=>"?").join(", "),j=await $.all(`SELECT ${L}, ${_.throughForeignKey} FROM ${_.throughTable} WHERE ${_.throughForeignKey} IN (${z})`,Q);if(j.length===0){for(let D of X)D.setRelation(Y,_.type==="hasManyThrough"?[]:null);continue}let E=new Map;for(let D of j)E.set(D[L],D[_.throughForeignKey]);let V=[...new Set(j.map((D)=>D[L]))],G=V.map(()=>"?").join(", "),J=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.targetForeignKey} IN (${G})`,V),W=U9(_.relatedModelName),F=W?.getDefinition?.()||W?.definition||this._definition,K=new Map;for(let D of J){let w=E.get(D[_.targetForeignKey]);if(w==null)continue;if(!K.has(w))K.set(w,[]);K.get(w).push(new t0(F,D))}for(let D of X){let w=K.get(D.get(Z))||[];D.setRelation(Y,_.type==="hasManyThrough"?w:w[0]??null)}}}}async get(){let X=I0(),{sql:$,params:Z}=this.buildQuery(),U=(await X.all($,Z)).map((_)=>new t0(this._definition,_));if(this._withRelations.length>0)await this.eagerLoadRelations(U);return U}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let X=await this.first();if(!X)throw Error(`No ${this._definition.name} found`);return X}async last(){let X=this._definition.primaryKey||"id";return this._orderBy=[{column:X,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let X=I0(),$=[],Z=`SELECT COUNT(*) as count FROM ${this._definition.table}`,Y=this.composeWhere($);if(Y)Z+=` WHERE ${Y}`;let U=await X.get(Z,$);return Number(U?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let X=await this.get();if(X.length===0)throw Error(`No ${this._definition.name} found`);if(X.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return X[0]}async increment(X,$=1){C9(X,"increment(column)");let Z=I0(),Y=[$],U=`UPDATE ${this._definition.table} SET ${X} = ${X} + ?`;if(a9(this._definition))U+=", updated_at = ?",Y.push(r9());if(this._wheres.length>0){let _=this.buildWhereClauses(Y);U+=` WHERE ${_}`}return(await Z.run(U,Y)).changes}decrement(X,$=1){return this.increment(X,-$)}async chunk(X,$){let Z=0;while(!0){let Y=new Y0(this._definition);Y._wheres=[...this._wheres],Y._orderBy=[...this._orderBy],Y._select=[...this._select],Y._withRelations=[...this._withRelations],Y._trashed=this._trashed,Y._limit=X,Y._offset=Z*X;let U=await Y.get();if(U.length===0)break;if(await $(U)===!1)break;if(U.length<X)break;Z++}}async paginate(X=1,$=15){let Z=await this.count(),Y=Math.ceil(Z/$);this._limit=$,this._offset=(X-1)*$;let U=await this.get();return{data:U,total:Z,page:X,perPage:$,lastPage:Y,hasMorePages:X<Y,isEmpty:U.length===0,from:U.length>0?(X-1)*$+1:null,to:U.length>0?(X-1)*$+U.length:null}}async pluck(X){C9(X,"pluck(column)");let $=I0(),Z=[],Y=`SELECT ${X} FROM ${this._definition.table}`,U=this.composeWhere(Z);if(U)Y+=` WHERE ${U}`;if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.map((Q)=>`${Q.column} ${Q.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return(await $.all(Y,Z)).map((Q)=>Q[X])}async aggregate(X,$){C9($,`${X}(column)`);let Z=I0(),Y=[],U=`SELECT ${X}(${$}) as v FROM ${this._definition.table}`,_=this.composeWhere(Y);if(_)U+=` WHERE ${_}`;let L=(await Z.get(U,Y))?.v;if(L==null)return null;if(typeof L==="string"){let z=Number(L);return L.trim()!==""&&!Number.isNaN(z)?z:L}return L}max(X){return this.aggregate("MAX",X)}min(X){return this.aggregate("MIN",X)}async avg(X){return Number(await this.aggregate("AVG",X)??0)||0}async sum(X){return Number(await this.aggregate("SUM",X)??0)||0}async delete(){let X=I0(),$=[],Z=`DELETE FROM ${this._definition.table}`;if(this._wheres.length>0)Z+=` WHERE ${this.buildWhereClauses($)}`;return(await X.run(Z,$)).changes}async update(X){let $=I0(),Z=Object.entries(X),Y=Z.map(([Q])=>`${Q} = ?`).join(", "),U=Z.map(([,Q])=>Q);if(a9(this._definition))U.push(r9());let _=`UPDATE ${this._definition.table} SET ${Y}${a9(this._definition)?", updated_at = ?":""}`;if(this._wheres.length>0)_+=` WHERE ${this.buildWhereClauses(U)}`;return(await $.run(_,U)).changes}}function bL(X){let $={query:()=>new Y0(X),where(Z,Y,U){return new Y0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new Y0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new Y0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new Y0(X).whereNotIn(Z,Y)},whereNull(Z){return new Y0(X).whereNull(Z)},whereNotNull(Z){return new Y0(X).whereNotNull(Z)},whereLike(Z,Y){return new Y0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new Y0(X).orderBy(Z,Y)},orderByDesc(Z){return new Y0(X).orderByDesc(Z)},select(...Z){return new Y0(X).select(...Z)},with(...Z){return new Y0(X).with(...Z)},limit:(Z)=>new Y0(X).limit(Z),take:(Z)=>new Y0(X).take(Z),skip:(Z)=>new Y0(X).skip(Z),withTrashed:()=>new Y0(X).withTrashed(),onlyTrashed:()=>new Y0(X).onlyTrashed(),async find(Z){let Y=I0(),U=X.primaryKey||"id",_=vX(X)?` AND ${v9} IS NULL`:"",Q=await Y.get(`SELECT * FROM ${X.table} WHERE ${U} = ?${_}`,[Z]);return Q?new t0(X,Q):void 0},async findOrFail(Z){let Y=await $.find(Z);if(!Y)throw Error(`${X.name} with id ${Z} not found`);return Y},async findMany(Z){let Y=I0(),U=X.primaryKey||"id",_=vX(X)?` AND ${v9} IS NULL`:"";return(await Y.all(`SELECT * FROM ${X.table} WHERE ${U} IN (${Z.map(()=>"?").join(", ")})${_}`,Z)).map((L)=>new t0(X,L))},all:()=>new Y0(X).get(),first:()=>new Y0(X).first(),firstOrFail:()=>new Y0(X).firstOrFail(),last:()=>new Y0(X).last(),count:()=>new Y0(X).count(),exists:()=>new Y0(X).exists(),doesntExist:()=>new Y0(X).doesntExist(),paginate:(Z,Y)=>new Y0(X).paginate(Z,Y),whereBetween(Z,Y){return new Y0(X).whereBetween(Z,Y)},whereNotBetween(Z,Y){return new Y0(X).whereNotBetween(Z,Y)},async create(Z){let Y=new t0(X,Z);return await Y.save(),Y},async createMany(Z){let Y=[];for(let U of Z)Y.push(await this.create(U));return Y},async updateOrCreate(Z,Y){let U=new Y0(X);for(let[Q,L]of Object.entries(Z))U=U.where(Q,L);let _=await U.first();if(_)return await _.update(Y),_;return this.create({...Z,...Y})},async firstOrCreate(Z,Y){let U=new Y0(X);for(let[Q,L]of Object.entries(Z))U=U.where(Q,L);return await U.first()||this.create({...Z,...Y})},async destroy(Z){let Y=I0(),U=X.primaryKey||"id";return(await Y.run(`DELETE FROM ${X.table} WHERE ${U} = ?`,[Z])).changes>0},remove(Z){return this.destroy(Z)},async truncate(){await I0().run(`DELETE FROM ${X.table}`,[])},getDefinition:()=>X,getTable:()=>X.table,make(Z={}){return new t0(X,Z)},latest:(Z="created_at")=>new Y0(X).orderByDesc(Z),oldest:(Z="created_at")=>new Y0(X).orderBy(Z,"asc"),max:(Z)=>new Y0(X).max(Z),min:(Z)=>new Y0(X).min(Z),avg:(Z)=>new Y0(X).avg(Z),sum:(Z)=>new Y0(X).sum(Z),pluck(Z){return new Y0(X).pluck(Z)}};return new Proxy($,{get(Z,Y){if(typeof Y==="string"&&Y.startsWith("where")&&Y.length>5){let U=Y.slice(5),_=U.charAt(0).toLowerCase()+U.slice(1);if(_ in X.attributes||_==="id"||_===X.primaryKey)return(Q)=>new Y0(X).where(_,Q)}return Reflect.get(Z,Y)}})}function fL(X){return bL(X)}async function QO(X){let $=I0(),Z=X.primaryKey||"id",Y=[];if(Y.push(X.autoIncrement!==!1?`${Z} INTEGER PRIMARY KEY AUTOINCREMENT`:`${Z} INTEGER PRIMARY KEY`),X.traits?.useUuid)Y.push("uuid TEXT UNIQUE");for(let[U,_]of Object.entries(X.attributes)){let Q="TEXT";if(_.type==="number")Q="INTEGER";else if(_.type==="boolean")Q="INTEGER";if(U.endsWith("_id"))Q="INTEGER";let L=`${U} ${Q}`;if(_.unique)L+=" UNIQUE";if(typeof _.foreignKey==="object"&&_.foreignKey!==null){let z=_.foreignKey;if(L+=` REFERENCES ${z.table}(${z.column??"id"})`,z.onDelete)L+=` ON DELETE ${z.onDelete.toUpperCase()}`;if(z.onUpdate)L+=` ON UPDATE ${z.onUpdate.toUpperCase()}`}Y.push(L)}if(a9(X))Y.push("created_at TEXT","updated_at TEXT");if(vX(X))Y.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${X.table} (${Y.join(", ")})`,[])}function gL(X){return new Proxy(X,{get($,Z){if(Z==="location")return $.address;if(Z==="datatype"){let{random:Y,number:U,string:_}=$;return{boolean:()=>Y?.boolean?.(),number:(Q)=>U?.int?.(Q),float:(Q)=>U?.float?.(Q),uuid:()=>crypto.randomUUID(),string:(Q)=>_?.alphanumeric?.(Q??10)}}return $[Z]}})}async function zO(X,$,Z){let Y=I0(),U=X.traits?.useSeeder,_=$??(typeof U==="object"&&U?U.count:10);if(!Z)try{let Q=await Promise.resolve().then(()=>(BL(),U7));Z=gL(Q.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let Q=0;Q<_;Q++){let L={};for(let[j,E]of Object.entries(X.attributes))if(E.factory)L[j]=E.factory(Z);if(a9(X)){let j=r9();L.created_at=j,L.updated_at=j}if(X.traits?.useUuid)L.uuid=crypto.randomUUID();let z=Object.keys(L);await Y.run(`INSERT INTO ${X.table} (${z.join(", ")}) VALUES (${z.map(()=>"?").join(", ")})`,Object.values(L))}}var E5,L8=null,tX,dL=500,o9=null,q9=null,eX=null,z1=null,L1=null,v9="deleted_at",j1="__btm_rel__",g1,d1,p1,X$,pL=1000,G7=e(()=>{d0(),$X(),e1(),E5=/^[A-Z_][A-Z0-9_]*$/i,tX=new Map,g1=new WeakMap,d1=new Map,p1=new Map,X$=new Map}),F7={};n1(F7,{registerModel:()=>EZ,registerBrowserModels:()=>sL,hasModel:()=>nL,getModelRegistry:()=>uL,getModel:()=>cL,getAllModels:()=>mL,defineModel:()=>G5,clearModelRegistry:()=>iL});function cL(X){return YX.get(X)}function mL(){return[...YX.values()]}function uL(){return Object.fromEntries(YX)}function nL(X){return YX.has(X)}function iL(){YX.clear()}function EZ(X,$){return YX.set(X,$),$}function lL(){return typeof window<"u"&&typeof document<"u"}function G5(X){let $;if(lL())$=n7(X);else{let Z=fL(X);$=Object.assign(Z,{definition:X,getDefinition:()=>X,getTable:()=>X.table,getName:()=>X.name})}return EZ(X.name,$),$}function sL(X){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...X}}var YX,P8=e(()=>{M6(),G7(),YX=new Map});class gX{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(X){this.driver=bX(X.config),this.client=X.client,this.tableName=X.config.tableName??""}table(X){return this.tableName=X,this}index(X){return this.indexName=X,this}entity(X){return this.entityType=X,this}whereKey(X,$,Z){return this.keyConditions.push({attribute:X,operator:$,value:Z}),this}wherePartitionKey(X,$){return this.whereKey(X,"=",$)}whereSortKey(X,$){return this.whereKey(X,"=",$)}whereSortKeyBeginsWith(X,$){return this.keyConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereSortKeyBetween(X,$,Z){return this.keyConditions.push({attribute:X,operator:"BETWEEN",values:[$,Z]}),this}where(X,$,Z){return this.filterConditions.push({attribute:X,operator:$,value:Z}),this}whereEquals(X,$){return this.where(X,"=",$)}whereLessThan(X,$){return this.where(X,"<",$)}whereLessThanOrEqual(X,$){return this.where(X,"<=",$)}whereGreaterThan(X,$){return this.where(X,">",$)}whereGreaterThanOrEqual(X,$){return this.where(X,">=",$)}whereBetween(X,$,Z){return this.filterConditions.push({attribute:X,operator:"BETWEEN",values:[$,Z]}),this}whereBeginsWith(X,$){return this.filterConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereContains(X,$){return this.where(X,"contains",$)}whereExists(X){return this.where(X,"attribute_exists")}whereNotExists(X){return this.where(X,"attribute_not_exists")}whereIn(X,$){return this.filterConditions.push({attribute:X,operator:"IN",values:$}),this}select(...X){return this.projectionAttrs.push(...X),this}limit(X){return this.limitValue=X,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(X=!0){return this.consistentReadValue=X,this}startFrom(X){return this.startKey=X,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let X=this.buildQueryParams(),$={TableName:X.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(X.indexName)$.IndexName=X.indexName;let Z=0;if(X.keyConditions.length>0){let Y=[];for(let U of X.keyConditions){let _=`#key${Z}`;if($.ExpressionAttributeNames[_]=U.attribute,U.operator==="begins_with"){let Q=`:keyval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`begins_with(${_}, ${Q})`)}else if(U.operator==="BETWEEN"){let Q=`:keyval${Z}a`,L=`:keyval${Z}b`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.values?.[0]}).v,$.ExpressionAttributeValues[L]=this.driver.marshall({v:U.values?.[1]}).v,Y.push(`${_} BETWEEN ${Q} AND ${L}`)}else{let Q=`:keyval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${_} ${U.operator} ${Q}`)}Z++}$.KeyConditionExpression=Y.join(" AND ")}if(X.filterConditions&&X.filterConditions.length>0){let Y=[];for(let U of X.filterConditions){let _=`#flt${Z}`;if($.ExpressionAttributeNames[_]=U.attribute,U.operator==="attribute_exists")Y.push(`attribute_exists(${_})`);else if(U.operator==="attribute_not_exists")Y.push(`attribute_not_exists(${_})`);else if(U.operator==="begins_with"||U.operator==="contains"){let Q=`:fltval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${U.operator}(${_}, ${Q})`)}else if(U.operator==="BETWEEN"){let Q=`:fltval${Z}a`,L=`:fltval${Z}b`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.values?.[0]}).v,$.ExpressionAttributeValues[L]=this.driver.marshall({v:U.values?.[1]}).v,Y.push(`${_} BETWEEN ${Q} AND ${L}`)}else if(U.operator==="IN"){let Q=(U.values??[]).map((L,z)=>`:fltval${Z}_${z}`);U.values?.forEach((L,z)=>{$.ExpressionAttributeValues[`:fltval${Z}_${z}`]=this.driver.marshall({v:L}).v}),Y.push(`${_} IN (${Q.join(", ")})`)}else{let Q=`:fltval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${_} ${U.operator} ${Q}`)}Z++}$.FilterExpression=Y.join(" AND ")}if(X.projectionAttributes&&X.projectionAttributes.length>0){let Y=[];for(let U of X.projectionAttributes){let _=`#proj${Z}`;$.ExpressionAttributeNames[_]=U,Y.push(_),Z++}$.ProjectionExpression=Y.join(", ")}if(X.limit!==void 0)$.Limit=X.limit;if(X.scanIndexForward!==void 0)$.ScanIndexForward=X.scanIndexForward;if(X.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(X.exclusiveStartKey);if(X.consistentRead)$.ConsistentRead=X.consistentRead;if(Object.keys($.ExpressionAttributeNames).length===0)delete $.ExpressionAttributeNames;if(Object.keys($.ExpressionAttributeValues).length===0)delete $.ExpressionAttributeValues;return $}toScanRequest(){let X=this.buildScanParams(),$={TableName:X.tableName};if(X.indexName)$.IndexName=X.indexName;if(X.filterConditions&&X.filterConditions.length>0){let{expression:Z,expressionAttributeNames:Y,expressionAttributeValues:U}=this.driver.buildFilterExpression(X.filterConditions);$.FilterExpression=Z,$.ExpressionAttributeNames=Y,$.ExpressionAttributeValues=U}if(X.projectionAttributes&&X.projectionAttributes.length>0){let{expression:Z,expressionAttributeNames:Y}=this.driver.buildProjectionExpression(X.projectionAttributes);$.ProjectionExpression=Z,$.ExpressionAttributeNames={...$.ExpressionAttributeNames,...Y}}if(X.limit!==void 0)$.Limit=X.limit;if(X.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(X.exclusiveStartKey);if(X.consistentRead)$.ConsistentRead=X.consistentRead;return $}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let X=this.toQueryRequest(),$=await this.client.query(X);return{items:$.Items?.map((Z)=>this.driver.unmarshall(Z)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let X=this.toScanRequest(),$=await this.client.scan(X);return{items:$.Items?.map((Z)=>this.driver.unmarshall(Z)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async getAll(){let X=[],$;do{if($)this.startFrom($);let Z=this.keyConditions.length>0?await this.query():await this.scan();if(Z.items)X.push(...Z.items);$=Z.lastEvaluatedKey}while($);return X}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return X.Select="COUNT",(this.keyConditions.length>0?await this.client.query(X):await this.client.scan(X)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class b9{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(X){this.driver=bX(X.config),this.client=X.client,this.tableName=X.config.tableName??""}table(X){return this.tableName=X,this}key(X){return this.keyData=X,this}item(X){return this.itemData=X,this}set(X,$){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[X]=$,this}setMany(X){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,X),this}remove(X){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(X),this}add(X,$){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[X]=$,this}deleteFromSet(X,$){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[X]=$,this}condition(X){return this.conditionExpr=X,this}ifNotExists(X="pk"){return this.conditionExpr=`attribute_not_exists(${X})`,this}ifExists(X="pk"){return this.conditionExpr=`attribute_exists(${X})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let X={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toUpdateRequest(){let X={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:$,expressionAttributeNames:Z,expressionAttributeValues:Y}=this.driver.buildUpdateExpression(this.updateExpressions);if($)X.UpdateExpression=$,X.ExpressionAttributeNames=Z,X.ExpressionAttributeValues=Y;if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toDeleteRequest(){let X={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toPutRequest(),$=await this.client.putItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toUpdateRequest(),$=await this.client.updateItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toDeleteRequest(),$=await this.client.deleteItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toGetRequest(),$=await this.client.getItem(X);if($.Item)return this.driver.unmarshall($.Item);return}}function LO(X){return new gX(X)}function jO(X){return new b9(X)}function EO(X){let $=bX(X.config);return{query:()=>new gX(X),item:()=>new b9(X),driver:$,registerEntity:(Z)=>$.registerEntity(Z),buildKey:(Z,Y)=>$.buildPrimaryKey(Z,Y)}}var F5=()=>{};class O7{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(X){this.config=X,this.pkAttribute=X.pkAttribute??"pk",this.skAttribute=X.skAttribute??"sk",this.typeAttribute=X.typeAttribute??"_type";for(let $ of X.entities)this.entities.set($.name,$)}getEntity(X){return this.entities.get(X)}registerEntity(X){this.entities.set(X.name,X)}buildKey(X,$){let Z=this.entities.get(X);if(!Z)throw Error(`Entity not found: ${X}`);let Y=this.interpolatePattern(Z.pkPattern,$),U=this.interpolatePattern(Z.skPattern,$);return{pk:Y,sk:U}}buildGSIKey(X,$,Z){let Y=this.entities.get(X);if(!Y)throw Error(`Entity not found: ${X}`);let U=Y.indexes?.find((L)=>L.name===$);if(!U)throw Error(`GSI not found: ${$} for entity ${X}`);let _=this.interpolatePattern(U.pkPattern,Z),Q=U.skPattern?this.interpolatePattern(U.skPattern,Z):void 0;return{pk:_,sk:Q}}createItem(X,$){let{pk:Z,sk:Y}=this.buildKey(X,$),U=this.entities.get(X),_={[this.pkAttribute]:Z,[this.skAttribute]:Y,[this.typeAttribute]:X,...$};if(U.indexes)for(let Q of U.indexes){let L=this.buildGSIKey(X,Q.name,$),z=this.config.indexes?.find((j)=>j.name===Q.name);if(z){if(_[z.pkAttribute]=L.pk,z.skAttribute&&L.sk)_[z.skAttribute]=L.sk}}return _}parseEntityType(X){if(X[this.typeAttribute])return X[this.typeAttribute];let $=X[this.pkAttribute];if(!$)return;for(let[Z,Y]of this.entities){let U=Y.pkPattern.split("${")[0];if($.startsWith(U))return Z}return}parseItem(X){let $=this.parseEntityType(X);if(!$)return;let{[this.pkAttribute]:Z,[this.skAttribute]:Y,[this.typeAttribute]:U,..._}=X;return{type:$,data:_}}getEntityPrefix(X){let $=this.entities.get(X);if(!$)throw Error(`Entity not found: ${X}`);return $.pkPattern.split("${")[0]}generateTableDefinition(){let X=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],$=[];if(this.config.indexes)for(let Z of this.config.indexes){if(!X.find((Y)=>Y.name===Z.pkAttribute))X.push({name:Z.pkAttribute,type:"S"});if(Z.skAttribute&&!X.find((Y)=>Y.name===Z.skAttribute))X.push({name:Z.skAttribute,type:"S"});$.push({indexName:Z.name,keySchema:{partitionKey:Z.pkAttribute,sortKey:Z.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:X,globalSecondaryIndexes:$.length>0?$:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(X,$){return X.replace(/\$\{(\w+)\}/g,(Z,Y)=>{if(!(Y in $))throw Error(`Missing value for pattern key: ${Y}`);return String($[Y])})}}class J7{manager;entityName;options;constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z}async create(X){let $=this.manager.createItem(this.entityName,X),Z=new b9(this.options).table(this.options.config.tableName).item($).ifNotExists("pk");if(this.options.client)await Z.put();return X}async get(X){let{pk:$,sk:Z}=this.manager.buildKey(this.entityName,X),Y=new b9(this.options).table(this.options.config.tableName).key({pk:$,sk:Z});if(!this.options.client)throw Error("DynamoDB client not provided");let U=await Y.get();if(!U)return;return this.manager.parseItem(U)?.data}async update(X,$){let{pk:Z,sk:Y}=this.manager.buildKey(this.entityName,X),U=new b9(this.options).table(this.options.config.tableName).key({pk:Z,sk:Y}).setMany($).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let _=await U.update();if(!_)return;return this.manager.parseItem(_)?.data}async delete(X){let{pk:$,sk:Z}=this.manager.buildKey(this.entityName,X),Y=new b9(this.options).table(this.options.config.tableName).key({pk:$,sk:Z});if(!this.options.client)throw Error("DynamoDB client not provided");return await Y.delete(),!0}query(){return new W7(this.manager,this.entityName,this.options)}async findAll(){let X=this.manager.typeAttribute??"_type",$=new gX(this.options).table(this.options.config.tableName).whereEquals(X,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await $.getAll()).map((Y)=>this.manager.parseItem(Y)).filter((Y)=>Y!==void 0).map((Y)=>Y.data)}}class W7{manager;entityName;options;builder;pkValue;skConditions=[];constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z,this.builder=new gX(Z).table(Z.config.tableName)}wherePartitionKey(X){let{pk:$}=this.manager.buildKey(this.entityName,X);this.pkValue=$;let Z=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(Z,$),this}whereSortKey(X){let{sk:$}=this.manager.buildKey(this.entityName,X),Z=this.manager.skAttribute??"sk";return this.builder.whereSortKey(Z,$),this}whereSortKeyBeginsWith(X){let $=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith($,X),this}useIndex(X,$){let Z=this.manager.buildGSIKey(this.entityName,X,$),Y=this.manager.config.indexes?.find((U)=>U.name===X);if(!Y)throw Error(`GSI configuration not found: ${X}`);return this.builder.index(X),this.builder.wherePartitionKey(Y.pkAttribute,Z.pk),this}where(X,$,Z){return this.builder.where(X,$,Z),this}select(...X){return this.builder.select(...X),this}limit(X){return this.builder.limit(X),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map(($)=>this.manager.parseItem($)).filter(($)=>$!==void 0).map(($)=>$.data)}async first(){return this.limit(1),(await this.execute())[0]}}function oL(X){return new O7(X)}function rL(X,$,Z){return new J7(X,$,Z)}var aL,V7=e(()=>{F5(),aL={simpleEntity:(X,$="id")=>({name:X,pkPattern:`${X.toUpperCase()}#\${${$}}`,skPattern:"METADATA",keyFields:[$]}),oneToMany:(X,$,Z="id",Y="id")=>({parent:{name:X,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]},child:{name:$,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`,keyFields:[Z,Y]}}),manyToMany:(X,$,Z="id",Y="relatedId")=>({entity:{name:X,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]},relation:{name:$,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`,keyFields:[Z,Y],indexes:[{name:"GSI1",pkPattern:`${X.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${Z}}`}]}}),hierarchical:(X,$="rootId",Z="path")=>({name:X,pkPattern:`ROOT#\${${$}}`,skPattern:`PATH#\${${Z}}`,keyFields:[$,Z]})}});function F6(X,$){let Z={};for(let[Y,U]of Object.entries(X))if(U)Z[Y]=U.replace(/\{([^}]+)\}/g,(_,Q)=>{return $[Q]!==void 0?String($[Q]):`{${Q}}`});return Z}async function tL(X){return{models:new Map}}function GO(X){return X}function FO(X){return X}function OO(X){return X}function JO(X){return X}class I7{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(X){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...X};let $={region:X.region,endpoint:X.endpoint,credentials:X.credentials,tableName:X.tableName};this.driver=bX($);let Z={tableName:X.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=oL(Z),this.queryBuilderOptions={config:$}}setClient(X){return this.queryBuilderOptions.client=X,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let X=await tL({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),$=[];for(let[,Z]of X.models)this.registerParsedModel(Z),$.push(Z);return $}registerModel(X){let $=this.parseWithTooling(X);return this.registerParsedModel($)}registerParsedModel(X){this.models.set(X.name,X);let $=this.toSingleTableEntity(X);this.singleTableManager.registerEntity($);let Z=this.toEntityMapping(X);return this.driver.registerEntity(Z),X}registerModels(X){return X.map(($)=>this.registerModel($))}getModel(X){return this.models.get(X)}getAllModels(){return Array.from(this.models.values())}repository(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return rL(this.singleTableManager,X,this.queryBuilderOptions)}query(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new gX(this.queryBuilderOptions).table(this.config.tableName).entity(X)}item(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new b9(this.queryBuilderOptions).table(this.config.tableName)}buildKey(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=F6(Z.keyPatterns,$);return{pk:Y.pk,sk:Y.sk}}createItem(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=F6(Z.keyPatterns,$),U=Y.pk,_=Y.sk,Q={[this.config.pkAttribute]:U,[this.config.skAttribute]:_,[this.config.entityTypeAttribute]:Z.name,...$};if(Z.hasTimestamps){let L=new Date().toISOString();if(!Q.createdAt)Q.createdAt=L;Q.updatedAt=L}if(Z.hasVersioning){if(!Q._v)Q._v=1}return Q}parseItem(X){let $=X[this.config.entityTypeAttribute];if(!$)return;let{[this.config.pkAttribute]:Z,[this.config.skAttribute]:Y,[this.config.entityTypeAttribute]:U,..._}=X;return{type:$,data:_}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(X){let $=this.models.get(X);if(!$)throw Error(`Model not found: ${X}`);return $.accessPatterns}parseWithTooling(X){let $=X.name.toUpperCase(),Z=X.primaryKey??"id",Y=this.config.keyDelimiter,U=this.parseAttributes(X),_=this.parseRelationships(X,Z),Q={pk:`${$}${Y}{${Z}}`,sk:`${$}${Y}{${Z}}`,...this.deriveGSIKeyPatterns($,Z,Y,_)},L=this.deriveAccessPatterns(X.name,$,Z,_);return{name:X.name,entityType:$,primaryKey:Z,attributes:U,relationships:_,keyPatterns:Q,accessPatterns:L,traits:X.traits??{},hasTimestamps:X.traits?.useTimestamps??!1,hasSoftDeletes:X.traits?.useSoftDeletes??!1,hasUuid:X.traits?.useUuid??!1,hasTtl:X.traits?.useTtl??!1,hasVersioning:X.traits?.useVersioning??!1,original:X}}parseAttributes(X){let $=[];if($.push({name:X.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),X.attributes)for(let[Z,Y]of Object.entries(X.attributes))$.push({name:Z,fillable:Y.fillable??!0,required:Y.required??!1,nullable:Y.nullable??!0,unique:Y.unique??!1,hidden:Y.hidden??!1,defaultValue:Y.default,cast:Y.cast,dynamoDbType:this.inferDynamoDBType(Y)});if(X.traits?.useTimestamps)$.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(X.traits?.useSoftDeletes)$.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return $}inferDynamoDBType(X){if(X.cast){let $=X.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes($))return"N";if(["boolean","bool"].includes($))return"BOOL";if(["array","list"].includes($))return"L";if(["object","json","map"].includes($))return"M"}if(X.validation?.rule){let $=String(X.validation.rule);if($.includes("integer")||$.includes("numeric")||$.includes("number"))return"N";if($.includes("boolean"))return"BOOL";if($.includes("array"))return"L";if($.includes("object"))return"M"}return"S"}parseRelationships(X,$){let Z=[];if(X.hasOne)for(let Y of X.hasOne)Z.push({type:"hasOne",relatedModel:Y,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(X.hasMany)for(let Y of X.hasMany)Z.push({type:"hasMany",relatedModel:Y,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,requiresGsi:!1});if(X.belongsTo)for(let Y of X.belongsTo)Z.push({type:"belongsTo",relatedModel:Y,foreignKey:`${Y.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(X.belongsToMany){let Y=Array.isArray(X.belongsToMany)?X.belongsToMany:Object.values(X.belongsToMany);for(let U of Y){let _=typeof U==="string"?U:U?.model;if(!_)continue;let Q=[X.name,_].sort();Z.push({type:"belongsToMany",relatedModel:_,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,pivotEntity:Q.join(""),requiresGsi:!0})}}return Z}deriveGSIKeyPatterns(X,$,Z,Y){let U={},_=1;for(let Q of Y)if(Q.requiresGsi&&_<=5)U[`gsi${_}pk`]=`${Q.relatedModel.toUpperCase()}${Z}{${Q.foreignKey}}`,U[`gsi${_}sk`]=`${X}${Z}{${$}}`,Q.gsiIndex=_,_++;return U}deriveAccessPatterns(X,$,Z,Y){let U=[];U.push({name:`Get ${X} by ID`,description:`Retrieve a single ${X} by its primary key`,entityType:$,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${$}#123`,exampleSk:`${$}#123`,efficient:!0}),U.push({name:`List all ${X}s`,description:`Scan all ${X} entities`,entityType:$,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:$,efficient:!1});for(let _ of Y){if(_.type==="hasMany")U.push({name:`Get ${_.relatedModel}s for ${X}`,description:`Query ${_.relatedModel}s related to a ${X}`,entityType:$,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${$}#123`,exampleSk:`${_.relatedModel.toUpperCase()}#`,efficient:!0});if(_.gsiIndex){let Q=`GSI${_.gsiIndex}`;U.push({name:`Get ${X}s by ${_.relatedModel}`,description:`Query ${X}s by their related ${_.relatedModel}`,entityType:$,operation:"query",index:Q,keyCondition:`gsi${_.gsiIndex}pk = :pk`,examplePk:`${_.relatedModel.toUpperCase()}#123`,efficient:!0})}}return U}toSingleTableEntity(X){let $=this.extractKeyFields(X.keyPatterns.pk);return{name:X.name,pkPattern:X.keyPatterns.pk,skPattern:X.keyPatterns.sk,keyFields:$,indexes:this.extractGSIPatterns(X.keyPatterns)}}extractKeyFields(X){let $=X.match(/\{([^}]+)\}/g);if(!$)return[];return $.map((Z)=>Z.slice(1,-1))}extractGSIPatterns(X){let $=[];for(let Z=1;Z<=5;Z++){let Y=`gsi${Z}pk`,U=`gsi${Z}sk`;if(X[Y])$.push({name:`GSI${Z}`,pkPattern:X[Y],skPattern:X[U]})}return $.length>0?$:void 0}toEntityMapping(X){return{entityType:X.name,pkPattern:X.keyPatterns.pk,skPattern:X.keyPatterns.sk}}buildGSIConfig(){let X=this.config.gsiConfig??{},$=[];if(X.gsi1pk)$.push({name:"GSI1",pkAttribute:X.gsi1pk,skAttribute:X.gsi1sk});if(X.gsi2pk)$.push({name:"GSI2",pkAttribute:X.gsi2pk,skAttribute:X.gsi2sk});if(X.gsi3pk)$.push({name:"GSI3",pkAttribute:X.gsi3pk,skAttribute:X.gsi3sk});return $}}function WO(X){return new I7(X)}function VO(X){return X.accessPatterns}function IO(X,$="#"){let Z=X.name.toUpperCase(),Y=X.primaryKey??"id";return{name:X.name,pkPattern:`${Z}${$}\${${Y}}`,skPattern:`${Z}${$}\${${Y}}`}}var eL=e(()=>{F5(),V7()});function K7(X){let $={};for(let Z of Object.keys(X)){let Y=X[Z],U=Y.definition??Y.getDefinition?.()??Y,_=U.table||`${String(U.name).toLowerCase()}s`,Q=U.attributes??{},L={};for(let z of Object.keys(Q))L[z]=void 0;$[_]={columns:L,primaryKey:U.primaryKey??"id"}}return $}async function dX(X){let $=X.cwd??Uj.cwd(),Z=X.modelsDir.startsWith("/")?X.modelsDir:`${$}/${X.modelsDir}`,Y={},U=Xj(Z);for(let _ of U){let Q=`${Z}/${_}`;if($j(Q).isDirectory())continue;let z=Yj(Q);if(![".ts",".mts",".cts",".js",".mjs",".cjs"].includes(z))continue;let j=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,E=await import(`${Q}${j}`),V=E.default??E,G=V.definition??V.getDefinition?.()??V,J=Zj(_,z),W=G.name??J;Y[W]={...G,name:W}}return Y}var _j=()=>{};function c1(X){if(typeof X==="string")return{model:X};if(X&&typeof X==="object"&&typeof X.model==="string"){let $=X;return{model:$.model,foreignKey:$.foreignKey,onDelete:$.onDelete}}return null}function Qj(X){if(!X)return[];return(Array.isArray(X)?X:typeof X==="object"?Object.values(X):[]).map(c1).filter((Z)=>Z!==null)}function zj(X){let $={},Z={},Y={},U={},_={};for(let Q of Object.keys(X)){let L=X[Q],z=L.definition??L.getDefinition?.()??L,j=z.table||`${String(z.name).toLowerCase()}s`;$[Q]=j,Z[j]=Q,Y[j]=z.primaryKey??"id";let E=(J)=>{if(!J)return{};let W={};if(Array.isArray(J)){for(let F of J){let K=c1(F);if(K)W[K.model]=K.model}return W}if(typeof J==="object"){for(let[F,K]of Object.entries(J)){let D=c1(K);if(D)W[F]=D.model}return W}return{}},V=(J)=>{if(!J)return{};if(Array.isArray(J)){let W={};for(let F of J)if(typeof F==="string")W[F]=F;else if(F&&typeof F==="object"&&typeof F.model==="string")W[F.model]=F;return W}return J},G=(J)=>{if(!J)return{};return J};if(U[j]={hasOne:E(z.hasOne),hasMany:E(z.hasMany),belongsTo:E(z.belongsTo),belongsToMany:V(z.belongsToMany),hasOneThrough:G(z.hasOneThrough),hasManyThrough:G(z.hasManyThrough),morphOne:E(z.morphOne),morphMany:E(z.morphMany),morphTo:z.morphTo,morphToMany:E(z.morphToMany),morphedByMany:E(z.morphedByMany)},z.scopes&&typeof z.scopes==="object"){_[j]={};for(let J of Object.keys(z.scopes)){let W=z.scopes[J];if(typeof W==="function")_[j][J]=W}}}return{modelToTable:$,tableToModel:Z,primaryKeys:Y,relations:U,scopes:_,models:X}}var R7=()=>{};function n0(X){if(f.verbose)console.log(X)}function qX(X){return X.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Z])/gi,"$1_$2").toLowerCase()}function Ej(X){let $=X;while($!==O6($)){if(D7(O5($,"package.json")))return $;$=O6($)}return M7.cwd()}function Gj(){let X=Ej(M7.cwd()),$=O5(X,"database","migrations");if(!D7($))Lj($,{recursive:!0}),n0(`-- Created SQL directory: ${$}`);return $}function H7(X,$){if(!X)return!1;let Z=Gj();q$++;let U=`${V5?String(q$).padStart(10,"0"):String(Math.floor(Date.now()/1000)+q$)}-${$}.sql`,_=O5(Z,U);return jj(_,X),n0(`-- Migration file created: ${U}`),x9++,!0}function J6(X){if(X.endsWith("_id"))return"bigint";if(X.endsWith("_at"))return"datetime";if(X.startsWith("is_")||X.startsWith("has_"))return"boolean";return}function W6(X){if(typeof X==="string"||typeof X==="number"||typeof X==="boolean"||typeof X==="bigint"||X instanceof Date)return X;return}function Fj(X){if(X&&typeof X==="object"&&"name"in X){let $=X;if($.name==="enum"||$.getRules&&Array.isArray($.getRules())){if($.enumValues&&Array.isArray($.enumValues))return $.enumValues.map((Z)=>String(Z));if($._values&&Array.isArray($._values))return $._values.map((Z)=>String(Z));if($.values&&Array.isArray($.values))return $.values.map((Z)=>String(Z))}}if(X&&typeof X==="object"){let $=X,Z=$.allowedValues||$.enumValues||$._values||$.values;if(Array.isArray(Z)&&Z.length>0)return Z.map((Y)=>String(Y))}return}function C7(X){if(!X?.rules||!Array.isArray(X.rules))return;for(let $ of X.rules)if($?.name==="max"||$?.name==="maxLength"){if($.params&&typeof $.params.max==="number")return $.params.max;if(Array.isArray($.args)&&typeof $.args[0]==="number")return $.args[0];if(typeof $.value==="number")return $.value;if(typeof $.expectedValue==="number")return $.expectedValue}return}function Oj(X){if(!X||typeof X!=="object")return;let $=X;if($.name)switch(String($.name).toLowerCase()){case"string":case"text":{let Y=C7($);return Y&&Y>255?"text":"string"}case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"json":return"json";case"enum":return"enum"}if($.type){let Z=String($.type).toLowerCase();if(Z==="string"||Z==="text")return"string";if(Z==="integer"||Z==="int")return"integer";if(Z==="bigint")return"bigint";if(Z==="float")return"float";if(Z==="number")return"integer";if(Z==="boolean")return"boolean";if(Z==="date")return"date";if(Z==="datetime")return"datetime";if(Z==="json")return"json"}return}function J5(X,$){let Z=zj(X),Y=[];for(let Q of Object.keys(X)){let L=X[Q],z=L.table||`${String(L.name).toLowerCase()}s`,j=L.primaryKey??"id",E=L.autoIncrement!==!1,V=L.attributes??{},G=[],J=[];if(!V[j])G.push({name:qX(j),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let H of Object.keys(V)){let x=V[H],h=qX(H),c=!0,y,g,v=H===j;if(y=Oj(x.validation?.rule),!y||y==="enum"){let o=Fj(x.validation?.rule);if(o&&o.length>0)y="enum",g=o}if(!y)y=J6(h);if(!y){let o=W6(x.default);if(typeof o==="string")y=o.length>255?"text":"string";else if(typeof o==="number")y=Number.isInteger(o)?"integer":"float";else if(typeof o==="boolean")y="boolean";else if(typeof o==="bigint")y="bigint";else if(o instanceof Date)y="datetime"}if(!y)y=v?"bigint":"string";let n=y==="string"?C7(x.validation?.rule):void 0,p={name:h,type:y,isPrimaryKey:v,isUnique:Boolean(x.unique),isNullable:!0,hasDefault:typeof x.default<"u",defaultValue:W6(x.default),enumValues:g,maxLength:typeof n==="number"&&n>0&&n<=255?n:void 0};if(h.endsWith("_id")&&x.foreignKey!==!1)if(typeof x.foreignKey==="object"&&x.foreignKey!==null){let o=x.foreignKey;if(p.references={table:o.table,column:o.column??"id",onDelete:o.onDelete,onUpdate:o.onUpdate},o.nullable!==void 0)p.isNullable=o.nullable}else{let D0=h.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(o0,a,B)=>B.toUpperCase()),M0=Z.modelToTable[D0];if(M0){let o0=Z.primaryKeys[M0]??"id";p.references={table:M0,column:o0}}}G.push(p)}let W=Qj(L.belongsTo);for(let H of W){let x=H.foreignKey??`${qX(H.model)}_id`;if(G.some((y)=>y.name===x))continue;let h=Z.modelToTable[H.model];if(!h)continue;let c=Z.primaryKeys[h]??"id";G.push({name:x,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:h,column:c,onDelete:H.onDelete}})}let F=L.traits;if(F?.useTimestamps??F?.timestampable??!1){if(!G.some((H)=>H.name==="created_at"))G.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"});if(!G.some((H)=>H.name==="updated_at"))G.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(F?.useSoftDeletes??F?.softDeletable??!1){if(!G.some((H)=>H.name==="deleted_at"))G.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(F?.useUuid??!1){if(!G.some((H)=>H.name==="uuid"))G.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let H of L.indexes??[])J.push({name:H.name,columns:H.columns.map((x)=>qX(x)),type:H.unique?"unique":"index",where:H.where});for(let H of G)if(H.isUnique&&!H.isPrimaryKey)J.push({name:`${z}_${H.name}_unique`,columns:[H.name],type:"unique"});let T=Array.isArray(L.shardKey)?L.shardKey.map(qX):void 0,N=Array.isArray(L.sortKey)?L.sortKey.map(qX):void 0,q=L.tableKind;Y.push({table:z,columns:G,indexes:J,shardKey:T,sortKey:N,tableKind:q})}let U=new Set(Y.map((Q)=>Q.table));function _(Q){if(!U.has(Q.table))U.add(Q.table),Y.push(Q)}for(let Q of Object.keys(X)){let L=X[Q],z=L?.traits??{},j=L.table||`${String(L.name).toLowerCase()}s`,E=j.replace(/s$/,"");if(z.likeable){let V=typeof z.likeable==="object"?z.likeable:{},G=V.table||`${j}_likes`,J=V.foreignKey||`${E}_id`;_({table:G,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:J,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${G}_user_target_unique`,columns:["user_id",J],type:"unique"}]})}if(z.taggable)_({table:"taggable",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(z.categorizable)_({table:"categorizable",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_slug_unique",columns:["slug"],type:"unique"}]}),_({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizable",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}],indexes:[{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let Q of Object.keys(X)){let L=X[Q],z=L?.belongsToMany;if(!z||typeof z!=="object"||Array.isArray(z))continue;let j=L.table||`${String(L.name).toLowerCase()}s`,E=j.replace(/s$/,"");for(let[V,G]of Object.entries(z)){let J=G;if(!J||typeof J!=="object")continue;if(J.through)continue;let W=J.pivot;if(!W||!W.columns&&!W.timestamps&&!W.uniques)continue;let F=J.model,D=X[F]?.table||`${String(F).toLowerCase()}s`,w=D.replace(/s$/,""),T=J.table||[E,w].sort().join("_"),N=J.foreignKey||`${E}_id`,q=J.relatedKey||`${w}_id`,H=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:q,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:D,column:"id"}}];if(W.columns)for(let[c,y]of Object.entries(W.columns)){let g=y,v=J6(c)??"string";H.push({name:c,type:v,isPrimaryKey:!1,isUnique:!1,isNullable:g?.nullable??!1,hasDefault:g?.default!==void 0,defaultValue:g?.default})}if(W.timestamps)H.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}),H.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let x=[],h=W.uniques&&W.uniques.length>0?W.uniques:[[N,q]];for(let c=0;c<h.length;c++){let y=h[c];x.push({name:`${T}_${y.join("_")}_unique${c>0?`_${c}`:""}`,columns:[...y],type:"unique"})}_({table:T,columns:H,indexes:x})}}return{dialect:$.dialect,tables:Y}}function W5(X,$={}){q$=0,x9=0,f9=0,V5=!0;let Z=$.dryRun?()=>!1:H7,Y=[],U=ZX(X.dialect);for(let Q of X.tables){let L=[],z=new Set;for(let V of Q.columns)if(V.type==="enum"&&V.enumValues&&V.enumValues.length>0){let G=`${Q.table}_${V.name}_type`;if(V.enumTypeName=G,!z.has(G)){let J=U.createEnumType(G,V.enumValues);if(J)L.push(J);z.add(G)}}let j=U.createTable(Q);L.push(j),Y.push(...L);let E=L.join(`
|
|
461
|
+
Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${$}': ${_}`)}}},lU=new E5,sU={email:(X)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(X)},phone:(X)=>{let $=/^\+?[1-9]\d{0,15}$/,Z=X.replace(/[\s\-()]/g,"");return Z.length>=7&&$.test(Z)},name:(X)=>{return/^[a-z\s\-']+$/i.test(X)&&X.length>=2&&X.length<=50},age:(X)=>{return Number.isInteger(X)&&X>=0&&X<=150},url:(X)=>{try{let $=new URL(X);return X.startsWith("http://")||X.startsWith("https://")}catch{return!1}},regex:(X)=>($)=>{return X.test($)},length:(X,$)=>(Z)=>{return Z.length>=X&&Z.length<=$},range:(X,$)=>(Z)=>{return Z>=X&&Z<=$}},oU={phoneByCountry:{field:"phone",dependsOn:"country",mapping:{"United States":"+1-###-###-####","United Kingdom":"+44 #### ### ###",Germany:"+49 ### ########",France:"+33 # ## ## ## ##",Spain:"+34 ### ## ## ##",Italy:"+39 ### ### ###",Japan:"+81 ##-####-####",China:"+86 ### #### ####",Australia:"+61 ### ### ###",Canada:"+1-###-###-####"}},postalCodeByCountry:{field:"postalCode",dependsOn:"country",mapping:{"United States":"#####","United Kingdom":"AA## #AA",Germany:"#####",France:"#####",Spain:"#####",Italy:"#####",Japan:"###-####",China:"######",Australia:"####",Canada:"A#A #A#"}},firstNameByGender:{field:"firstName",dependsOn:"gender",mapping:{male:["John","Michael","David","James","Robert","William","Richard","Thomas","Christopher","Daniel"],female:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen"]}}},rU={commonFirstNames:{items:[{item:"John",weight:100},{item:"Michael",weight:85},{item:"David",weight:80},{item:"James",weight:75},{item:"Robert",weight:70},{item:"William",weight:65},{item:"Richard",weight:60},{item:"Thomas",weight:55},{item:"Christopher",weight:50},{item:"Daniel",weight:45}]},ageDistribution:{items:[{item:25,weight:80},{item:30,weight:90},{item:35,weight:95},{item:40,weight:100},{item:45,weight:85},{item:50,weight:70},{item:55,weight:55},{item:60,weight:40},{item:65,weight:25},{item:70,weight:15}]},countryDistribution:{items:[{item:"United States",weight:100},{item:"China",weight:95},{item:"India",weight:90},{item:"Brazil",weight:60},{item:"Russia",weight:55},{item:"Japan",weight:50},{item:"Germany",weight:45},{item:"United Kingdom",weight:40},{item:"France",weight:35},{item:"Italy",weight:30}]}},aU=[".","_","-",""],tU=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","fugiat","nulla","pariatur","excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"],eU=["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Hyundai","Kia","Mazda","Subaru","Lexus","Tesla","Volvo","Porsche","Jeep","Ram","GMC","Dodge","Chrysler","Buick","Cadillac","Acura","Infiniti","Genesis","Land Rover","Jaguar","Mini"],X7=["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Silverado","Tacoma","Altima","Sentra","Rogue","Model 3","Model Y","Model S","X5","X3","3 Series","5 Series","C-Class","E-Class","A4","Q5","Golf","Jetta","Passat","Tiguan","Escape","Explorer","Mustang","Ranger","Malibu","Equinox","Traverse","Wrangler","Grand Cherokee","Cherokee","Compass"],$7=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],Z7=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],Y7=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],h1="abcdefghijklmnopqrstuvwxyz".split(""),v1=new jZ,U7=v1}),_7={};i1(_7,{validateData:()=>A$,selectWeightedItem:()=>k$,isInWorkspace:()=>AX,installPackage:()=>cU,globalProviderRegistry:()=>lU,getConfig:()=>EL,generateRealisticData:()=>JL,faker:()=>v1,detectPackageManager:()=>pU,defaultConfig:()=>XZ,default:()=>U7,config:()=>y1,applyRelationships:()=>p9,applyConstraints:()=>OL,WordModule:()=>M$,WeightedSelections:()=>rU,VehicleModule:()=>D$,ValidationRules:()=>sU,SystemModule:()=>R$,StringModule:()=>t8,SportModule:()=>K$,ScienceModule:()=>I$,Random:()=>e8,PhoneModule:()=>V$,PersonModule:()=>W$,NumberModule:()=>a8,MusicModule:()=>J$,LoremModule:()=>r8,LocaleLoader:()=>Y9,InternetModule:()=>O$,ImageModule:()=>o8,HelpersModule:()=>s8,HackerModule:()=>F$,GitModule:()=>l8,FoodModule:()=>G$,FinanceModule:()=>i8,Faker:()=>jZ,DateModule:()=>n8,DatabaseModule:()=>u8,DataRelationships:()=>oU,DataProviderRegistry:()=>E5,CompanyModule:()=>E$,CommerceModule:()=>j$,ColorModule:()=>L$,BookModule:()=>z$,AnimalModule:()=>Q$,AddressModule:()=>_$});var yL=t(()=>{BL()});function r9(){let X=new Date().toISOString();return W0(f.dialect)?X.slice(0,19).replace("T"," "):X}function w9(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);if(X.length>64)throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' exceeds 64 chars`);if(!G5.test(X))throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Q7(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);let Z=X.split(".");if(Z.length>2||Z.some((Y)=>Y.length===0||Y.length>64||!G5.test(Y)))throw TypeError(`[bun-query-builder] ${$}: invalid ORDER BY column '${X}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function U9(X){if(!L8)try{L8=(P8(),c7(O7)).getModel}catch{L8=()=>{return}}return L8(X)}function j6(X){let $=tX.get(X);if($!==void 0)return $;let Z=0,Y=X.replace(/\?/g,()=>`$${++Z}`);if(tX.size>=pL)tX.clear();return tX.set(X,Y),Y}function E6(X){if(X==null)return 0;if(typeof X.affectedRows==="number")return X.affectedRows;if(typeof X.count==="number")return X.count;if(Array.isArray(X))return X.length;return 0}function G6(X){if(X==null||typeof X!=="object")return null;if("insertId"in X&&X.insertId!=null)return X.insertId;if("lastInsertRowid"in X&&X.lastInsertRowid!=null)return X.lastInsertRowid;return null}class f1{sqliteDb;dialect="sqlite";constructor(X){this.sqliteDb=X}all(X,$){return Promise.resolve(this.sqliteDb.query(X).all(...$))}get(X,$){return Promise.resolve(this.sqliteDb.query(X).get(...$)??void 0)}run(X,$){let Z=this.sqliteDb.run(X,$);return Promise.resolve({changes:Z.changes,lastInsertId:Z.lastInsertRowid})}insert(X,$){return this.run(X,$)}}class z7{dialect;constructor(X){this.dialect=X}conn(){return BX()}text(X){return this.dialect==="postgres"?j6(X):X}async all(X,$){let Z=await this.conn().unsafe(this.text(X),$);return Array.isArray(Z)?Z:[]}async get(X,$){let Z=await this.conn().unsafe(this.text(X),$);if(Array.isArray(Z))return Z[0]??void 0;return Z??void 0}async run(X,$){let Z=await this.conn().unsafe(this.text(X),$);return{changes:E6(Z),lastInsertId:G6(Z)}}async insert(X,$,Z){if(this.dialect==="postgres"){let _=await this.conn().unsafe(`${j6(X)} RETURNING ${Z}`,$),Q=Array.isArray(_)?_[0]:_;return{changes:1,lastInsertId:Q?Q[Z]??null:null}}let Y=await this.conn().unsafe(X,$),U=G6(Y);if(U==null){let _=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);U=(Array.isArray(_)?_[0]:_)?.id??null}return{changes:E6(Y)||1,lastInsertId:U}}}function L7(X){if(X.database instanceof b1)o9=X.database;else o9=new b1(X.database||":memory:",{create:!0}),e1(o9);P9=null,eX=null}function K0(){if(o9){if(!P9||eX!==o9)P9=new f1(o9),eX=o9,z1="sqlite",L1=null;return P9}let X=f.dialect,$=f.database?.database??null;if(P9&&eX===null&&z1===X&&L1===$)return P9;if(eX=null,z1=X,L1=$,X==="sqlite"){let Z=new b1($||":memory:",{create:!0});e1(Z),P9=new f1(Z)}else P9=new z7(X);return P9}function j7(){let X=K0();if(X.sqliteDb)return X.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${X.dialect}'. Use the async model API instead.`)}function vX(X){let $=X.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function a9(X){let $=X.traits;return Boolean($?.useTimestamps||$?.timestampable)}function hL(X){let $=g1.get(X);if($)return $;let Z=new Set,Y=X.belongsToMany;if(Y){if(Array.isArray(Y)){for(let U of Y)if(typeof U==="string")Z.add(U.toLowerCase());else if(U&&typeof U==="object"&&U.model)Z.add(U.model.toLowerCase())}else if(typeof Y==="object")for(let U of Object.keys(Y))Z.add(U)}return g1.set(X,Z),Z}function F6(X){let $={};for(let[Z,Y]of Object.entries(X))$[o0(Z)]=Y;return $}function vL(X,$){if(X[$])return X[$];let Z=o0($);if(X[Z])return X[Z];for(let Y of Object.keys(X))if(o0(Y)===Z)return X[Y];return}class t0{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor(X,$={}){this._definition=X,this._attributes=F6({...$}),this._original=null;let Z=hL(X);if(Z.size===0)return;let Y=this;return new Proxy(this,{get(U,_,Q){if(typeof _==="string"&&Z.has(_)&&!(_ in U))return()=>{let L=E7(X,_);if(!L||L.type!=="belongsToMany")throw Error(`[orm] relation '${_}' did not resolve to a belongsToMany on '${X.name}'`);let z=U9(L.relatedModelName),j=z?.getDefinition?.()||z?.definition;if(!j)throw Error(`[orm] related model '${L.relatedModelName}' is not registered`);return new G7(Y,X,L,j)};return Reflect.get(U,_,Q)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(X){let $=this._definition.get?.[X];if($)try{let Z=$(this._attributes);if(Z!==void 0)return Z}catch{}return this._attributes[o0(X)]}getAttribute(X){return this._attributes[o0(X)]}getAttributes(){return{...this._attributes}}set(X,$){if(this._original===null)this._original={...this._attributes};this._attributes[o0(X)]=$}only(X){let $={};for(let Z of X)$[Z]=this._attributes[Z];return $}except(X){let $=new Set(X.map((Y)=>Y)),Z={};for(let Y of Object.keys(this._attributes))if(!$.has(Y))Z[Y]=this._attributes[Y];return Z}getRelation(X){return this._relations[X]}setRelation(X,$){this._relations[X]=$}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let X=this._definition.primaryKey||"id";return this._attributes[X]}isDirty(X){if(this._original===null)return!1;if(X)return this._attributes[X]!==this._original[X];return Object.keys(this._attributes).some(($)=>this._attributes[$]!==this._original[$])}isClean(X){return!this.isDirty(X)}getOriginal(X){return this.getOriginalAttributes()[X]}getChanges(){if(this._original===null)return{};let X={};for(let $ of Object.keys(this._attributes))if(this._attributes[$]!==this._original[$])X[$]=this._attributes[$];return X}fill(X){let $=this._definition.attributes;for(let[Z,Y]of Object.entries(X)){let U=vL($,Z),_=!U&&o0(Z).endsWith("_id");if(U?.fillable&&!U?.guarded||_){if(this._original===null)this._original={...this._attributes};this._attributes[o0(Z)]=Y}}return this}forceFill(X){if(this._original===null)this._original={...this._attributes};return Object.assign(this._attributes,F6(X)),this}async save(){let X=K0(),$=this._definition.primaryKey||"id",Z=this._definition.hooks,Y=this._definition.set||{};for(let[U,_]of Object.entries(Y))if(this.isDirty(U))this._attributes[U]=_(this._attributes);if(this._attributes[$]){await Z?.beforeUpdate?.(this,this.getChanges());let U=this.getChanges(),_=Object.keys(U);if(_.length>0){let Q=_.map((z)=>`${z} = ?`).join(", "),L=[...Object.values(U),this._attributes[$]];if(a9(this._definition)){let z=r9();await X.run(`UPDATE ${this._definition.table} SET ${Q}, updated_at = ? WHERE ${$} = ?`,[...Object.values(U),z,this._attributes[$]])}else await X.run(`UPDATE ${this._definition.table} SET ${Q} WHERE ${$} = ?`,L)}await Z?.afterUpdate?.(this)}else{let U=this._definition.attributes,_={};for(let[j,E]of Object.entries(U)){if(E.guarded)continue;let V=o0(j);if(this._attributes[V]!==void 0)_[V]=this._attributes[V]}for(let j of Object.keys(this._attributes))if(j.endsWith("_id")&&j!==$&&!(j in _))_[j]=this._attributes[j];if(a9(this._definition)){let j=r9();_.created_at=j,_.updated_at=j}if(this._definition.traits?.useUuid&&!_.uuid)_.uuid=crypto.randomUUID();await Z?.beforeCreate?.(_);let Q=Object.keys(_),L=Q.map(()=>"?").join(", "),z=await X.insert(`INSERT INTO ${this._definition.table} (${Q.join(", ")}) VALUES (${L})`,Object.values(_),$);for(let[j,E]of Object.entries(_))this._attributes[j]=E;if(z.lastInsertId!=null)this._attributes[$]=z.lastInsertId;await Z?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(X){return this.fill(X),this.save()}async fresh(){let X=K0(),$=this._definition.primaryKey||"id",Z=this._attributes[$];if(Z==null)return null;let Y=await X.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);if(!Y)return null;return new t0(this._definition,Y)}async delete(){let X=K0(),$=this._definition.primaryKey||"id",Z=this._attributes[$],Y=this._definition.hooks;if(!Z)throw Error("Cannot delete a model without a primary key");if(await Y?.beforeDelete?.(this),vX(this._definition)){let U=r9();await X.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${$} = ?`,[U,Z]),this._attributes[b9]=U}else await X.run(`DELETE FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);return await Y?.afterDelete?.(this),!0}async restore(){if(!vX(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let X=this._definition.primaryKey||"id",$=this._attributes[X];if(!$)throw Error("Cannot restore a model without a primary key");return await K0().run(`UPDATE ${this._definition.table} SET ${b9} = ? WHERE ${X} = ?`,[null,$]),this._attributes[b9]=null,this._original=null,this}trashed(){return this._attributes[b9]!=null}async refresh(){let X=K0(),$=this._definition.primaryKey||"id",Z=this._attributes[$];if(!Z)throw Error("Cannot refresh a model without a primary key");let Y=await X.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);if(!Y)return null;return this._attributes=Y,this._original=null,this}replicate(){let X=this._definition.primaryKey||"id",$={...this._attributes};return delete $[X],delete $.uuid,delete $.created_at,delete $.updated_at,new t0(this._definition,$)}toArray(){let X={...this._attributes};for(let[$,Z]of Object.entries(this._relations))if(Array.isArray(Z))X[$]=Z.map((Y)=>Y.toArray());else if(Z)X[$]=Z.toArray();else X[$]=null;return X}toJSON(){let X=new Set;for(let[Z,Y]of Object.entries(this._definition.attributes))if(Y.hidden)X.add(Z);let $={};for(let[Z,Y]of Object.entries(this._attributes))if(!X.has(Z))$[Z]=Y;for(let[Z,Y]of Object.entries(this._relations))if(Array.isArray(Y))$[Z]=Y.map((U)=>U.toJSON());else if(Y)$[Z]=Y.toJSON();else $[Z]=null;return $}}function o0(X){let $=d1.get(X);if($!==void 0)return $;return $=X.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),d1.set(X,$),$}function i9(X){let $=p1.get(X);if($!==void 0)return $;let Z=o0(X);if(Z.endsWith("y")&&!Z.endsWith("ay")&&!Z.endsWith("ey")&&!Z.endsWith("oy")&&!Z.endsWith("uy"))$=Z.slice(0,-1)+"ies";else if(Z.endsWith("s")||Z.endsWith("x")||Z.endsWith("ch")||Z.endsWith("sh"))$=`${Z}es`;else $=`${Z}s`;return p1.set(X,$),$}function E7(X,$){let{name:Z,table:Y}=X,U=X.primaryKey||"id";function _(W){if(!W)return null;if(Array.isArray(W)){for(let F of W){let K=typeof F==="string"?F:F?.model||"";if(K&&K.toLowerCase()===$.toLowerCase())return K}return null}if(typeof W==="object"){for(let[F,K]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||F}return null}function Q(){let W=X.belongsToMany;if(!W)return null;if(Array.isArray(W)){for(let F of W)if(typeof F==="string"){if(F.toLowerCase()===$.toLowerCase())return{entry:F}}else if(F&&typeof F==="object"&&F.model){if(F.model.toLowerCase()===$.toLowerCase())return{entry:F}}return null}if(typeof W==="object"){for(let[F,K]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:K}}return null}let L=_(X.hasMany);if(L){let F=U9(L)?.getTable?.()||i9(L),K=o0(Z)+"_id";return{type:"hasMany",relatedModelName:L,relatedTable:F,foreignKey:K,localKey:U}}let z=_(X.hasOne);if(z){let F=U9(z)?.getTable?.()||i9(z),K=o0(Z)+"_id";return{type:"hasOne",relatedModelName:z,relatedTable:F,foreignKey:K,localKey:U}}let j=_(X.belongsTo);if(j){let W=U9(j),F=W?.getTable?.()||i9(j),K=W?.getDefinition?.()?.primaryKey||"id",D=o0(j)+"_id";return{type:"belongsTo",relatedModelName:j,relatedTable:F,foreignKey:D,localKey:K}}let E=Q();if(E){let W=typeof E.entry==="object",F=W?E.entry.model:E.entry,D=U9(F)?.getTable?.()||i9(F),w=W?E.entry:null,T,N;if(w?.table)T=w.table;else if(w?.through){N=w.through;let h=U9(w.through);if(!h)throw Error(`[orm] belongsToMany relation '${$}' on '${Z}' references unknown through model '${w.through}'. Make sure '${w.through}' is registered.`);T=h.getTable?.()||h.getDefinition?.()?.table||i9(w.through)}else{let h=Y.endsWith("s")?Y.slice(0,-1):Y,p=D.endsWith("s")?D.slice(0,-1):D;T=[h,p].sort().join("_")}let q=w?.foreignKey||`${Y.endsWith("s")?Y.slice(0,-1):Y}_id`,H=w?.relatedKey||`${D.endsWith("s")?D.slice(0,-1):D}_id`,S=[];if(w?.pivot?.columns)for(let h of Object.keys(w.pivot.columns))S.push(h);if(N){let h=U9(N),p=h?.getDefinition?.()||h?.definition,d=p?.attributes??{},B=p?.primaryKey??"id";for(let v of Object.keys(d)){if(v===q||v===H||v===B)continue;if(!S.includes(v))S.push(v)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:D,foreignKey:q,localKey:U,pivotTable:T,pivotFkParent:q,pivotFkRelated:H,pivotColumns:S,pivotModelName:N,pivotTimestamps:Boolean(w?.pivot?.timestamps)}}let V=(W,F)=>{if(!W||typeof W!=="object"||Array.isArray(W))return null;let K=W[$]??W[Object.keys(W).find((p)=>p.toLowerCase()===$.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:D,target:w}=K;if(!D||!w)return null;let T=U9(D),N=T?.getDefinition?.()||T?.definition,q=T?.getTable?.()||N?.table||i9(D),H=N?.primaryKey||"id",h=U9(w)?.getTable?.()||i9(w);return{type:F,relatedModelName:w,relatedTable:h,foreignKey:`${o0(Z)}_id`,localKey:U,throughTable:q,throughForeignKey:`${o0(Z)}_id`,throughLocalKey:H,targetForeignKey:`${bL(q)}_id`}},G=V(X.hasManyThrough,"hasManyThrough");if(G)return G;let J=V(X.hasOneThrough,"hasOneThrough");if(J)return J;return null}function bL(X){return X.endsWith("s")?X.slice(0,-1):X}class G7{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(X,$,Z,Y){this._parent=X,this._parentDef=$,this._resolved=Z,this._relatedDef=Y}get parentId(){let X=this._parentDef.primaryKey||"id";return this._parent.get(X)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(X,$,Z){if(Z===void 0)this._wheres.push({sql:`${this.relatedTable}.${X} = ?`,params:[$]});else this._wheres.push({sql:`${this.relatedTable}.${X} ${String($)} ?`,params:[Z]});return this}wherePivot(X,$,Z){if(Z===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${X} = ?`,params:[$]});else this._pivotWheres.push({sql:`${this.pivotTable}.${X} ${String($)} ?`,params:[Z]});return this}wherePivotIn(X,$){if(!$.length)return this;let Z=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IN (${Z})`,params:[...$]}),this}wherePivotNotIn(X,$){if(!$.length)return this;let Z=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${X} NOT IN (${Z})`,params:[...$]}),this}wherePivotNull(X){return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IS NULL`,params:[]}),this}wherePivotNotNull(X){return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IS NOT NULL`,params:[]}),this}orderBy(X,$="asc"){if(Q7(X,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push(`${X} ${$.toUpperCase()}`),this}limit(X){if(!Number.isFinite(X)||X<0||!Number.isInteger(X))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${X}`);return this._limit=X,this}offset(X){if(!Number.isFinite(X)||X<0||!Number.isInteger(X))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${X}`);return this._offset=X,this}relatedSelectColumns(){let X=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),$=this._relatedDef.traits;if($?.useTimestamps||$?.timestampable)X.add("created_at"),X.add("updated_at");if($?.useSoftDeletes||$?.softDeletable)X.add("deleted_at");if($?.useUuid)X.add("uuid");return[...X]}buildSelect(){let X=[],Z=`SELECT ${this.relatedSelectColumns().map((Y)=>`${this.relatedTable}.${Y} AS ${j1}${Y}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;Z+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,Z+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,X.push(this.parentId);for(let Y of this._pivotWheres)Z+=` AND ${Y.sql}`,X.push(...Y.params);for(let Y of this._wheres)Z+=` AND ${Y.sql}`,X.push(...Y.params);if(this._orderBy.length>0)Z+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)Z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Z+=` OFFSET ${this._offset}`;return{sql:Z,params:X}}hydrateRows(X){let $=this.fkParent,Z=this.fkRelated;return X.map((Y)=>{let U={},_={};for(let[L,z]of Object.entries(Y))if(L.startsWith(j1))U[L.slice(j1.length)]=z;else if(L!==$&&L!==Z)_[L]=z;let Q=new t0(this._relatedDef,U);return Q.pivot=_,Q})}async get(){let X=K0(),{sql:$,params:Z}=this.buildSelect(),Y=await X.all($,Z);return this.hydrateRows(Y)}async first(){return this._limit=1,(await this.get())[0]}async count(){let X=K0(),$=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Z=[this.parentId];for(let U of this._pivotWheres)$+=` AND ${U.sql}`,Z.push(...U.params);let Y=await X.get($,Z);return Number(Y?.count??0)}async exists(){return await this.count()>0}now(){return r9()}async attach(X,$={}){let Z=K0(),Y=Array.isArray(X)?X:[X];if(Y.length===0)return 0;let U=this._resolved.pivotTimestamps?this.now():null,_=0;for(let Q of Y){let L={[this.fkParent]:this.parentId,[this.fkRelated]:Q,...$};if(U){if(L.created_at===void 0)L.created_at=U;if(L.updated_at===void 0)L.updated_at=U}let z=Object.keys(L),j=z.map(()=>"?").join(", "),E=`INSERT INTO ${this.pivotTable} (${z.join(", ")}) VALUES (${j})`,V=z.map((G)=>L[G]);await Z.run(E,V),_++}return _}async detach(X){let $=K0(),Z=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Y=[this.parentId];if(X!==void 0&&X!==null){let U=Array.isArray(X)?X:[X];if(U.length===0)return 0;let _=U.map(()=>"?").join(", ");Z+=` AND ${this.fkRelated} IN (${_})`,Y.push(...U)}return(await $.run(Z,Y)).changes}async updateExistingPivot(X,$){let Z=K0(),Y={...$};if(this._resolved.pivotTimestamps&&Y.updated_at===void 0)Y.updated_at=this.now();let U=Object.keys(Y);if(U.length===0)return 0;let _=U.map((z)=>`${z} = ?`).join(", "),Q=`UPDATE ${this.pivotTable} SET ${_} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,L=[...U.map((z)=>Y[z]),this.parentId,X];return(await Z.run(Q,L)).changes}async sync(X){let $=K0(),Z=new Map;for(let j of X)if(j!=null&&typeof j==="object"&&"id"in j){let{id:E,...V}=j;Z.set(E,V)}else Z.set(j,{});let Y=await $.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),U=new Set(Y.map((j)=>j[this.fkRelated])),_=[],Q=[],L=[],z=[...U].filter((j)=>!Z.has(j));if(z.length>0)await this.detach(z),Q.push(...z);for(let[j,E]of Z)if(!U.has(j))await this.attach(j,E),_.push(j);else if(Object.keys(E).length>0)await this.updateExistingPivot(j,E),L.push(j);return{attached:_,detached:Q,updated:L}}async toggle(X){let $=K0(),Z=Array.isArray(X)?X:[X];if(Z.length===0)return{attached:[],detached:[]};let Y=Z.map(()=>"?").join(", "),U=await $.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${Y})`,[this.parentId,...Z]),_=new Set(U.map((z)=>z[this.fkRelated])),Q=Z.filter((z)=>!_.has(z)),L=Z.filter((z)=>_.has(z));if(Q.length>0)await this.attach(Q);if(L.length>0)await this.detach(L);return{attached:Q,detached:L}}}class U0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(X){this._definition=X}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}whereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"and"}),this}orWhereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"or"}),this}whereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"and"}),this}orWhereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"or"}),this}whereNull(X){return w9(X,"whereNull(column)"),this._wheres.push({column:X,operator:"=",value:null,boolean:"and"}),this}orWhereNull(X){return w9(X,"orWhereNull(column)"),this._wheres.push({column:X,operator:"=",value:null,boolean:"or"}),this}whereNotNull(X){return w9(X,"whereNotNull(column)"),this._wheres.push({column:X,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(X){return w9(X,"orWhereNotNull(column)"),this._wheres.push({column:X,operator:"!=",value:null,boolean:"or"}),this}whereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"and"}),this}orWhereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"or"}),this}whereNotLike(X,$){return this._wheres.push({column:X,operator:"not like",value:$,boolean:"and"}),this}orWhereNotLike(X,$){return this._wheres.push({column:X,operator:"not like",value:$,boolean:"or"}),this}whereRaw(X,...$){return this._wheres.push({raw:X,rawParams:$,boolean:"and"}),this}orWhereRaw(X,...$){return this._wheres.push({raw:X,rawParams:$,boolean:"or"}),this}whereGroup(X){return this._addGroup("and",X)}orWhereGroup(X){return this._addGroup("or",X)}_addGroup(X,$){let Z=new U0(this._definition);if($(Z),Z._wheres.length===0)return this;let Y=[],U=Z.buildWhereClauses(Y);if(!U)return this;return this._wheres.push({raw:`(${U})`,rawParams:Y,boolean:X}),this}whereBetween(X,$){return w9(X,"whereBetween(column)"),this._wheres.push({column:X,operator:">=",value:$[0],boolean:"and"}),this._wheres.push({column:X,operator:"<=",value:$[1],boolean:"and"}),this}whereNotBetween(X,$){w9(X,"whereNotBetween(column)");let Z=X;return this._wheres.push({raw:`(${Z} < ? OR ${Z} > ?)`,rawParams:[$[0],$[1]],boolean:"and"}),this}when(X,$){if(X)return $(this);return this}orderBy(X,$="asc"){if(Q7(X,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}orderByAsc(X){return this.orderBy(X,"asc")}limit(X){return this._limit=X,this}take(X){return this.limit(X)}offset(X){return this._offset=X,this}skip(X){return this.offset(X)}select(...X){return this._select=X,this}with(...X){return this._withRelations=X,this}getWithRelations(){return this._withRelations}buildWhereClauses(X){let $=[];for(let Z=0;Z<this._wheres.length;Z++){let Y=this._wheres[Z],U;if(Y.raw){if(U=Y.raw,Y.rawParams&&Y.rawParams.length>0)X.push(...Y.rawParams)}else if(Y.value===null)U=Y.operator==="="?`${Y.column} IS NULL`:`${Y.column} IS NOT NULL`;else if(Y.operator==="in"||Y.operator==="not in"){let _=Y.value;U=`${Y.column} ${Y.operator.toUpperCase()} (${_.map(()=>"?").join(", ")})`,X.push(..._)}else U=`${Y.column} ${Y.operator} ?`,X.push(Y.value);$.push(Z===0?U:`${Y.boolean.toUpperCase()} ${U}`)}return $.join(" ")}softDeleteClause(){if(this._trashed==="include"||!vX(this._definition))return"";return this._trashed==="only"?`${b9} IS NOT NULL`:`${b9} IS NULL`}composeWhere(X){let $=this._wheres.length>0?this.buildWhereClauses(X):"",Z=this.softDeleteClause();if($&&Z)return`(${$}) AND ${Z}`;return $||Z}buildQuery(){let X=[],$=`SELECT ${this._select.join(", ")} FROM ${this._definition.table}`,Z=this.composeWhere(X);if(Z)$+=` WHERE ${Z}`;if(this._orderBy.length>0)$+=` ORDER BY ${this._orderBy.map((Y)=>`${Y.column} ${Y.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)$+=` LIMIT ${this._limit}`;if(this._offset!==void 0)$+=` OFFSET ${this._offset}`;return{sql:$,params:X}}toSql(){return this.buildQuery()}async eagerLoadRelations(X){if(X.length===0||this._withRelations.length===0)return;let $=K0(),Z=this._definition.primaryKey||"id";for(let Y of this._withRelations){let U=`${this._definition.name}:${Y}`,_=X$.get(U);if(_===void 0){if(_=E7(this._definition,Y),X$.size>=cL)X$.clear();X$.set(U,_)}if(!_)continue;if(_.type==="hasMany"||_.type==="hasOne"){let Q=X.map((V)=>V.get(Z)).filter((V)=>V!=null);if(Q.length===0)continue;let L=Q.map(()=>"?").join(", "),z=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.foreignKey} IN (${L})`,Q),j=U9(_.relatedModelName),E=j?.getDefinition?.()||j?.definition||this._definition;if(_.type==="hasMany"){let V=new Map;for(let G of z){let J=G[_.foreignKey];if(!V.has(J))V.set(J,[]);V.get(J).push(G)}for(let G of X){let J=V.get(G.get(Z))||[];G.setRelation(Y,J.map((W)=>new t0(E,W)))}}else{let V=new Map;for(let G of z)V.set(G[_.foreignKey],G);for(let G of X){let J=V.get(G.get(Z));G.setRelation(Y,J?new t0(E,J):null)}}}if(_.type==="belongsTo"){let Q=new Set;for(let J of X){let W=J._attributes[_.foreignKey];if(W!=null)Q.add(W)}let L=[...Q];if(L.length===0)continue;let z=L.map(()=>"?").join(", "),j=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.localKey} IN (${z})`,L),E=U9(_.relatedModelName),V=E?.getDefinition?.()||E?.definition||this._definition,G=new Map;for(let J of j)G.set(J[_.localKey],J);for(let J of X){let W=J._attributes[_.foreignKey],F=G.get(W);J.setRelation(Y,F?new t0(V,F):null)}}if(_.type==="belongsToMany"){let Q=X.map((w)=>w.get(Z)).filter((w)=>w!=null);if(Q.length===0)continue;if(!_.pivotTable||!_.pivotFkParent||!_.pivotFkRelated)continue;let L=Q.map(()=>"?").join(", "),z=await $.all(`SELECT * FROM ${_.pivotTable} WHERE ${_.pivotFkParent} IN (${L})`,Q);if(z.length===0){for(let w of X)w.setRelation(Y,[]);continue}let j=new Set;for(let w of z){let T=w[_.pivotFkRelated];if(T!=null)j.add(T)}let E=[...j],V=U9(_.relatedModelName),G=V?.getDefinition?.()||V?.definition||this._definition,J=G?.primaryKey||"id",W=[];if(E.length>0){let w=E.map(()=>"?").join(", ");W=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${J} IN (${w})`,E)}let F=new Map;for(let w of W)F.set(w[J],w);let K=new Map;for(let w of z){let T=w[_.pivotFkParent];if(!K.has(T))K.set(T,[]);K.get(T).push(w)}let D=new Set([_.pivotFkParent,_.pivotFkRelated]);for(let w of X){let T=w.get(Z),q=(K.get(T)||[]).map((H)=>{let S=F.get(H[_.pivotFkRelated]);if(!S)return null;let h=new t0(G,S),p={};for(let[d,B]of Object.entries(H))if(!D.has(d))p[d]=B;return h.pivot=p,h}).filter((H)=>H!==null);w.setRelation(Y,q)}}if(_.type==="hasManyThrough"||_.type==="hasOneThrough"){let Q=X.map((D)=>D.get(Z)).filter((D)=>D!=null);if(Q.length===0)continue;let L=_.throughLocalKey||"id",z=Q.map(()=>"?").join(", "),j=await $.all(`SELECT ${L}, ${_.throughForeignKey} FROM ${_.throughTable} WHERE ${_.throughForeignKey} IN (${z})`,Q);if(j.length===0){for(let D of X)D.setRelation(Y,_.type==="hasManyThrough"?[]:null);continue}let E=new Map;for(let D of j)E.set(D[L],D[_.throughForeignKey]);let V=[...new Set(j.map((D)=>D[L]))],G=V.map(()=>"?").join(", "),J=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.targetForeignKey} IN (${G})`,V),W=U9(_.relatedModelName),F=W?.getDefinition?.()||W?.definition||this._definition,K=new Map;for(let D of J){let w=E.get(D[_.targetForeignKey]);if(w==null)continue;if(!K.has(w))K.set(w,[]);K.get(w).push(new t0(F,D))}for(let D of X){let w=K.get(D.get(Z))||[];D.setRelation(Y,_.type==="hasManyThrough"?w:w[0]??null)}}}}async get(){let X=K0(),{sql:$,params:Z}=this.buildQuery(),U=(await X.all($,Z)).map((_)=>new t0(this._definition,_));if(this._withRelations.length>0)await this.eagerLoadRelations(U);return U}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let X=await this.first();if(!X)throw Error(`No ${this._definition.name} found`);return X}async last(){let X=this._definition.primaryKey||"id";return this._orderBy=[{column:X,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let X=K0(),$=[],Z=`SELECT COUNT(*) as count FROM ${this._definition.table}`,Y=this.composeWhere($);if(Y)Z+=` WHERE ${Y}`;let U=await X.get(Z,$);return Number(U?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let X=await this.get();if(X.length===0)throw Error(`No ${this._definition.name} found`);if(X.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return X[0]}async increment(X,$=1){w9(X,"increment(column)");let Z=K0(),Y=[$],U=`UPDATE ${this._definition.table} SET ${X} = ${X} + ?`;if(a9(this._definition))U+=", updated_at = ?",Y.push(r9());if(this._wheres.length>0){let _=this.buildWhereClauses(Y);U+=` WHERE ${_}`}return(await Z.run(U,Y)).changes}decrement(X,$=1){return this.increment(X,-$)}async chunk(X,$){let Z=0;while(!0){let Y=new U0(this._definition);Y._wheres=[...this._wheres],Y._orderBy=[...this._orderBy],Y._select=[...this._select],Y._withRelations=[...this._withRelations],Y._trashed=this._trashed,Y._limit=X,Y._offset=Z*X;let U=await Y.get();if(U.length===0)break;if(await $(U)===!1)break;if(U.length<X)break;Z++}}async paginate(X=1,$=15){let Z=await this.count(),Y=Math.ceil(Z/$);this._limit=$,this._offset=(X-1)*$;let U=await this.get();return{data:U,total:Z,page:X,perPage:$,lastPage:Y,hasMorePages:X<Y,isEmpty:U.length===0,from:U.length>0?(X-1)*$+1:null,to:U.length>0?(X-1)*$+U.length:null}}async pluck(X){w9(X,"pluck(column)");let $=K0(),Z=[],Y=`SELECT ${X} FROM ${this._definition.table}`,U=this.composeWhere(Z);if(U)Y+=` WHERE ${U}`;if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.map((Q)=>`${Q.column} ${Q.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return(await $.all(Y,Z)).map((Q)=>Q[X])}async aggregate(X,$){w9($,`${X}(column)`);let Z=K0(),Y=[],U=`SELECT ${X}(${$}) as v FROM ${this._definition.table}`,_=this.composeWhere(Y);if(_)U+=` WHERE ${_}`;let L=(await Z.get(U,Y))?.v;if(L==null)return null;if(typeof L==="string"){let z=Number(L);return L.trim()!==""&&!Number.isNaN(z)?z:L}return L}max(X){return this.aggregate("MAX",X)}min(X){return this.aggregate("MIN",X)}async avg(X){return Number(await this.aggregate("AVG",X)??0)||0}async sum(X){return Number(await this.aggregate("SUM",X)??0)||0}async delete(){let X=K0(),$=[],Z=`DELETE FROM ${this._definition.table}`;if(this._wheres.length>0)Z+=` WHERE ${this.buildWhereClauses($)}`;return(await X.run(Z,$)).changes}async update(X){let $=K0(),Z=Object.entries(X),Y=Z.map(([Q])=>`${Q} = ?`).join(", "),U=Z.map(([,Q])=>Q);if(a9(this._definition))U.push(r9());let _=`UPDATE ${this._definition.table} SET ${Y}${a9(this._definition)?", updated_at = ?":""}`;if(this._wheres.length>0)_+=` WHERE ${this.buildWhereClauses(U)}`;return(await $.run(_,U)).changes}}function fL(X){let $={query:()=>new U0(X),where(Z,Y,U){return new U0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new U0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new U0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new U0(X).whereNotIn(Z,Y)},whereNull(Z){return new U0(X).whereNull(Z)},whereNotNull(Z){return new U0(X).whereNotNull(Z)},whereLike(Z,Y){return new U0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new U0(X).orderBy(Z,Y)},orderByDesc(Z){return new U0(X).orderByDesc(Z)},select(...Z){return new U0(X).select(...Z)},with(...Z){return new U0(X).with(...Z)},limit:(Z)=>new U0(X).limit(Z),take:(Z)=>new U0(X).take(Z),skip:(Z)=>new U0(X).skip(Z),withTrashed:()=>new U0(X).withTrashed(),onlyTrashed:()=>new U0(X).onlyTrashed(),async find(Z){let Y=K0(),U=X.primaryKey||"id",_=vX(X)?` AND ${b9} IS NULL`:"",Q=await Y.get(`SELECT * FROM ${X.table} WHERE ${U} = ?${_}`,[Z]);return Q?new t0(X,Q):void 0},async findOrFail(Z){let Y=await $.find(Z);if(!Y)throw Error(`${X.name} with id ${Z} not found`);return Y},async findMany(Z){let Y=K0(),U=X.primaryKey||"id",_=vX(X)?` AND ${b9} IS NULL`:"";return(await Y.all(`SELECT * FROM ${X.table} WHERE ${U} IN (${Z.map(()=>"?").join(", ")})${_}`,Z)).map((L)=>new t0(X,L))},all:()=>new U0(X).get(),first:()=>new U0(X).first(),firstOrFail:()=>new U0(X).firstOrFail(),last:()=>new U0(X).last(),count:()=>new U0(X).count(),exists:()=>new U0(X).exists(),doesntExist:()=>new U0(X).doesntExist(),paginate:(Z,Y)=>new U0(X).paginate(Z,Y),whereBetween(Z,Y){return new U0(X).whereBetween(Z,Y)},whereNotBetween(Z,Y){return new U0(X).whereNotBetween(Z,Y)},async create(Z){let Y=new t0(X,Z);return await Y.save(),Y},async createMany(Z){let Y=[];for(let U of Z)Y.push(await this.create(U));return Y},async updateOrCreate(Z,Y){let U=new U0(X);for(let[Q,L]of Object.entries(Z))U=U.where(Q,L);let _=await U.first();if(_)return await _.update(Y),_;return this.create({...Z,...Y})},async firstOrCreate(Z,Y){let U=new U0(X);for(let[Q,L]of Object.entries(Z))U=U.where(Q,L);return await U.first()||this.create({...Z,...Y})},async destroy(Z){let Y=K0(),U=X.primaryKey||"id";return(await Y.run(`DELETE FROM ${X.table} WHERE ${U} = ?`,[Z])).changes>0},remove(Z){return this.destroy(Z)},async truncate(){await K0().run(`DELETE FROM ${X.table}`,[])},getDefinition:()=>X,getTable:()=>X.table,make(Z={}){return new t0(X,Z)},latest:(Z="created_at")=>new U0(X).orderByDesc(Z),oldest:(Z="created_at")=>new U0(X).orderBy(Z,"asc"),max:(Z)=>new U0(X).max(Z),min:(Z)=>new U0(X).min(Z),avg:(Z)=>new U0(X).avg(Z),sum:(Z)=>new U0(X).sum(Z),pluck(Z){return new U0(X).pluck(Z)}};return new Proxy($,{get(Z,Y){if(typeof Y==="string"&&Y.startsWith("where")&&Y.length>5){let U=Y.slice(5),_=U.charAt(0).toLowerCase()+U.slice(1);if(_ in X.attributes||_==="id"||_===X.primaryKey)return(Q)=>new U0(X).where(_,Q)}return Reflect.get(Z,Y)}})}function gL(X){return fL(X)}async function LO(X){let $=K0(),Z=X.primaryKey||"id",Y=[];if(Y.push(X.autoIncrement!==!1?`${Z} INTEGER PRIMARY KEY AUTOINCREMENT`:`${Z} INTEGER PRIMARY KEY`),X.traits?.useUuid)Y.push("uuid TEXT UNIQUE");for(let[U,_]of Object.entries(X.attributes)){let Q="TEXT";if(_.type==="number")Q="INTEGER";else if(_.type==="boolean")Q="INTEGER";if(U.endsWith("_id"))Q="INTEGER";let L=`${U} ${Q}`;if(_.unique)L+=" UNIQUE";if(typeof _.foreignKey==="object"&&_.foreignKey!==null){let z=_.foreignKey;if(L+=` REFERENCES ${z.table}(${z.column??"id"})`,z.onDelete)L+=` ON DELETE ${z.onDelete.toUpperCase()}`;if(z.onUpdate)L+=` ON UPDATE ${z.onUpdate.toUpperCase()}`}Y.push(L)}if(a9(X))Y.push("created_at TEXT","updated_at TEXT");if(vX(X))Y.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${X.table} (${Y.join(", ")})`,[])}function dL(X){return new Proxy(X,{get($,Z){if(Z==="location")return $.address;if(Z==="datatype"){let{random:Y,number:U,string:_}=$;return{boolean:()=>Y?.boolean?.(),number:(Q)=>U?.int?.(Q),float:(Q)=>U?.float?.(Q),uuid:()=>crypto.randomUUID(),string:(Q)=>_?.alphanumeric?.(Q??10)}}return $[Z]}})}async function jO(X,$,Z){let Y=K0(),U=X.traits?.useSeeder,_=$??(typeof U==="object"&&U?U.count:10);if(!Z)try{let Q=await Promise.resolve().then(()=>(yL(),_7));Z=dL(Q.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let Q=0;Q<_;Q++){let L={};for(let[j,E]of Object.entries(X.attributes))if(E.factory)L[j]=E.factory(Z);if(a9(X)){let j=r9();L.created_at=j,L.updated_at=j}if(X.traits?.useUuid)L.uuid=crypto.randomUUID();let z=Object.keys(L);await Y.run(`INSERT INTO ${X.table} (${z.join(", ")}) VALUES (${z.map(()=>"?").join(", ")})`,Object.values(L))}}var G5,L8=null,tX,pL=500,o9=null,P9=null,eX=null,z1=null,L1=null,b9="deleted_at",j1="__btm_rel__",g1,d1,p1,X$,cL=1000,F7=t(()=>{d0(),$X(),X5(),G5=/^[A-Z_][A-Z0-9_]*$/i,tX=new Map,g1=new WeakMap,d1=new Map,p1=new Map,X$=new Map}),O7={};i1(O7,{registerModel:()=>EZ,registerBrowserModels:()=>oL,hasModel:()=>iL,getModelRegistry:()=>nL,getModel:()=>mL,getAllModels:()=>uL,defineModel:()=>F5,clearModelRegistry:()=>lL});function mL(X){return YX.get(X)}function uL(){return[...YX.values()]}function nL(){return Object.fromEntries(YX)}function iL(X){return YX.has(X)}function lL(){YX.clear()}function EZ(X,$){return YX.set(X,$),$}function sL(){return typeof window<"u"&&typeof document<"u"}function F5(X){let $;if(sL())$=i7(X);else{let Z=gL(X);$=Object.assign(Z,{definition:X,getDefinition:()=>X,getTable:()=>X.table,getName:()=>X.name})}return EZ(X.name,$),$}function oL(X){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...X}}var YX,P8=t(()=>{H6(),F7(),YX=new Map});class gX{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(X){this.driver=bX(X.config),this.client=X.client,this.tableName=X.config.tableName??""}table(X){return this.tableName=X,this}index(X){return this.indexName=X,this}entity(X){return this.entityType=X,this}whereKey(X,$,Z){return this.keyConditions.push({attribute:X,operator:$,value:Z}),this}wherePartitionKey(X,$){return this.whereKey(X,"=",$)}whereSortKey(X,$){return this.whereKey(X,"=",$)}whereSortKeyBeginsWith(X,$){return this.keyConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereSortKeyBetween(X,$,Z){return this.keyConditions.push({attribute:X,operator:"BETWEEN",values:[$,Z]}),this}where(X,$,Z){return this.filterConditions.push({attribute:X,operator:$,value:Z}),this}whereEquals(X,$){return this.where(X,"=",$)}whereLessThan(X,$){return this.where(X,"<",$)}whereLessThanOrEqual(X,$){return this.where(X,"<=",$)}whereGreaterThan(X,$){return this.where(X,">",$)}whereGreaterThanOrEqual(X,$){return this.where(X,">=",$)}whereBetween(X,$,Z){return this.filterConditions.push({attribute:X,operator:"BETWEEN",values:[$,Z]}),this}whereBeginsWith(X,$){return this.filterConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereContains(X,$){return this.where(X,"contains",$)}whereExists(X){return this.where(X,"attribute_exists")}whereNotExists(X){return this.where(X,"attribute_not_exists")}whereIn(X,$){return this.filterConditions.push({attribute:X,operator:"IN",values:$}),this}select(...X){return this.projectionAttrs.push(...X),this}limit(X){return this.limitValue=X,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(X=!0){return this.consistentReadValue=X,this}startFrom(X){return this.startKey=X,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let X=this.buildQueryParams(),$={TableName:X.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(X.indexName)$.IndexName=X.indexName;let Z=0;if(X.keyConditions.length>0){let Y=[];for(let U of X.keyConditions){let _=`#key${Z}`;if($.ExpressionAttributeNames[_]=U.attribute,U.operator==="begins_with"){let Q=`:keyval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`begins_with(${_}, ${Q})`)}else if(U.operator==="BETWEEN"){let Q=`:keyval${Z}a`,L=`:keyval${Z}b`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.values?.[0]}).v,$.ExpressionAttributeValues[L]=this.driver.marshall({v:U.values?.[1]}).v,Y.push(`${_} BETWEEN ${Q} AND ${L}`)}else{let Q=`:keyval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${_} ${U.operator} ${Q}`)}Z++}$.KeyConditionExpression=Y.join(" AND ")}if(X.filterConditions&&X.filterConditions.length>0){let Y=[];for(let U of X.filterConditions){let _=`#flt${Z}`;if($.ExpressionAttributeNames[_]=U.attribute,U.operator==="attribute_exists")Y.push(`attribute_exists(${_})`);else if(U.operator==="attribute_not_exists")Y.push(`attribute_not_exists(${_})`);else if(U.operator==="begins_with"||U.operator==="contains"){let Q=`:fltval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${U.operator}(${_}, ${Q})`)}else if(U.operator==="BETWEEN"){let Q=`:fltval${Z}a`,L=`:fltval${Z}b`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.values?.[0]}).v,$.ExpressionAttributeValues[L]=this.driver.marshall({v:U.values?.[1]}).v,Y.push(`${_} BETWEEN ${Q} AND ${L}`)}else if(U.operator==="IN"){let Q=(U.values??[]).map((L,z)=>`:fltval${Z}_${z}`);U.values?.forEach((L,z)=>{$.ExpressionAttributeValues[`:fltval${Z}_${z}`]=this.driver.marshall({v:L}).v}),Y.push(`${_} IN (${Q.join(", ")})`)}else{let Q=`:fltval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${_} ${U.operator} ${Q}`)}Z++}$.FilterExpression=Y.join(" AND ")}if(X.projectionAttributes&&X.projectionAttributes.length>0){let Y=[];for(let U of X.projectionAttributes){let _=`#proj${Z}`;$.ExpressionAttributeNames[_]=U,Y.push(_),Z++}$.ProjectionExpression=Y.join(", ")}if(X.limit!==void 0)$.Limit=X.limit;if(X.scanIndexForward!==void 0)$.ScanIndexForward=X.scanIndexForward;if(X.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(X.exclusiveStartKey);if(X.consistentRead)$.ConsistentRead=X.consistentRead;if(Object.keys($.ExpressionAttributeNames).length===0)delete $.ExpressionAttributeNames;if(Object.keys($.ExpressionAttributeValues).length===0)delete $.ExpressionAttributeValues;return $}toScanRequest(){let X=this.buildScanParams(),$={TableName:X.tableName};if(X.indexName)$.IndexName=X.indexName;if(X.filterConditions&&X.filterConditions.length>0){let{expression:Z,expressionAttributeNames:Y,expressionAttributeValues:U}=this.driver.buildFilterExpression(X.filterConditions);$.FilterExpression=Z,$.ExpressionAttributeNames=Y,$.ExpressionAttributeValues=U}if(X.projectionAttributes&&X.projectionAttributes.length>0){let{expression:Z,expressionAttributeNames:Y}=this.driver.buildProjectionExpression(X.projectionAttributes);$.ProjectionExpression=Z,$.ExpressionAttributeNames={...$.ExpressionAttributeNames,...Y}}if(X.limit!==void 0)$.Limit=X.limit;if(X.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(X.exclusiveStartKey);if(X.consistentRead)$.ConsistentRead=X.consistentRead;return $}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let X=this.toQueryRequest(),$=await this.client.query(X);return{items:$.Items?.map((Z)=>this.driver.unmarshall(Z)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let X=this.toScanRequest(),$=await this.client.scan(X);return{items:$.Items?.map((Z)=>this.driver.unmarshall(Z)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async getAll(){let X=[],$;do{if($)this.startFrom($);let Z=this.keyConditions.length>0?await this.query():await this.scan();if(Z.items)X.push(...Z.items);$=Z.lastEvaluatedKey}while($);return X}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return X.Select="COUNT",(this.keyConditions.length>0?await this.client.query(X):await this.client.scan(X)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class f9{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(X){this.driver=bX(X.config),this.client=X.client,this.tableName=X.config.tableName??""}table(X){return this.tableName=X,this}key(X){return this.keyData=X,this}item(X){return this.itemData=X,this}set(X,$){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[X]=$,this}setMany(X){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,X),this}remove(X){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(X),this}add(X,$){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[X]=$,this}deleteFromSet(X,$){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[X]=$,this}condition(X){return this.conditionExpr=X,this}ifNotExists(X="pk"){return this.conditionExpr=`attribute_not_exists(${X})`,this}ifExists(X="pk"){return this.conditionExpr=`attribute_exists(${X})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let X={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toUpdateRequest(){let X={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:$,expressionAttributeNames:Z,expressionAttributeValues:Y}=this.driver.buildUpdateExpression(this.updateExpressions);if($)X.UpdateExpression=$,X.ExpressionAttributeNames=Z,X.ExpressionAttributeValues=Y;if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toDeleteRequest(){let X={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toPutRequest(),$=await this.client.putItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toUpdateRequest(),$=await this.client.updateItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toDeleteRequest(),$=await this.client.deleteItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toGetRequest(),$=await this.client.getItem(X);if($.Item)return this.driver.unmarshall($.Item);return}}function EO(X){return new gX(X)}function GO(X){return new f9(X)}function FO(X){let $=bX(X.config);return{query:()=>new gX(X),item:()=>new f9(X),driver:$,registerEntity:(Z)=>$.registerEntity(Z),buildKey:(Z,Y)=>$.buildPrimaryKey(Z,Y)}}var O5=()=>{};class J7{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(X){this.config=X,this.pkAttribute=X.pkAttribute??"pk",this.skAttribute=X.skAttribute??"sk",this.typeAttribute=X.typeAttribute??"_type";for(let $ of X.entities)this.entities.set($.name,$)}getEntity(X){return this.entities.get(X)}registerEntity(X){this.entities.set(X.name,X)}buildKey(X,$){let Z=this.entities.get(X);if(!Z)throw Error(`Entity not found: ${X}`);let Y=this.interpolatePattern(Z.pkPattern,$),U=this.interpolatePattern(Z.skPattern,$);return{pk:Y,sk:U}}buildGSIKey(X,$,Z){let Y=this.entities.get(X);if(!Y)throw Error(`Entity not found: ${X}`);let U=Y.indexes?.find((L)=>L.name===$);if(!U)throw Error(`GSI not found: ${$} for entity ${X}`);let _=this.interpolatePattern(U.pkPattern,Z),Q=U.skPattern?this.interpolatePattern(U.skPattern,Z):void 0;return{pk:_,sk:Q}}createItem(X,$){let{pk:Z,sk:Y}=this.buildKey(X,$),U=this.entities.get(X),_={[this.pkAttribute]:Z,[this.skAttribute]:Y,[this.typeAttribute]:X,...$};if(U.indexes)for(let Q of U.indexes){let L=this.buildGSIKey(X,Q.name,$),z=this.config.indexes?.find((j)=>j.name===Q.name);if(z){if(_[z.pkAttribute]=L.pk,z.skAttribute&&L.sk)_[z.skAttribute]=L.sk}}return _}parseEntityType(X){if(X[this.typeAttribute])return X[this.typeAttribute];let $=X[this.pkAttribute];if(!$)return;for(let[Z,Y]of this.entities){let U=Y.pkPattern.split("${")[0];if($.startsWith(U))return Z}return}parseItem(X){let $=this.parseEntityType(X);if(!$)return;let{[this.pkAttribute]:Z,[this.skAttribute]:Y,[this.typeAttribute]:U,..._}=X;return{type:$,data:_}}getEntityPrefix(X){let $=this.entities.get(X);if(!$)throw Error(`Entity not found: ${X}`);return $.pkPattern.split("${")[0]}generateTableDefinition(){let X=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],$=[];if(this.config.indexes)for(let Z of this.config.indexes){if(!X.find((Y)=>Y.name===Z.pkAttribute))X.push({name:Z.pkAttribute,type:"S"});if(Z.skAttribute&&!X.find((Y)=>Y.name===Z.skAttribute))X.push({name:Z.skAttribute,type:"S"});$.push({indexName:Z.name,keySchema:{partitionKey:Z.pkAttribute,sortKey:Z.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:X,globalSecondaryIndexes:$.length>0?$:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(X,$){return X.replace(/\$\{(\w+)\}/g,(Z,Y)=>{if(!(Y in $))throw Error(`Missing value for pattern key: ${Y}`);return String($[Y])})}}class W7{manager;entityName;options;constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z}async create(X){let $=this.manager.createItem(this.entityName,X),Z=new f9(this.options).table(this.options.config.tableName).item($).ifNotExists("pk");if(this.options.client)await Z.put();return X}async get(X){let{pk:$,sk:Z}=this.manager.buildKey(this.entityName,X),Y=new f9(this.options).table(this.options.config.tableName).key({pk:$,sk:Z});if(!this.options.client)throw Error("DynamoDB client not provided");let U=await Y.get();if(!U)return;return this.manager.parseItem(U)?.data}async update(X,$){let{pk:Z,sk:Y}=this.manager.buildKey(this.entityName,X),U=new f9(this.options).table(this.options.config.tableName).key({pk:Z,sk:Y}).setMany($).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let _=await U.update();if(!_)return;return this.manager.parseItem(_)?.data}async delete(X){let{pk:$,sk:Z}=this.manager.buildKey(this.entityName,X),Y=new f9(this.options).table(this.options.config.tableName).key({pk:$,sk:Z});if(!this.options.client)throw Error("DynamoDB client not provided");return await Y.delete(),!0}query(){return new V7(this.manager,this.entityName,this.options)}async findAll(){let X=this.manager.typeAttribute??"_type",$=new gX(this.options).table(this.options.config.tableName).whereEquals(X,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await $.getAll()).map((Y)=>this.manager.parseItem(Y)).filter((Y)=>Y!==void 0).map((Y)=>Y.data)}}class V7{manager;entityName;options;builder;pkValue;skConditions=[];constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z,this.builder=new gX(Z).table(Z.config.tableName)}wherePartitionKey(X){let{pk:$}=this.manager.buildKey(this.entityName,X);this.pkValue=$;let Z=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(Z,$),this}whereSortKey(X){let{sk:$}=this.manager.buildKey(this.entityName,X),Z=this.manager.skAttribute??"sk";return this.builder.whereSortKey(Z,$),this}whereSortKeyBeginsWith(X){let $=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith($,X),this}useIndex(X,$){let Z=this.manager.buildGSIKey(this.entityName,X,$),Y=this.manager.config.indexes?.find((U)=>U.name===X);if(!Y)throw Error(`GSI configuration not found: ${X}`);return this.builder.index(X),this.builder.wherePartitionKey(Y.pkAttribute,Z.pk),this}where(X,$,Z){return this.builder.where(X,$,Z),this}select(...X){return this.builder.select(...X),this}limit(X){return this.builder.limit(X),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map(($)=>this.manager.parseItem($)).filter(($)=>$!==void 0).map(($)=>$.data)}async first(){return this.limit(1),(await this.execute())[0]}}function rL(X){return new J7(X)}function aL(X,$,Z){return new W7(X,$,Z)}var tL,I7=t(()=>{O5(),tL={simpleEntity:(X,$="id")=>({name:X,pkPattern:`${X.toUpperCase()}#\${${$}}`,skPattern:"METADATA",keyFields:[$]}),oneToMany:(X,$,Z="id",Y="id")=>({parent:{name:X,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]},child:{name:$,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`,keyFields:[Z,Y]}}),manyToMany:(X,$,Z="id",Y="relatedId")=>({entity:{name:X,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]},relation:{name:$,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`,keyFields:[Z,Y],indexes:[{name:"GSI1",pkPattern:`${X.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${Z}}`}]}}),hierarchical:(X,$="rootId",Z="path")=>({name:X,pkPattern:`ROOT#\${${$}}`,skPattern:`PATH#\${${Z}}`,keyFields:[$,Z]})}});function O6(X,$){let Z={};for(let[Y,U]of Object.entries(X))if(U)Z[Y]=U.replace(/\{([^}]+)\}/g,(_,Q)=>{return $[Q]!==void 0?String($[Q]):`{${Q}}`});return Z}async function eL(X){return{models:new Map}}function OO(X){return X}function JO(X){return X}function WO(X){return X}function VO(X){return X}class K7{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(X){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...X};let $={region:X.region,endpoint:X.endpoint,credentials:X.credentials,tableName:X.tableName};this.driver=bX($);let Z={tableName:X.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=rL(Z),this.queryBuilderOptions={config:$}}setClient(X){return this.queryBuilderOptions.client=X,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let X=await eL({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),$=[];for(let[,Z]of X.models)this.registerParsedModel(Z),$.push(Z);return $}registerModel(X){let $=this.parseWithTooling(X);return this.registerParsedModel($)}registerParsedModel(X){this.models.set(X.name,X);let $=this.toSingleTableEntity(X);this.singleTableManager.registerEntity($);let Z=this.toEntityMapping(X);return this.driver.registerEntity(Z),X}registerModels(X){return X.map(($)=>this.registerModel($))}getModel(X){return this.models.get(X)}getAllModels(){return Array.from(this.models.values())}repository(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return aL(this.singleTableManager,X,this.queryBuilderOptions)}query(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new gX(this.queryBuilderOptions).table(this.config.tableName).entity(X)}item(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new f9(this.queryBuilderOptions).table(this.config.tableName)}buildKey(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=O6(Z.keyPatterns,$);return{pk:Y.pk,sk:Y.sk}}createItem(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=O6(Z.keyPatterns,$),U=Y.pk,_=Y.sk,Q={[this.config.pkAttribute]:U,[this.config.skAttribute]:_,[this.config.entityTypeAttribute]:Z.name,...$};if(Z.hasTimestamps){let L=new Date().toISOString();if(!Q.createdAt)Q.createdAt=L;Q.updatedAt=L}if(Z.hasVersioning){if(!Q._v)Q._v=1}return Q}parseItem(X){let $=X[this.config.entityTypeAttribute];if(!$)return;let{[this.config.pkAttribute]:Z,[this.config.skAttribute]:Y,[this.config.entityTypeAttribute]:U,..._}=X;return{type:$,data:_}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(X){let $=this.models.get(X);if(!$)throw Error(`Model not found: ${X}`);return $.accessPatterns}parseWithTooling(X){let $=X.name.toUpperCase(),Z=X.primaryKey??"id",Y=this.config.keyDelimiter,U=this.parseAttributes(X),_=this.parseRelationships(X,Z),Q={pk:`${$}${Y}{${Z}}`,sk:`${$}${Y}{${Z}}`,...this.deriveGSIKeyPatterns($,Z,Y,_)},L=this.deriveAccessPatterns(X.name,$,Z,_);return{name:X.name,entityType:$,primaryKey:Z,attributes:U,relationships:_,keyPatterns:Q,accessPatterns:L,traits:X.traits??{},hasTimestamps:X.traits?.useTimestamps??!1,hasSoftDeletes:X.traits?.useSoftDeletes??!1,hasUuid:X.traits?.useUuid??!1,hasTtl:X.traits?.useTtl??!1,hasVersioning:X.traits?.useVersioning??!1,original:X}}parseAttributes(X){let $=[];if($.push({name:X.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),X.attributes)for(let[Z,Y]of Object.entries(X.attributes))$.push({name:Z,fillable:Y.fillable??!0,required:Y.required??!1,nullable:Y.nullable??!0,unique:Y.unique??!1,hidden:Y.hidden??!1,defaultValue:Y.default,cast:Y.cast,dynamoDbType:this.inferDynamoDBType(Y)});if(X.traits?.useTimestamps)$.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(X.traits?.useSoftDeletes)$.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return $}inferDynamoDBType(X){if(X.cast){let $=X.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes($))return"N";if(["boolean","bool"].includes($))return"BOOL";if(["array","list"].includes($))return"L";if(["object","json","map"].includes($))return"M"}if(X.validation?.rule){let $=String(X.validation.rule);if($.includes("integer")||$.includes("numeric")||$.includes("number"))return"N";if($.includes("boolean"))return"BOOL";if($.includes("array"))return"L";if($.includes("object"))return"M"}return"S"}parseRelationships(X,$){let Z=[];if(X.hasOne)for(let Y of X.hasOne)Z.push({type:"hasOne",relatedModel:Y,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(X.hasMany)for(let Y of X.hasMany)Z.push({type:"hasMany",relatedModel:Y,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,requiresGsi:!1});if(X.belongsTo)for(let Y of X.belongsTo)Z.push({type:"belongsTo",relatedModel:Y,foreignKey:`${Y.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(X.belongsToMany){let Y=Array.isArray(X.belongsToMany)?X.belongsToMany:Object.values(X.belongsToMany);for(let U of Y){let _=typeof U==="string"?U:U?.model;if(!_)continue;let Q=[X.name,_].sort();Z.push({type:"belongsToMany",relatedModel:_,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,pivotEntity:Q.join(""),requiresGsi:!0})}}return Z}deriveGSIKeyPatterns(X,$,Z,Y){let U={},_=1;for(let Q of Y)if(Q.requiresGsi&&_<=5)U[`gsi${_}pk`]=`${Q.relatedModel.toUpperCase()}${Z}{${Q.foreignKey}}`,U[`gsi${_}sk`]=`${X}${Z}{${$}}`,Q.gsiIndex=_,_++;return U}deriveAccessPatterns(X,$,Z,Y){let U=[];U.push({name:`Get ${X} by ID`,description:`Retrieve a single ${X} by its primary key`,entityType:$,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${$}#123`,exampleSk:`${$}#123`,efficient:!0}),U.push({name:`List all ${X}s`,description:`Scan all ${X} entities`,entityType:$,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:$,efficient:!1});for(let _ of Y){if(_.type==="hasMany")U.push({name:`Get ${_.relatedModel}s for ${X}`,description:`Query ${_.relatedModel}s related to a ${X}`,entityType:$,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${$}#123`,exampleSk:`${_.relatedModel.toUpperCase()}#`,efficient:!0});if(_.gsiIndex){let Q=`GSI${_.gsiIndex}`;U.push({name:`Get ${X}s by ${_.relatedModel}`,description:`Query ${X}s by their related ${_.relatedModel}`,entityType:$,operation:"query",index:Q,keyCondition:`gsi${_.gsiIndex}pk = :pk`,examplePk:`${_.relatedModel.toUpperCase()}#123`,efficient:!0})}}return U}toSingleTableEntity(X){let $=this.extractKeyFields(X.keyPatterns.pk);return{name:X.name,pkPattern:X.keyPatterns.pk,skPattern:X.keyPatterns.sk,keyFields:$,indexes:this.extractGSIPatterns(X.keyPatterns)}}extractKeyFields(X){let $=X.match(/\{([^}]+)\}/g);if(!$)return[];return $.map((Z)=>Z.slice(1,-1))}extractGSIPatterns(X){let $=[];for(let Z=1;Z<=5;Z++){let Y=`gsi${Z}pk`,U=`gsi${Z}sk`;if(X[Y])$.push({name:`GSI${Z}`,pkPattern:X[Y],skPattern:X[U]})}return $.length>0?$:void 0}toEntityMapping(X){return{entityType:X.name,pkPattern:X.keyPatterns.pk,skPattern:X.keyPatterns.sk}}buildGSIConfig(){let X=this.config.gsiConfig??{},$=[];if(X.gsi1pk)$.push({name:"GSI1",pkAttribute:X.gsi1pk,skAttribute:X.gsi1sk});if(X.gsi2pk)$.push({name:"GSI2",pkAttribute:X.gsi2pk,skAttribute:X.gsi2sk});if(X.gsi3pk)$.push({name:"GSI3",pkAttribute:X.gsi3pk,skAttribute:X.gsi3sk});return $}}function IO(X){return new K7(X)}function KO(X){return X.accessPatterns}function RO(X,$="#"){let Z=X.name.toUpperCase(),Y=X.primaryKey??"id";return{name:X.name,pkPattern:`${Z}${$}\${${Y}}`,skPattern:`${Z}${$}\${${Y}}`}}var Xj=t(()=>{O5(),I7()});function R7(X){let $={};for(let Z of Object.keys(X)){let Y=X[Z],U=Y.definition??Y.getDefinition?.()??Y,_=U.table||`${String(U.name).toLowerCase()}s`,Q=U.attributes??{},L={};for(let z of Object.keys(Q))L[z]=void 0;$[_]={columns:L,primaryKey:U.primaryKey??"id"}}return $}async function dX(X){let $=X.cwd??_j.cwd(),Z=X.modelsDir.startsWith("/")?X.modelsDir:`${$}/${X.modelsDir}`,Y={},U=$j(Z);for(let _ of U){let Q=`${Z}/${_}`;if(Zj(Q).isDirectory())continue;let z=Uj(Q);if(![".ts",".mts",".cts",".js",".mjs",".cjs"].includes(z))continue;let j=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,E=await import(`${Q}${j}`),V=E.default??E,G=V.definition??V.getDefinition?.()??V,J=Yj(_,z),W=G.name??J;Y[W]={...G,name:W}}return Y}var Qj=()=>{};function c1(X){if(typeof X==="string")return{model:X};if(X&&typeof X==="object"&&typeof X.model==="string"){let $=X;return{model:$.model,foreignKey:$.foreignKey,onDelete:$.onDelete}}return null}function zj(X){if(!X)return[];return(Array.isArray(X)?X:typeof X==="object"?Object.values(X):[]).map(c1).filter((Z)=>Z!==null)}function Lj(X){let $={},Z={},Y={},U={},_={};for(let Q of Object.keys(X)){let L=X[Q],z=L.definition??L.getDefinition?.()??L,j=z.table||`${String(z.name).toLowerCase()}s`;$[Q]=j,Z[j]=Q,Y[j]=z.primaryKey??"id";let E=(J)=>{if(!J)return{};let W={};if(Array.isArray(J)){for(let F of J){let K=c1(F);if(K)W[K.model]=K.model}return W}if(typeof J==="object"){for(let[F,K]of Object.entries(J)){let D=c1(K);if(D)W[F]=D.model}return W}return{}},V=(J)=>{if(!J)return{};if(Array.isArray(J)){let W={};for(let F of J)if(typeof F==="string")W[F]=F;else if(F&&typeof F==="object"&&typeof F.model==="string")W[F.model]=F;return W}return J},G=(J)=>{if(!J)return{};return J};if(U[j]={hasOne:E(z.hasOne),hasMany:E(z.hasMany),belongsTo:E(z.belongsTo),belongsToMany:V(z.belongsToMany),hasOneThrough:G(z.hasOneThrough),hasManyThrough:G(z.hasManyThrough),morphOne:E(z.morphOne),morphMany:E(z.morphMany),morphTo:z.morphTo,morphToMany:E(z.morphToMany),morphedByMany:E(z.morphedByMany)},z.scopes&&typeof z.scopes==="object"){_[j]={};for(let J of Object.keys(z.scopes)){let W=z.scopes[J];if(typeof W==="function")_[j][J]=W}}}return{modelToTable:$,tableToModel:Z,primaryKeys:Y,relations:U,scopes:_,models:X}}var D7=()=>{};function i0(X){if(f.verbose)console.log(X)}function qX(X){return X.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Z])/gi,"$1_$2").toLowerCase()}function Gj(X){let $=X;while($!==J6($)){if(M7(J5($,"package.json")))return $;$=J6($)}return H7.cwd()}function Fj(){let X=Gj(H7.cwd()),$=J5(X,"database","migrations");if(!M7($))jj($,{recursive:!0}),i0(`-- Created SQL directory: ${$}`);return $}function C7(X,$){if(!X)return!1;let Z=Fj();q$++;let U=`${I5?String(q$).padStart(10,"0"):String(Math.floor(Date.now()/1000)+q$)}-${$}.sql`,_=J5(Z,U);return Ej(_,X),i0(`-- Migration file created: ${U}`),B9++,!0}function W6(X){if(X.endsWith("_id"))return"bigint";if(X.endsWith("_at"))return"datetime";if(X.startsWith("is_")||X.startsWith("has_"))return"boolean";return}function V6(X){if(typeof X==="string"||typeof X==="number"||typeof X==="boolean"||typeof X==="bigint"||X instanceof Date)return X;return}function Oj(X){if(X&&typeof X==="object"&&"name"in X){let $=X;if($.name==="enum"||$.getRules&&Array.isArray($.getRules())){if($.enumValues&&Array.isArray($.enumValues))return $.enumValues.map((Z)=>String(Z));if($._values&&Array.isArray($._values))return $._values.map((Z)=>String(Z));if($.values&&Array.isArray($.values))return $.values.map((Z)=>String(Z))}}if(X&&typeof X==="object"){let $=X,Z=$.allowedValues||$.enumValues||$._values||$.values;if(Array.isArray(Z)&&Z.length>0)return Z.map((Y)=>String(Y))}return}function w7(X){if(!X?.rules||!Array.isArray(X.rules))return;for(let $ of X.rules)if($?.name==="max"||$?.name==="maxLength"){if($.params&&typeof $.params.max==="number")return $.params.max;if(Array.isArray($.args)&&typeof $.args[0]==="number")return $.args[0];if(typeof $.value==="number")return $.value;if(typeof $.expectedValue==="number")return $.expectedValue}return}function Jj(X){if(!X||typeof X!=="object")return;let $=X;if($.name)switch(String($.name).toLowerCase()){case"string":case"text":{let Y=w7($);return Y&&Y>255?"text":"string"}case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"json":return"json";case"enum":return"enum"}if($.type){let Z=String($.type).toLowerCase();if(Z==="string"||Z==="text")return"string";if(Z==="integer"||Z==="int")return"integer";if(Z==="bigint")return"bigint";if(Z==="float")return"float";if(Z==="number")return"integer";if(Z==="boolean")return"boolean";if(Z==="date")return"date";if(Z==="datetime")return"datetime";if(Z==="json")return"json"}return}function W5(X,$){let Z=Lj(X),Y=[];for(let Q of Object.keys(X)){let L=X[Q],z=L.table||`${String(L.name).toLowerCase()}s`,j=L.primaryKey??"id",E=L.autoIncrement!==!1,V=L.attributes??{},G=[],J=[];if(!V[j])G.push({name:qX(j),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let H of Object.keys(V)){let S=V[H],h=qX(H),p=Boolean(S.validation?.rule?.isRequired),d=H===j?!1:S.nullable??!(S.required??p),B,v,n=H===j;if(B=Jj(S.validation?.rule),!B||B==="enum"){let e=Oj(S.validation?.rule);if(e&&e.length>0)B="enum",v=e}if(!B)B=W6(h);if(!B){let e=V6(S.default);if(typeof e==="string")B=e.length>255?"text":"string";else if(typeof e==="number")B=Number.isInteger(e)?"integer":"float";else if(typeof e==="boolean")B="boolean";else if(typeof e==="bigint")B="bigint";else if(e instanceof Date)B="datetime"}if(!B)B=n?"bigint":"string";let c=B==="string"?w7(S.validation?.rule):void 0,X0={name:h,type:B,isPrimaryKey:n,isUnique:Boolean(S.unique),isNullable:d,hasDefault:typeof S.default<"u",defaultValue:V6(S.default),enumValues:v,maxLength:typeof c==="number"&&c>0&&c<=255?c:void 0};if(h.endsWith("_id")&&S.foreignKey!==!1)if(typeof S.foreignKey==="object"&&S.foreignKey!==null){let e=S.foreignKey;if(X0.references={table:e.table,column:e.column??"id",onDelete:e.onDelete,onUpdate:e.onUpdate},e.nullable!==void 0)X0.isNullable=e.nullable}else{let q0=h.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(o,y,K9)=>K9.toUpperCase()),u0=Z.modelToTable[q0];if(u0){let o=Z.primaryKeys[u0]??"id";X0.references={table:u0,column:o}}}G.push(X0)}let W=zj(L.belongsTo);for(let H of W){let S=H.foreignKey??`${qX(H.model)}_id`;if(G.some((d)=>d.name===S))continue;let h=Z.modelToTable[H.model];if(!h)continue;let p=Z.primaryKeys[h]??"id";G.push({name:S,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:h,column:p,onDelete:H.onDelete}})}let F=L.traits;if(F?.useTimestamps??F?.timestampable??!1){if(!G.some((H)=>H.name==="created_at"))G.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"});if(!G.some((H)=>H.name==="updated_at"))G.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(F?.useSoftDeletes??F?.softDeletable??!1){if(!G.some((H)=>H.name==="deleted_at"))G.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(F?.useUuid??!1){if(!G.some((H)=>H.name==="uuid"))G.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let H of L.indexes??[])J.push({name:H.name,columns:H.columns.map((S)=>qX(S)),type:H.unique?"unique":"index",where:H.where});for(let H of G)if(H.isUnique&&!H.isPrimaryKey)J.push({name:`${z}_${H.name}_unique`,columns:[H.name],type:"unique"});let T=Array.isArray(L.shardKey)?L.shardKey.map(qX):void 0,N=Array.isArray(L.sortKey)?L.sortKey.map(qX):void 0,q=L.tableKind;Y.push({table:z,columns:G,indexes:J,shardKey:T,sortKey:N,tableKind:q})}let U=new Set(Y.map((Q)=>Q.table));function _(Q){if(!U.has(Q.table))U.add(Q.table),Y.push(Q)}for(let Q of Object.keys(X)){let L=X[Q],z=L?.traits??{},j=L.table||`${String(L.name).toLowerCase()}s`,E=j.replace(/s$/,"");if(z.likeable){let V=typeof z.likeable==="object"?z.likeable:{},G=V.table||`${j}_likes`,J=V.foreignKey||`${E}_id`;_({table:G,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:J,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${G}_user_target_unique`,columns:["user_id",J],type:"unique"}]})}if(z.taggable)_({table:"taggable",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(z.categorizable)_({table:"categorizable",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_slug_unique",columns:["slug"],type:"unique"}]}),_({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizable",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}],indexes:[{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let Q of Object.keys(X)){let L=X[Q],z=L?.belongsToMany;if(!z||typeof z!=="object"||Array.isArray(z))continue;let j=L.table||`${String(L.name).toLowerCase()}s`,E=j.replace(/s$/,"");for(let[V,G]of Object.entries(z)){let J=G;if(!J||typeof J!=="object")continue;if(J.through)continue;let W=J.pivot;if(!W||!W.columns&&!W.timestamps&&!W.uniques)continue;let F=J.model,D=X[F]?.table||`${String(F).toLowerCase()}s`,w=D.replace(/s$/,""),T=J.table||[E,w].sort().join("_"),N=J.foreignKey||`${E}_id`,q=J.relatedKey||`${w}_id`,H=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:q,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:D,column:"id"}}];if(W.columns)for(let[p,d]of Object.entries(W.columns)){let B=d,v=W6(p)??"string";H.push({name:p,type:v,isPrimaryKey:!1,isUnique:!1,isNullable:B?.nullable??!1,hasDefault:B?.default!==void 0,defaultValue:B?.default})}if(W.timestamps)H.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}),H.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let S=[],h=W.uniques&&W.uniques.length>0?W.uniques:[[N,q]];for(let p=0;p<h.length;p++){let d=h[p];S.push({name:`${T}_${d.join("_")}_unique${p>0?`_${p}`:""}`,columns:[...d],type:"unique"})}_({table:T,columns:H,indexes:S})}}return{dialect:$.dialect,tables:Y}}function V5(X,$={}){q$=0,B9=0,g9=0,I5=!0;let Z=$.dryRun?()=>!1:C7,Y=[],U=ZX(X.dialect),{tables:_,deferredForeignKeys:Q}=Wj(X.tables,X.dialect);for(let z of _){let j={...z,columns:z.columns.map((W)=>Q.has(m1(z.table,W.name))?{...W,references:void 0}:W)},E=[],V=new Set;for(let W of j.columns)if(W.type==="enum"&&W.enumValues&&W.enumValues.length>0){let F=`${j.table}_${W.name}_type`;if(W.enumTypeName=F,!V.has(F)){let K=U.createEnumType(F,W.enumValues);if(K)E.push(K);V.add(F)}}let G=U.createTable(j);E.push(G);for(let W of j.indexes)E.push(U.createIndex(j.table,W));Y.push(...E);let J=E.join(`
|
|
462
462
|
|
|
463
|
-
`);Z(
|
|
464
|
-
`)}function
|
|
465
|
-
`)}function
|
|
463
|
+
`);Z(J,`create-${j.table}-table`)}for(let z of _)for(let j of z.columns)if(j.references&&Q.has(m1(z.table,j.name))){let E=U.addForeignKey(z.table,j.name,j.references.table,j.references.column,j.references.onDelete,j.references.onUpdate);if(!E)continue;Y.push(E),Z(E,`alter-${z.table}-${j.name}`)}if(B9+g9===0)i0("-- Nothing to migrate");else{let z=[];if(B9>0)z.push(`${B9} created`);if(g9>0)z.push(`${g9} updated`);i0(`-- Migration files: ${z.join(", ")}`)}return Y}function m1(X,$){return`${X}\x00${$}`}function Wj(X,$){if($==="sqlite"||X.length<2)return{tables:X,deferredForeignKeys:new Set};let Z=new Map(X.map((z)=>[z.table,z])),Y=new Map;for(let z of X)Y.set(z.table,new Set(z.columns.map((j)=>j.references?.table).filter((j)=>Boolean(j&&j!==z.table&&Z.has(j)))));let U=[],_=new Set;while(U.length<X.length){let z=X.find((j)=>!_.has(j.table)&&[...Y.get(j.table)??[]].every((E)=>_.has(E)));if(!z)break;U.push(z),_.add(z.table)}let Q=new Set(X.filter((z)=>!_.has(z.table)).map((z)=>z.table)),L=new Set;for(let z of X){if(!Q.has(z.table))continue;for(let j of z.columns)if(j.references&&Q.has(j.references.table)&&j.references.table!==z.table)L.add(m1(z.table,j.name))}return U.push(...X.filter((z)=>Q.has(z.table))),{tables:U,deferredForeignKeys:L}}function PO(X){return V5(X).join(`
|
|
464
|
+
`)}function TO(X,$){return Mj(X,$).join(`
|
|
465
|
+
`)}function Vj(X){let $=n7("crypto");function Z(U){if(U==null||typeof U!=="object"||U instanceof Date)return U;if(Array.isArray(U))return U.map((Q)=>Z(Q));let _={};for(let Q of Object.keys(U).sort())_[Q]=Z(U[Q]);return _}let Y=JSON.stringify(Z(X));return $.createHash("sha256").update(Y).digest("hex")}function I6(X){let $={};for(let Z of X)$[Z.table]=Z;return $}function j8(X){let $={};for(let Z of X)$[Z.name]=Z;return $}function u1(X,$){if($==="sqlite"){if(X.name.endsWith("_id")&&WU(X.type))return"INTEGER";switch(X.type){case"string":case"text":case"date":case"datetime":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}return X.type}function n1(X){if(!X.hasDefault||X.defaultValue===void 0)return;let $=X.defaultValue;if($ instanceof Date)return $.toISOString();if(typeof $==="boolean")return $?"1":"0";if(typeof $==="bigint"||typeof $==="number")return String($);let Z=String($).trim();if(Z=Z.replace(/::[\w ]+$/i,"").trim(),Z.startsWith("'")&&Z.endsWith("'")||Z.startsWith('"')&&Z.endsWith('"'))Z=Z.slice(1,-1);let Y=Z.toUpperCase();if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(Y))return Y==="NOW()"?"CURRENT_TIMESTAMP":Y;if(X.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(Z))return"1";if(/^(?:0|f|false|no)$/i.test(Z))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(Z))return String(Number(Z));return Z}function Ij(X,$,Z){if(u1(X,Z)!==u1($,Z))return!0;if(X.isNullable!==$.isNullable)return!0;if(X.hasDefault!==$.hasDefault)return!0;if(n1(X)!==n1($))return!0;if(X.isUnique!==$.isUnique)return!0;if(X.type==="enum"&&$.type==="enum"){let Y=(X.enumValues||[]).slice().sort().join(","),U=($.enumValues||[]).slice().sort().join(",");if(Y!==U)return!0}return!1}function K6(X,$){return JSON.stringify([u1(X,$),X.isPrimaryKey,X.isUnique,X.isNullable,X.hasDefault,n1(X)??null,(X.enumValues??[]).slice().sort(),X.references?[X.references.table,X.references.column,X.references.onDelete??null,X.references.onUpdate??null]:null])}function Kj(X,$,Z){let Y=Object.keys(X).filter((E)=>!$[E]),U=Object.keys($).filter((E)=>!X[E]),_=new Map,Q=new Map;for(let E of Y){let V=K6(X[E],Z),G=_.get(V)??[];G.push(E),_.set(V,G)}for(let E of U){let V=K6($[E],Z),G=Q.get(V)??[];G.push(E),Q.set(V,G)}let L=[],z=new Set,j=new Set;for(let[E,V]of _){let G=Q.get(E);if(V.length===1&&G&&G.length===1)L.push({from:V[0],to:G[0]}),z.add(V[0]),j.add(G[0])}return{renames:L,removed:Y.filter((E)=>!z.has(E)),added:U.filter((E)=>!j.has(E))}}function Rj(X,$){let Z=X.columns.find((Y)=>Y.name===$);if(Z&&(Z.isPrimaryKey||Z.isUnique||Z.references))return!0;return X.indexes.some((Y)=>Y.columns.includes($))}function Dj(X,$){if(Boolean(X)!==Boolean($))return!0;if(!X||!$)return!1;let Z=(Y)=>(Y??"no action").toLowerCase();return X.table!==$.table||X.column!==$.column||Z(X.onDelete)!==Z($.onDelete)||Z(X.onUpdate)!==Z($.onUpdate)}function R6(X){let $={};for(let Z of X){let Y=`${Z.type}:${Z.name}:${Z.columns.join(",")}`;$[Y]=Z}return $}function q7(X,$,Z={}){if(!X||X.dialect!==$.dialect){let W=V5($,{dryRun:Z.dryRun}),F=$.tables.map((K)=>({kind:"create_table",table:K.table,destructive:!1,sql:""}));return{statements:W,operations:F}}let Y=Z.applyRenames!==!1,U=Z.dryRun?()=>!1:C7;q$=0,B9=0,g9=0,I5=!1;let _=[],Q=[],L=ZX($.dialect),z=$.dialect,j=I6(X.tables),E=I6($.tables);for(let W of Object.keys(j))if(!E[W]){let F=L.dropTable(W);_.push(F),Q.push({kind:"drop_table",table:W,destructive:!0,sql:F}),U(F,`drop-${W}-table`),i0(`-- Detected dropped table: ${W}`)}for(let W of Object.keys(E))if(!j[W]){let F=E[W],K=[],D=new Set;for(let N of F.columns)if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let q=`${F.table}_${N.name}_type`;if(N.enumTypeName=q,!D.has(q)){let H=L.createEnumType(q,N.enumValues);if(H)K.push(H);D.add(q)}}let w=L.createTable(F);K.push(w),_.push(...K),Q.push({kind:"create_table",table:F.table,destructive:!1,sql:w});let T=K.join(`
|
|
466
466
|
|
|
467
|
-
`);U(T,`create-${F.table}-table`)}for(let W of Object.keys(E))if(!j[W]){let F=E[W];for(let K of F.indexes){let D=L.createIndex(F.table,K);_.push(D),Q.push({kind:"create_index",table:F.table,column:K.name,destructive:!1,sql:D}),U(D,`create-${K.name}-index-in-${F.table}`)}}for(let W of Object.keys(E))if(!j[W]){let F=E[W];for(let K of F.columns)if(K.references){let D=L.addForeignKey(F.table,K.name,K.references.table,K.references.column,K.references.onDelete,K.references.onUpdate);if(!D)continue;_.push(D),Q.push({kind:"add_foreign_key",table:F.table,column:K.name,destructive:!1,sql:D}),U(D,`alter-${F.table}-${K.name}`)}}let V=new Set;for(let W of Object.keys(E)){let F=j[W],K=E[W];if(!F)continue;let D=j8(F.columns),w=j8(K.columns);for(let T of Object.keys(w))if(!D[T]){let N=w[T];if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let q=`${K.table}_${N.name}_type`;if(N.enumTypeName=q,!V.has(q)){let H=L.createEnumType(q,N.enumValues);if(H)_.push(H),Q.push({kind:"create_enum",table:K.table,column:N.name,destructive:!1,sql:H}),U(H,`create-${q}-enum`);V.add(q)}}}}for(let W of Object.keys(E)){let F=j[W],K=E[W];if(!F)continue;let D=j8(F.columns),w=j8(K.columns),T=
|
|
467
|
+
`);U(T,`create-${F.table}-table`)}for(let W of Object.keys(E))if(!j[W]){let F=E[W];for(let K of F.indexes){let D=L.createIndex(F.table,K);_.push(D),Q.push({kind:"create_index",table:F.table,column:K.name,destructive:!1,sql:D}),U(D,`create-${K.name}-index-in-${F.table}`)}}for(let W of Object.keys(E))if(!j[W]){let F=E[W];for(let K of F.columns)if(K.references){let D=L.addForeignKey(F.table,K.name,K.references.table,K.references.column,K.references.onDelete,K.references.onUpdate);if(!D)continue;_.push(D),Q.push({kind:"add_foreign_key",table:F.table,column:K.name,destructive:!1,sql:D}),U(D,`alter-${F.table}-${K.name}`)}}let V=new Set;for(let W of Object.keys(E)){let F=j[W],K=E[W];if(!F)continue;let D=j8(F.columns),w=j8(K.columns);for(let T of Object.keys(w))if(!D[T]){let N=w[T];if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let q=`${K.table}_${N.name}_type`;if(N.enumTypeName=q,!V.has(q)){let H=L.createEnumType(q,N.enumValues);if(H)_.push(H),Q.push({kind:"create_enum",table:K.table,column:N.name,destructive:!1,sql:H}),U(H,`create-${q}-enum`);V.add(q)}}}}for(let W of Object.keys(E)){let F=j[W],K=E[W];if(!F)continue;let D=j8(F.columns),w=j8(K.columns),T=R6(F.indexes),N=R6(K.indexes),q=[],H=Object.keys(D).filter((v)=>!w[v]),S=Object.keys(w).filter((v)=>!D[v]);if(Y){let v=Kj(D,w,z);q=v.renames,H=v.removed,S=v.added}let h=Object.keys(w).filter((v)=>D[v]&&Ij(D[v],w[v],z)),p=Object.keys(w).filter((v)=>D[v]&&Dj(D[v].references,w[v].references));if(z==="sqlite"){if(h.length>0||p.length>0||H.some((n)=>Rj(F,n))){let n={},c=new Map(q.map((o)=>[o.to,o.from]));for(let o of K.columns)if(D[o.name])n[o.name]=o.name;else if(c.has(o.name))n[o.name]=c.get(o.name);let X0=`_qb_tmp_${K.table}`,e=0;while((j[X0]||E[X0])&&e<100)e+=1,X0=`_qb_tmp_${K.table}_${e}`;let q0=L.rebuildTable({target:K,tempName:X0,columnSource:n});_.push(q0);let u0=h.some((o)=>D[o].type!==w[o].type);Q.push({kind:"rebuild_table",table:K.table,destructive:H.length>0||u0,sql:q0});for(let o of q)Q.push({kind:"rename_column",table:K.table,from:o.from,to:o.to,destructive:!1,confidence:"high",sql:q0});for(let o of H)Q.push({kind:"drop_column",table:K.table,column:o,destructive:!0,sql:q0});i0(`-- Detected SQLite table rebuild required: ${K.table}`),U(q0,`alter-${K.table}-table`);continue}}let d=[],B=!1;for(let v of Object.keys(T))if(!N[v]){let n=T[v],c=L.dropIndex(K.table,n.name);d.push(c),_.push(c),Q.push({kind:"drop_index",table:K.table,column:n.name,destructive:!1,sql:c}),i0(`-- Detected dropped index: ${n.name} from ${K.table}`),B=!0}for(let v of q){let n=L.renameColumn(K.table,v.from,v.to);d.push(n),_.push(n),Q.push({kind:"rename_column",table:K.table,from:v.from,to:v.to,destructive:!1,confidence:"high",sql:n}),i0(`-- Detected renamed column: ${K.table}.${v.from} -> ${v.to}`),B=!0}for(let v of H){let n=L.dropColumn(K.table,v);d.push(n),_.push(n),Q.push({kind:"drop_column",table:K.table,column:v,destructive:!0,sql:n}),i0(`-- Detected dropped column: ${K.table}.${v}`),B=!0}for(let v of h){let n=D[v],c=w[v],X0=L.modifyColumn(K.table,c);d.push(X0),_.push(X0),Q.push({kind:"modify_column",table:K.table,column:v,destructive:n.type!==c.type,sql:X0}),i0(`-- Detected column change: ${K.table}.${v} (${n.type} -> ${c.type})`),B=!0}for(let v of p){let n=w[v];if(!n.references)continue;let c=L.addForeignKey(K.table,n.name,n.references.table,n.references.column,n.references.onDelete,n.references.onUpdate);if(!c)continue;d.push(c),_.push(c),Q.push({kind:"add_foreign_key",table:K.table,column:v,destructive:!1,sql:c}),i0(`-- Detected foreign-key change: ${K.table}.${v} -> ${n.references.table}(${n.references.column})`),B=!0}for(let v of S){let n=w[v],c=L.addColumn(K.table,n);if(d.push(c),_.push(c),Q.push({kind:"add_column",table:K.table,column:n.name,destructive:!1,sql:c}),i0(`-- Detected new column: ${K.table}.${n.name}`),B=!0,n.references){let X0=L.addForeignKey(K.table,n.name,n.references.table,n.references.column,n.references.onDelete,n.references.onUpdate);if(X0)d.push(X0),_.push(X0),Q.push({kind:"add_foreign_key",table:K.table,column:n.name,destructive:!1,sql:X0})}}for(let v of Object.keys(N))if(!T[v]){let n=N[v],c=L.createIndex(K.table,n);d.push(c),_.push(c),Q.push({kind:"create_index",table:K.table,column:n.name,destructive:!1,sql:c}),i0(`-- Detected new index: ${n.name} in ${K.table}`),B=!0}if(B){let v=d.join(`
|
|
468
468
|
|
|
469
|
-
`);U(v,`alter-${K.table}-table`)}}if(
|
|
469
|
+
`);U(v,`alter-${K.table}-table`)}}if(B9+g9===0)i0("-- Nothing to migrate");else{let W=[];if(B9>0)W.push(`${B9} created`);if(g9>0)W.push(`${g9} updated`);i0(`-- Migration files: ${W.join(", ")}`)}return{statements:_.length===0?["-- No changes detected"]:_,operations:Q}}function Mj(X,$,Z={}){return q7(X,$,Z).statements}var q$=0,B9=0,g9=0,I5=!0,Hj=t(()=>{d0(),_Z(),D7()});function NO(X){return X}class Cj{get order(){return 100}get description(){return}}function SO(X){return X}var y0=t(async()=>{P8(),P8(),Rz(),H6(),UZ(),P8(),await d0(),_Z(),O5(),I7(),Xj(),Q2(),Qj(),D7(),Hj(),F7(),X5()});await y0();var T7=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000","PRAGMA wal_autocheckpoint = 1"];function qj(X){for(let $ of T7)try{X.unsafe($).execute().catch(()=>{})}catch{}}var P7=new WeakSet;function N7(){try{let X=j7?.();if(!X||typeof X.run!=="function"||P7.has(X))return;for(let $ of T7)try{X.run($)}catch{}P7.add(X)}catch{}}function cO(X){L7(X),N7()}function mO(X){let $=R0(X);if(!X?.sql&&f.dialect==="sqlite")qj($),N7();return $}var Pj=new Map;function uO(X,$){let Z=EZ;if(typeof Z==="function")return Z(X,$);Pj.set(X,$);let Y=typeof $?.getDefinition==="function"?$.getDefinition():$?.definition;if(Y&&typeof Y==="object")F5(Y);return $}var Tj=/^[A-Z_][A-Z0-9_]*$/i;function Nj(X,$={}){if(typeof X!=="string"||X.length===0)return{valid:!1,reason:"empty"};if(X.length>64)return{valid:!1,reason:"too-long"};if(!Tj.test(X))return{valid:!1,reason:"invalid-shape"};if($.allowlist&&!$.allowlist.includes(X))return{valid:!1,reason:"not-in-allowlist"};return{valid:!0}}function nO(X,$={}){let Z=Nj(X,$);if(Z.valid)return;let Y=$.context?` in ${$.context}`:"";throw Error(`[query-builder] Refusing to use ${JSON.stringify(X)} as a SQL identifier${Y} \u2014 ${Z.reason}`)}var S7=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function Sj(X){return typeof X==="string"&&S7.has(X.toLowerCase())}function iO(X,$){if(Sj(X))return;let Z=$?` in ${$}`:"";throw Error(`[query-builder] Refusing to use ${JSON.stringify(X)} as a SQL operator${Z} \u2014 not in the allowed set (${[...S7].join(", ")})`)}export{vG as wipeDatabase,SF as waitReady,Vz as validateSchema,Nj as validateIdentifier,wF as unsafe,VO as unmarshallItem,JO as toModelInstance,OO as toDynamoDBItem,TG as tinker,gG as tableInfo,l_ as startConsole,RO as stacksModelToEntity,zQ as sqlTypeToAttr,CF as sql,LF as showModel,m_ as setQueryCacheMaxSize,C_ as setConfig,jO as seedModel,Ez as runSeeders,DF as runSeeder,RG as runBenchmark,w_ as resolveSqlitePragmas,PX as resolvePivot,O6 as resolveKeyPattern,SQ as resetDatabase,KG as resetConnection,VF as relationDiagram,uO as registerModel,oL as registerBrowserModels,MG as raw,FF as queryExplainAll,jF as ping,eL as parseStacksModels,yG as optimizeDatabase,LF as modelShow,zU as modelNameForTable,nQ as migrateStatus,XF as migrateRollback,mj as migrateModels,UF as migrateList,rG as migrateGenerate,WO as marshallObject,MF as makeSeeder,nG as makeModel,dX as loadModels,DG as iterateAllPivots,Sj as isSafeOperator,W0 as isMysqlLike,cj as isDefinitionEqual,gj as isBrowser,pG as introspectDatabase,dG as introspect,UQ as inspectTable,AG as importData,T8 as hashTableDefinition,Vj as hashMigrationPlan,iL as hasModel,h0 as getPlaceholders,i as getPlaceholder,nL as getModelRegistry,mL as getModel,ZX as getDialectDriver,j7 as getDatabase,OG as getConfig,fj as getBrowserConfig,uL as getAllModels,PO as generateSqlString,V5 as generateSql,GQ as generateModelSource,HU as generateMigration,TO as generateDiffSqlString,Mj as generateDiffSql,q7 as generateDiffOperations,VF as generateDiagram,KO as generateAccessPatterns,HF as freshDatabase,fG as file,e7 as extractTableDefinition,X2 as extractModelSchema,G6 as extractInsertId,E6 as extractChanges,SG as exportData,FF as explainAllQueries,bG as explain,NQ as executeMigration,_2 as dynamo,kG as dumpDatabase,SO as defineSeeder,NO as defineModels,F5 as defineModel,M1 as defaultConfig,vG as dbWipe,xG as dbStats,yG as dbOptimize,t_ as dbInfo,LO as createTableFromModel,rL as createSingleTableManager,aL as createRepository,mO as createQueryBuilder,gL as createModel,Y2 as createMigrationDriver,IO as createDynamoDBToolingAdapter,EO as createDynamoDBQueryBuilder,GO as createDynamoDBItemBuilder,bX as createDynamoDBDriver,FO as createDynamoDBClient,uj as createDynamo,q6 as createClient,i7 as createBrowserModel,dj as createBrowserDb,$2 as convertSchemaToDefinition,cO as configureOrm,pj as configureModels,bj as configureBrowser,f as config,c_ as clearQueryCache,lL as clearModelRegistry,NF as checkSchema,n1 as canonicalizeDefault,u1 as canonicalStorageType,CG as cacheStats,wG as cacheConfig,HG as cacheClear,Lj as buildSchemaMeta,W5 as buildMigrationPlan,Z2 as buildDynamoDBMigrationPlan,R7 as buildDatabaseSchema,M6 as browserQuery,l7 as browserAuth,N7 as bootstrapModelExecutorPragmas,iO as assertSafeOperator,nO as assertSafeIdentifier,qj as applySqlitePragmas,e1 as applySqliteBootstrapPragmas,W7 as SingleTableRepository,V7 as SingleTableQueryBuilder,tL as SingleTablePatterns,J7 as SingleTableManager,JU as SingleStoreDriver,Cj as Seeder,VU as SQLiteDriver,T7 as SQLITE_BOOTSTRAP_PRAGMAS,mO as QueryBuilder,OU as PostgresDriver,Y5 as MySQLDriver,a7 as Model,R9 as MIGRATIONS_TABLE,A6 as EntityQueryBuilder,K7 as DynamoDBToolingAdapter,gX as DynamoDBQueryBuilder,T6 as DynamoDBMigrationTracker,S6 as DynamoDBMigrationDriver,f9 as DynamoDBItemBuilder,C6 as DynamoDBDriverImpl,w6 as DynamoDBClient,YU as DEFAULT_SQLITE_PRAGMAS,y9 as BrowserQueryError,D6 as BrowserQueryBuilder,G7 as BelongsToManyRelationBuilder};
|