@stacksjs/query-builder 0.70.111 → 0.70.112

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.
Files changed (2) hide show
  1. package/dist/index.js +48 -48
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,26 +1,26 @@
1
1
  // @bun
2
- var m0=import.meta.require;import{existsSync as H5,statSync as C5}from"fs";import{existsSync as E2,mkdirSync as oj,readdirSync as rj,readFileSync as G2,writeFileSync as aj}from"fs";import{homedir as LX}from"os";import{dirname as XE,resolve as L9}from"path";import S8 from"process";import{existsSync as w5,statSync as q5}from"fs";import{existsSync as F1,mkdirSync as F2,readdirSync as O2,writeFileSync as J2}from"fs";import{homedir as jX}from"os";import{dirname as P5,resolve as s0}from"path";import t9 from"process";import{join as W2,relative as V2,resolve as T5}from"path";import A8 from"process";import{existsSync as k6,mkdirSync as EE,readdirSync as GE,writeFileSync as FE}from"fs";import{homedir as FZ}from"os";import{dirname as WE,resolve as i0}from"path";import T$ from"process";import{join as I2,relative as R2,resolve as N5}from"path";import k8 from"process";import{existsSync as x6,mkdirSync as DE,readdirSync as ME,writeFileSync as HE}from"fs";import{dirname as wE,resolve as x8}from"path";import O1 from"process";import{Buffer as v9}from"buffer";import{createCipheriv as K2,createDecipheriv as D2,randomBytes as OZ}from"crypto";import{closeSync as JZ,createReadStream as S5,createWriteStream as M2,existsSync as WZ,fsyncSync as A5,openSync as k5,writeFileSync as H2}from"fs";import{access as C2,constants as x5,mkdir as w2,readdir as g$,rename as B5,stat as EX,unlink as d$,writeFile as VZ}from"fs/promises";import{join as GX}from"path";import g0 from"process";import{pipeline as q2}from"stream/promises";import{createGzip as y5}from"zlib";import FX from"process";import T9 from"process";import{Buffer as D9}from"buffer";import{createCipheriv as P2,createDecipheriv as T2,randomBytes as IZ}from"crypto";import{closeSync as RZ,createReadStream as h5,createWriteStream as N2,existsSync as p$,fsyncSync as v5,openSync as b5,writeFileSync as S2}from"fs";import{access as A2,constants as f5,mkdir as k2,readdir as c$,rename as g5,stat as OX,unlink as m$,writeFile as KZ}from"fs/promises";import{isAbsolute as x2,join as JX,resolve as B2}from"path";import j0 from"process";import{pipeline as y2}from"stream/promises";import{createGzip as d5}from"zlib";import WX from"process";import N9 from"process";import u$ from"process";import{existsSync as n$}from"fs";import{resolve as DZ}from"path";import{existsSync as h2}from"fs";import{existsSync as v2,readdirSync as b2}from"fs";import{extname as MZ,resolve as p5}from"path";import f2 from"process";import{join as g2,relative as d2,resolve as c5}from"path";import B8 from"process";import{Buffer as M9}from"buffer";import{createCipheriv as p2,createDecipheriv as c2,randomBytes as HZ}from"crypto";import{closeSync as CZ,createReadStream as m5,createWriteStream as m2,existsSync as i$,fsyncSync as u5,openSync as n5,writeFileSync as u2}from"fs";import{access as n2,constants as i5,mkdir as i2,readdir as l$,rename as l5,stat as VX,unlink as s$,writeFile as wZ}from"fs/promises";import{isAbsolute as l2,join as IX,resolve as s2}from"path";import E0 from"process";import{pipeline as o2}from"stream/promises";import{createGzip as s5}from"zlib";import RX from"process";import S9 from"process";import o$ from"process";import{existsSync as r$}from"fs";import{resolve as qZ}from"path";import{existsSync as r2}from"fs";import{Database as N_}from"bun:sqlite";import{mkdirSync as S_}from"fs";import{dirname as A_}from"path";import e$ from"process";import Z8 from"process";import{createInterface as o_}from"readline";import{existsSync as t_,readFileSync as e_,writeFileSync as aX}from"fs";import SY from"process";import AY from"process";import{existsSync as T1,mkdirSync as MQ,writeFileSync as HQ}from"fs";import{dirname as kY,join as N1}from"path";import FU from"process";import{existsSync as d9,mkdirSync as RU,mkdtempSync as qQ,readdirSync as KU,readFileSync as DU,rmSync as PQ,unlinkSync as C8,writeFileSync as MU}from"fs";import{tmpdir as TQ}from"os";import{join as n0}from"path";import y$ from"process";import{existsSync as S1,readFileSync as bQ,unlinkSync as fQ}from"fs";import{dirname as BY,join as Q5}from"path";import NU from"process";import{existsSync as SU,readdirSync as uQ}from"fs";import{dirname as yY,join as AU}from"path";import kU from"process";import{readdirSync as oQ}from"fs";import{extname as pZ,join as hY}from"path";import rQ from"process";import{readdirSync as eQ,readFileSync as vY,statSync as Xz}from"fs";import{extname as bY,join as $z}from"path";import{writeFileSync as Yz}from"fs";import{join as Uz}from"path";import _z from"process";import{existsSync as c8,mkdirSync as jz,readdirSync as Ez,writeFileSync as Gz}from"fs";import{dirname as fY,join as m9}from"path";import h$ from"process";import{existsSync as Vz}from"fs";import{dirname as gY,join as BU}from"path";import yU from"process";import{existsSync as Hz}from"fs";import{join as Cz}from"path";import wz from"process";import{existsSync as dY,statSync as pY}from"fs";import{join as qz,relative as Pz,resolve as cY}from"path";import m8 from"process";import{Buffer as H9}from"buffer";import{createCipheriv as Tz,createDecipheriv as Nz,randomBytes as cZ}from"crypto";import{closeSync as mZ,createReadStream as mY,createWriteStream as Sz,existsSync as Y8,fsyncSync as uY,openSync as nY,writeFileSync as Az}from"fs";import{access as kz,constants as iY,mkdir as xz,readdir as U8,rename as lY,stat as DX,unlink as _8,writeFile as uZ}from"fs/promises";import{isAbsolute as Bz,join as MX,resolve as yz}from"path";import W0 from"process";import{pipeline as hz}from"stream/promises";import{createGzip as sY}from"zlib";import HX from"process";import A9 from"process";import Q8 from"process";import{existsSync as z8}from"fs";import{resolve as nZ}from"path";import{existsSync as vz}from"fs";import{existsSync as A1,mkdirSync as bz,readdirSync as fz,readFileSync as gz,writeFileSync as dz}from"fs";import{homedir as CX}from"os";import{dirname as oY,resolve as o0}from"path";import XX from"process";import{existsSync as pz,readdirSync as cz}from"fs";import{extname as iZ,resolve as rY}from"path";import mz from"process";import{spawnSync as uz}from"child_process";import{existsSync as NX,readFileSync as nz}from"fs";import{join as SX}from"path";import hU from"process";import{Database as f1}from"bun:sqlite";import{readdirSync as Yj,statSync as Uj}from"fs";import{basename as _j,extname as Qj}from"path";import zj from"process";import{existsSync as C7,mkdirSync as Gj,writeFileSync as Fj}from"fs";import{dirname as J6,join as J5}from"path";import w7 from"process";var{defineProperty:G1,getOwnPropertyNames:p7,getOwnPropertyDescriptor:c7}=Object,m7=Object.prototype.hasOwnProperty;function u7(X){return this[X]}var n7=(X)=>{var $=(K5??=new WeakMap).get(X),Z;if($)return $;if($=G1({},"__esModule",{value:!0}),X&&typeof X==="object"||typeof X==="function"){for(var Y of p7(X))if(!m7.call($,Y))G1($,Y,{get:u7.bind(X,Y),enumerable:!(Z=c7(X,Y))||Z.enumerable})}return K5.set(X,$),$},K5,i7=(X)=>X;function l7(X,$){this[X]=i7.bind(null,$)}var i1=(X,$)=>{for(var Z in $)G1(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:l7.bind($,Z)})},e=(X,$)=>()=>(X&&($=X(X=0)),$),s7=import.meta.require;function gj(X){Q0={...Q0,...X}}function dj(){return Q0}function pj(){return typeof window<"u"&&typeof document<"u"}async function G8(){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 u0(){let X={"Content-Type":"application/json",Accept:"application/json",...Q0.headers},$=await G8();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 u0()}),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 u0()});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 u0()});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 u0(),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 u0(),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 u0()})).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 u0()});return E9(U)}toState(){return{...this.state}}}function M6(X){return new D6(X)}function cj(){return new Proxy({},{get:(X,$)=>{return()=>M6($)}})}class xX{_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 D0{_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 u0()}),Z=await E9($);return(Array.isArray(Z)?Z:Z.data).map((U)=>new xX(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 u0()});if(Z.status===404)return null;let Y=await E9(Z),U="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new xX(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 u0()});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 u0()}),_=await E9(U);return{..._,data:_.data.map((Q)=>new xX(this._definition,Q))}}}function o7(X){return new Proxy({query:()=>new D0(X),where(Z,Y,U){return new D0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new D0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new D0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new D0(X).whereNotIn(Z,Y)},whereNull(Z){return new D0(X).whereNull(Z)},whereNotNull(Z){return new D0(X).whereNotNull(Z)},whereLike(Z,Y){return new D0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new D0(X).orderBy(Z,Y)},orderByDesc(Z){return new D0(X).orderByDesc(Z)},select(...Z){return new D0(X).select(...Z)},limit:(Z)=>new D0(X).limit(Z),take:(Z)=>new D0(X).take(Z),skip:(Z)=>new D0(X).skip(Z),latest:(Z="created_at")=>new D0(X).latest(Z),oldest:(Z="created_at")=>new D0(X).oldest(Z),async find(Z){return new D0(X).find(Z)},async findOrFail(Z){return new D0(X).findOrFail(Z)},async all(){return new D0(X).get()},async first(){return new D0(X).first()},async firstOrFail(){return new D0(X).firstOrFail()},async count(){return new D0(X).count()},async exists(){return new D0(X).exists()},async paginate(Z,Y){return new D0(X).paginate(Z,Y)},async pluck(Z){return new D0(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 u0(),body:JSON.stringify(_)}),L=await E9(Q),z="data"in L&&!Array.isArray(L.data)?L.data:L;return new xX(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 u0(),body:JSON.stringify(Q)}),z=await E9(L),j="data"in z&&!Array.isArray(z.data)?z.data:z;return new xX(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 u0()})).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 D0(X).where(_,Q)}return Reflect.get(Z,Y)}})}var Q0,y9,r7,a7,H6=e(()=>{Q0={baseUrl:""},y9=class extends Error{status;constructor($,Z){super($);this.name="BrowserQueryError",this.status=Z}},r7={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 G8())try{await fetch(`${Q0.baseUrl}/logout`,{method:"POST",headers:await u0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await G8())return null;try{let $=await fetch(`${Q0.baseUrl}/user`,{method:"GET",headers:await u0()});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:G8},a7=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 gX(X){return new C6(X)}async function lX(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 t7(X,$,Z,Y){let U=await lX(new TextEncoder().encode(`AWS4${X}`),$),_=await lX(U,Z),Q=await lX(_,Y);return lX(Q,"aws4_request")}async function e7(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(`
2
+ var m0=import.meta.require;import{existsSync as C5,statSync as w5}from"fs";import{existsSync as E2,mkdirSync as oj,readdirSync as rj,readFileSync as G2,writeFileSync as aj}from"fs";import{homedir as LX}from"os";import{dirname as XE,resolve as L9}from"path";import S8 from"process";import{existsSync as q5,statSync as P5}from"fs";import{existsSync as F1,mkdirSync as F2,readdirSync as O2,writeFileSync as J2}from"fs";import{homedir as jX}from"os";import{dirname as T5,resolve as s0}from"path";import t9 from"process";import{join as W2,relative as V2,resolve as N5}from"path";import A8 from"process";import{existsSync as x6,mkdirSync as EE,readdirSync as GE,writeFileSync as FE}from"fs";import{homedir as FZ}from"os";import{dirname as WE,resolve as i0}from"path";import T$ from"process";import{join as I2,relative as R2,resolve as S5}from"path";import k8 from"process";import{existsSync as B6,mkdirSync as DE,readdirSync as ME,writeFileSync as HE}from"fs";import{dirname as wE,resolve as x8}from"path";import O1 from"process";import{Buffer as b9}from"buffer";import{createCipheriv as K2,createDecipheriv as D2,randomBytes as OZ}from"crypto";import{closeSync as JZ,createReadStream as A5,createWriteStream as M2,existsSync as WZ,fsyncSync as k5,openSync as x5,writeFileSync as H2}from"fs";import{access as C2,constants as B5,mkdir as w2,readdir as g$,rename as y5,stat as EX,unlink as d$,writeFile as VZ}from"fs/promises";import{join as GX}from"path";import g0 from"process";import{pipeline as q2}from"stream/promises";import{createGzip as h5}from"zlib";import FX from"process";import T9 from"process";import{Buffer as D9}from"buffer";import{createCipheriv as P2,createDecipheriv as T2,randomBytes as IZ}from"crypto";import{closeSync as RZ,createReadStream as v5,createWriteStream as N2,existsSync as p$,fsyncSync as b5,openSync as f5,writeFileSync as S2}from"fs";import{access as A2,constants as g5,mkdir as k2,readdir as c$,rename as d5,stat as OX,unlink as m$,writeFile as KZ}from"fs/promises";import{isAbsolute as x2,join as JX,resolve as B2}from"path";import j0 from"process";import{pipeline as y2}from"stream/promises";import{createGzip as p5}from"zlib";import WX from"process";import N9 from"process";import u$ from"process";import{existsSync as n$}from"fs";import{resolve as DZ}from"path";import{existsSync as h2}from"fs";import{existsSync as v2,readdirSync as b2}from"fs";import{extname as MZ,resolve as c5}from"path";import f2 from"process";import{join as g2,relative as d2,resolve as m5}from"path";import B8 from"process";import{Buffer as M9}from"buffer";import{createCipheriv as p2,createDecipheriv as c2,randomBytes as HZ}from"crypto";import{closeSync as CZ,createReadStream as u5,createWriteStream as m2,existsSync as i$,fsyncSync as n5,openSync as i5,writeFileSync as u2}from"fs";import{access as n2,constants as l5,mkdir as i2,readdir as l$,rename as s5,stat as VX,unlink as s$,writeFile as wZ}from"fs/promises";import{isAbsolute as l2,join as IX,resolve as s2}from"path";import E0 from"process";import{pipeline as o2}from"stream/promises";import{createGzip as o5}from"zlib";import RX from"process";import S9 from"process";import o$ from"process";import{existsSync as r$}from"fs";import{resolve as qZ}from"path";import{existsSync as r2}from"fs";import{Database as N_}from"bun:sqlite";import{mkdirSync as S_}from"fs";import{dirname as A_}from"path";import e$ from"process";import Z8 from"process";import{createInterface as o_}from"readline";import{existsSync as t_,readFileSync as e_,writeFileSync as aX}from"fs";import AY from"process";import kY from"process";import{existsSync as T1,mkdirSync as MQ,writeFileSync as HQ}from"fs";import{dirname as xY,join as N1}from"path";import OU from"process";import{existsSync as v9,mkdirSync as KU,mkdtempSync as qQ,readdirSync as DU,readFileSync as U5,rmSync as PQ,unlinkSync as C8,writeFileSync as MU}from"fs";import{tmpdir as TQ}from"os";import{join as n0}from"path";import y$ from"process";import{existsSync as S1,readFileSync as bQ,unlinkSync as fQ}from"fs";import{dirname as yY,join as z5}from"path";import NU from"process";import{existsSync as SU,readdirSync as uQ}from"fs";import{dirname as hY,join as AU}from"path";import kU from"process";import{readdirSync as oQ}from"fs";import{extname as pZ,join as vY}from"path";import rQ from"process";import{readdirSync as eQ,readFileSync as bY,statSync as Xz}from"fs";import{extname as fY,join as $z}from"path";import{writeFileSync as Yz}from"fs";import{join as Uz}from"path";import _z from"process";import{existsSync as c8,mkdirSync as jz,readdirSync as Ez,writeFileSync as Gz}from"fs";import{dirname as gY,join as m9}from"path";import h$ from"process";import{existsSync as Vz}from"fs";import{dirname as dY,join as BU}from"path";import yU from"process";import{existsSync as Hz}from"fs";import{join as Cz}from"path";import wz from"process";import{existsSync as pY,statSync as cY}from"fs";import{join as qz,relative as Pz,resolve as mY}from"path";import m8 from"process";import{Buffer as H9}from"buffer";import{createCipheriv as Tz,createDecipheriv as Nz,randomBytes as cZ}from"crypto";import{closeSync as mZ,createReadStream as uY,createWriteStream as Sz,existsSync as Y8,fsyncSync as nY,openSync as iY,writeFileSync as Az}from"fs";import{access as kz,constants as lY,mkdir as xz,readdir as U8,rename as sY,stat as DX,unlink as _8,writeFile as uZ}from"fs/promises";import{isAbsolute as Bz,join as MX,resolve as yz}from"path";import W0 from"process";import{pipeline as hz}from"stream/promises";import{createGzip as oY}from"zlib";import HX from"process";import A9 from"process";import Q8 from"process";import{existsSync as z8}from"fs";import{resolve as nZ}from"path";import{existsSync as vz}from"fs";import{existsSync as A1,mkdirSync as bz,readdirSync as fz,readFileSync as gz,writeFileSync as dz}from"fs";import{homedir as CX}from"os";import{dirname as rY,resolve as o0}from"path";import XX from"process";import{existsSync as pz,readdirSync as cz}from"fs";import{extname as iZ,resolve as aY}from"path";import mz from"process";import{spawnSync as uz}from"child_process";import{existsSync as NX,readFileSync as nz}from"fs";import{join as SX}from"path";import hU from"process";import{Database as f1}from"bun:sqlite";import{readdirSync as Yj,statSync as Uj}from"fs";import{basename as _j,extname as Qj}from"path";import zj from"process";import{existsSync as C7,mkdirSync as Gj,writeFileSync as Fj}from"fs";import{dirname as W6,join as W5}from"path";import w7 from"process";var{defineProperty:G1,getOwnPropertyNames:p7,getOwnPropertyDescriptor:c7}=Object,m7=Object.prototype.hasOwnProperty;function u7(X){return this[X]}var n7=(X)=>{var $=(D5??=new WeakMap).get(X),Z;if($)return $;if($=G1({},"__esModule",{value:!0}),X&&typeof X==="object"||typeof X==="function"){for(var Y of p7(X))if(!m7.call($,Y))G1($,Y,{get:u7.bind(X,Y),enumerable:!(Z=c7(X,Y))||Z.enumerable})}return D5.set(X,$),$},D5,i7=(X)=>X;function l7(X,$){this[X]=i7.bind(null,$)}var i1=(X,$)=>{for(var Z in $)G1(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:l7.bind($,Z)})},e=(X,$)=>()=>(X&&($=X(X=0)),$),s7=import.meta.require;function gj(X){Q0={...Q0,...X}}function dj(){return Q0}function pj(){return typeof window<"u"&&typeof document<"u"}async function G8(){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 u0(){let X={"Content-Type":"application/json",Accept:"application/json",...Q0.headers},$=await G8();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 M6{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 u0()}),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 u0()});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 u0()});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 u0(),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 u0(),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 u0()})).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 u0()});return E9(U)}toState(){return{...this.state}}}function H6(X){return new M6(X)}function cj(){return new Proxy({},{get:(X,$)=>{return()=>H6($)}})}class xX{_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 D0{_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 u0()}),Z=await E9($);return(Array.isArray(Z)?Z:Z.data).map((U)=>new xX(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 u0()});if(Z.status===404)return null;let Y=await E9(Z),U="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new xX(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 u0()});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 u0()}),_=await E9(U);return{..._,data:_.data.map((Q)=>new xX(this._definition,Q))}}}function o7(X){return new Proxy({query:()=>new D0(X),where(Z,Y,U){return new D0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new D0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new D0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new D0(X).whereNotIn(Z,Y)},whereNull(Z){return new D0(X).whereNull(Z)},whereNotNull(Z){return new D0(X).whereNotNull(Z)},whereLike(Z,Y){return new D0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new D0(X).orderBy(Z,Y)},orderByDesc(Z){return new D0(X).orderByDesc(Z)},select(...Z){return new D0(X).select(...Z)},limit:(Z)=>new D0(X).limit(Z),take:(Z)=>new D0(X).take(Z),skip:(Z)=>new D0(X).skip(Z),latest:(Z="created_at")=>new D0(X).latest(Z),oldest:(Z="created_at")=>new D0(X).oldest(Z),async find(Z){return new D0(X).find(Z)},async findOrFail(Z){return new D0(X).findOrFail(Z)},async all(){return new D0(X).get()},async first(){return new D0(X).first()},async firstOrFail(){return new D0(X).firstOrFail()},async count(){return new D0(X).count()},async exists(){return new D0(X).exists()},async paginate(Z,Y){return new D0(X).paginate(Z,Y)},async pluck(Z){return new D0(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 u0(),body:JSON.stringify(_)}),L=await E9(Q),z="data"in L&&!Array.isArray(L.data)?L.data:L;return new xX(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 u0(),body:JSON.stringify(Q)}),z=await E9(L),j="data"in z&&!Array.isArray(z.data)?z.data:z;return new xX(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 u0()})).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 D0(X).where(_,Q)}return Reflect.get(Z,Y)}})}var Q0,y9,r7,a7,C6=e(()=>{Q0={baseUrl:""},y9=class extends Error{status;constructor($,Z){super($);this.name="BrowserQueryError",this.status=Z}},r7={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 G8())try{await fetch(`${Q0.baseUrl}/logout`,{method:"POST",headers:await u0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await G8())return null;try{let $=await fetch(`${Q0.baseUrl}/user`,{method:"GET",headers:await u0()});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:G8},a7=H6});class w6{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 gX(X){return new w6(X)}async function lX(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 M5(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 t7(X,$,Z,Y){let U=await lX(new TextEncoder().encode(`AWS4${X}`),$),_=await lX(U,Z),Q=await lX(_,Y);return lX(Q,"aws4_request")}async function e7(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((d)=>d.toLowerCase()).join(";"),R=await D5(Y),D=[X,E,V,W,F,R].join(`
5
- `),q=await D5(D),w="AWS4-HMAC-SHA256",A=`${j}/${_}/${Q}/aws4_request`,P=[w,z,A,q].join(`
6
- `),H=await t7(U.secretAccessKey,j,_,Q),N=await lX(H,P),S=Array.from(new Uint8Array(N)).map((d)=>d.toString(16).padStart(2,"0")).join(""),h=`${w} Credential=${U.accessKeyId}/${A}, SignedHeaders=${F}, Signature=${S}`;return{...G,authorization:h}}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 e7("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 mj(X){h9={...h9,...X},F8=null,O8=null}function l9(){if(!F8)F8=q6({region:h9.region??"us-east-1",endpoint:h9.endpoint,credentials:h9.credentials});return F8}function s9(){if(!O8)O8=gX({region:h9.region??"us-east-1",endpoint:h9.endpoint,credentials:h9.credentials});return O8}class X2{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}`,R=`:val${G}`;E[F]=J,V[R]=Y.marshall({v:W}).v,j.push(`${F} = ${R}`),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,F8=null,O8=null,$2=e(()=>{h9={region:process.env.AWS_REGION??"us-east-1"}});function N8(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 Z2(X){let $=Y2(X);return U2($)}function Y2(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 U2(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:N8($)}}function uj(X,$){return N8(X)===N8($)}class T6{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 $=`${mX}#${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 $=`${mX}#${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),_=`${mX}#${X}`,Q=`${M5}#${String(U).padStart(6,"0")}`,L={tableName:X,hash:N8($),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(`${mX}#`,"");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=`${mX}#${X}`;for(let Y of $){let U=`${M5}#${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",mX="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 $=Z2(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 Q2(X){return new S6(X)}async function nj(X,$){return Q2($).migrateModels(X)}var z2=e(()=>{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=gX($),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 ij(){return new l1}var L2,j2=e(()=>{$2(),z2(),N6(),L2=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 a2(X,$){this[X]=y4.bind(null,$)}class J1{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 W1{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 t2(X,$={}){let Y=Object.keys($).sort().map((U)=>`${U}:${$[U]}`).join("|");return Y?`${X}:${Y}`:X}function e2(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function X4(X){return X.getStats().size*2}function s1(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&q0($[0])&&"id"in $[0]&&$[0].id===3&&q0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(q0($)&&q0(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(q0(X)&&"arr"in X&&Array.isArray(X.arr)&&q0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&q0($[0])&&q0(X[0])){let Y=[...$];for(let U of X)if(q0(U)&&"name"in U){if(!Y.find((Q)=>q0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(q0(U)&&"path"in U){if(!Y.find((Q)=>q0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>y8(_,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(!q0($)||!q0(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(q0(U)&&q0(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&&q0(U[0])&&q0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(q0(Q)&&"name"in Q){if(!_.find((z)=>q0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(q0(Q)&&"path"in Q){if(!_.find((z)=>q0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>y8(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 y8(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(!y8(X[Z],$[Z]))return!1;return!0}if(q0(X)&&q0($)){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(!y8(X[U],$[U]))return!1}return!0}return!1}function q0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function $4(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 Z4({name:X="",cwd:$,defaultConfig:Z}){let Y=$||O1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],_=[`${X}.config`,`.${X}.config`,X,`.${X}`];for(let Q of _)for(let L of U){let z=x8(Y,`${Q}${L}`),j=await $4(z,Z);if(j!==null)return j}try{let Q=x8(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 Y4(X,$={}){let Z=k8.cwd();while(Z.includes("storage"))Z=N5(Z,"..");let Y=N5(Z,X||"");if($?.relative)return R2(k8.cwd(),Y);return Y}async function U4(){try{let X=await Z4({name:"clarity",defaultConfig:W8,cwd:k8.cwd(),endpoint:"",headers:{}});return{...W8,...X}}catch{return W8}}function N0(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _4(){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 _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:FX.pid,hostname:$(),environment:FX.env.NODE_ENV||"development",platform:FX.platform,version:FX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:FX.env.NODE_ENV||FX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class h8{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??g0.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{...V8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...V8};return{...V8,...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 C2(this.config.logDirectory,x5.F_OK|x5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await w2(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(!WZ(this.currentLogFile))await VZ(this.currentLogFile,"",{mode:420});if(U=k5(this.currentLogFile,"a",420),H2(U,z,{flag:"a"}),A5(U),U!==void 0)JZ(U),U=void 0;if((await EX(this.currentLogFile)).size===0){if(await VZ(this.currentLogFile,z,{flag:"w",mode:420}),(await EX(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{JZ(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 GX(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 GX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return GX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(N0())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 OZ(16).toString("hex")}generateKey(){return OZ(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=OZ(16),Y=K2("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(N0())return;let X=await EX(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 g$(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 EX(Z).catch(()=>null))try{if(await B5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await d$(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 VZ(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 EX(Z).catch(()=>null))await B5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await g$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await d$(GX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=S5(X),Y=M2($),U=y5();await q2(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()})),WZ(this.currentLogFile))try{let X=k5(this.currentLogFile,"r+");A5(X),JZ(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 g$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await d$(GX(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?C0.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=g0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${C0.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&&!N0()){let j=t6[X],E=this.options.showTags!==!1&&this.name?C0.gray(this.formatTag(this.name)):"",V;switch(X){case"debug":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:C0.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:C0.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(`
4
+ `,F=J.map((d)=>d.toLowerCase()).join(";"),R=await M5(Y),D=[X,E,V,W,F,R].join(`
5
+ `),q=await M5(D),w="AWS4-HMAC-SHA256",A=`${j}/${_}/${Q}/aws4_request`,P=[w,z,A,q].join(`
6
+ `),H=await t7(U.secretAccessKey,j,_,Q),N=await lX(H,P),S=Array.from(new Uint8Array(N)).map((d)=>d.toString(16).padStart(2,"0")).join(""),h=`${w} Credential=${U.accessKeyId}/${A}, SignedHeaders=${F}, Signature=${S}`;return{...G,authorization:h}}class q6{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 e7("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 P6(X){return new q6(X)}function mj(X){h9={...h9,...X},F8=null,O8=null}function l9(){if(!F8)F8=P6({region:h9.region??"us-east-1",endpoint:h9.endpoint,credentials:h9.credentials});return F8}function s9(){if(!O8)O8=gX({region:h9.region??"us-east-1",endpoint:h9.endpoint,credentials:h9.credentials});return O8}class X2{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 T6(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}`,R=`:val${G}`;E[F]=J,V[R]=Y.marshall({v:W}).v,j.push(`${F} = ${R}`),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 T6{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,F8=null,O8=null,$2=e(()=>{h9={region:process.env.AWS_REGION??"us-east-1"}});function N8(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 Z2(X){let $=Y2(X);return U2($)}function Y2(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 U2(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:N8($)}}function uj(X,$){return N8(X)===N8($)}class N6{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 $=`${mX}#${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 $=`${mX}#${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),_=`${mX}#${X}`,Q=`${H5}#${String(U).padStart(6,"0")}`,L={tableName:X,hash:N8($),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(`${mX}#`,"");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=`${mX}#${X}`;for(let Y of $){let U=`${H5}#${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",mX="MIGRATION",H5="VERSION",S6=()=>{};class A6{client;tracker;config;constructor(X){this.config=X,this.client=P6({region:X.region,endpoint:X.endpoint,credentials:X.credentials}),this.tracker=new N6(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 $=Z2(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 Q2(X){return new A6(X)}async function nj(X,$){return Q2($).migrateModels(X)}var z2=e(()=>{S6()});class k6{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=gX($),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 k6(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 ij(){return new l1}var L2,j2=e(()=>{$2(),z2(),S6(),L2=new l1});class y6{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 h6{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 a2(X,$){this[X]=y4.bind(null,$)}class J1{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(!q5(X))return!0;return P5(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=q5(Z)?P5(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 W1{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 t2(X,$={}){let Y=Object.keys($).sort().map((U)=>`${U}:${$[U]}`).join("|");return Y?`${X}:${Y}`:X}function e2(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function X4(X){return X.getStats().size*2}function s1(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&q0($[0])&&"id"in $[0]&&$[0].id===3&&q0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(q0($)&&q0(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(q0(X)&&"arr"in X&&Array.isArray(X.arr)&&q0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&q0($[0])&&q0(X[0])){let Y=[...$];for(let U of X)if(q0(U)&&"name"in U){if(!Y.find((Q)=>q0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(q0(U)&&"path"in U){if(!Y.find((Q)=>q0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>y8(_,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(!q0($)||!q0(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(q0(U)&&q0(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&&q0(U[0])&&q0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(q0(Q)&&"name"in Q){if(!_.find((z)=>q0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(q0(Q)&&"path"in Q){if(!_.find((z)=>q0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>y8(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 y8(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(!y8(X[Z],$[Z]))return!1;return!0}if(q0(X)&&q0($)){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(!y8(X[U],$[U]))return!1}return!0}return!1}function q0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function $4(X,$){if(!B6(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 Z4({name:X="",cwd:$,defaultConfig:Z}){let Y=$||O1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],_=[`${X}.config`,`.${X}.config`,X,`.${X}`];for(let Q of _)for(let L of U){let z=x8(Y,`${Q}${L}`),j=await $4(z,Z);if(j!==null)return j}try{let Q=x8(Y,"package.json");if(B6(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 Y4(X,$={}){let Z=k8.cwd();while(Z.includes("storage"))Z=S5(Z,"..");let Y=S5(Z,X||"");if($?.relative)return R2(k8.cwd(),Y);return Y}async function U4(){try{let X=await Z4({name:"clarity",defaultConfig:W8,cwd:k8.cwd(),endpoint:"",headers:{}});return{...W8,...X}}catch{return W8}}function N0(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _4(){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 v6{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:FX.pid,hostname:$(),environment:FX.env.NODE_ENV||"development",platform:FX.platform,version:FX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:FX.env.NODE_ENV||FX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class h8{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 v6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??g0.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{...V8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...V8};return{...V8,...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 C2(this.config.logDirectory,B5.F_OK|B5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await w2(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:b9.from(X);try{if(!WZ(this.currentLogFile))await VZ(this.currentLogFile,"",{mode:420});if(U=x5(this.currentLogFile,"a",420),H2(U,z,{flag:"a"}),k5(U),U!==void 0)JZ(U),U=void 0;if((await EX(this.currentLogFile)).size===0){if(await VZ(this.currentLogFile,z,{flag:"w",mode:420}),(await EX(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{JZ(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 GX(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 GX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return GX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(N0())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 OZ(16).toString("hex")}generateKey(){return OZ(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=OZ(16),Y=K2("aes-256-gcm",$,Z),U=b9.concat([Y.update(X,"utf8"),Y.final()]),_=Y.getAuthTag();return{encrypted:b9.concat([Z,U,_]),iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=h5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(b9.from(b9.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;let X=await EX(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 g$(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 EX(Z).catch(()=>null))try{if(await y5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await d$(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 VZ(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 EX(Z).catch(()=>null))await y5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await g$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await d$(GX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=A5(X),Y=M2($),U=h5();await q2(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()})),WZ(this.currentLogFile))try{let X=x5(this.currentLogFile,"r+");k5(X),JZ(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 g$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await d$(GX(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?C0.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=g0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${C0.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&&!N0()){let j=e6[X],E=this.options.showTags!==!1&&this.name?C0.gray(this.formatTag(this.name)):"",V;switch(X){case"debug":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:C0.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:C0.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
7
  `);for(let J of G)if(J.trim()&&!J.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:C0.gray(` ${J}`),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 z=`${_} ${this.environment}.${X.toUpperCase()}: ${Q}
8
8
  `;if(L)z+=`${L}
9
9
  `;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(X){let $=performance.now();if(this.fancy&&!N0()){let Z=this.options.showTags!==!1&&this.name?C0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:C0.blue("\u25D0"),tag:Z,message:`${C0.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&&!N0()){let E=this.options.showTags!==!1&&this.name?C0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:C0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!N0())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 h8($,{...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(!WZ(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=D2("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 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($);if(this.fancy&&!N0()){let _=X.split(`
10
+ `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!N0()){let E=this.options.showTags!==!1&&this.name?C0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:C0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!N0())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 h8($,{...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(!WZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return A5(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=b9.isBuffer(X)?X:b9.from(X,"base64"),U=Y.slice(0,16),_=Y.slice(-16),Q=Y.slice(16,-16),L=D2("aes-256-gcm",Z,U);return L.setAuthTag(_),b9.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 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($);if(this.fancy&&!N0()){let _=X.split(`
11
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:C0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Z,message:C0.cyan(L)})),j.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:Z,message:C0.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Z,message:C0.cyan(z),showTimestamp:!1}))}else if(!N0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
12
12
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt(X){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${C0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();g0.stdin.removeListener("data",Z);try{if(typeof g0.stdin.setRawMode==="function")g0.stdin.setRawMode(!1)}catch{}g0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof g0.stdin.setRawMode==="function")g0.stdin.setRawMode(!0)}catch{}g0.stdin.resume(),g0.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&&!N0()){let Q=this.options.showTags!==!1&&this.name?C0.gray(this.formatTag(this.name)):"",L=C0.blue("\u25D0");console.error(`${L} ${Q} ${C0.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Z}
13
13
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress(X,$=""){if(!this.enabled||!this.fancy||N0()||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||N0())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||N0())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||N0())return;g0.stdout.write(`${"\r".padEnd(g0.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||N0()||!g0.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,_=C0.green("\u2501".repeat(Y)),Q=C0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=$||Z===100?C0.green("\u2713"):C0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${C0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=g0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,g0.stdout.write(X.lastRenderedLine),$)g0.stdout.write(`
14
- `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||N0()||!g0.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 g$(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 _=GX(this.config.logDirectory,Y);if(X.before)try{if((await EX(_)).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 d$(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 J8(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&V0($[0])&&"id"in $[0]&&$[0].id===3&&V0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(V0($)&&V0(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(V0(X)&&"arr"in X&&Array.isArray(X.arr)&&V0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&V0($[0])&&V0(X[0])){let Y=[...$];for(let U of X)if(V0(U)&&"name"in U){if(!Y.find((Q)=>V0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(V0(U)&&"path"in U){if(!Y.find((Q)=>V0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>v8(_,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(!V0($)||!V0(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(V0(U)&&V0(Z[Y]))Z[Y]=J8(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&V0(U[0])&&V0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(V0(Q)&&"name"in Q){if(!_.find((z)=>V0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(V0(Q)&&"path"in Q){if(!_.find((z)=>V0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>v8(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"?$:J8(X,$);if(Array.isArray(X))return Z==="replace"?$:J8(X,$);if(!V0($)||!V0(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]=J8(Q,_);else if(V0(_)&&V0(Q))Y[U]=o1(Q,_,Z);else Y[U]=_}return Y}function v8(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(!v8(X[Z],$[Z]))return!1;return!0}if(V0(X)&&V0($)){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(!v8(X[U],$[U]))return!1}return!0}return!1}function V0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function a$(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 Q4(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)p0.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=T$.env[J]||T$.env[W];if(F!==void 0){if(Z)p0.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 R=JSON.parse(F);if(Array.isArray(R))z[j]=R;else z[j]=F.split(",").map((D)=>D.trim())}catch{z[j]=F.split(",").map((R)=>R.trim())}else z[j]=F}}}return z}return _(U)}async function z4({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)?Q4(X,U,_):U,j=Z||T$.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(_)p0.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,i0(j,"config"),i0(j,".config"),Y?i0(j,Y):void 0].filter(Boolean)));for(let R of F){if(_)p0.info(`Searching for configuration in: ${R}`);let q=[i0(j,"config"),i0(j,".config")].concat(Y?[i0(j,Y)]:[]).includes(R)?[...V,...G,...J,...W]:[...G,...V,...W,...J];for(let w of q)for(let A of E){let P=i0(R,`${w}${A}`),H=await a$(P,z,L);if(H!==null){if(_)p0.success(`Configuration loaded from: ${P}`);return H}}}if(X){let R=i0(FZ(),".config",X),D=["config",`${X}.config`];if($)D.push(`${$}.config`);if(_)p0.info(`Checking user config directory: ${R}`);for(let q of D)for(let w of E){let A=i0(R,`${q}${w}`),P=await a$(A,z,L);if(P!==null){if(_)p0.success(`Configuration loaded from user config directory: ${A}`);return P}}}if(X){let R=i0(FZ(),".config"),D=[`.${X}.config`];if($)D.push(`.${$}.config`);if(_)p0.info(`Checking user config directory for dotfile configs: ${R}`);for(let q of D)for(let w of E){let A=i0(R,`${q}${w}`),P=await a$(A,z,L);if(P!==null){if(_)p0.success(`Configuration loaded from user config directory dotfile: ${A}`);return P}}}if(X){let R=FZ(),D=[`.${X}.config`,`.${X}`];if($)D.push(`.${$}.config`),D.push(`.${$}`);if(_)p0.info(`Checking user home directory for dotfile configs: ${R}`);for(let q of D)for(let w of E){let A=i0(R,`${q}${w}`),P=await a$(A,z,L);if(P!==null){if(_)p0.success(`Configuration loaded from user home directory: ${A}`);return P}}}try{let R=i0(j,"package.json");if(k6(R)){let D=await import(R),q=D[X];if(!q&&$){if(q=D[$],q&&_)p0.success(`Using alias "${$}" configuration from package.json`)}if(q&&typeof q==="object"&&!Array.isArray(q))try{if(_)p0.success(`Configuration loaded from package.json: ${q===D[X]?X:$}`);return o1(z,q,L)}catch(w){if(_)p0.warn("Failed to merge package.json config:",w)}}}catch(R){if(_)p0.warn("Failed to load package.json:",R)}if(_)p0.info(`No configuration found for "${X}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function L4(X,$={}){let Z=A8.cwd();while(Z.includes("storage"))Z=T5(Z,"..");let Y=T5(Z,X||"");if($?.relative)return V2(A8.cwd(),Y);return Y}async function j4(){try{let X=await z4({name:"clarity",alias:"logging",defaultConfig:I8,cwd:A8.cwd()});return{...I8,...X||{}}}catch{return I8}}function A0(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E4(){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 E4(),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:WX.pid,hostname:$(),environment:WX.env.NODE_ENV||"development",platform:WX.platform,version:WX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:WX.env.NODE_ENV||WX.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={...D1},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??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},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{...R8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...R8};return{...R8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:D1.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!A0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await A2(this.config.logDirectory,f5.F_OK|f5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await k2(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(!p$(this.currentLogFile))await KZ(this.currentLogFile,"",{mode:420});if(U=b5(this.currentLogFile,"a",420),S2(U,z,{flag:"a"}),v5(U),U!==void 0)RZ(U),U=void 0;if((await OX(this.currentLogFile)).size===0){if(await KZ(this.currentLogFile,z,{flag:"w",mode:420}),(await OX(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{RZ(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 JX(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 JX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return JX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(A0())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 IZ(16).toString("hex")}generateKey(){return IZ(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=IZ(16),Y=P2("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(A0())return;if(!this.shouldWriteToFile())return;let X=await OX(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 c$(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 OX(Z).catch(()=>null))try{if(await g5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await m$(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 OX(Z).catch(()=>null))await g5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await c$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await m$(JX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=h5(X),Y=N2($),U=d5();await y2(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()})),p$(this.currentLogFile))try{let X=b5(this.currentLogFile,"r+");v5(X),RZ(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(!A0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await c$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await m$(JX(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()?F0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||A0())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} ${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(A0())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(x2($)||$.startsWith("./")||$.startsWith("../"))$=B2($);else return null;return p$($)?$: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?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(`
14
+ `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||N0()||!g0.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 g$(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 _=GX(this.config.logDirectory,Y);if(X.before)try{if((await EX(_)).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 d$(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 J8(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&V0($[0])&&"id"in $[0]&&$[0].id===3&&V0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(V0($)&&V0(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(V0(X)&&"arr"in X&&Array.isArray(X.arr)&&V0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&V0($[0])&&V0(X[0])){let Y=[...$];for(let U of X)if(V0(U)&&"name"in U){if(!Y.find((Q)=>V0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(V0(U)&&"path"in U){if(!Y.find((Q)=>V0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>v8(_,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(!V0($)||!V0(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(V0(U)&&V0(Z[Y]))Z[Y]=J8(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&V0(U[0])&&V0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(V0(Q)&&"name"in Q){if(!_.find((z)=>V0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(V0(Q)&&"path"in Q){if(!_.find((z)=>V0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>v8(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"?$:J8(X,$);if(Array.isArray(X))return Z==="replace"?$:J8(X,$);if(!V0($)||!V0(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]=J8(Q,_);else if(V0(_)&&V0(Q))Y[U]=o1(Q,_,Z);else Y[U]=_}return Y}function v8(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(!v8(X[Z],$[Z]))return!1;return!0}if(V0(X)&&V0($)){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(!v8(X[U],$[U]))return!1}return!0}return!1}function V0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function a$(X,$,Z="replace"){if(!x6(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 Q4(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)p0.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=T$.env[J]||T$.env[W];if(F!==void 0){if(Z)p0.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 R=JSON.parse(F);if(Array.isArray(R))z[j]=R;else z[j]=F.split(",").map((D)=>D.trim())}catch{z[j]=F.split(",").map((R)=>R.trim())}else z[j]=F}}}return z}return _(U)}async function z4({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)?Q4(X,U,_):U,j=Z||T$.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(_)p0.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,i0(j,"config"),i0(j,".config"),Y?i0(j,Y):void 0].filter(Boolean)));for(let R of F){if(_)p0.info(`Searching for configuration in: ${R}`);let q=[i0(j,"config"),i0(j,".config")].concat(Y?[i0(j,Y)]:[]).includes(R)?[...V,...G,...J,...W]:[...G,...V,...W,...J];for(let w of q)for(let A of E){let P=i0(R,`${w}${A}`),H=await a$(P,z,L);if(H!==null){if(_)p0.success(`Configuration loaded from: ${P}`);return H}}}if(X){let R=i0(FZ(),".config",X),D=["config",`${X}.config`];if($)D.push(`${$}.config`);if(_)p0.info(`Checking user config directory: ${R}`);for(let q of D)for(let w of E){let A=i0(R,`${q}${w}`),P=await a$(A,z,L);if(P!==null){if(_)p0.success(`Configuration loaded from user config directory: ${A}`);return P}}}if(X){let R=i0(FZ(),".config"),D=[`.${X}.config`];if($)D.push(`.${$}.config`);if(_)p0.info(`Checking user config directory for dotfile configs: ${R}`);for(let q of D)for(let w of E){let A=i0(R,`${q}${w}`),P=await a$(A,z,L);if(P!==null){if(_)p0.success(`Configuration loaded from user config directory dotfile: ${A}`);return P}}}if(X){let R=FZ(),D=[`.${X}.config`,`.${X}`];if($)D.push(`.${$}.config`),D.push(`.${$}`);if(_)p0.info(`Checking user home directory for dotfile configs: ${R}`);for(let q of D)for(let w of E){let A=i0(R,`${q}${w}`),P=await a$(A,z,L);if(P!==null){if(_)p0.success(`Configuration loaded from user home directory: ${A}`);return P}}}try{let R=i0(j,"package.json");if(x6(R)){let D=await import(R),q=D[X];if(!q&&$){if(q=D[$],q&&_)p0.success(`Using alias "${$}" configuration from package.json`)}if(q&&typeof q==="object"&&!Array.isArray(q))try{if(_)p0.success(`Configuration loaded from package.json: ${q===D[X]?X:$}`);return o1(z,q,L)}catch(w){if(_)p0.warn("Failed to merge package.json config:",w)}}}catch(R){if(_)p0.warn("Failed to load package.json:",R)}if(_)p0.info(`No configuration found for "${X}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function L4(X,$={}){let Z=A8.cwd();while(Z.includes("storage"))Z=N5(Z,"..");let Y=N5(Z,X||"");if($?.relative)return V2(A8.cwd(),Y);return Y}async function j4(){try{let X=await z4({name:"clarity",alias:"logging",defaultConfig:I8,cwd:A8.cwd()});return{...I8,...X||{}}}catch{return I8}}function A0(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E4(){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 b6{async format(X){let $=await E4(),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:WX.pid,hostname:$(),environment:WX.env.NODE_ENV||"development",platform:WX.platform,version:WX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:WX.env.NODE_ENV||WX.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={...D1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new b6,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},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{...R8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...R8};return{...R8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:D1.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!A0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await A2(this.config.logDirectory,g5.F_OK|g5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await k2(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(!p$(this.currentLogFile))await KZ(this.currentLogFile,"",{mode:420});if(U=f5(this.currentLogFile,"a",420),S2(U,z,{flag:"a"}),b5(U),U!==void 0)RZ(U),U=void 0;if((await OX(this.currentLogFile)).size===0){if(await KZ(this.currentLogFile,z,{flag:"w",mode:420}),(await OX(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{RZ(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 JX(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 JX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return JX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(A0())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 IZ(16).toString("hex")}generateKey(){return IZ(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=IZ(16),Y=P2("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=p5(),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(A0())return;if(!this.shouldWriteToFile())return;let X=await OX(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 c$(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 OX(Z).catch(()=>null))try{if(await d5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await m$(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 OX(Z).catch(()=>null))await d5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await c$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await m$(JX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=v5(X),Y=N2($),U=p5();await y2(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()})),p$(this.currentLogFile))try{let X=f5(this.currentLogFile,"r+");b5(X),RZ(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(!A0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await c$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await m$(JX(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()?F0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||A0())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} ${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(A0())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(x2($)||$.startsWith("./")||$.startsWith("../"))$=B2($);else return null;return p$($)?$: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?"":XU[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(`
15
15
  `);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(!A0()){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
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()&&!A0()&&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()&&!A0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,z="info")=>{if(!A0()&&j0.stdout.isTTY)j0.stdout.write(`
18
18
  `);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!A0()&&j0.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),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?F0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":F0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!A0())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(A0())throw Error("createReadStream is not supported in browser environments");if(!p$(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=T2("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 A0()}isServerMode(){return!A0()}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(`
19
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=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:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!A0())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(A0())throw Error("createReadStream is not supported in browser environments");if(!p$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return v5(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=T2("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 A0()}isServerMode(){return!A0()}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
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: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(!A0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
21
21
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(A0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${F0.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?F0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${F0.blue("\u25D0")} `;console.error(`${j}${z} ${F0.cyan(Y)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
22
22
  `.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,_=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=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(`
23
- `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||A0()||!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(A0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await c$(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 _=JX(this.config.logDirectory,Y);if(X.before)try{if((await OX(_)).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 m$(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 G4(X){return X instanceof K8}function F4(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 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 S$.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=u$.env[z]||(j?u$.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=u$.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof D8)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(u$.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 ${$}:
23
+ `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||A0()||!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(A0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await c$(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 _=JX(this.config.logDirectory,Y);if(X.before)try{if((await OX(_)).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 m$(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 f6(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 g6(X){return X instanceof $9}function G4(X){return X instanceof K8}function F4(X){if(g6(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 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 S$.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=u$.env[z]||(j?u$.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=u$.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof D8)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(u$.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,21 +32,21 @@ var m0=import.meta.require;import{existsSync as H5,statSync as C5}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 O4(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 I4(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 J4(X,$);case"smart":return W4(X,$,Y);default:return $}return $}function J4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>V1(U,Y)))Z.push(Y);return Z}function W4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(G9($[0])&&G9(X[0]))return V4(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 V4(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 I4(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 V1(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(!V1(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(!V1(X[U],$[U]))return!1}return!0}return!1}function G9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class YZ{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=yX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!n$(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 Z$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new Z$(X,Error("Configuration must export a valid object"),"unknown");let R={config:r1($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)yX.setWithFileCheck("file",R,X,_);return R}catch(j){throw j instanceof Error?c9.configLoad(X,j):c9.configLoad(X,Error(String(j)))}};if(Q)return S$.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(DZ($,`${_}${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 n$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!n$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=DZ(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=DZ(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(!n$(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 S$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!h2($))throw new Y$($,[{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 Y$($,[{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 I1{fileLoader=new YZ;envProcessor=new ZZ;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)I9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw I9.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(s0(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?sX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)I9.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)I9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?sX(X,Z,U):Z,L=[s0(jX(),".config",X),s0(jX(),".config"),jX()];for(let z of L){if(U)I9.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)I9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?sX(X,Y,_):Y;try{let z=s0(Z,"package.json");if(!F1(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(_)I9.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(_)I9.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:sX(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 yX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);yX.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,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(jX(),".config",X),s0(jX(),".config"),jX()],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 R4(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)I9.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 K4(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 D4(X,$,Z="replace"){let Y=new YZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function sX(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=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 M4(X){let $=s0(t9.cwd(),X.configDir),Z=s0(t9.cwd(),X.generatedDir),Y=s0(Z,"config-types.ts");if(!F1(P5(Y)))F2(P5(Y),{recursive:!0,mode:511});let U=F1($)?O2($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${j_}
35
+ `;return Z}}function O4(X,$){let Z=t6("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function d6(X,$,Z={}){return p6(X,$,Z,new WeakMap)}function p6(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 c6(X,$,U,Y);if(!G9($)||!G9(X))return $;return I4(X,$,Z,Y)}function c6(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 J4(X,$);case"smart":return W4(X,$,Y);default:return $}return $}function J4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>V1(U,Y)))Z.push(Y);return Z}function W4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(G9($[0])&&G9(X[0]))return V4(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 V4(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 I4(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]=p6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=c6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function r1(X,$,Z="replace"){return d6(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function V1(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(!V1(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(!V1(X[U],$[U]))return!1}return!0}return!1}function G9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class YZ{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=yX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!n$(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 Z$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new Z$(X,Error("Configuration must export a valid object"),"unknown");let R={config:r1($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)yX.setWithFileCheck("file",R,X,_);return R}catch(j){throw j instanceof Error?c9.configLoad(X,j):c9.configLoad(X,Error(String(j)))}};if(Q)return S$.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(DZ($,`${_}${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 f6(async()=>{return n$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!n$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=DZ(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=DZ(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(!n$(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 S$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!h2($))throw new Y$($,[{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 Y$($,[{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}]}}}class I1{fileLoader=new YZ;envProcessor=new ZZ;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)I9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw I9.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(s0(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?sX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)I9.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)I9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?sX(X,Z,U):Z,L=[s0(jX(),".config",X),s0(jX(),".config"),jX()];for(let z of L){if(U)I9.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)I9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?sX(X,Y,_):Y;try{let z=s0(Z,"package.json");if(!F1(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(_)I9.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(_)I9.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:sX(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 yX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);yX.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,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(jX(),".config",X),s0(jX(),".config"),jX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function r5(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 R4(X){return k9.loadConfig({...X,__strictErrorHandling:!0})}async function m6(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)I9.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 K4(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"&&r5(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"&&r5($)))return(await k9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function D4(X,$,Z="replace"){let Y=new YZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function sX(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=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 M4(X){let $=s0(t9.cwd(),X.configDir),Z=s0(t9.cwd(),X.generatedDir),Y=s0(Z,"config-types.ts");if(!F1(T5(Y)))F2(T5(Y),{recursive:!0,mode:511});let U=F1($)?O2($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${j_}
36
36
  export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
37
- `;J2(Y,_,{mode:438})}function H4(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)I9.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 C4(X){let $=p5(f2.cwd(),X?.configDir||"./config");function Z(){if(!v2($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=b2($).filter((z)=>U.has(MZ(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=MZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=MZ(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(`,
37
+ `;J2(Y,_,{mode:438})}function H4(X){let $=null,Z=null,Y=()=>{if(!Z)Z=m6(X).then((_)=>{return $=_,_},(_)=>{let Q="defaultConfig"in X?X.defaultConfig:{};if($=Q,"verbose"in X&&X.verbose)I9.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 C4(X){let $=c5(f2.cwd(),X?.configDir||"./config");function Z(){if(!v2($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=b2($).filter((z)=>U.has(MZ(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=MZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=MZ(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=c5($,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 w4(X,$={}){let Z=B8.cwd();while(Z.includes("storage"))Z=c5(Z,"..");let Y=c5(Z,X||"");if($?.relative)return d2(B8.cwd(),Y);return Y}function k0(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q4(){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 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:RX.pid,hostname:$(),environment:RX.env.NODE_ENV||"development",platform:RX.platform,version:RX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:RX.env.NODE_ENV||RX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class f8{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={...U$},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??E0.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{...M8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...M8};return{...M8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:U$.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!k0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await n2(this.config.logDirectory,i5.F_OK|i5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await i2(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(!i$(this.currentLogFile))await wZ(this.currentLogFile,"",{mode:420});if(U=n5(this.currentLogFile,"a",420),u2(U,z,{flag:"a"}),u5(U),U!==void 0)CZ(U),U=void 0;if((await VX(this.currentLogFile)).size===0){if(await wZ(this.currentLogFile,z,{flag:"w",mode:420}),(await VX(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{CZ(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 IX(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 IX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return IX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(k0())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 HZ(16).toString("hex")}generateKey(){return HZ(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=HZ(16),Y=p2("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(k0())return;if(!this.shouldWriteToFile())return;let X=await VX(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 l$(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 VX(Z).catch(()=>null))try{if(await l5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await s$(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 VX(Z).catch(()=>null))await l5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await l$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await s$(IX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=m5(X),Y=m2($),U=s5();await o2(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()})),i$(this.currentLogFile))try{let X=n5(this.currentLogFile,"r+");u5(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(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await l$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await s$(IX(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()?O0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||k0())return!1;let X=typeof E0.env.NO_COLOR<"u",$=E0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof E0.stderr<"u"&&E0.stderr.isTTY||typeof E0.stdout<"u"&&E0.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=E0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${O0.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 _=O0.underline(O0.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)=>O0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>O0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>O0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>O0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>O0.strikethrough(Y)),$}supportsHyperlinks(){if(k0())return!1;let X=E0.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=E0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(l2($)||$.startsWith("./")||$.startsWith("../"))$=s2($);else return null;return i$($)?$: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?O0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:O0.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:O0.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(`
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 w4(X,$={}){let Z=B8.cwd();while(Z.includes("storage"))Z=m5(Z,"..");let Y=m5(Z,X||"");if($?.relative)return d2(B8.cwd(),Y);return Y}function k0(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q4(){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 u6{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:RX.pid,hostname:$(),environment:RX.env.NODE_ENV||"development",platform:RX.platform,version:RX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:RX.env.NODE_ENV||RX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class f8{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={...U$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new u6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??E0.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{...M8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...M8};return{...M8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:U$.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!k0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await n2(this.config.logDirectory,l5.F_OK|l5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await i2(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(!i$(this.currentLogFile))await wZ(this.currentLogFile,"",{mode:420});if(U=i5(this.currentLogFile,"a",420),u2(U,z,{flag:"a"}),n5(U),U!==void 0)CZ(U),U=void 0;if((await VX(this.currentLogFile)).size===0){if(await wZ(this.currentLogFile,z,{flag:"w",mode:420}),(await VX(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{CZ(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 IX(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 IX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return IX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(k0())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 HZ(16).toString("hex")}generateKey(){return HZ(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=HZ(16),Y=p2("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=o5(),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(k0())return;if(!this.shouldWriteToFile())return;let X=await VX(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 l$(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 VX(Z).catch(()=>null))try{if(await s5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await s$(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 VX(Z).catch(()=>null))await s5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await l$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await s$(IX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=u5(X),Y=m2($),U=o5();await o2(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()})),i$(this.currentLogFile))try{let X=i5(this.currentLogFile,"r+");n5(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(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await l$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await s$(IX(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()?O0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||k0())return!1;let X=typeof E0.env.NO_COLOR<"u",$=E0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof E0.stderr<"u"&&E0.stderr.isTTY||typeof E0.stdout<"u"&&E0.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=E0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${O0.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 _=O0.underline(O0.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)=>O0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>O0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>O0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>O0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>O0.strikethrough(Y)),$}supportsHyperlinks(){if(k0())return!1;let X=E0.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=E0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(l2($)||$.startsWith("./")||$.startsWith("../"))$=s2($);else return null;return i$($)?$: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?"":ZU[X],G=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:O0.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:O0.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
45
  `);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:O0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!k0()){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
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()&&!k0()&&E0.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()&&!k0()&&E0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,z="info")=>{if(!k0()&&E0.stdout.isTTY)E0.stdout.write(`
48
48
  `);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!k0()&&E0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":O0.blue("\u25D0"),tag:Z,message:`${O0.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?O0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":O0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!k0())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 f8($,{...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(k0())throw Error("createReadStream is not supported in browser environments");if(!i$(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=c2("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 k0()}isServerMode(){return!k0()}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(`
49
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":O0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!k0())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 f8($,{...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(k0())throw Error("createReadStream is not supported in browser environments");if(!i$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return u5(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=c2("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 k0()}isServerMode(){return!k0()}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
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:O0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:O0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:O0.cyan(E),showTimestamp:!1}))}else if(!k0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
51
51
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(k0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${O0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();E0.stdin.removeListener("data",Z);try{if(typeof E0.stdin.setRawMode==="function")E0.stdin.setRawMode(!1)}catch{}E0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof E0.stdin.setRawMode==="function")E0.stdin.setRawMode(!0)}catch{}E0.stdin.resume(),E0.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?O0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${O0.blue("\u25D0")} `;console.error(`${j}${z} ${O0.cyan(Y)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
52
52
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!E0.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,_=O0.green("\u2501".repeat(Y)),Q=O0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?O0.green("\u2713"):O0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${O0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=E0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,E0.stdout.write(X.lastRenderedLine),$)E0.stdout.write(`
@@ -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 T4(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 k4(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 N4(X,$);case"smart":return S4(X,$,Y);default:return $}return $}function N4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>R1(U,Y)))Z.push(Y);return Z}function S4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(F9($[0])&&F9(X[0]))return A4(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 A4(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 k4(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 T4(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function R1(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(!R1(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(!R1(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=N$.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!r$(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 g8(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new g8(X,Error("Configuration must export a valid object"),"unknown");let R={config:i6($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)N$.setWithFileCheck("file",R,X,_);return R}catch(j){throw j instanceof Error?e9.configLoad(X,j):e9.configLoad(X,Error(String(j)))}};if(Q)return UZ.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(qZ($,`${_}${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 P4(async()=>{return r$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!r$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=qZ(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=qZ(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(!r$(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 UZ.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!r2($))throw new d8($,[{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 d8($,[{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 x4(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)V9.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 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=_||S8.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}"${x4(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?t$(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=_?t$(X,Z,U):Z,L=[L9(LX(),".config",X),L9(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?t$(X,Y,_):Y;try{let z=L9(Z,"package.json");if(!E2(z))return null;let j={};try{j=JSON.parse(G2(z,"utf8"))}catch(G){if(_)V9.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(_)V9.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(_)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:t$(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 N$.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);N$.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(LX(),".config",X),L9(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)}}async function B4(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 H8.loadConfig(X);else Y=await H8.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 H8.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}function t$(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=S8.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 N$,UZ,r6,y4=(X)=>X,h4=(X,$)=>{for(var Z in $)r6(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:a2.bind($,Z)})},v4=(X,$)=>()=>(X&&($=X(X=0)),$),PZ,a6,yX,S$,r5,b4,f4,a5,W8,K1,d0,C0,g4,t5,d4,e5,p4,c4,TZ,m4,XY,$Y,NZ,u4,n4,i4,l4,V8,t6,s4,p0,o4,r4,ZY,I8,D1,x0,F0,a4,YY,t4,UY,e4,X_,SZ,$_,_Y,QY,Z_,AZ,Y_,U_,__,Q_,z_,R8,e6,L_,j_="0.15.6",$9,K8,Z$,kZ,xZ,D8,BZ,yZ,Y$,hZ,vZ,c9,zY,XU,I9,k9,LY,jY,EY,GY,bZ,U$,E_,B0,O0,G_,FY,F_,OY,O_,J_,fZ,W_,JY,WY,V_,gZ,I_,R_,K_,D_,M_,M8,$U,H_,W9,VY,g8,IY,RY,M1,KY,DY,d8,MY,HY,e9,ZU,V9,H8,C_,w_,q_=e(()=>{N$=new B6,UZ=new y6,r6=Object.defineProperty,PZ={},h4(PZ,{withErrorRecovery:()=>b6,tryLoadConfig:()=>D4,loadConfigWithResult:()=>R4,loadConfig:()=>c6,isRetryableError:()=>F4,isConfigNotFoundError:()=>G4,isBunfigError:()=>f6,globalPerformanceMonitor:()=>S$,globalCache:()=>yX,getEnvOrDefault:()=>O4,generateConfigTypes:()=>M4,defaultGeneratedDir:()=>jY,defaultConfigDir:()=>LY,deepMergeWithArrayStrategy:()=>r1,deepMerge:()=>g6,createLibraryConfig:()=>H4,config:()=>K4,bunfigPlugin:()=>C4,applyEnvVarsToConfig:()=>sX,TypeGenerationError:()=>yZ,SchemaValidationError:()=>Y$,PluginError:()=>vZ,PerformanceMonitor:()=>W1,FileSystemError:()=>BZ,ErrorFactory:()=>c9,EnvVarError:()=>D8,EnvProcessor:()=>ZZ,ConfigValidator:()=>a1,ConfigValidationError:()=>kZ,ConfigNotFoundError:()=>K8,ConfigMergeError:()=>xZ,ConfigLoader:()=>I1,ConfigLoadError:()=>Z$,ConfigFileLoader:()=>YZ,ConfigCache:()=>J1,CacheUtils:()=>r5,BunfigError:()=>$9,BrowserConfigError:()=>hZ,ArrayMergeStrategies:()=>zY}),EY=v4(async()=>{a6=import.meta.require,yX=new J1,S$=new W1,r5={createKey:t2,isEquivalent:e2,estimateMemoryUsage:X4},b4=x8(O1.cwd(),"config"),f4=x8(O1.cwd(),"src/generated"),a5=k8.env.CLARITY_LOG_DIR||I2(Y4(),"logs"),W8={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 U4(),d0={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"},C0=d0,g4=d0.red,t5=d0.green,d4=d0.yellow,e5=d0.blue,p4=d0.magenta,c4=d0.cyan,TZ=d0.white,m4=d0.gray,XY=d0.bgRed,$Y=d0.bgYellow,NZ=d0.bold,u4=d0.dim,n4=d0.italic,i4=d0.underline,l4=d0.reset,V8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t6={debug:"\uD83D\uDD0D",info:e5("\u2139"),success:t5("\u2713"),warning:$Y(TZ(NZ(" WARN "))),error:XY(TZ(NZ(" ERROR ")))},s4=new h8("stacks"),p0=new h8("bunfig",{showTags:!0}),o4=i0(T$.cwd(),"config"),r4=i0(T$.cwd(),"src/generated"),ZY=A8.env.CLARITY_LOG_DIR||W2(L4(),"logs"),I8={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},D1=await j4(),x0={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=x0,a4=x0.red,YY=x0.green,t4=x0.yellow,UY=x0.blue,e4=x0.magenta,X_=x0.cyan,SZ=x0.white,$_=x0.gray,_Y=x0.bgRed,QY=x0.bgYellow,Z_=x0.bgGray,AZ=x0.bold,Y_=x0.dim,U_=x0.italic,__=x0.underline,Q_=x0.strikethrough,z_=x0.reset,R8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},e6={debug:"\uD83D\uDD0D",info:UY("\u2139"),success:YY("\u2713"),warning:QY(SZ(AZ(" WARN "))),error:_Y(SZ(AZ(" ERROR ")))},L_=new b8("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})}},Z$=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}},kZ=class extends $9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},xZ=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}},D8=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})}},BZ=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}},yZ=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}},Y$=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})}},hZ=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})}},vZ=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 Z$(X,$,Z)},configValidation(X,$,Z){return new kZ(X,$,Z)},configMerge(X,$,Z,Y){return new xZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new D8(X,$,Z,Y)},fileSystem(X,$,Z){return new BZ(X,$,Z)},typeGeneration(X,$,Z){return new yZ(X,$,Z)},schemaValidation(X,$,Z){return new Y$(X,$,Z)},browserConfig(X,$,Z,Y){return new hZ(X,$,Z,Y)},plugin(X,$,Z){return new vZ(X,$,Z)}},zY={replace:"replace",concat:"concat",smart:"smart"},XU=/^https?:\/\//,I9=new b8("bunfig",{showTags:!0}),k9=new I1,LY=s0(t9.cwd(),"config"),jY=s0(t9.cwd(),"src/generated")}),GY=B8.env.CLARITY_LOG_DIR||g2(w4(),"logs"),bZ={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},U$={...bZ},E_=(async()=>{try{let{loadConfig:X}=await EY().then(()=>PZ),$=await X({name:"clarity",alias:"logging",defaultConfig:bZ,cwd:B8.cwd()});if($)Object.assign(U$,$)}catch{}return U$})(),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"},O0=B0,G_=B0.red,FY=B0.green,F_=B0.yellow,OY=B0.blue,O_=B0.magenta,J_=B0.cyan,fZ=B0.white,W_=B0.gray,JY=B0.bgRed,WY=B0.bgYellow,V_=B0.bgGray,gZ=B0.bold,I_=B0.dim,R_=B0.italic,K_=B0.underline,D_=B0.strikethrough,M_=B0.reset,M8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$U={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:FY("\u2713"),warning:WY(fZ(gZ(" WARN "))),error:JY(fZ(gZ(" ERROR ")))},H_=new f8("stacks"),W9=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 W9{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})}},g8=class extends W9{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 W9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},RY=class extends W9{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}},M1=class extends W9{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 W9{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 W9{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}},d8=class extends W9{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 W9{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 W9{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 g8(X,$,Z)},configValidation(X,$,Z){return new IY(X,$,Z)},configMerge(X,$,Z,Y){return new RY(X,$,Z,Y)},envVar(X,$,Z,Y){return new M1(X,$,Z,Y)},fileSystem(X,$,Z){return new KY(X,$,Z)},typeGeneration(X,$,Z){return new DY(X,$,Z)},schemaValidation(X,$,Z){return new d8(X,$,Z)},browserConfig(X,$,Z,Y){return new MY(X,$,Z,Y)},plugin(X,$,Z){return new HY(X,$,Z)}},ZU=/^https?:\/\//,V9=new f8("bunfig",{showTags:!0}),H8=new o6,C_=L9(S8.cwd(),"config"),w_=L9(S8.cwd(),"src/generated")});function I0(X=f.dialect){return X==="mysql"||X==="singlestore"}function l(X){if(f.dialect==="postgres")return`$${X}`;return"?"}function b0(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 WG(){if(!_$)_$=await B4({name:"query-builder",alias:"qb",defaultConfig:H1}),P_(_$);return f}function P_(X){if(X.dialect&&uX&&X.dialect!==uX){let $=`${uX}->${X.dialect}`;if(!C1.has($))C1.add($),console.warn(`[query-builder] setConfig({ dialect: '${X.dialect}' }) overrides a previous setConfig({ dialect: '${uX}' }). 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)uX=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(_$)Object.assign(_$,f)}var H1,CY,f,_$=null,uX=null,C1,c0=e(()=>{q_(),H1={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]??={...H1},C1=new Set});function T_(){let X=f.sqlite?.pragmas;return Array.isArray(X)?X:YU}function e1(X){for(let $ of T_())try{X.run($)}catch{}}var YU,X5=e(()=>{c0(),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 $=A_(X);if($&&$!==".")S_($,{recursive:!0})}this.db=new N_(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(`
65
+ `;return Z}}function T4(X,$,Z={}){return n6(X,$,Z,new WeakMap)}function n6(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 i6(X,$,U,Y);if(!F9($)||!F9(X))return $;return k4(X,$,Z,Y)}function i6(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 N4(X,$);case"smart":return S4(X,$,Y);default:return $}return $}function N4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>R1(U,Y)))Z.push(Y);return Z}function S4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(F9($[0])&&F9(X[0]))return A4(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 A4(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 k4(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]=n6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=i6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function l6(X,$,Z="replace"){return T4(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function R1(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(!R1(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(!R1(X[U],$[U]))return!1}return!0}return!1}function F9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class s6{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=N$.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!r$(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 g8(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new g8(X,Error("Configuration must export a valid object"),"unknown");let R={config:l6($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)N$.setWithFileCheck("file",R,X,_);return R}catch(j){throw j instanceof Error?e9.configLoad(X,j):e9.configLoad(X,Error(String(j)))}};if(Q)return UZ.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(qZ($,`${_}${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 P4(async()=>{return r$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!r$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=qZ(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=qZ(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(!r$(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 o6{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 UZ.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!r2($))throw new d8($,[{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 d8($,[{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:YU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function x4(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 r6{fileLoader=new s6;envProcessor=new t1;validator=new o6;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){if(L instanceof Error&&L.name==="ConfigNotFoundError")throw 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=_||S8.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}"${x4(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?t$(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=_?t$(X,Z,U):Z,L=[L9(LX(),".config",X),L9(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?t$(X,Y,_):Y;try{let z=L9(Z,"package.json");if(!E2(z))return null;let j={};try{j=JSON.parse(G2(z,"utf8"))}catch(G){if(_)V9.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(_)V9.success(`Configuration loaded from package.json: ${V}`);return{config:l6(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:t$(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 N$.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);N$.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(LX(),".config",X),L9(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)}}async function B4(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 H8.loadConfig(X);else Y=await H8.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 H8.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}function t$(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=S8.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 N$,UZ,a6,y4=(X)=>X,h4=(X,$)=>{for(var Z in $)a6(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:a2.bind($,Z)})},v4=(X,$)=>()=>(X&&($=X(X=0)),$),PZ,t6,yX,S$,a5,b4,f4,t5,W8,K1,d0,C0,g4,e5,d4,XY,p4,c4,TZ,m4,$Y,ZY,NZ,u4,n4,i4,l4,V8,e6,s4,p0,o4,r4,YY,I8,D1,x0,F0,a4,UY,t4,_Y,e4,X_,SZ,$_,QY,zY,Z_,AZ,Y_,U_,__,Q_,z_,R8,XU,L_,j_="0.15.6",$9,K8,Z$,kZ,xZ,D8,BZ,yZ,Y$,hZ,vZ,c9,LY,$U,I9,k9,jY,EY,GY,FY,bZ,U$,E_,B0,O0,G_,OY,F_,JY,O_,J_,fZ,W_,WY,VY,V_,gZ,I_,R_,K_,D_,M_,M8,ZU,H_,W9,IY,g8,RY,KY,M1,DY,MY,d8,HY,CY,e9,YU,V9,H8,C_,w_,q_=e(()=>{N$=new y6,UZ=new h6,a6=Object.defineProperty,PZ={},h4(PZ,{withErrorRecovery:()=>f6,tryLoadConfig:()=>D4,loadConfigWithResult:()=>R4,loadConfig:()=>m6,isRetryableError:()=>F4,isConfigNotFoundError:()=>G4,isBunfigError:()=>g6,globalPerformanceMonitor:()=>S$,globalCache:()=>yX,getEnvOrDefault:()=>O4,generateConfigTypes:()=>M4,defaultGeneratedDir:()=>EY,defaultConfigDir:()=>jY,deepMergeWithArrayStrategy:()=>r1,deepMerge:()=>d6,createLibraryConfig:()=>H4,config:()=>K4,bunfigPlugin:()=>C4,applyEnvVarsToConfig:()=>sX,TypeGenerationError:()=>yZ,SchemaValidationError:()=>Y$,PluginError:()=>vZ,PerformanceMonitor:()=>W1,FileSystemError:()=>BZ,ErrorFactory:()=>c9,EnvVarError:()=>D8,EnvProcessor:()=>ZZ,ConfigValidator:()=>a1,ConfigValidationError:()=>kZ,ConfigNotFoundError:()=>K8,ConfigMergeError:()=>xZ,ConfigLoader:()=>I1,ConfigLoadError:()=>Z$,ConfigFileLoader:()=>YZ,ConfigCache:()=>J1,CacheUtils:()=>a5,BunfigError:()=>$9,BrowserConfigError:()=>hZ,ArrayMergeStrategies:()=>LY}),GY=v4(async()=>{t6=import.meta.require,yX=new J1,S$=new W1,a5={createKey:t2,isEquivalent:e2,estimateMemoryUsage:X4},b4=x8(O1.cwd(),"config"),f4=x8(O1.cwd(),"src/generated"),t5=k8.env.CLARITY_LOG_DIR||I2(Y4(),"logs"),W8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:t5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},K1=await U4(),d0={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"},C0=d0,g4=d0.red,e5=d0.green,d4=d0.yellow,XY=d0.blue,p4=d0.magenta,c4=d0.cyan,TZ=d0.white,m4=d0.gray,$Y=d0.bgRed,ZY=d0.bgYellow,NZ=d0.bold,u4=d0.dim,n4=d0.italic,i4=d0.underline,l4=d0.reset,V8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},e6={debug:"\uD83D\uDD0D",info:XY("\u2139"),success:e5("\u2713"),warning:ZY(TZ(NZ(" WARN "))),error:$Y(TZ(NZ(" ERROR ")))},s4=new h8("stacks"),p0=new h8("bunfig",{showTags:!0}),o4=i0(T$.cwd(),"config"),r4=i0(T$.cwd(),"src/generated"),YY=A8.env.CLARITY_LOG_DIR||W2(L4(),"logs"),I8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},D1=await j4(),x0={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=x0,a4=x0.red,UY=x0.green,t4=x0.yellow,_Y=x0.blue,e4=x0.magenta,X_=x0.cyan,SZ=x0.white,$_=x0.gray,QY=x0.bgRed,zY=x0.bgYellow,Z_=x0.bgGray,AZ=x0.bold,Y_=x0.dim,U_=x0.italic,__=x0.underline,Q_=x0.strikethrough,z_=x0.reset,R8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XU={debug:"\uD83D\uDD0D",info:_Y("\u2139"),success:UY("\u2713"),warning:zY(SZ(AZ(" WARN "))),error:QY(SZ(AZ(" ERROR ")))},L_=new b8("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})}},Z$=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}},kZ=class extends $9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},xZ=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}},D8=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})}},BZ=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}},yZ=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}},Y$=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})}},hZ=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})}},vZ=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 Z$(X,$,Z)},configValidation(X,$,Z){return new kZ(X,$,Z)},configMerge(X,$,Z,Y){return new xZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new D8(X,$,Z,Y)},fileSystem(X,$,Z){return new BZ(X,$,Z)},typeGeneration(X,$,Z){return new yZ(X,$,Z)},schemaValidation(X,$,Z){return new Y$(X,$,Z)},browserConfig(X,$,Z,Y){return new hZ(X,$,Z,Y)},plugin(X,$,Z){return new vZ(X,$,Z)}},LY={replace:"replace",concat:"concat",smart:"smart"},$U=/^https?:\/\//,I9=new b8("bunfig",{showTags:!0}),k9=new I1,jY=s0(t9.cwd(),"config"),EY=s0(t9.cwd(),"src/generated")}),FY=B8.env.CLARITY_LOG_DIR||g2(w4(),"logs"),bZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},U$={...bZ},E_=(async()=>{try{let{loadConfig:X}=await GY().then(()=>PZ),$=await X({name:"clarity",alias:"logging",defaultConfig:bZ,cwd:B8.cwd()});if($)Object.assign(U$,$)}catch{}return U$})(),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"},O0=B0,G_=B0.red,OY=B0.green,F_=B0.yellow,JY=B0.blue,O_=B0.magenta,J_=B0.cyan,fZ=B0.white,W_=B0.gray,WY=B0.bgRed,VY=B0.bgYellow,V_=B0.bgGray,gZ=B0.bold,I_=B0.dim,R_=B0.italic,K_=B0.underline,D_=B0.strikethrough,M_=B0.reset,M8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ZU={debug:"\uD83D\uDD0D",info:JY("\u2139"),success:OY("\u2713"),warning:VY(fZ(gZ(" WARN "))),error:WY(fZ(gZ(" ERROR ")))},H_=new f8("stacks"),W9=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}${$}`}},IY=class extends W9{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})}},g8=class extends W9{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}},RY=class extends W9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},KY=class extends W9{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}},M1=class extends W9{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})}},DY=class extends W9{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}},MY=class extends W9{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}},d8=class extends W9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},HY=class extends W9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},CY=class extends W9{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 IY(X,$,Z)},configLoad(X,$,Z){return new g8(X,$,Z)},configValidation(X,$,Z){return new RY(X,$,Z)},configMerge(X,$,Z,Y){return new KY(X,$,Z,Y)},envVar(X,$,Z,Y){return new M1(X,$,Z,Y)},fileSystem(X,$,Z){return new DY(X,$,Z)},typeGeneration(X,$,Z){return new MY(X,$,Z)},schemaValidation(X,$,Z){return new d8(X,$,Z)},browserConfig(X,$,Z,Y){return new HY(X,$,Z,Y)},plugin(X,$,Z){return new CY(X,$,Z)}},YU=/^https?:\/\//,V9=new f8("bunfig",{showTags:!0}),H8=new r6,C_=L9(S8.cwd(),"config"),w_=L9(S8.cwd(),"src/generated")});function I0(X=f.dialect){return X==="mysql"||X==="singlestore"}function l(X){if(f.dialect==="postgres")return`$${X}`;return"?"}function b0(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 WG(){if(!_$)_$=await B4({name:"query-builder",alias:"qb",defaultConfig:H1}),P_(_$);return f}function P_(X){if(X.dialect&&uX&&X.dialect!==uX){let $=`${uX}->${X.dialect}`;if(!C1.has($))C1.add($),console.warn(`[query-builder] setConfig({ dialect: '${X.dialect}' }) overrides a previous setConfig({ dialect: '${uX}' }). 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)uX=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(_$)Object.assign(_$,f)}var H1,wY,f,_$=null,uX=null,C1,c0=e(()=>{q_(),H1={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}},wY=Symbol.for("bun-query-builder.config"),f=globalThis[wY]??={...H1},C1=new Set});function T_(){let X=f.sqlite?.pragmas;return Array.isArray(X)?X:UU}function e1(X){for(let $ of T_())try{X.run($)}catch{}}var UU,X5=e(()=>{c0(),UU=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]}),{SQL:qY}=globalThis.Bun;class _U{db;constructor(X){if(X!==":memory:"&&!X.startsWith(":")){let $=A_(X);if($&&$!==".")S_($,{recursive:!0})}this.db=new N_(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 PY(X){return{__raw:!0,value:X,toString:()=>X}}function TY(X){let $=X.trimStart();for(;;)if($.startsWith("--")){let Z=$.indexOf(`
66
66
  `);$=Z===-1?"":$.slice(Z+1).trimStart()}else if($.startsWith("/*")){let Z=$.indexOf("*/");$=Z===-1?"":$.slice(Z+2).trimStart()}else return $}function k_(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=k_(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 x_(X,$){if((X==="postgres"||X==="mysql"||X==="singlestore")&&e$.env.DB_CONNECTION===X){let j=e$.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",R=j.DB_SSL==="true"||j.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${F}://${V}:${G}@${J}${W?`:${W}`:""}/${E}${R}`}if($.url)return $.url;let{database:Z,username:Y,password:U,host:_="localhost",port:Q,ssl:L}=$,z=L||e$.env.DB_SSL==="true"||e$.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 B_(){let X=f.dialect,$=x_(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 y_(){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 hX(X=!1){let $=y_();if(X||oX!==null&&w1!==$||!oX)oX=B_(),w1=$;return oX}function DG(){oX=null,w1=null}async function dZ(X){try{return await X(hX())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Z=hX(!0);return await X(Z)}throw $}}function h_(){return new Proxy(function(){},{get(X,$){let Z=hX(),Y=Z[$];if(typeof Y==="function")return Y.bind(Z);return Y},apply(X,$,Z){return hX()(...Z)}})}var oX=null,w1=null,c,$X=e(()=>{c0(),X5(),c=h_()});async function MG(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=H0();console.log("-- Setting up test table...");try{await c.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await c.unsafe(`
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=TY(Z.trim());if(V)$.push(V);Z="";continue}Z+=j}let L=TY(Z.trim());if(L)$.push(L);return $}function NY(X){let $=new _U(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 PY(_);return Z([""])}Y.raw=(_)=>PY(_),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=k_(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 x_(X,$){if((X==="postgres"||X==="mysql"||X==="singlestore")&&e$.env.DB_CONNECTION===X){let j=e$.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",R=j.DB_SSL==="true"||j.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${F}://${V}:${G}@${J}${W?`:${W}`:""}/${E}${R}`}if($.url)return $.url;let{database:Z,username:Y,password:U,host:_="localhost",port:Q,ssl:L}=$,z=L||e$.env.DB_SSL==="true"||e$.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 QU(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 B_(){let X=f.dialect,$=x_(X,f.database);try{if(X==="sqlite")return NY($);let Z=QU(f.database.pool);return Object.keys(Z).length>0?new qY($,Z):new qY($)}catch(Z){if(console.error(`[query-builder] Failed to create database connection for dialect '${X}': ${Z.message}`),X==="sqlite")return NY(":memory:");throw Z}}function y_(){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:QU(X.pool)})}function hX(X=!1){let $=y_();if(X||oX!==null&&w1!==$||!oX)oX=B_(),w1=$;return oX}function DG(){oX=null,w1=null}async function dZ(X){try{return await X(hX())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Z=hX(!0);return await X(Z)}throw $}}function h_(){return new Proxy(function(){},{get(X,$){let Z=hX(),Y=Z[$];if(typeof Y==="function")return Y.bind(Z);return Y},apply(X,$,Z){return hX()(...Z)}})}var oX=null,w1=null,c,$X=e(()=>{c0(),X5(),c=h_()});async function MG(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=H0();console.log("-- Setting up test table...");try{await c.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await c.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 c.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 c.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 v_=e(()=>{$X(),v0()});function b_(X){return X.endsWith("s")?X.slice(0,-1):X}function TX(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 q=U($),w=U(E);V=[q,w].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 q=Y.models[G],w=q?.definition??q?.getDefinition?.()??q,A=w?.attributes??{};for(let[P,H]of Object.entries(A)){if(P===J||P===W||P===(w?.primaryKey??"id"))continue;F[P]={default:H?.default,nullable:H?.nullable,validation:H?.validation}}}let R=Boolean(z?.pivot?.timestamps),D=Object.keys(F);return{pivotTable:V,fkParent:J,fkRelated:W,pivotColumns:D,pivotColumnDefs:F,pivotModelName:G,timestamps:R,relatedModelName:j,relatedTable:E,hasConfig:L}}function*HG(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=TX(X,Y,Q,$);if(L)yield{parentTable:Y,relationKey:Q,resolved:L}}}}function p8(X){return typeof X==="object"&&X!==null&&"raw"in X&&typeof X.raw==="string"}function CG(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 t0(X){return I0(f.dialect)?`\`${X.replace(/`/g,"``")}\``:`"${X.replace(/"/g,'""')}"`}function X8(X,$=1){let Z=Object.keys(X[0]??{}),Y=[],U=$,_=X.map((Q)=>{return`(${Z.map((z)=>{return Y.push(Q[z]),l(U++)}).join(", ")})`});return{colsSql:Z.map(t0).join(", "),valuesSql:_.join(", "),params:Y,nextIndex:U}}function nX(X){return Boolean(X&&(X.onSlowQuery||X.slowQueryThresholdMs!=null&&X.slowQueryThresholdMs>=0))}function NY(X){if(typeof X==="string")return X;if(p8(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 p(X,$){if(!o.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 f0(X,$){if(typeof X!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof X}`);let Z=X.toLowerCase();if(!q1.has(Z))throw TypeError(`[query-builder] ${$}: refusing to use '${X}' as a SQL operator \u2014 not in the allowed set (${[...q1].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 f_($),X;if(X===null||X===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${X}`);if(p8(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 f_(X){if(P1.has(X))return;P1.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 g_(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 d_(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 p_(X,$){if(!$||$.length===0)return!1;let Z=X&&(X.code||X.sqlState||X.sqlstate);if(!Z)return!1;return $.includes(Z)}function c_(X){return new Promise(($)=>setTimeout($,X))}function $8(X){let $=rX.get(X);if($!==void 0)return $;let Z=m_(X);if(rX.size>=l_)rX.clear();return rX.set(X,Z),Z}function m_(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 R=J.match(F);if(!R)continue;Z.push({key:W,start:E}),E+=R[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 u_(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 H0(X){let $=X?.sql??hX(),Z=X?.meta,Y=X?.schema,U=new Map;function _(G){if(Array.isArray(G)){let[D,q,w]=G;p(D,"where(column)");let A=String(D);switch(q){case"in":if(Array.isArray(w)){let P=b0(w.length);return $.unsafe(`${A} IN (${P})`,w)}return $.unsafe(`${A} IN (${l(1)})`,[w]);case"not in":if(Array.isArray(w)){let P=b0(w.length);return $.unsafe(`${A} NOT IN (${P})`,w)}return $.unsafe(`${A} NOT IN (${l(1)})`,[w]);case"like":return $.unsafe(`${A} LIKE ${l(1)}`,[w]);case"is":case"is not":{if(w!==null&&w!==void 0)throw TypeError(`[query-builder] where(..., '${q}', ?): operator '${q}' only accepts NULL/undefined as value, got ${typeof w} (${String(w)})`);return $.unsafe(`${A} IS ${q==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${A} <> ${l(1)}`,[w]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${A} ${q} ${l(1)}`,[w]);default:throw TypeError(`[query-builder] where(..., '${String(q)}', ?): 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=[],R=1;for(let D of J){p(D,"where(object key)");let q=G[D];if(Array.isArray(q)){let w=b0(q.length,R);W.push(`${D} IN (${w})`),F.push(...q),R+=q.length}else W.push(`${D} = ${l(R++)}`),F.push(q)}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,R=F?.slowQueryThresholdMs,D=R!=null&&R>=0,q=Boolean(F?.onSlowQuery||D),w=F&&(F.onQueryStart||F.onQueryEnd||F.onQueryError||F.startSpan||q),A=W?.timeoutMs&&W.timeoutMs>0||W?.signal;if(!w&&!A)return G.execute();let P=L(G),H=z(G),N=Date.now(),S;try{if(F?.onQueryStart?.({sql:P,params:H,kind:J}),F?.startSpan)S=F.startSpan({sql:P,params:H,kind:J})}catch{}let h=!1,d=(u,i)=>{if(h)return;h=!0;let m=Date.now()-N;try{if(u)F?.onQueryError?.({sql:P,params:H,error:u,durationMs:m,kind:J});else if(F?.onQueryEnd?.({sql:P,params:H,durationMs:m,rowCount:i,kind:J}),D&&m>=R)if(F?.onSlowQuery)F.onSlowQuery({sql:P,params:H,durationMs:m,kind:J});else console.warn(`[query-builder] slow query (${m}ms >= ${R}ms): ${P}`)}catch{}try{S?.end(u)}catch{}},v=G.execute(),n=[v],a;if(W?.timeoutMs&&W.timeoutMs>0){let u=new Promise((i,m)=>{a=setTimeout(()=>{try{G.cancel?.()}catch{}let X0=Error(`Query timed out after ${W.timeoutMs}ms`);X0.code="EBQBTIMEOUT",m(X0)},W.timeoutMs)});n.push(u)}if(W?.signal){if(W.signal.aborted){try{G.cancel?.()}catch{}let i=Error("Query aborted");return i.code="EBQBABORT",d(i),Promise.reject(i)}let u=()=>{try{G.cancel?.()}catch{}};W.signal.addEventListener("abort",u,{once:!0}),v.finally(()=>{W.signal?.removeEventListener("abort",u)})}return Promise.race(n).then((u)=>{clearTimeout(a);let i=Array.isArray(u)?u.length:typeof u==="number"?u:void 0;return d(void 0,i),u}).catch((u)=>{throw clearTimeout(a),d(u),u})}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)}`,R=null,D=()=>{if(R===null){let O=$8(F);R=y.length>0?$.unsafe(O,y):$.unsafe(O)}return R},q=(O,I)=>{let M=!o.WHERE.test(F)?"WHERE":O==="WHERE"?"AND":O;F=`${F} ${M} ${I}`},w=(O,I)=>{let K=I.__rawState?.();if(K){let M=y.length,C=f.dialect==="postgres"?K.sql.replace(/\$(\d+)/g,(T,k)=>`$${Number(k)+M}`):K.sql;F+=` ${O} ${C}`,y.push(...K.params)}else F+=` ${O} ${String(I.toSQL())}`;R=null},A=(O)=>{let I=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,K=0,M=-1,C;while(C=I.exec(F))if(C[0]==="(")K++;else if(C[0]===")")K=Math.max(0,K-1);else if(K===0){M=C.index;break}F=M>=0?`${F.slice(0,M)}${O} ${F.slice(M)}`:`${F} ${O}`,R=null},P=new Set,H,N,S=!1,h=!1,d=!1,v=new Map,n=new Set,a=60000,u=(O)=>{if(f.relations.singularizeStrategy==="none")return O;return O.endsWith("s")?O.slice(0,-1):O},i=(O)=>{if(!Z)return null;return TX(Z,String(G),O,{singularize:u,models:Z.models})},m=(O)=>{if(!O||typeof O!=="object"||n.size===0)return O;let I;for(let K of Object.keys(O))if(K.startsWith("pivot_")){if(!I)I={};I[K.slice(6)]=O[K],delete O[K]}if(I)O.pivot=I;return O},X0=(O)=>{if(n.size===0||!O)return O;if(Array.isArray(O))for(let I=0;I<O.length;I++)m(O[I]);else m(O);return O},R0=(O)=>{if(!Z)return;if(P.has(O.pivotTable))return;let I=String(G),K=Z.primaryKeys[I]??"id";p(O.pivotTable,"wherePivot auto-join (pivot table)"),p(O.fkParent,"wherePivot auto-join (parent FK)"),p(I,"wherePivot auto-join (parent table)"),p(K,"wherePivot auto-join (parent PK)"),R=W`${D()} LEFT JOIN ${W(O.pivotTable)} ON ${W(`${O.pivotTable}.${O.fkParent}`)} = ${W(`${I}.${K}`)}`,F=`${F} LEFT JOIN ${O.pivotTable} ON ${O.pivotTable}.${O.fkParent} = ${I}.${K}`,P.add(O.pivotTable)},z0=[],y=[],J9=(O)=>{if(o.SELECT_STAR.test(F))F=F.replace(o.SELECT_STAR,`SELECT *, ${O}`);else if(o.SELECT.test(F))F=F.replace(o.SELECT_FROM,`SELECT $1, ${O} FROM`);let I=String(D());if(o.SELECT_STAR.test(I)){let K=I.replace(o.SELECT_STAR,`SELECT *, ${O}`);R=$.unsafe(K)}else if(o.SELECT.test(I)){if(o.SELECT_FROM.exec(I)){let M=I.replace(o.SELECT_FROM,`SELECT $1, ${O} FROM`);R=$.unsafe(M)}}},G0=(O,I,K,M)=>{J9(`${O} ${g_(K,M)} AS ${I}`)},_X=(O,I,K,M)=>{p(O,"relationship subquery (parent table)"),p(I,"relationship subquery (target table)"),p(K,"relationship subquery (primary key)");let C=`${O.endsWith("s")?O.slice(0,-1):O}_id`;p(C,"relationship subquery (foreign key)");let T=`SELECT 1 FROM ${I} WHERE ${I}.${C} = ${O}.${K}`;if(M){let x=M({where:(g,B,b)=>{return p(g,"relationship subquery condition"),`${I}.${g} ${f0(B,"whereHas callback")} ${q9(b)}`}});if(x)T+=` AND ${x}`}return T},v$=(O,I,K,M)=>{p(O,"relationship subquery (parent table)"),p(I,"relationship subquery (target table)"),p(K,"relationship subquery (primary key)");let C=`${I.endsWith("s")?I.slice(0,-1):I}_id`;p(C,"relationship subquery (foreign key)");let T=`SELECT 1 FROM ${I} WHERE ${I}.${K} = ${O}.${C}`;if(M){let x=M({where:(g,B,b)=>{return p(g,"relationship subquery condition"),`${I}.${g} ${f0(B,"whereHas callback")} ${q9(b)}`}});if(x)T+=` AND ${x}`}return T},b$=(O,I,K,M,C,T)=>{p(O,"relationship subquery (parent table)"),p(I,"relationship subquery (target table)"),p(K,"relationship subquery (primary key)"),p(M,"relationship subquery (target primary key)");let k=T&&Z?TX(Z,O,T,{singularize:u,models:Z.models}):null,x=u(O),g=u(I),B=k?.pivotTable??[x,g].sort().join("_"),b=k?.fkParent??`${x}_id`,s=k?.fkRelated??`${g}_id`;p(B,"relationship subquery (pivot table)"),p(b,"relationship subquery (foreign key A)"),p(s,"relationship subquery (foreign key B)");let $0=`SELECT 1 FROM ${B} JOIN ${I} ON ${I}.${M} = ${B}.${s} WHERE ${B}.${b} = ${O}.${K}`;if(C){let r=C({where:(S0,X9,_9)=>{return p(S0,"relationship subquery condition"),`${I}.${S0} ${f0(X9,"whereHas callback")} ${q9(_9)}`}});if(r)$0+=` AND ${r}`}return $0},B7=(O,I,K)=>{p(O,"withCount (parent table)"),p(I,"withCount (target table)"),p(K,"withCount (primary key)");let M=`${O.endsWith("s")?O.slice(0,-1):O}_id`;return p(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${I} WHERE ${I}.${M} = ${O}.${K})`},y7=(O,I,K,M)=>{p(O,"withCount (parent table)"),p(I,"withCount (target table)"),p(K,"withCount (primary key)");let C=M&&Z?TX(Z,O,M,{singularize:u,models:Z.models}):null,T=u(O),k=u(I),x=C?.pivotTable??[T,k].sort().join("_"),g=C?.fkParent??`${T}_id`;return p(x,"withCount (pivot table)"),p(g,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${x} WHERE ${x}.${g} = ${O}.${K})`},f$=(O,I,K)=>{if(!Z)return;p(K,`with${O[0]}${O.slice(1).toLowerCase()} (column)`);let M=String(G),C=Z.relations?.[M];if(!C)return;let T=Object.entries(C).find(([r,S0])=>S0&&typeof S0==="object"&&(I in S0));if(!T)return;let[k,x]=T,g=x[I],B=typeof g==="string"?g:g?.model||g?.target||g,b=Z.modelToTable[B]||B,s=Z.primaryKeys[M]??"id";p(b,`with${O} (target table)`);let $0=`${O}(${b}.${K})`,P0;if(k==="hasMany"||k==="hasOne"){let r=`${M.endsWith("s")?M.slice(0,-1):M}_id`;p(r,`with${O} (foreign key)`),P0=`(SELECT ${$0} FROM ${b} WHERE ${b}.${r} = ${M}.${s})`}else if(k==="belongsToMany"){let r=Z?TX(Z,M,I,{singularize:u,models:Z.models}):null,S0=u(M),X9=u(b),_9=r?.pivotTable??[S0,X9].sort().join("_"),QX=r?.fkParent??`${S0}_id`,_0=r?.fkRelated??`${X9}_id`,cX=Z.primaryKeys[b]??"id";p(_9,`with${O} (pivot table)`),p(QX,`with${O} (foreign key)`),p(_0,`with${O} (related key)`),P0=`(SELECT ${$0} FROM ${_9} JOIN ${b} ON ${b}.${cX} = ${_9}.${_0} WHERE ${_9}.${QX} = ${M}.${s})`}else return;J9(`${P0} AS ${I}_${O.toLowerCase()}_${K}`)},R5=()=>{if(v.size===0)return;let O=[];for(let[I,K]of v.entries()){let M=i(I);if(!M)continue;for(let T of K)p(T,"withPivot");let C=K.map((T)=>`${M.pivotTable}.${T} AS pivot_${T}`);O.push(...C)}if(O.length>0){let I=O.join(", ");J9(I)}};return new Proxy({distinct(){return F=F.replace(/^SELECT\s+/i,"SELECT DISTINCT "),R=null,this},distinctOn(...O){let I=O.map(String).join(", ");return F=F.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${I}) `),R=null,this},selectRaw(O){let I=KX(O,"selectRaw(fragment)"),K=F.indexOf(" FROM ");if(K!==-1)F=`${F.substring(0,K)}, ${I}${F.substring(K)}`;else F+=`, ${I}`;return R=null,this},rowNumber(O="row_number",I,K){let M=[];if(I){let x=Array.isArray(I)?I:[I];M.push(`PARTITION BY ${x.join(", ")}`)}if(K&&K.length)M.push(`ORDER BY ${K.map(([x,g])=>`${x} ${g==="desc"?"DESC":"ASC"}`).join(", ")}`);let T=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${O}`,k=F.indexOf(" FROM ");if(k!==-1)F=`${F.substring(0,k)}, ${T}${F.substring(k)}`;else F+=`, ${T}`;return R=null,this},denseRank(O="dense_rank",I,K){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(K&&K.length)C.push(`ORDER BY ${K.map(([g,B])=>`${g} ${B==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`DENSE_RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,x=F.indexOf(" FROM ");if(x!==-1)F=`${F.substring(0,x)}, ${k}${F.substring(x)}`;else F+=`, ${k}`;return R=null,this},rank(O="rank",I,K){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(K&&K.length)C.push(`ORDER BY ${K.map(([g,B])=>`${g} ${B==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,x=F.indexOf(" FROM ");if(x!==-1)F=`${F.substring(0,x)}, ${k}${F.substring(x)}`;else F+=`, ${k}`;return R=null,this},over(O,I,K={}){return G0(O,I,K.partitionBy,K.orderBy),this},lag(O,I={}){let K=[O,String(I.offset??1)];if(I.defaultValue!==void 0)K.push(String(I.defaultValue));return G0(`LAG(${K.join(", ")})`,I.alias??`${O}_lag`,I.partitionBy,I.orderBy),this},lead(O,I={}){let K=[O,String(I.offset??1)];if(I.defaultValue!==void 0)K.push(String(I.defaultValue));return G0(`LEAD(${K.join(", ")})`,I.alias??`${O}_lead`,I.partitionBy,I.orderBy),this},sumOver(O,I={}){return G0(`SUM(${O})`,I.alias??`${O}_sum`,I.partitionBy,I.orderBy),this},avgOver(O,I={}){return G0(`AVG(${O})`,I.alias??`${O}_avg`,I.partitionBy,I.orderBy),this},countOver(O="*",I={}){return G0(`COUNT(${O})`,I.alias??"count_over",I.partitionBy,I.orderBy),this},minOver(O,I={}){return G0(`MIN(${O})`,I.alias??`${O}_min`,I.partitionBy,I.orderBy),this},maxOver(O,I={}){return G0(`MAX(${O})`,I.alias??`${O}_max`,I.partitionBy,I.orderBy),this},firstValue(O,I={}){return G0(`FIRST_VALUE(${O})`,I.alias??`${O}_first`,I.partitionBy,I.orderBy),this},lastValue(O,I={}){return G0(`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 K=I.map(NY),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(F),C=M?M[1]:"",T=F.indexOf(" FROM ");if(T!==-1)F=`SELECT ${C}${K.join(", ")}${F.substring(T)}`;else F=`SELECT ${C}${K.join(", ")} FROM ${G}`;return R=null,this},addSelect(...O){if(!O.length)return this;let I=O.map(NY),K=F.indexOf(" FROM ");if(K!==-1)F=`${F.substring(0,K)}, ${I.join(", ")}${F.substring(K)}`;else F+=`, ${I.join(", ")}`;return R=null,this},with(...O){if(!Z||!O||O.length===0)return this;let I=[];for(let B of O){if(!B)continue;if(typeof B==="string")I.push({name:B});else if(typeof B==="object"&&!Array.isArray(B))for(let[b,s]of Object.entries(B))if(typeof s==="function")I.push({name:b,callback:s});else I.push({name:b})}if(I.length===0)return this;let K=f.relations.maxEagerLoad??50;if(I.length>K)throw Error(`[query-builder] Too many relationships to eager load (${I.length}). Maximum allowed: ${K}`);let M=String(G),C=new Set,T=new Set,k=new Map,x=(B)=>{let b=Z.relations?.[B];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=(B,b,s=0,$0)=>{let P0=f.relations.maxDepth??10;if(s>=P0)throw Error(`[query-builder] Maximum relationship depth (${P0}) exceeded at '${b}'. Consider using separate queries or increasing maxDepth.`);let r=Z.relations?.[B];if(!r)return B;let S0=(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=[],w0=(L0,a0,R9)=>{p(String(L0),"with() constraint column");let zX=f0(a0,"with() constraint operator");Y0.push(`${Z0}.${String(L0)} ${zX} ${q9(R9)}`)},K0=(L0)=>()=>{throw Error(`[query-builder] with('${b}', ...): ${L0} 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.)`)},T0={where:(L0,a0,R9)=>{if(Array.isArray(L0))w0(L0[0],L0[1],L0[2]);else if(L0&&typeof L0==="object")for(let zX of Object.keys(L0))w0(zX,"=",L0[zX]);else if(a0!==void 0&&R9!==void 0)w0(L0,a0,R9);else if(a0!==void 0)w0(L0,"=",a0);return T0},whereIn:(L0,a0)=>{return p(String(L0),"with() constraint column"),Y0.push(`${Z0}.${String(L0)} IN (${a0.map(q9).join(", ")})`),T0},whereNull:(L0)=>{return p(String(L0),"with() constraint column"),Y0.push(`${Z0}.${String(L0)} IS NULL`),T0},whereNotNull:(L0)=>{return p(String(L0),"with() constraint column"),Y0.push(`${Z0}.${String(L0)} IS NOT NULL`),T0},orderBy:K0("orderBy()"),limit:K0("limit()"),offset:K0("offset()"),take:K0("take()")};return $0(T0),Y0.length?` AND ${Y0.join(" AND ")}`:""},_9=()=>{let Z0=(K0)=>{let T0=K0?.[b];return T0?Z.modelToTable[T0]:void 0},Y0=(K0)=>{let T0=K0?.[b],L0=typeof T0==="string"?T0:T0?.model;return L0?Z.modelToTable[L0]:void 0},w0=(K0)=>{let T0=K0?.[b];return T0?.target?Z.modelToTable[T0.target]:void 0};return Z0(r?.hasOne)||Z0(r?.hasMany)||Z0(r?.belongsTo)||Y0(r?.belongsToMany)||w0(r?.hasOneThrough)||w0(r?.hasManyThrough)||Z0(r?.morphOne)||Z0(r?.morphMany)||Z0(r?.morphToMany)||Z0(r?.morphedByMany)},QX=_9()??(Z.modelToTable[b]||Z.tableToModel[b]?Z.modelToTable[b]??b:b),_0=String(QX);if(!QX||!_9()&&!Z.modelToTable[b]&&!Z.tableToModel[b]){let Z0=x(B);if(Z0.length>0&&!Z0.includes(b)){let Y0=` Available relationships: ${Z0.join(", ")}`;throw Error(`[query-builder] Relationship '${b}' not found on table '${B}'.${Y0}`)}}if(f.relations.detectCycles!==!1){let Z0=`${B}->${_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===B)return B;let cX=r?.hasOneThrough?.[b]||r?.hasManyThrough?.[b];if(cX){let{through:Z0,target:Y0}=cX,w0=Z.modelToTable[Z0]||Z0,K0=Z.modelToTable[Y0]||Y0,T0=Z.primaryKeys[B]??"id",L0=Z.primaryKeys[w0]??"id",a0=`${u(B)}_id`,R9=`${u(w0)}_id`;return A(`LEFT JOIN ${w0} ON ${w0}.${a0} = ${B}.${T0} LEFT JOIN ${K0} ON ${K0}.${R9} = ${w0}.${L0}`),P.add(w0),P.add(K0),K0}if(Boolean(r?.belongsToMany?.[b])){let Z0=TX(Z,B,b,{singularize:u,models:Z.models}),Y0=Z0?.pivotTable??[u(B),u(_0)].sort().join("_"),w0=Z.primaryKeys[B]??"id",K0=Z.primaryKeys[_0]??"id",T0=Z0?.fkParent??`${u(B)}_id`,L0=Z0?.fkRelated??`${u(_0)}_id`;return A(`LEFT JOIN ${Y0} ON ${Y0}.${T0} = ${B}.${w0} LEFT JOIN ${_0} ON ${_0}.${K0} = ${Y0}.${L0}${X9(_0)}`),P.add(Y0),P.add(_0),_0}if(Boolean(r?.morphToMany?.[b])){let Z0=b,Y0=`${u(_0)}_${Z0}`,w0=Z.primaryKeys[B]??"id",K0=Z.primaryKeys[_0]??"id",T0=`${Z0}_type`,L0=`${Z0}_id`,a0=`${u(_0)}_id`,R9=q9(Z.tableToModel[B]||B);return A(`LEFT JOIN ${Y0} ON ${Y0}.${L0} = ${B}.${w0} AND ${Y0}.${T0} = ${R9} LEFT JOIN ${_0} ON ${_0}.${K0} = ${Y0}.${a0}`),P.add(Y0),P.add(_0),_0}if(Boolean(r?.morphedByMany?.[b])){let Z0=r.morphedByMany?.[b]||b,Y0=Z.modelToTable[Z0]||Z0,w0=u(B),K0=`${u(Y0)}_${w0}`,T0=Z.primaryKeys[B]??"id",L0=Z.primaryKeys[Y0]??"id",a0=`${w0}_type`,R9=`${w0}_id`,zX=`${u(Y0)}_id`,d7=q9(Z.tableToModel[Y0]||Y0);return A(`LEFT JOIN ${K0} ON ${K0}.${zX} = ${B}.${T0} LEFT JOIN ${Y0} ON ${Y0}.${L0} = ${K0}.${R9} AND ${K0}.${a0} = ${d7}`),P.add(K0),P.add(Y0),Y0}if(Boolean(r?.belongsTo?.[b])){let Z0=`${u(_0)}_id`,Y0=Z.primaryKeys[_0]??"id";return A(`LEFT JOIN ${_0} ON ${B}.${Z0} = ${_0}.${Y0}${X9(_0)}`),P.add(_0),_0}let h7=Boolean(r?.morphOne?.[b]),v7=Boolean(r?.morphMany?.[b]);if(h7||v7){let Z0=`${b}_type`,Y0=`${b}_id`,w0=Z.primaryKeys[B]??"id",K0=q9(Z.tableToModel[B]||B);return A(`LEFT JOIN ${_0} ON ${_0}.${Y0} = ${B}.${w0} AND ${_0}.${Z0} = ${K0}`),P.add(_0),_0}let b7=`${u(B)}_id`,f7=Z.primaryKeys[B]??"id",g7=`${S0(_0)}${X9(_0)}`;return A(`LEFT JOIN ${_0} ON ${_0}.${b7} = ${B}.${f7}${g7}`),P.add(_0),_0};for(let B of I){let b=B.name.trim();if(B.callback)k.set(b,B.callback);let s=b.split("."),$0=M,P0=0;for(let r of s){if(!r||r.trim().length===0)continue;let S0=r.trim(),X9=k.get(S0);$0=g($0,S0,P0,X9)||$0,P0++}T.add(b)}if(v.size>0){let B=[];for(let[b,s]of v.entries()){let $0=i(b);if(!$0)continue;let P0=s.map((r)=>`${$0.pivotTable}.${r} AS pivot_${r}`);B.push(...P0)}if(B.length>0){let b=B.join(", ");J9(b)}}return R=null,this},whereHas(O,I){if(!Z)return this;let K=String(G),M=Z.relations?.[K];if(!M)throw Error(`[query-builder] No relationships defined for table '${K}'`);let C=Object.entries(M).find(([s,$0])=>$0&&typeof $0==="object"&&(O in $0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${K}'`);let[T,k]=C,x=k[O],g=typeof x==="string"?x:x?.model||x?.target||x,B=Z.modelToTable[g]||g,b;if(T==="hasMany"||T==="hasOne"){let s=Z.primaryKeys[K]??"id";b=_X(K,B,s,I)}else if(T==="belongsTo"){let s=Z.primaryKeys[B]??"id";b=v$(K,B,s,I)}else if(T==="belongsToMany"){let s=Z.primaryKeys[K]??"id",$0=Z.primaryKeys[B]??"id";b=b$(K,B,s,$0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${T}' for whereHas`);R=W`${D()} WHERE EXISTS (${W([b])})`;try{q("WHERE",`EXISTS (${b})`)}catch{}return this},whereDoesntHave(O,I){if(!Z)return this;let K=String(G),M=Z.relations?.[K];if(!M)throw Error(`[query-builder] No relationships defined for table '${K}'`);let C=Object.entries(M).find(([s,$0])=>$0&&typeof $0==="object"&&(O in $0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${K}'`);let[T,k]=C,x=k[O],g=typeof x==="string"?x:x?.model||x?.target||x,B=Z.modelToTable[g]||g,b;if(T==="hasMany"||T==="hasOne"){let s=Z.primaryKeys[K]??"id";b=_X(K,B,s,I)}else if(T==="belongsTo"){let s=Z.primaryKeys[B]??"id";b=v$(K,B,s,I)}else if(T==="belongsToMany"){let s=Z.primaryKeys[K]??"id",$0=Z.primaryKeys[B]??"id";b=b$(K,B,s,$0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${T}' for whereDoesntHave`);R=W`${D()} WHERE NOT EXISTS (${W([b])})`;try{q("WHERE",`NOT EXISTS (${b})`)}catch{}return this},has(O){if(!Z)return this;let I=String(G),K=Z.relations?.[I];if(!K)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(K).find(([b,s])=>s&&typeof s==="object"&&(O in s));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,T]=M,k=T[O],x=typeof k==="string"?k:k?.model||k?.target||k,g=Z.modelToTable[x]||x,B;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";B=_X(I,g,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[g]??"id";B=v$(I,g,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",s=Z.primaryKeys[g]??"id";B=b$(I,g,b,s,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for has`);R=W`${D()} WHERE EXISTS (${W([B])})`;try{q("WHERE",`EXISTS (${B})`)}catch{}return this},doesntHave(O){if(!Z)return this;let I=String(G),K=Z.relations?.[I];if(!K)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(K).find(([b,s])=>s&&typeof s==="object"&&(O in s));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,T]=M,k=T[O],x=typeof k==="string"?k:k?.model||k?.target||k,g=Z.modelToTable[x]||x,B;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";B=_X(I,g,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[g]??"id";B=v$(I,g,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",s=Z.primaryKeys[g]??"id";B=b$(I,g,b,s,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for doesntHave`);R=W`${D()} WHERE NOT EXISTS (${W([B])})`;try{q("WHERE",`NOT EXISTS (${B})`)}catch{}return this},withCount(...O){if(!Z||!O||O.length===0)return this;let I=String(G);for(let K of O){let M=Z.relations?.[I];if(!M)continue;let C=Object.entries(M).find(([P0,r])=>r&&typeof r==="object"&&(K in r));if(!C)continue;let[T,k]=C,x=k[K],g=typeof x==="string"?x:x?.model||x?.target||x,B=Z.modelToTable[g]||g,b=Z.primaryKeys[I]??"id",s;if(T==="hasMany"||T==="hasOne")s=B7(I,B,b);else if(T==="belongsToMany")s=y7(I,B,b,K);else continue;let $0=`${K}_count`;J9(`${s} AS ${$0}`)}return this},withSum(O,I){return f$("SUM",O,I),this},withAvg(O,I){return f$("AVG",O,I),this},withMax(O,I){return f$("MAX",O,I),this},withMin(O,I){return f$("MIN",O,I),this},applyPivotColumns(){return R5(),this},withPivot(O,...I){if(!Z)return this;let K=String(G),M=i(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${K}'`);let C=I&&I.length>0?I:M.hasConfig?M.pivotColumns:[];if(C.length===0)return this;if(v.set(O,C),M.hasConfig)n.add(O);return R5(),this},wherePivot(O,I,K,M){if(!Z)return this;let C=i(O);if(!C)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(C.pivotTable,"wherePivot (pivot table)"),p(I,"wherePivot (column)"),R0(C);let T=M===void 0?"=":String(K),k=M===void 0?K:M,x=y.length+1,g=`${C.pivotTable}.${I} ${T} ${l(x)}`;z0.push(g),y.push(k);let B=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${B} ${g}`,R=null,C.hasConfig)n.add(O);return this},wherePivotIn(O,I,K){if(!Z||!Array.isArray(K)||K.length===0)return this;let M=i(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(M.pivotTable,"wherePivotIn (pivot table)"),p(I,"wherePivotIn (column)"),R0(M);let C=b0(K.length,y.length+1),T=`${M.pivotTable}.${I} IN (${C})`;z0.push(T),y.push(...K);let k=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${k} ${T}`,R=null,M.hasConfig)n.add(O);return this},wherePivotNotIn(O,I,K){if(!Z||!Array.isArray(K)||K.length===0)return this;let M=i(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(M.pivotTable,"wherePivotNotIn (pivot table)"),p(I,"wherePivotNotIn (column)"),R0(M);let C=b0(K.length,y.length+1),T=`${M.pivotTable}.${I} NOT IN (${C})`;z0.push(T),y.push(...K);let k=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${k} ${T}`,R=null,M.hasConfig)n.add(O);return this},wherePivotNull(O,I){if(!Z)return this;let K=i(O);if(!K)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(K.pivotTable,"wherePivotNull (pivot table)"),p(I,"wherePivotNull (column)"),R0(K);let M=`${K.pivotTable}.${I} IS NULL`;z0.push(M);let C=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,R=null,K.hasConfig)n.add(O);return this},wherePivotNotNull(O,I){if(!Z)return this;let K=i(O);if(!K)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(K.pivotTable,"wherePivotNotNull (pivot table)"),p(I,"wherePivotNotNull (column)"),R0(K);let M=`${K.pivotTable}.${I} IS NOT NULL`;z0.push(M);let C=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,R=null,K.hasConfig)n.add(O);return this},where(O,I,K){let M=()=>o.WHERE.test(F)?"AND":"WHERE";if(typeof O==="string"&&I!==void 0){p(String(O),"where(column)"),f0(I,"where(operator)");let C=String(I).toLowerCase();if(C==="in"||C==="not in"){let k=Array.isArray(K)?K:[K],x=b0(k.length,y.length+1),g=`${String(O)} ${C.toUpperCase()} (${x})`;return z0.push(g),y.push(...k),F=`${F} ${M()} ${g}`,R=null,this}let T=y.length+1;return z0.push(`${String(O)} ${String(I)} ${l(T)}`),y.push(K),F=`${F} ${M()} ${String(O)} ${String(I)} ${l(T)}`,R=null,this}if(Array.isArray(O)){let[C,T,k]=O,x=String(C);p(x,"where(column)");let g=f0(T,"where(operator)");if(g==="in"||g==="not in"){let B=Array.isArray(k)?k:[k],b=b0(B.length,y.length+1);z0.push(`${x} ${g.toUpperCase()} (${b})`),y.push(...B),F=`${F} ${M()} ${x} ${g.toUpperCase()} (${b})`,R=null}else{let B=y.length+1;z0.push(`${x} ${g} ${l(B)}`),y.push(k),F=`${F} ${M()} ${x} ${g} ${l(B)}`,R=null}return this}if(O&&typeof O==="object"&&!p8(O)){let C=O,T=Object.keys(C),k=[];for(let x of T){p(x,"where(column)");let g=C[x];if(Array.isArray(g)){let B=b0(g.length,y.length+1);k.push(`${x} IN (${B})`),z0.push(`${x} IN (${B})`),y.push(...g)}else{let B=y.length+1;k.push(`${x} = ${l(B)}`),z0.push(`${x} = ${l(B)}`),y.push(g)}}if(k.length>0)F=`${F} ${M()} ${k.join(" AND ")}`,R=null;return this}if(p8(O))return z0.push(O.raw),F=`${F} ${M()} ${O.raw}`,R=null,this;return this},whereNull(O){p(String(O),"whereNull(column)");let I=o.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NULL`,R=null,this},whereNotNull(O){p(String(O),"whereNotNull(column)");let I=o.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NOT NULL`,R=null,this},whereBetween(O,I,K){p(String(O),"whereBetween(column)");let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1;return F=`${F} ${M} ${String(O)} BETWEEN ${l(C)} AND ${l(C+1)}`,y.push(I,K),R=null,this},whereExists(O){let I=o.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} EXISTS (${O.toSQL()})`,R=null,this},whereJsonContains(O,I){p(String(O),"whereJsonContains(column)");let K=o.WHERE.test(F)?"AND":"WHERE",M=f.dialect,C=y.length+1;if(M==="postgres"){if(f.sql?.jsonContainsMode==="function")F+=` ${K} jsonb_contains(${O}, ${l(C)})`;else F+=` ${K} ${O} @> ${l(C)}`;y.push(JSON.stringify(I))}else if(I0(M))F+=` ${K} JSON_CONTAINS(${O}, ${l(C)})`,y.push(JSON.stringify(I));else if(Array.isArray(I)){let T=I.map((k,x)=>`EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${l(C+x)})`);F+=` ${K} (${T.join(" AND ")})`;for(let k of I)y.push(k)}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+=` ${K} EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${l(C)})`,y.push(I);return R=null,this},whereJsonPath(O,I,K){if(f0(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=o.WHERE.test(F)?"AND":"WHERE",T=y.length+1;if(M==="postgres")F+=` ${C} ${O} ${I} ${l(T)}`;else if(I0(M))F+=` ${C} JSON_EXTRACT(${O}) ${I} ${l(T)}`;else F+=` ${C} json_extract(${O}) ${I} ${l(T)}`;return y.push(K),R=null,this},whereLike(O,I,K=!1){let M=l(y.length+1);return q("WHERE",`${K?String(O):`LOWER(${String(O)})`} LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},whereILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("WHERE",`${String(O)} ILIKE ${K}`);else q("WHERE",`LOWER(${String(O)}) LIKE LOWER(${K})`);return y.push(I),R=null,this},orWhereLike(O,I,K=!1){let M=l(y.length+1);return q("OR",`${K?String(O):`LOWER(${String(O)})`} LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},orWhereILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("OR",`${String(O)} ILIKE ${K}`);else q("OR",`LOWER(${String(O)}) LIKE LOWER(${K})`);return y.push(I),R=null,this},whereNotLike(O,I,K=!1){let M=l(y.length+1);return q("WHERE",`${K?String(O):`LOWER(${String(O)})`} NOT LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},whereNotILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("WHERE",`${String(O)} NOT ILIKE ${K}`);else q("WHERE",`LOWER(${String(O)}) NOT LIKE LOWER(${K})`);return y.push(I),R=null,this},orWhereNotLike(O,I,K=!1){let M=l(y.length+1);return q("OR",`${K?String(O):`LOWER(${String(O)})`} NOT LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},orWhereNotILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("OR",`${String(O)} NOT ILIKE ${K}`);else q("OR",`LOWER(${String(O)}) NOT LIKE LOWER(${K})`);return y.push(I),R=null,this},whereAny(O,I,K){if(O.length===0)return this;let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1,T=O.map((k,x)=>`${k} ${I} ${l(C+x)}`);F+=` ${M} (${T.join(" OR ")})`;for(let k=0;k<O.length;k++)y.push(K);return R=null,this},whereAll(O,I,K){if(O.length===0)return this;let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1,T=O.map((k,x)=>`${k} ${I} ${l(C+x)}`);F+=` ${M} (${T.join(" AND ")})`;for(let k=0;k<O.length;k++)y.push(K);return R=null,this},whereNone(O,I,K){if(O.length===0)return this;let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1,T=O.map((k,x)=>`${k} ${I} ${l(C+x)}`);F+=` ${M} NOT (${T.join(" OR ")})`;for(let k=0;k<O.length;k++)y.push(K);return R=null,this},whereNotBetween(O,I,K){p(String(O),"whereNotBetween(column)");let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1;return F+=` ${M} ${O} NOT BETWEEN ${l(C)} AND ${l(C+1)}`,y.push(I,K),R=null,this},whereDate(O,I,K){p(O,"whereDate(column)");let M=K instanceof Date?K.toISOString():typeof K==="string"?K:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof K}`)})(),C=o.WHERE.test(F)?"AND":"WHERE",T=y.length+1;return F+=` ${C} ${O} ${I} ${l(T)}`,y.push(M),R=null,this},whereRaw(O){let I=KX(O,"whereRaw(fragment)"),K=o.WHERE.test(F)?"AND":"WHERE";return F+=` ${K} ${I}`,R=null,this},whereColumn(O,I,K){p(O,"whereColumn(left)"),p(K,"whereColumn(right)");let M=o.WHERE.test(F)?"AND":"WHERE";return F+=` ${M} ${O} ${I} ${K}`,R=null,this},orWhereColumn(O,I,K){return p(O,"orWhereColumn(left)"),p(K,"orWhereColumn(right)"),F+=` OR ${O} ${I} ${K}`,R=null,this},whereIn(O,I){p(String(O),"whereIn(column)");let K=o.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=b0(I.length,y.length+1);F+=` ${K} ${O} IN (${M})`,y.push(...I)}else F+=` ${K} ${O} IN (${String(I.toSQL())})`;return R=null,this},orWhereIn(O,I){if(p(String(O),"orWhereIn(column)"),Array.isArray(I)){let K=b0(I.length,y.length+1);F+=` OR ${O} IN (${K})`,y.push(...I)}else F+=` OR ${O} IN (${String(I.toSQL())})`;return R=null,this},whereNotIn(O,I){p(String(O),"whereNotIn(column)");let K=o.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=b0(I.length,y.length+1);F+=` ${K} ${O} NOT IN (${M})`,y.push(...I)}else F+=` ${K} ${O} NOT IN (${String(I.toSQL())})`;return R=null,this},orWhereNotIn(O,I){if(p(String(O),"orWhereNotIn(column)"),Array.isArray(I)){let K=b0(I.length,y.length+1);F+=` OR ${O} NOT IN (${K})`,y.push(...I)}else F+=` OR ${O} NOT IN (${String(I.toSQL())})`;return R=null,this},whereNested(O){let I=o.WHERE.test(F)?"AND":"WHERE",K=O.toSQL?String(O.toSQL()):String(O);return F+=` ${I} (${K})`,R=null,this},orWhereNested(O){let I=O.toSQL?String(O.toSQL()):String(O);return F+=` OR (${I})`,R=null,this},andWhere(O,I,K){if(typeof O==="string"&&I!==void 0){p(String(O),"andWhere(column)"),f0(I,"andWhere(operator)");let M=y.length+1;return z0.push(`${String(O)} ${String(I)} ${l(M)}`),y.push(K),F=`${F} AND ${String(O)} ${String(I)} ${l(M)}`,R=null,this}if(Array.isArray(O)){let[M,C,T]=O,k=String(M);p(k,"andWhere(column)");let x=f0(C,"andWhere(operator)");if(x==="in"||x==="not in"){let g=Array.isArray(T)?T:[T],B=b0(g.length,y.length+1);z0.push(`${k} ${x.toUpperCase()} (${B})`),y.push(...g),F=`${F} AND ${k} ${x.toUpperCase()} (${B})`,R=null}else{let g=y.length+1;z0.push(`${k} ${x} ${l(g)}`),y.push(T),F=`${F} AND ${k} ${x} ${l(g)}`,R=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let T of M){let k=O[T];if(Array.isArray(k)){let x=b0(k.length,y.length+1);C.push(`${T} IN (${x})`),z0.push(`${T} IN (${x})`),y.push(...k)}else{let x=y.length+1;C.push(`${T} = ${l(x)}`),z0.push(`${T} = ${l(x)}`),y.push(k)}}if(C.length>0)F=`${F} AND ${C.join(" AND ")}`,R=null;return this}if(O&&typeof O.raw<"u")return z0.push(O.raw),F=`${F} AND ${O.raw}`,R=null,this;return this},orWhere(O,I,K){if(typeof O==="string"&&I!==void 0){p(String(O),"orWhere(column)"),f0(I,"orWhere(operator)");let M=y.length+1;return z0.push(`OR ${String(O)} ${String(I)} ${l(M)}`),y.push(K),F=`${F} OR ${String(O)} ${String(I)} ${l(M)}`,R=null,this}if(Array.isArray(O)){let[M,C,T]=O,k=String(M);p(k,"orWhere(column)");let x=f0(C,"orWhere(operator)");if(x==="in"||x==="not in"){let g=Array.isArray(T)?T:[T],B=b0(g.length,y.length+1);z0.push(`OR ${k} ${x.toUpperCase()} (${B})`),y.push(...g),F=`${F} OR ${k} ${x.toUpperCase()} (${B})`,R=null}else{let g=y.length+1;z0.push(`OR ${k} ${x} ${l(g)}`),y.push(T),F=`${F} OR ${k} ${x} ${l(g)}`,R=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let T of M){let k=O[T];if(Array.isArray(k)){let x=b0(k.length,y.length+1);C.push(`${T} IN (${x})`),z0.push(`OR ${T} IN (${x})`),y.push(...k)}else{let x=y.length+1;C.push(`${T} = ${l(x)}`),z0.push(`OR ${T} = ${l(x)}`),y.push(k)}}if(C.length>0)F=`${F} OR ${C.join(" AND ")}`,R=null;return this}if(O&&typeof O.raw<"u")return z0.push(`OR ${O.raw}`),F=`${F} OR ${O.raw}`,R=null,this;return this},orderBy(O,I="asc"){let K=I==="asc"?"ASC":"DESC";return F=o.ORDER_BY.test(F)?`${F}, ${O} ${K}`:`${F} ORDER BY ${O} ${K}`,R=null,this},orderByDesc(O){return F=o.ORDER_BY.test(F)?`${F}, ${O} DESC`:`${F} ORDER BY ${O} DESC`,R=null,this},inRandomOrder(){let O=f.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return F=o.ORDER_BY.test(F)?`${F}, ${O}`:`${F} ORDER BY ${O}`,R=null,this},reorder(O,I="asc"){return F=F.replace(/ORDER BY[\s\S]*$/i,""),F+=` ORDER BY ${O} ${I==="asc"?"ASC":"DESC"}`,R=null,this},latest(O){let I=O??f.timestamps.defaultOrderColumn;return F=o.ORDER_BY.test(F)?`${F}, ${I} DESC`:`${F} ORDER BY ${I} DESC`,R=null,this},oldest(O){let I=O??f.timestamps.defaultOrderColumn;return F=o.ORDER_BY.test(F)?`${F}, ${I} ASC`:`${F} ORDER BY ${I} ASC`,R=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=o.LIMIT.test(F)?F.replace(o.LIMIT,` LIMIT ${O}`):`${F} LIMIT ${O}`,R=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=o.OFFSET.test(F)?F.replace(o.OFFSET,` OFFSET ${O}`):`${F} OFFSET ${O}`,R=null,this},join(O,I,K,M){return p(O,"join(table)"),Q9(I,"join(onLeft)"),Q9(M,"join(onRight)"),f0(K,"join(operator)"),A(`JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},joinSub(O,I,K,M,C){return p(I,"joinSub(alias)"),Q9(K,"joinSub(onLeft)"),Q9(C,"joinSub(onRight)"),f0(M,"joinSub(operator)"),A(`JOIN (${String(O.toSQL())}) AS ${I} ON ${K} ${M} ${C}`),P.add(I),this},innerJoin(O,I,K,M){return p(O,"innerJoin(table)"),Q9(I,"innerJoin(onLeft)"),Q9(M,"innerJoin(onRight)"),f0(K,"innerJoin(operator)"),A(`INNER JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},leftJoin(O,I,K,M){return p(O,"leftJoin(table)"),Q9(I,"leftJoin(onLeft)"),Q9(M,"leftJoin(onRight)"),f0(K,"leftJoin(operator)"),A(`LEFT JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},leftJoinSub(O,I,K,M,C){return p(I,"leftJoinSub(alias)"),Q9(K,"leftJoinSub(onLeft)"),Q9(C,"leftJoinSub(onRight)"),f0(M,"leftJoinSub(operator)"),A(`LEFT JOIN (${String(O.toSQL())}) AS ${I} ON ${K} ${M} ${C}`),P.add(I),this},rightJoin(O,I,K,M){return p(O,"rightJoin(table)"),Q9(I,"rightJoin(onLeft)"),Q9(M,"rightJoin(onRight)"),f0(K,"rightJoin(operator)"),A(`RIGHT JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},crossJoin(O){return p(O,"crossJoin(table)"),A(`CROSS JOIN ${O}`),P.add(O),this},crossJoinSub(O,I){return p(I,"crossJoinSub(alias)"),A(`CROSS JOIN (${String(O.toSQL())}) AS ${I}`),P.add(I),this},selectAllRelations(){if(!Y)return this;let O=String(G),I=Object.keys(Y[O]?.columns??{}),K=[];if(I.length>0)K.push(W`${W(O)}.*`);for(let M of P){let C=Object.keys(Y[M]?.columns??{});for(let T of C){let k=f.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${T}`.replace(/_([a-z])/g,(x,g)=>g.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${T}`:`${M}_${T}`;K.push(W`${W(`${M}.${T}`)} AS ${W(k)}`)}}if(K.length>0){let M=I.length>0?`${O}.*`:"",C=[];for(let x of P){let g=Object.keys(Y[x]?.columns??{});for(let B of g){let b=f.aliasing.relationColumnAliasFormat==="camelCase"?`${x}_${B}`.replace(/_([a-z])/g,(s,$0)=>$0.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${x}.${B}`:`${x}_${B}`;C.push(`${x}.${B} AS ${b}`)}}let T=[M,...C].filter(Boolean).join(", "),k=F.indexOf(" FROM ");if(k!==-1)F=`SELECT ${T}${F.substring(k)}`;else F=`SELECT ${T} FROM ${O}`;R=null}return this},groupBy(...O){if(O.length)F=o.GROUP_BY.test(F)?`${F}, ${O.join(", ")}`:`${F} GROUP BY ${O.join(", ")}`,R=null;return this},groupByRaw(O){let I=KX(O,"groupByRaw(fragment)");return F=o.GROUP_BY.test(F)?`${F}, ${I}`:`${F} GROUP BY ${I}`,R=null,this},having(O){let I=/\bHAVING\b/i.test(F)?"AND":"HAVING";if(Array.isArray(O)){let K=y.length+1;F=`${F} ${I} ${O[0]} ${O[1]} ${l(K)}`,y.push(O[2]),R=null}else if(O&&typeof O==="object"&&!("raw"in O)){let K=Object.keys(O),M=K.length;if(M){let C=y.length,T=Array.from({length:M});for(let k=0;k<M;k++){let x=K[k];T[k]=`${x} = ${l(C+k+1)}`,y.push(O[x])}F=`${F} ${I} ${T.join(" AND ")}`,R=null}}else if(O&&typeof O.raw<"u")F+=` ${I} ${O.raw}`,R=null;return this},havingRaw(O){let I=KX(O,"havingRaw(fragment)"),K=/\bHAVING\b/i.test(F)?"AND":"HAVING";return F+=` ${K} ${I}`,R=null,this},orderByRaw(O){let I=KX(O,"orderByRaw(fragment)");return F=o.ORDER_BY.test(F)?`${F}, ${I}`:`${F} ORDER BY ${I}`,R=null,this},union(O){return w("UNION",O),this},unionAll(O){return w("UNION ALL",O),this},intersect(O){return w("INTERSECT",O),this},intersectAll(O){return w("INTERSECT ALL",O),this},except(O){return w("EXCEPT",O),this},exceptAll(O){return w("EXCEPT ALL",O),this},forPage(O,I){let K=Math.max(1,Math.floor(O)),M=Math.max(1,Math.floor(I));return F+=` LIMIT ${M} OFFSET ${(K-1)*M}`,R=null,this},toSQL(){let O=$8(F);return{sql:O,toString:()=>O,execute:()=>D().execute(),values:()=>D().values(),raw:()=>D().raw()}},async value(O){let I=W`${D()} LIMIT 1`,K=await j(I,"select",{signal:N,timeoutMs:H}),[M]=K;return M?.[O]},async pluck(O,I){let K=await j(D(),"select",{signal:N,timeoutMs:H});if(I){let M={};for(let C of K){let T=String(C?.[I]);if(Object.prototype.hasOwnProperty.call(M,T))throw Error(`[query-builder] pluck(${O}, ${I}): duplicate key '${T}' \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[T]=C?.[O]}return M}return K.map((M)=>M?.[O])},async exists(){let O=W`SELECT EXISTS (${D()}) as e`,I=await j(O,"select",{signal:N,timeoutMs:H}),[K]=I;return Boolean(K?.e)},async doesntExist(){return!await this.exists()},async paginate(O,I=1,K={}){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(K.tx){let s=$8(F),$0=[...y],P0=await K.tx.unsafe(`SELECT COUNT(*) as c FROM (${s}) as sub`,$0),r=Number(P0?.[0]?.c??0),S0=Math.max(1,Math.ceil(r/O)),X9=Math.max(1,Math.min(I,S0)),_9=(X9-1)*O;return{data:await K.tx.unsafe(`${s} LIMIT ${O} OFFSET ${_9}`,$0),meta:{perPage:O,page:X9,total:r,lastPage:S0}}}let M=W`SELECT COUNT(*) as c FROM (${D()}) as sub`,C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C,k=Number(T?.c??0),x=Math.max(1,Math.ceil(k/O)),g=Math.max(1,Math.min(I,x)),B=(g-1)*O;return{data:await j(W`${D()} LIMIT ${O} OFFSET ${B}`,"select",{signal:N,timeoutMs:H}),meta:{perPage:O,page:g,total:k,lastPage:x}}},async simplePaginate(O,I=1){let K=Math.max(1,I),M=(K-1)*O,C=await j(W`${D()} LIMIT ${O+1} OFFSET ${M}`,"select",{signal:N,timeoutMs:H}),T=C.length>O;return{data:T?C.slice(0,O):C,meta:{perPage:O,page:K,hasMore:T}}},async cursorPaginate(O,I,K="id",M="asc"){let C=D();if(I!==void 0&&I!==null)if(Array.isArray(K)){let s=K.map((S0)=>W(String(S0))),$0=M==="asc"?W`>`:W`<`,P0=W`(${W(s)})`,r=W`(${W(I)})`;C=W`${C} WHERE ${P0} ${$0} ${r}`}else C=M==="asc"?W`${C} WHERE ${W(String(K))} > ${I}`:W`${C} WHERE ${W(String(K))} < ${I}`;if(Array.isArray(K)){let $0=K.map((P0)=>W`${W(String(P0))} ${M==="asc"?W`ASC`:W`DESC`}`).reduce((P0,r,S0)=>S0===0?r:W`${P0}, ${r}`);C=W`${C} ORDER BY ${$0} LIMIT ${O+1}`}else C=W`${C} ORDER BY ${W(String(K))} ${M==="asc"?W`ASC`:W`DESC`} LIMIT ${O+1}`;let T=await j(C,"select",{signal:N,timeoutMs:H}),k=T.length>O,x=T.slice(0,O),g=x[x.length-1],B=k&&g?Array.isArray(K)?K.map((s)=>g[s]):g[K]:null,b=x.length?Array.isArray(K)?K.map((s)=>x[0]?.[s]):x[0]?.[K]:null;return{data:x,meta:{perPage:O,nextCursor:B??null,prevCursor:b}}},async chunk(O,I){let K=1;while(!0){let{data:M,meta:C}=await this.paginate(O,K);if(M.length===0)break;if(await I(M),K>=C.lastPage)break;K+=1}},async chunkById(O,I="id",K){let M;while(!0){let{data:C,meta:T}=await this.cursorPaginate(O,M,I,"asc");if(C.length===0)break;if(K)await K(C);if(M=T.nextCursor,!M)break}},async eachById(O,I="id",K){await this.chunkById(O,I,async(M)=>{for(let C of M)await K?.(C)})},withTimeout(O){return H=Math.max(1,Math.floor(O)),this},abort(O){return N=O,this},withTrashed(){return S=!0,h=!1,this},onlyTrashed(){S=!0,h=!0;let O=f.softDeletes?.column||"deleted_at",I=(C,T)=>{let k=C.toUpperCase(),x=0;for(let g=0;g<C.length;g++){let B=C[g];if(B==="(")x++;else if(B===")")x--;else if(x===0&&k.substring(g,g+5)==="WHERE"&&(g===0||/\s/.test(C[g-1]??""))&&/\s/.test(C[g+5]??""))return`${C.substring(0,g)}WHERE ${T} AND ${C.substring(g+6)}`}return`${C} WHERE ${T}`},K=`${G}.${O} IS NOT NULL`;F=I(F,K);let M=String(D());return R=W([I(M,K)]),this},scope(O,I){let K=String(G),C=Z?.scopes?.[K]?.[O];if(C)return C(this,I);return this},when(O,I,K){if(O)return I(this);if(K)return K(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 a=O,d=!0,this},async explain(){let O=W`EXPLAIN ${D()}`;return await j(O,"select",{signal:N,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||nX(O));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!I){let T=$._prepareStatement;if(T){let k=T(F);return X0(y.length>0?k.all(...y):k.all())}}if(R=y.length>0?$.unsafe(F,y):$.unsafe(F),!f.softDeletes?.enabled&&!d&&!H&&!N&&!I){let T=D()._stmt,k=D()._params;if(T)return X0(k&&k.length>0?T.all(...k):T.all());return X0(await D().execute())}if(!f.softDeletes?.enabled&&!d&&!H&&!N)return X0(await j(D(),"select"));let K=D();if(f.softDeletes?.enabled&&f.softDeletes.defaultFilter&&!S){let T=f.softDeletes.column,k=String(G);if((Y?Boolean(Y[k]?.columns?.[T]):!0)&&!o.DELETED_AT.test(F))K=W`${D()} WHERE ${W(String(T))} IS ${h?W`NOT NULL`:W`NULL`}`,q("WHERE",`${String(T)} IS ${h?"NOT ":""}NULL`)}let M=d?`${String(K)}\x00${JSON.stringify(y)}`:"";if(d){let T=A$.get(M);if(T)return T}let C=await j(K,"select",{signal:N,timeoutMs:H});if(d)A$.set(M,C,a);return X0(C)},async executeTakeFirst(){let O=await j(D(),"select",{signal:N,timeoutMs:H});return m(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||nX(O));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!I){let C=$._prepareStatement;if(C){let T=F.includes(" LIMIT ")?F:`${F} LIMIT 1`,k=C(T),x=y.length>0?k.all(...y):k.all();return m(x[0])}}let K=await j(W`${D()} LIMIT 1`,"select",{signal:N,timeoutMs:H}),[M]=K;return m(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",K=await j(W`${D()} WHERE ${W(I)} = ${O} LIMIT 1`,"select",{signal:N,timeoutMs:H}),[M]=K;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:N,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),K;if(I)K=`SELECT COUNT(*) as c FROM (${F}) AS _bqb_count_sub`;else if(O!==-1)K=`SELECT COUNT(*) as c${F.substring(O)}`;else K=`SELECT COUNT(*) as c FROM ${G}`;let M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||nX(M));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!C){let g=$._prepareStatement;if(g){let B=g(K),b=y.length>0?B.all(...y):B.all();return Number(b[0]?.c??0)}}let T=y.length>0?$.unsafe(K,y):$.unsafe(K),k=await j(T,"select",{signal:N,timeoutMs:H}),[x]=k;return Number(x?.c??0)},async avg(O){let I=F.indexOf(" FROM "),K=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||nX(M));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!C){let g=$._prepareStatement;if(g){let B=g(K),b=y.length>0?B.all(...y):B.all();return Number(b[0]?.a??0)}}let T=y.length>0?$.unsafe(K,y):$.unsafe(K),k=await j(T,"select",{signal:N,timeoutMs:H}),[x]=k;return Number(x?.a??0)},async sum(O){let I=F.indexOf(" FROM "),K=I!==-1?`SELECT SUM(${O}) as s${F.substring(I)}`:`SELECT SUM(${O}) as s FROM ${G}`,M=y.length>0?$.unsafe(K,y):$.unsafe(K),C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C;return Number(T?.s??0)},async max(O){let I=F.indexOf(" FROM "),K=I!==-1?`SELECT MAX(${O}) as m${F.substring(I)}`:`SELECT MAX(${O}) as m FROM ${G}`,M=y.length>0?$.unsafe(K,y):$.unsafe(K),C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C;return T?.m},async min(O){let I=F.indexOf(" FROM "),K=I!==-1?`SELECT MIN(${O}) as m${F.substring(I)}`:`SELECT MIN(${O}) as m FROM ${G}`,M=y.length>0?$.unsafe(K,y):$.unsafe(K),C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C;return T?.m},lockForUpdate(){return F+=" FOR UPDATE",R=null,this},sharedLock(){let O=f.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return F+=` ${O}`,R=null,this},withCTE(O,I){return p(O,"withCTE(name)"),F=`WITH ${O} AS (${String(I.toSQL())}) ${F}`,R=null,this},withRecursive(O,I){return p(O,"withRecursive(name)"),F=`WITH RECURSIVE ${O} AS (${String(I.toSQL())}) ${F}`,R=null,this},execute(){return j(D(),"select",{signal:N,timeoutMs:H})},values(){return D().values()},toParams(){return[...y]},__rawState(){return{sql:$8(F),params:[...y]}},raw(){return D().raw()},get rows(){return},get row(){return},cancel(){try{D().cancel()}catch{}}},{get(O,I,K){let M=Reflect.get(O,I,K);if(M!==void 0)return M;if(typeof I==="string"&&(I.startsWith("where")||I.startsWith("orWhere")||I.startsWith("andWhere"))){let C=I.startsWith("orWhere"),T=I.startsWith("andWhere"),k=`${String(G)}|${I}`,x=U.get(k);if(x===void 0){let B=I.replace(/^(?:or|and)?where/i,"");if(!B)U.set(k,""),x="";else{let b=B.charAt(0).toLowerCase()+B.slice(1),s=B.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),$0=Y?Object.keys(Y[String(G)]?.columns??{}):[];x=[s,b,b.toLowerCase()].find((P0)=>$0.includes(P0))??s,U.set(k,x)}}if(x==="")return()=>K;let g=x;return(B)=>{let b=Array.isArray(B)?W`${W(g)} IN ${W(B)}`:W`${W(g)} = ${B}`;if(R=C?W`${D()} OR ${b}`:T?W`${D()} AND ${b}`:W`${D()} WHERE ${b}`,Array.isArray(B)){let s=b0(B.length,y.length+1);q(C?"OR":T?"AND":"WHERE",`${g} IN (${s})`),y.push(...B)}else{let s=l(y.length+1);q(C?"OR":T?"AND":"WHERE",`${g} = ${s}`),y.push(B)}return K}}return Reflect.get(O,I,K)}})}return{configure(G){return Object.assign(f,G),this},id(G){if(!o.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(!o.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.")}}p(String(J),"selectFromSub(alias)");let F=typeof G.__rawState==="function"?G.__rawState():null,R=G.toSQL(),D=F?.sql??(typeof R==="string"?R:R?.sql??String(R)),q=F?.params??(Array.isArray(R?.values)?R.values:[]),w=`SELECT * FROM (${D}) AS ${String(J)}`,A=(H,N,S,h,d,v,n)=>{let a=!S?"WHERE":n==="WHERE"?"AND":n,u=[...N],i=(X0,R0,z0)=>{p(X0,"selectFromSub where(column)");let y=f0(R0,"selectFromSub where(operator)");if(y==="in"||y==="not in"){let G0=Array.isArray(z0)?z0:[z0],_X=b0(G0.length,u.length+1);return u.push(...G0),`${X0} ${y.toUpperCase()} (${_X})`}let J9=l(u.length+1);return u.push(z0),`${X0} ${y} ${J9}`},m;if(typeof h==="string"&&d!==void 0)m=i(h,d,v);else if(Array.isArray(h)&&h.length===3)m=i(h[0],h[1],h[2]);else if(h&&typeof h==="object")m=Object.entries(h).map(([X0,R0])=>i(X0,"=",R0)).join(" AND ");else return{text:H,params:N};return{text:`${H} ${a} ${m}`,params:u}};function P(H,N,S=!1){let h=()=>N.length>0?$.unsafe(H,N):$.unsafe(H),d={distinct(){return P(H.replace(/^SELECT\s+/i,"SELECT DISTINCT "),N,S)},distinctOn(...v){let n=v.map(String).join(", ");return P(H.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${n}) `),N,S)},selectRaw(v){let n=KX(v,"selectFromSub.selectRaw(fragment)"),a=H.indexOf(" FROM "),u=a!==-1?`${H.slice(0,a)}, ${n}${H.slice(a)}`:`${H}, ${n}`;return P(u,N,S)},where(v,n,a){let u=A(H,N,S,v,n,a,"WHERE");return P(u.text,u.params,!0)},andWhere(v,n,a){let u=A(H,N,S,v,n,a,"AND");return P(u.text,u.params,!0)},orWhere(v,n,a){let u=A(H,N,S,v,n,a,"OR");return P(u.text,u.params,!0)},orderBy(v,n="asc"){p(String(v),"selectFromSub.orderBy(column)");let a=n==="asc"?"ASC":"DESC",u=o.ORDER_BY.test(H)?`${H}, ${v} ${a}`:`${H} ORDER BY ${v} ${a}`;return P(u,N,S)},limit(v){if(!Number.isInteger(v)||v<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${v}`);let n=o.LIMIT.test(H)?H.replace(o.LIMIT,` LIMIT ${v}`):`${H} LIMIT ${v}`;return P(n,N,S)},offset(v){if(!Number.isInteger(v)||v<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${v}`);let n=o.OFFSET.test(H)?H.replace(o.OFFSET,` OFFSET ${v}`):`${H} OFFSET ${v}`;return P(n,N,S)},toSQL(){return E(h(),H)},async execute(){return j(h(),"select")},async executeTakeFirst(){let v=await j(h(),"select");return Array.isArray(v)?v[0]:v},async executeTakeFirstOrThrow(){let v=await j(h(),"select"),n=Array.isArray(v)?v[0]:v;if(!n)throw Error("Record not found");return n},async get(){return j(h(),"select")},async first(){let v=await j(h(),"select");return Array.isArray(v)?v[0]:v},async firstOrFail(){let v=await j(h(),"select"),n=Array.isArray(v)?v[0]:v;if(!n)throw Error("No rows found");return n},async count(){let v=N.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,N):$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),n=await j(v,"select");return Number(n?.[0]?.c??0)},async exists(){let v=N.length>0?$.unsafe(`SELECT EXISTS(${H}) as e`,N):$.unsafe(`SELECT EXISTS(${H}) as e`),n=await j(v,"select");return Boolean(n?.[0]?.e)},async doesntExist(){return!await d.exists()},values(){return h().values()},raw(){return h().raw()},cancel(){try{h().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:(v)=>v(d),when:W("when"),tap:()=>d,dump:()=>d,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>h().simple(),toText:()=>H,toParams:()=>[...N],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 P(w,q)},insertInto(G){let J,W="",F=[],R=f.dialect==="postgres",D=R?(w)=>`"${String(w).replace(/"/g,'""')}"`:I0(f.dialect)?(w)=>`\`${String(w).replace(/`/g,"``")}\``:(w)=>`"${String(w).replace(/"/g,'""')}"`,q=R?(w)=>`$${w+1}`:(w)=>"?";return{values(w){let A=Array.isArray(w)?w:[w],P=A.length;if(P===0)return J=$.unsafe("SELECT 1"),this;let H=A[0],N=Object.keys(H),S=N.length,h=P*S;if(F.length=h,P===1)if(!R){let d=D(N[0]),v="?";F[0]=H[N[0]];for(let n=1;n<S;n++)d+=`,${D(N[n])}`,v+=",?",F[n]=H[N[n]];W=`INSERT INTO ${D(G)}(${d})VALUES(${v})`}else{let d=N.map((v)=>D(v)).join(",");W=`INSERT INTO ${D(G)}(${d})VALUES(`;for(let v=0;v<S;v++){if(v>0)W+=",";W+=q(v),F[v]=H[N[v]]}W+=")"}else{let d=N.map((n)=>D(n)).join(",");W=`INSERT INTO ${D(G)}(${d})VALUES`;let v=0;for(let n=0;n<P;n++){let a=A[n];if(n===0)W+="(";else W+="),(";for(let u=0;u<S;u++){if(u>0)W+=",";W+=q(v),F[v++]=a[N[u]]}}W+=")"}if(!$._prepareStatement)J=$.unsafe(W,F);return this},returning(...w){let A=`${W} RETURNING ${w.join(", ")}`,P=$.unsafe(A,F),H=async()=>{let N=await j(P,"insert");return Array.isArray(N)?N[0]:N};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>E(P,A),execute:()=>j(P,"insert"),get:()=>j(P,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let N=await H();if(!N)throw Error("Insert with RETURNING returned no rows");return N},async executeTakeFirstOrThrow(){let N=await H();if(!N)throw Error("Insert with RETURNING returned no rows");return N}}},toSQL(){if(!J)J=$.unsafe(W,F);return E(J,W)},execute(){let w=f.hooks;if(!(w&&(w.onQueryStart||w.onQueryEnd||w.onQueryError||w.startSpan||w.beforeCreate||w.afterCreate||nX(w)))){let P=$._prepareStatement;if(P){let H=P(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 w=await j(J,"insert");if(!w)throw Error("Insert failed");return w},returningAll(){let w=`${W} RETURNING *`,A=$.unsafe(w,F),P=async()=>{let H=await j(A,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>E(A,w),execute:()=>j(A,"insert"),get:()=>j(A,"insert"),first:P,executeTakeFirst:P,async firstOrFail(){let H=await P();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await P();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(G){let J,W=[],F=(D)=>{let q=String(D);if(I0(f.dialect))return`\`${q.replace(/`/g,"``")}\``;return`"${q.replace(/"/g,'""')}"`},R=`UPDATE ${F(String(G))}`;return{set(D){let q=Object.keys(D),w=q.length,A=Array.from({length:w});for(let P=0;P<w;P++){let H=q[P];A[P]=`${F(H)} = ${l(P+1)}`,W.push(D[H])}return R=`${R} SET ${A.join(", ")}`,J=$.unsafe(R,W),this},where(D,q,w){let A=()=>o.WHERE.test(R)?"AND":"WHERE";if(typeof D==="string"&&q!==void 0){let P=W.length+1;return R=`${R} ${A()} ${F(D)} ${q} ${l(P)}`,W.push(w),J=$.unsafe(R,W),this}if(Array.isArray(D)){let[P,H,N]=D,S=W.length+1;return R=`${R} ${A()} ${F(String(P))} ${String(H)} ${l(S)}`,W.push(N),J=$.unsafe(R,W),this}if(D&&typeof D==="object"&&!("raw"in D)){let P=Object.keys(D),H=P.length,N=W.length,S=Array.from({length:H});for(let h=0;h<H;h++)S[h]=`${F(P[h])} = ${l(N+h+1)}`,W.push(D[P[h]]);R=`${R} ${A()} ${S.join(" AND ")}`,J=$.unsafe(R,W)}return this},returning(...D){let q=`${R} RETURNING ${D.join(", ")}`,w=W.length>0?$.unsafe(q,W):$.unsafe(q),A=async()=>{let H=await j(w,"update");return Array.isArray(H)?H[0]:H},P={where:()=>P,andWhere:()=>P,orWhere:()=>P,orderBy:()=>P,limit:()=>P,offset:()=>P,toSQL:()=>E(w,q),execute:()=>j(w,"update"),get:()=>j(w,"update"),first:A,executeTakeFirst:A,async firstOrFail(){let H=await A();if(!H)throw Error("Update with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await A();if(!H)throw Error("Update with RETURNING returned no rows");return H}};return P},toSQL(){if(!J)J=W.length>0?$.unsafe(R,W):$.unsafe(R);return E(J,R)},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=`${R} RETURNING *`,q=W.length>0?$.unsafe(D,W):$.unsafe(D);return{toSQL:()=>E(q,D),execute:()=>j(q,"update"),async executeTakeFirst(){let w=await j(q,"update");return Array.isArray(w)?w[0]:w},async executeTakeFirstOrThrow(){let w=await j(q,"update"),A=Array.isArray(w)?w[0]:w;if(!A)throw Error("Update with RETURNING failed");return A}}}}},deleteFrom(G){let J=(P)=>{let H=String(P);if(I0(f.dialect))return`\`${H.replace(/`/g,"``")}\``;return`"${H.replace(/"/g,'""')}"`},F=`DELETE FROM ${J(String(G))}`,R=null,D=[],q=null,w=()=>o.WHERE.test(F)?"AND":"WHERE",A=()=>{if(R===null)R=D.length>0?$.unsafe(F,D):$.unsafe(F);return R};return{where(P,H,N){if(q=P,typeof P==="string"&&H!==void 0){let S=D.length+1;return F+=` ${w()} ${J(P)} ${H} ${l(S)}`,D.push(N),R=null,this}if(Array.isArray(P)){let[S,h,d]=P,v=D.length+1;return F+=` ${w()} ${J(String(S))} ${h} ${l(v)}`,D.push(d),R=null,this}if(P&&typeof P==="object"&&!("raw"in P)){let S=Object.keys(P),h=[];for(let d of S){let v=D.length+1;h.push(`${J(d)} = ${l(v)}`),D.push(P[d])}return F+=` ${w()} ${h.join(" AND ")}`,R=null,this}return R=Q({},A(),P),this},returning(...P){let H=`${F} RETURNING ${P.join(", ")}`,N=D.length>0?$.unsafe(H,D):$.unsafe(H),S=async()=>{let d=await j(N,"delete");return Array.isArray(d)?d[0]:d},h={where:()=>h,andWhere:()=>h,orWhere:()=>h,orderBy:()=>h,limit:()=>h,offset:()=>h,toSQL:()=>E(N,H),execute:()=>j(N,"delete"),get:()=>j(N,"delete"),first:S,executeTakeFirst:S,async firstOrFail(){let d=await S();if(!d)throw Error("Delete with RETURNING returned no rows");return d},async executeTakeFirstOrThrow(){let d=await S();if(!d)throw Error("Delete with RETURNING returned no rows");return d}};return h},toSQL(){return E(A(),F)},async execute(){try{await f.hooks?.beforeDelete?.({table:String(G),where:q})}catch(H){throw H}let P=await j(A(),"delete");try{await f.hooks?.afterDelete?.({table:String(G),where:q,result:P})}catch{}return P},async executeTakeFirst(){return{numDeletedRows:await j(A(),"delete")}},async executeTakeFirstOrThrow(){let P=await j(A(),"delete");if(P===0)throw Error("No rows deleted");return{numDeletedRows:P}},returningAll(){let P=`${F} RETURNING *`,H=D.length>0?$.unsafe(P,D):$.unsafe(P);return{toSQL:()=>E(H,P),execute:()=>j(H,"delete"),async executeTakeFirst(){let N=await j(H,"delete");return Array.isArray(N)?N[0]:N},async executeTakeFirstOrThrow(){let N=await j(H,"delete"),S=Array.isArray(N)?N[0]:N;if(!S)throw Error("Delete with RETURNING failed");return S}}}}},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),R=c`SELECT pg_advisory_lock(${F})`;await j(R,"raw");return}if(I0(f.dialect)){let J=`bqb:${String(G)}`,W=c`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 q=0;q<J.length;q++)W=W*31+J.charCodeAt(q)|0;let F=typeof G==="number"?G:Math.abs(W),R=c`SELECT pg_try_advisory_lock(${F}) as ok`,D=await j(R,"raw");return Boolean(D?.[0]?.ok)}if(I0(f.dialect)){let J=`bqb:${String(G)}`,W=c`SELECT GET_LOCK(${J}, 0) AS ok`,F=await j(W,"raw");return Number(F?.[0]?.ok)===1}return!1},unsafe(G,J){return $.unsafe(G,J)},file(G,J){return c.file(G,J)},async reserve(){let G=await c.reserve(),J=H0({sql:G,meta:Z,schema:Y});return J.release=()=>G.release(),J},async close(G){await c.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=c`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((R)=>setTimeout(R,W))}throw Error("Database not ready after waiting")},async transaction(G,J){let F={...X?.txDefaults,...J},R=X?.sql??c,D=X?.inTransaction===!0,q=D&&typeof R?.savepoint==="function"?"savepoint":"begin",w=async(H)=>{F.logger?.({type:"start",attempt:H});let N=Date.now();return await R[q](async(S)=>{let h=H0({sql:S,meta:Z,schema:Y,inTransaction:!0});if(F?.isolation&&!D){let n=F.isolation,a=n==="read committed"?"READ COMMITTED":n==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(f.dialect==="postgres")await S.unsafe(`SET TRANSACTION ISOLATION LEVEL ${a}`);else if(I0(f.dialect))await S.unsafe(`SET TRANSACTION ISOLATION LEVEL ${a}`);else if(n!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${n}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(F?.readOnly)if(f.dialect==="postgres")await S.unsafe("SET TRANSACTION READ ONLY");else if(I0(f.dialect))await S.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(h),v=Date.now()-N;return F.logger?.({type:"commit",attempt:H,durationMs:v}),d})},A=Math.max(0,F?.retries??0),P=0;for(;;)try{let H=await w(P+1);return F?.afterCommit?.(),H}catch(H){let N=d_(H)||p_(H,F.sqlStates);if(P<A&&N){P++,F?.onRetry?.(P,H);let S=u_(P,F.backoff);if(S>0)await c_(S);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=H0({sql:W,meta:Z,schema:Y});return await G(F)})},async beginDistributed(G,J){return await(X?.sql??c).beginDistributed(G,async(R)=>{let D=H0({sql:R,meta:Z,schema:Y});return await J(D)})},async commitDistributed(G){await c.commitDistributed(G)},async rollbackDistributed(G){await c.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:R,params:D}=X8(W),q=t0(String(G)),w=I0(f.dialect)?`INSERT IGNORE INTO ${q} (${F}) VALUES ${R}`:`INSERT INTO ${q} (${F}) VALUES ${R} ON CONFLICT DO NOTHING`;return c.unsafe(w,D).execute()},async insertGetId(G,J,W="id"){let{colsSql:F,valuesSql:R,params:D}=X8([J]),q=t0(String(G));if(I0(f.dialect)){await c.unsafe(`INSERT INTO ${q} (${F}) VALUES ${R}`,D).execute();let[A]=await c.unsafe("SELECT LAST_INSERT_ID() as id").execute();return A?.id}if(f.dialect==="sqlite"){let A=await c.unsafe(`INSERT INTO ${q} (${F}) VALUES ${R}`,D).execute();if(A?.lastInsertRowid!=null)return A.lastInsertRowid;let[P]=await c.unsafe("SELECT last_insert_rowid() as id").execute();return P?.id}let[w]=await c.unsafe(`INSERT INTO ${q} (${F}) VALUES ${R} RETURNING ${t0(String(W))} as id`,D).execute();return w?.id},async updateOrInsert(G,J,W){let F=t0(String(G)),R=Object.keys(J),D=1,q=R.map((S)=>`${t0(S)} = ${l(D++)}`).join(" AND "),w=R.map((S)=>J[S]);if((await c.unsafe(`SELECT 1 FROM ${F} WHERE ${q} LIMIT 1`,w).execute()).length){let S=Object.keys(W),h=1,d=S.map((a)=>`${t0(a)} = ${l(h++)}`).join(", "),v=R.map((a)=>`${t0(a)} = ${l(h++)}`).join(" AND "),n=[...S.map((a)=>W[a]),...R.map((a)=>J[a])];return await c.unsafe(`UPDATE ${F} SET ${d} WHERE ${v}`,n).execute(),!0}let{colsSql:P,valuesSql:H,params:N}=X8([{...J,...W}]);return await c.unsafe(`INSERT INTO ${F} (${P}) VALUES ${H}`,N).execute(),!0},async upsert(G,J,W,F){let R=W.map((d)=>String(d)),D=(F??[]).map((d)=>String(d)),q=J;if(!q.length)return;let{colsSql:w,valuesSql:A,params:P}=X8(q),H=t0(String(G)),N=`INSERT INTO ${H} (${w}) VALUES ${A}`;if(I0(f.dialect)){if(D.length===0)return c.unsafe(`INSERT IGNORE INTO ${H} (${w}) VALUES ${A}`,P).execute();let d=D.map((v)=>`${t0(v)} = VALUES(${t0(v)})`).join(", ");return c.unsafe(`${N} ON DUPLICATE KEY UPDATE ${d}`,P).execute()}let S=R.map(t0).join(", ");if(D.length===0)return c.unsafe(`${N} ON CONFLICT (${S}) DO NOTHING`,P).execute();let h=D.map((d)=>`${t0(d)} = EXCLUDED.${t0(d)}`).join(", ");return c.unsafe(`${N} ON CONFLICT (${S}) DO UPDATE SET ${h}`,P).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 c.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=c`INSERT INTO ${c(String(G))} ${c(J)} RETURNING ${c(String(W))} as id`,[R]=await F.execute();if(console.log("resultId",R),!R?.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(R.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${R.id}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${R.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 R=await this.selectFrom(G).find(F);if(!R)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:R})}catch{}return R}},async createMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),R=F.length,D=J.length,q=Array.from({length:D*R}),w=I0(f.dialect)?(H)=>`\`${String(H).replace(/`/g,"``")}\``:(H)=>`"${String(H).replace(/"/g,'""')}"`,A=`INSERT INTO ${w(String(G))}(${F.map(w).join(",")})VALUES`,P=0;for(let H=0;H<D;H++){if(H>0)A+=",";A+="(";let N=J[H];for(let S=0;S<R;S++){if(S>0)A+=",";A+=l(P+1),q[P++]=N[F[S]]}A+=")"}return $.unsafe(A,q).execute()},async insertMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),R=F.length,D=J.length,q=D*R,w=Array(q),A=f.dialect==="postgres",P;if(!A){let S=Array(R);for(let h=0;h<R;h++)S[h]="?";P=`(${S.join(",")})`}else P="";let H=Array(D+2);H[0]=`INSERT INTO ${G}(${F.join(",")})VALUES`;let N=0;if(!A){for(let S=0;S<D;S++){let h=J[S];H[S+1]=P;for(let d=0;d<R;d++)w[N++]=h[F[d]]}return $.unsafe(H[0]+H.slice(1,D+1).join(","),w).execute()}for(let S=0;S<D;S++){let h=J[S],d=Array(R);for(let v=0;v<R;v++)d[v]=`$${N+1}`,w[N++]=h[F[v]];H[S+1]=`(${d.join(",")})`}return $.unsafe(H[0]+H.slice(1,D+1).join(","),w).execute()},async updateMany(G,J,W){let F=Object.keys(W),R=F.length;if(R===0)return 0;let D=[],q=Array.from({length:R});for(let A=0;A<R;A++)q[A]=`${F[A]}=${l(A+1)}`,D.push(W[F[A]]);let w=`UPDATE ${G} SET ${q.join(",")}`;if(Array.isArray(J))w+=` WHERE ${J[0]}${J[1]}${l(D.length+1)}`,D.push(J[2]);else if(J&&typeof J==="object"&&!("raw"in J)){let A=Object.keys(J),P=A.length;if(P>0){let H=D.length,N=Array.from({length:P});for(let S=0;S<P;S++)N[S]=`${A[S]}=${l(H+S+1)}`,D.push(J[A[S]]);w+=` WHERE ${N.join(" AND ")}`}}return $.unsafe(w,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 q=0;q<F;q++)D[q]=`$${q+1}`;return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${D.join(",")})`,J).execute()}let R=Array(F);for(let D=0;D<F;D++)R[D]="?";return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${R.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 R=Z?.primaryKeys[String(G)]??"id",D=F[R],q=D!=null?await this.selectFrom(G).find(D):await this.selectFrom(G).where(J).first();if(!q)throw Error("updateOrCreate() failed to retrieve updated row");return q}return await this.create(G,{...J,...W})},async count(G,J){let W=J?c(String(J)):c`*`,F=c`SELECT COUNT(${W}) as c FROM ${c(String(G))}`,[R]=await F.execute();return Number(R?.c??0)},async sum(G,J){let W=c`SELECT SUM(${c(String(J))}) as s FROM ${c(String(G))}`,[F]=await W.execute();return Number(F?.s??0)},async avg(G,J){let W=c`SELECT AVG(${c(String(J))}) as a FROM ${c(String(G))}`,[F]=await W.execute();return Number(F?.a??0)},async min(G,J){let W=c`SELECT MIN(${c(String(J))}) as m FROM ${c(String(G))}`,[F]=await W.execute();return F?.m},async max(G,J){let W=c`SELECT MAX(${c(String(J))}) as m FROM ${c(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,R]of Object.entries(J))if(R&&typeof R==="object"&&Object.keys(R).length>0)W[F]=R;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,R]of Object.entries(W))if(R&&typeof R==="object"&&J in R)return F;return null},getRelationshipTarget(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,R]of Object.entries(W))if(R&&typeof R==="object"&&J in R){let D=R[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 n_(){A$.clear()}function i_(X){A$.setMaxSize(X)}var o,q1,P1,A$,rX,l_=500,_Z=e(()=>{c0(),$X(),o={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},q1=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]),P1=new Set,A$=new QU,rX=new Map});async function wG(){console.log("-- Clearing query cache..."),n_(),console.log("-- \u2713 Query cache cleared")}async function qG(){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 PG(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");i_($),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 s_=e(()=>{_Z()});async function r_(){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=H0(),$=o_({input:Z8.stdin,output:Z8.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 c.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 v_=e(()=>{$X(),v0()});function b_(X){return X.endsWith("s")?X.slice(0,-1):X}function TX(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 q=U($),w=U(E);V=[q,w].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 q=Y.models[G],w=q?.definition??q?.getDefinition?.()??q,A=w?.attributes??{};for(let[P,H]of Object.entries(A)){if(P===J||P===W||P===(w?.primaryKey??"id"))continue;F[P]={default:H?.default,nullable:H?.nullable,validation:H?.validation}}}let R=Boolean(z?.pivot?.timestamps),D=Object.keys(F);return{pivotTable:V,fkParent:J,fkRelated:W,pivotColumns:D,pivotColumnDefs:F,pivotModelName:G,timestamps:R,relatedModelName:j,relatedTable:E,hasConfig:L}}function*HG(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=TX(X,Y,Q,$);if(L)yield{parentTable:Y,relationKey:Q,resolved:L}}}}function p8(X){return typeof X==="object"&&X!==null&&"raw"in X&&typeof X.raw==="string"}function CG(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 t0(X){return I0(f.dialect)?`\`${X.replace(/`/g,"``")}\``:`"${X.replace(/"/g,'""')}"`}function X8(X,$=1){let Z=Object.keys(X[0]??{}),Y=[],U=$,_=X.map((Q)=>{return`(${Z.map((z)=>{return Y.push(Q[z]),l(U++)}).join(", ")})`});return{colsSql:Z.map(t0).join(", "),valuesSql:_.join(", "),params:Y,nextIndex:U}}function nX(X){return Boolean(X&&(X.onSlowQuery||X.slowQueryThresholdMs!=null&&X.slowQueryThresholdMs>=0))}function SY(X){if(typeof X==="string")return X;if(p8(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 p(X,$){if(!o.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 f0(X,$){if(typeof X!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof X}`);let Z=X.toLowerCase();if(!q1.has(Z))throw TypeError(`[query-builder] ${$}: refusing to use '${X}' as a SQL operator \u2014 not in the allowed set (${[...q1].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 f_($),X;if(X===null||X===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${X}`);if(p8(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 f_(X){if(P1.has(X))return;P1.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 g_(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 zU{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 d_(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 p_(X,$){if(!$||$.length===0)return!1;let Z=X&&(X.code||X.sqlState||X.sqlstate);if(!Z)return!1;return $.includes(Z)}function c_(X){return new Promise(($)=>setTimeout($,X))}function $8(X){let $=rX.get(X);if($!==void 0)return $;let Z=m_(X);if(rX.size>=l_)rX.clear();return rX.set(X,Z),Z}function m_(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 R=J.match(F);if(!R)continue;Z.push({key:W,start:E}),E+=R[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 u_(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 H0(X){let $=X?.sql??hX(),Z=X?.meta,Y=X?.schema,U=new Map;function _(G){if(Array.isArray(G)){let[D,q,w]=G;p(D,"where(column)");let A=String(D);switch(q){case"in":if(Array.isArray(w)){let P=b0(w.length);return $.unsafe(`${A} IN (${P})`,w)}return $.unsafe(`${A} IN (${l(1)})`,[w]);case"not in":if(Array.isArray(w)){let P=b0(w.length);return $.unsafe(`${A} NOT IN (${P})`,w)}return $.unsafe(`${A} NOT IN (${l(1)})`,[w]);case"like":return $.unsafe(`${A} LIKE ${l(1)}`,[w]);case"is":case"is not":{if(w!==null&&w!==void 0)throw TypeError(`[query-builder] where(..., '${q}', ?): operator '${q}' only accepts NULL/undefined as value, got ${typeof w} (${String(w)})`);return $.unsafe(`${A} IS ${q==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${A} <> ${l(1)}`,[w]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${A} ${q} ${l(1)}`,[w]);default:throw TypeError(`[query-builder] where(..., '${String(q)}', ?): 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=[],R=1;for(let D of J){p(D,"where(object key)");let q=G[D];if(Array.isArray(q)){let w=b0(q.length,R);W.push(`${D} IN (${w})`),F.push(...q),R+=q.length}else W.push(`${D} = ${l(R++)}`),F.push(q)}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,R=F?.slowQueryThresholdMs,D=R!=null&&R>=0,q=Boolean(F?.onSlowQuery||D),w=F&&(F.onQueryStart||F.onQueryEnd||F.onQueryError||F.startSpan||q),A=W?.timeoutMs&&W.timeoutMs>0||W?.signal;if(!w&&!A)return G.execute();let P=L(G),H=z(G),N=Date.now(),S;try{if(F?.onQueryStart?.({sql:P,params:H,kind:J}),F?.startSpan)S=F.startSpan({sql:P,params:H,kind:J})}catch{}let h=!1,d=(u,i)=>{if(h)return;h=!0;let m=Date.now()-N;try{if(u)F?.onQueryError?.({sql:P,params:H,error:u,durationMs:m,kind:J});else if(F?.onQueryEnd?.({sql:P,params:H,durationMs:m,rowCount:i,kind:J}),D&&m>=R)if(F?.onSlowQuery)F.onSlowQuery({sql:P,params:H,durationMs:m,kind:J});else console.warn(`[query-builder] slow query (${m}ms >= ${R}ms): ${P}`)}catch{}try{S?.end(u)}catch{}},v=G.execute(),n=[v],a;if(W?.timeoutMs&&W.timeoutMs>0){let u=new Promise((i,m)=>{a=setTimeout(()=>{try{G.cancel?.()}catch{}let X0=Error(`Query timed out after ${W.timeoutMs}ms`);X0.code="EBQBTIMEOUT",m(X0)},W.timeoutMs)});n.push(u)}if(W?.signal){if(W.signal.aborted){try{G.cancel?.()}catch{}let i=Error("Query aborted");return i.code="EBQBABORT",d(i),Promise.reject(i)}let u=()=>{try{G.cancel?.()}catch{}};W.signal.addEventListener("abort",u,{once:!0}),v.finally(()=>{W.signal?.removeEventListener("abort",u)})}return Promise.race(n).then((u)=>{clearTimeout(a);let i=Array.isArray(u)?u.length:typeof u==="number"?u:void 0;return d(void 0,i),u}).catch((u)=>{throw clearTimeout(a),d(u),u})}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)}`,R=null,D=()=>{if(R===null){let O=$8(F);R=y.length>0?$.unsafe(O,y):$.unsafe(O)}return R},q=(O,I)=>{let M=!o.WHERE.test(F)?"WHERE":O==="WHERE"?"AND":O;F=`${F} ${M} ${I}`},w=(O,I)=>{let K=I.__rawState?.();if(K){let M=y.length,C=f.dialect==="postgres"?K.sql.replace(/\$(\d+)/g,(T,k)=>`$${Number(k)+M}`):K.sql;F+=` ${O} ${C}`,y.push(...K.params)}else F+=` ${O} ${String(I.toSQL())}`;R=null},A=(O)=>{let I=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,K=0,M=-1,C;while(C=I.exec(F))if(C[0]==="(")K++;else if(C[0]===")")K=Math.max(0,K-1);else if(K===0){M=C.index;break}F=M>=0?`${F.slice(0,M)}${O} ${F.slice(M)}`:`${F} ${O}`,R=null},P=new Set,H,N,S=!1,h=!1,d=!1,v=new Map,n=new Set,a=60000,u=(O)=>{if(f.relations.singularizeStrategy==="none")return O;return O.endsWith("s")?O.slice(0,-1):O},i=(O)=>{if(!Z)return null;return TX(Z,String(G),O,{singularize:u,models:Z.models})},m=(O)=>{if(!O||typeof O!=="object"||n.size===0)return O;let I;for(let K of Object.keys(O))if(K.startsWith("pivot_")){if(!I)I={};I[K.slice(6)]=O[K],delete O[K]}if(I)O.pivot=I;return O},X0=(O)=>{if(n.size===0||!O)return O;if(Array.isArray(O))for(let I=0;I<O.length;I++)m(O[I]);else m(O);return O},R0=(O)=>{if(!Z)return;if(P.has(O.pivotTable))return;let I=String(G),K=Z.primaryKeys[I]??"id";p(O.pivotTable,"wherePivot auto-join (pivot table)"),p(O.fkParent,"wherePivot auto-join (parent FK)"),p(I,"wherePivot auto-join (parent table)"),p(K,"wherePivot auto-join (parent PK)"),R=W`${D()} LEFT JOIN ${W(O.pivotTable)} ON ${W(`${O.pivotTable}.${O.fkParent}`)} = ${W(`${I}.${K}`)}`,F=`${F} LEFT JOIN ${O.pivotTable} ON ${O.pivotTable}.${O.fkParent} = ${I}.${K}`,P.add(O.pivotTable)},z0=[],y=[],J9=(O)=>{if(o.SELECT_STAR.test(F))F=F.replace(o.SELECT_STAR,`SELECT *, ${O}`);else if(o.SELECT.test(F))F=F.replace(o.SELECT_FROM,`SELECT $1, ${O} FROM`);let I=String(D());if(o.SELECT_STAR.test(I)){let K=I.replace(o.SELECT_STAR,`SELECT *, ${O}`);R=$.unsafe(K)}else if(o.SELECT.test(I)){if(o.SELECT_FROM.exec(I)){let M=I.replace(o.SELECT_FROM,`SELECT $1, ${O} FROM`);R=$.unsafe(M)}}},G0=(O,I,K,M)=>{J9(`${O} ${g_(K,M)} AS ${I}`)},_X=(O,I,K,M)=>{p(O,"relationship subquery (parent table)"),p(I,"relationship subquery (target table)"),p(K,"relationship subquery (primary key)");let C=`${O.endsWith("s")?O.slice(0,-1):O}_id`;p(C,"relationship subquery (foreign key)");let T=`SELECT 1 FROM ${I} WHERE ${I}.${C} = ${O}.${K}`;if(M){let x=M({where:(g,B,b)=>{return p(g,"relationship subquery condition"),`${I}.${g} ${f0(B,"whereHas callback")} ${q9(b)}`}});if(x)T+=` AND ${x}`}return T},v$=(O,I,K,M)=>{p(O,"relationship subquery (parent table)"),p(I,"relationship subquery (target table)"),p(K,"relationship subquery (primary key)");let C=`${I.endsWith("s")?I.slice(0,-1):I}_id`;p(C,"relationship subquery (foreign key)");let T=`SELECT 1 FROM ${I} WHERE ${I}.${K} = ${O}.${C}`;if(M){let x=M({where:(g,B,b)=>{return p(g,"relationship subquery condition"),`${I}.${g} ${f0(B,"whereHas callback")} ${q9(b)}`}});if(x)T+=` AND ${x}`}return T},b$=(O,I,K,M,C,T)=>{p(O,"relationship subquery (parent table)"),p(I,"relationship subquery (target table)"),p(K,"relationship subquery (primary key)"),p(M,"relationship subquery (target primary key)");let k=T&&Z?TX(Z,O,T,{singularize:u,models:Z.models}):null,x=u(O),g=u(I),B=k?.pivotTable??[x,g].sort().join("_"),b=k?.fkParent??`${x}_id`,s=k?.fkRelated??`${g}_id`;p(B,"relationship subquery (pivot table)"),p(b,"relationship subquery (foreign key A)"),p(s,"relationship subquery (foreign key B)");let $0=`SELECT 1 FROM ${B} JOIN ${I} ON ${I}.${M} = ${B}.${s} WHERE ${B}.${b} = ${O}.${K}`;if(C){let r=C({where:(S0,X9,_9)=>{return p(S0,"relationship subquery condition"),`${I}.${S0} ${f0(X9,"whereHas callback")} ${q9(_9)}`}});if(r)$0+=` AND ${r}`}return $0},B7=(O,I,K)=>{p(O,"withCount (parent table)"),p(I,"withCount (target table)"),p(K,"withCount (primary key)");let M=`${O.endsWith("s")?O.slice(0,-1):O}_id`;return p(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${I} WHERE ${I}.${M} = ${O}.${K})`},y7=(O,I,K,M)=>{p(O,"withCount (parent table)"),p(I,"withCount (target table)"),p(K,"withCount (primary key)");let C=M&&Z?TX(Z,O,M,{singularize:u,models:Z.models}):null,T=u(O),k=u(I),x=C?.pivotTable??[T,k].sort().join("_"),g=C?.fkParent??`${T}_id`;return p(x,"withCount (pivot table)"),p(g,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${x} WHERE ${x}.${g} = ${O}.${K})`},f$=(O,I,K)=>{if(!Z)return;p(K,`with${O[0]}${O.slice(1).toLowerCase()} (column)`);let M=String(G),C=Z.relations?.[M];if(!C)return;let T=Object.entries(C).find(([r,S0])=>S0&&typeof S0==="object"&&(I in S0));if(!T)return;let[k,x]=T,g=x[I],B=typeof g==="string"?g:g?.model||g?.target||g,b=Z.modelToTable[B]||B,s=Z.primaryKeys[M]??"id";p(b,`with${O} (target table)`);let $0=`${O}(${b}.${K})`,P0;if(k==="hasMany"||k==="hasOne"){let r=`${M.endsWith("s")?M.slice(0,-1):M}_id`;p(r,`with${O} (foreign key)`),P0=`(SELECT ${$0} FROM ${b} WHERE ${b}.${r} = ${M}.${s})`}else if(k==="belongsToMany"){let r=Z?TX(Z,M,I,{singularize:u,models:Z.models}):null,S0=u(M),X9=u(b),_9=r?.pivotTable??[S0,X9].sort().join("_"),QX=r?.fkParent??`${S0}_id`,_0=r?.fkRelated??`${X9}_id`,cX=Z.primaryKeys[b]??"id";p(_9,`with${O} (pivot table)`),p(QX,`with${O} (foreign key)`),p(_0,`with${O} (related key)`),P0=`(SELECT ${$0} FROM ${_9} JOIN ${b} ON ${b}.${cX} = ${_9}.${_0} WHERE ${_9}.${QX} = ${M}.${s})`}else return;J9(`${P0} AS ${I}_${O.toLowerCase()}_${K}`)},K5=()=>{if(v.size===0)return;let O=[];for(let[I,K]of v.entries()){let M=i(I);if(!M)continue;for(let T of K)p(T,"withPivot");let C=K.map((T)=>`${M.pivotTable}.${T} AS pivot_${T}`);O.push(...C)}if(O.length>0){let I=O.join(", ");J9(I)}};return new Proxy({distinct(){return F=F.replace(/^SELECT\s+/i,"SELECT DISTINCT "),R=null,this},distinctOn(...O){let I=O.map(String).join(", ");return F=F.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${I}) `),R=null,this},selectRaw(O){let I=KX(O,"selectRaw(fragment)"),K=F.indexOf(" FROM ");if(K!==-1)F=`${F.substring(0,K)}, ${I}${F.substring(K)}`;else F+=`, ${I}`;return R=null,this},rowNumber(O="row_number",I,K){let M=[];if(I){let x=Array.isArray(I)?I:[I];M.push(`PARTITION BY ${x.join(", ")}`)}if(K&&K.length)M.push(`ORDER BY ${K.map(([x,g])=>`${x} ${g==="desc"?"DESC":"ASC"}`).join(", ")}`);let T=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${O}`,k=F.indexOf(" FROM ");if(k!==-1)F=`${F.substring(0,k)}, ${T}${F.substring(k)}`;else F+=`, ${T}`;return R=null,this},denseRank(O="dense_rank",I,K){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(K&&K.length)C.push(`ORDER BY ${K.map(([g,B])=>`${g} ${B==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`DENSE_RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,x=F.indexOf(" FROM ");if(x!==-1)F=`${F.substring(0,x)}, ${k}${F.substring(x)}`;else F+=`, ${k}`;return R=null,this},rank(O="rank",I,K){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(K&&K.length)C.push(`ORDER BY ${K.map(([g,B])=>`${g} ${B==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,x=F.indexOf(" FROM ");if(x!==-1)F=`${F.substring(0,x)}, ${k}${F.substring(x)}`;else F+=`, ${k}`;return R=null,this},over(O,I,K={}){return G0(O,I,K.partitionBy,K.orderBy),this},lag(O,I={}){let K=[O,String(I.offset??1)];if(I.defaultValue!==void 0)K.push(String(I.defaultValue));return G0(`LAG(${K.join(", ")})`,I.alias??`${O}_lag`,I.partitionBy,I.orderBy),this},lead(O,I={}){let K=[O,String(I.offset??1)];if(I.defaultValue!==void 0)K.push(String(I.defaultValue));return G0(`LEAD(${K.join(", ")})`,I.alias??`${O}_lead`,I.partitionBy,I.orderBy),this},sumOver(O,I={}){return G0(`SUM(${O})`,I.alias??`${O}_sum`,I.partitionBy,I.orderBy),this},avgOver(O,I={}){return G0(`AVG(${O})`,I.alias??`${O}_avg`,I.partitionBy,I.orderBy),this},countOver(O="*",I={}){return G0(`COUNT(${O})`,I.alias??"count_over",I.partitionBy,I.orderBy),this},minOver(O,I={}){return G0(`MIN(${O})`,I.alias??`${O}_min`,I.partitionBy,I.orderBy),this},maxOver(O,I={}){return G0(`MAX(${O})`,I.alias??`${O}_max`,I.partitionBy,I.orderBy),this},firstValue(O,I={}){return G0(`FIRST_VALUE(${O})`,I.alias??`${O}_first`,I.partitionBy,I.orderBy),this},lastValue(O,I={}){return G0(`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 K=I.map(SY),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(F),C=M?M[1]:"",T=F.indexOf(" FROM ");if(T!==-1)F=`SELECT ${C}${K.join(", ")}${F.substring(T)}`;else F=`SELECT ${C}${K.join(", ")} FROM ${G}`;return R=null,this},addSelect(...O){if(!O.length)return this;let I=O.map(SY),K=F.indexOf(" FROM ");if(K!==-1)F=`${F.substring(0,K)}, ${I.join(", ")}${F.substring(K)}`;else F+=`, ${I.join(", ")}`;return R=null,this},with(...O){if(!Z||!O||O.length===0)return this;let I=[];for(let B of O){if(!B)continue;if(typeof B==="string")I.push({name:B});else if(typeof B==="object"&&!Array.isArray(B))for(let[b,s]of Object.entries(B))if(typeof s==="function")I.push({name:b,callback:s});else I.push({name:b})}if(I.length===0)return this;let K=f.relations.maxEagerLoad??50;if(I.length>K)throw Error(`[query-builder] Too many relationships to eager load (${I.length}). Maximum allowed: ${K}`);let M=String(G),C=new Set,T=new Set,k=new Map,x=(B)=>{let b=Z.relations?.[B];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=(B,b,s=0,$0)=>{let P0=f.relations.maxDepth??10;if(s>=P0)throw Error(`[query-builder] Maximum relationship depth (${P0}) exceeded at '${b}'. Consider using separate queries or increasing maxDepth.`);let r=Z.relations?.[B];if(!r)return B;let S0=(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=[],w0=(L0,a0,R9)=>{p(String(L0),"with() constraint column");let zX=f0(a0,"with() constraint operator");Y0.push(`${Z0}.${String(L0)} ${zX} ${q9(R9)}`)},K0=(L0)=>()=>{throw Error(`[query-builder] with('${b}', ...): ${L0} 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.)`)},T0={where:(L0,a0,R9)=>{if(Array.isArray(L0))w0(L0[0],L0[1],L0[2]);else if(L0&&typeof L0==="object")for(let zX of Object.keys(L0))w0(zX,"=",L0[zX]);else if(a0!==void 0&&R9!==void 0)w0(L0,a0,R9);else if(a0!==void 0)w0(L0,"=",a0);return T0},whereIn:(L0,a0)=>{return p(String(L0),"with() constraint column"),Y0.push(`${Z0}.${String(L0)} IN (${a0.map(q9).join(", ")})`),T0},whereNull:(L0)=>{return p(String(L0),"with() constraint column"),Y0.push(`${Z0}.${String(L0)} IS NULL`),T0},whereNotNull:(L0)=>{return p(String(L0),"with() constraint column"),Y0.push(`${Z0}.${String(L0)} IS NOT NULL`),T0},orderBy:K0("orderBy()"),limit:K0("limit()"),offset:K0("offset()"),take:K0("take()")};return $0(T0),Y0.length?` AND ${Y0.join(" AND ")}`:""},_9=()=>{let Z0=(K0)=>{let T0=K0?.[b];return T0?Z.modelToTable[T0]:void 0},Y0=(K0)=>{let T0=K0?.[b],L0=typeof T0==="string"?T0:T0?.model;return L0?Z.modelToTable[L0]:void 0},w0=(K0)=>{let T0=K0?.[b];return T0?.target?Z.modelToTable[T0.target]:void 0};return Z0(r?.hasOne)||Z0(r?.hasMany)||Z0(r?.belongsTo)||Y0(r?.belongsToMany)||w0(r?.hasOneThrough)||w0(r?.hasManyThrough)||Z0(r?.morphOne)||Z0(r?.morphMany)||Z0(r?.morphToMany)||Z0(r?.morphedByMany)},QX=_9()??(Z.modelToTable[b]||Z.tableToModel[b]?Z.modelToTable[b]??b:b),_0=String(QX);if(!QX||!_9()&&!Z.modelToTable[b]&&!Z.tableToModel[b]){let Z0=x(B);if(Z0.length>0&&!Z0.includes(b)){let Y0=` Available relationships: ${Z0.join(", ")}`;throw Error(`[query-builder] Relationship '${b}' not found on table '${B}'.${Y0}`)}}if(f.relations.detectCycles!==!1){let Z0=`${B}->${_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===B)return B;let cX=r?.hasOneThrough?.[b]||r?.hasManyThrough?.[b];if(cX){let{through:Z0,target:Y0}=cX,w0=Z.modelToTable[Z0]||Z0,K0=Z.modelToTable[Y0]||Y0,T0=Z.primaryKeys[B]??"id",L0=Z.primaryKeys[w0]??"id",a0=`${u(B)}_id`,R9=`${u(w0)}_id`;return A(`LEFT JOIN ${w0} ON ${w0}.${a0} = ${B}.${T0} LEFT JOIN ${K0} ON ${K0}.${R9} = ${w0}.${L0}`),P.add(w0),P.add(K0),K0}if(Boolean(r?.belongsToMany?.[b])){let Z0=TX(Z,B,b,{singularize:u,models:Z.models}),Y0=Z0?.pivotTable??[u(B),u(_0)].sort().join("_"),w0=Z.primaryKeys[B]??"id",K0=Z.primaryKeys[_0]??"id",T0=Z0?.fkParent??`${u(B)}_id`,L0=Z0?.fkRelated??`${u(_0)}_id`;return A(`LEFT JOIN ${Y0} ON ${Y0}.${T0} = ${B}.${w0} LEFT JOIN ${_0} ON ${_0}.${K0} = ${Y0}.${L0}${X9(_0)}`),P.add(Y0),P.add(_0),_0}if(Boolean(r?.morphToMany?.[b])){let Z0=b,Y0=`${u(_0)}_${Z0}`,w0=Z.primaryKeys[B]??"id",K0=Z.primaryKeys[_0]??"id",T0=`${Z0}_type`,L0=`${Z0}_id`,a0=`${u(_0)}_id`,R9=q9(Z.tableToModel[B]||B);return A(`LEFT JOIN ${Y0} ON ${Y0}.${L0} = ${B}.${w0} AND ${Y0}.${T0} = ${R9} LEFT JOIN ${_0} ON ${_0}.${K0} = ${Y0}.${a0}`),P.add(Y0),P.add(_0),_0}if(Boolean(r?.morphedByMany?.[b])){let Z0=r.morphedByMany?.[b]||b,Y0=Z.modelToTable[Z0]||Z0,w0=u(B),K0=`${u(Y0)}_${w0}`,T0=Z.primaryKeys[B]??"id",L0=Z.primaryKeys[Y0]??"id",a0=`${w0}_type`,R9=`${w0}_id`,zX=`${u(Y0)}_id`,d7=q9(Z.tableToModel[Y0]||Y0);return A(`LEFT JOIN ${K0} ON ${K0}.${zX} = ${B}.${T0} LEFT JOIN ${Y0} ON ${Y0}.${L0} = ${K0}.${R9} AND ${K0}.${a0} = ${d7}`),P.add(K0),P.add(Y0),Y0}if(Boolean(r?.belongsTo?.[b])){let Z0=`${u(_0)}_id`,Y0=Z.primaryKeys[_0]??"id";return A(`LEFT JOIN ${_0} ON ${B}.${Z0} = ${_0}.${Y0}${X9(_0)}`),P.add(_0),_0}let h7=Boolean(r?.morphOne?.[b]),v7=Boolean(r?.morphMany?.[b]);if(h7||v7){let Z0=`${b}_type`,Y0=`${b}_id`,w0=Z.primaryKeys[B]??"id",K0=q9(Z.tableToModel[B]||B);return A(`LEFT JOIN ${_0} ON ${_0}.${Y0} = ${B}.${w0} AND ${_0}.${Z0} = ${K0}`),P.add(_0),_0}let b7=`${u(B)}_id`,f7=Z.primaryKeys[B]??"id",g7=`${S0(_0)}${X9(_0)}`;return A(`LEFT JOIN ${_0} ON ${_0}.${b7} = ${B}.${f7}${g7}`),P.add(_0),_0};for(let B of I){let b=B.name.trim();if(B.callback)k.set(b,B.callback);let s=b.split("."),$0=M,P0=0;for(let r of s){if(!r||r.trim().length===0)continue;let S0=r.trim(),X9=k.get(S0);$0=g($0,S0,P0,X9)||$0,P0++}T.add(b)}if(v.size>0){let B=[];for(let[b,s]of v.entries()){let $0=i(b);if(!$0)continue;let P0=s.map((r)=>`${$0.pivotTable}.${r} AS pivot_${r}`);B.push(...P0)}if(B.length>0){let b=B.join(", ");J9(b)}}return R=null,this},whereHas(O,I){if(!Z)return this;let K=String(G),M=Z.relations?.[K];if(!M)throw Error(`[query-builder] No relationships defined for table '${K}'`);let C=Object.entries(M).find(([s,$0])=>$0&&typeof $0==="object"&&(O in $0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${K}'`);let[T,k]=C,x=k[O],g=typeof x==="string"?x:x?.model||x?.target||x,B=Z.modelToTable[g]||g,b;if(T==="hasMany"||T==="hasOne"){let s=Z.primaryKeys[K]??"id";b=_X(K,B,s,I)}else if(T==="belongsTo"){let s=Z.primaryKeys[B]??"id";b=v$(K,B,s,I)}else if(T==="belongsToMany"){let s=Z.primaryKeys[K]??"id",$0=Z.primaryKeys[B]??"id";b=b$(K,B,s,$0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${T}' for whereHas`);R=W`${D()} WHERE EXISTS (${W([b])})`;try{q("WHERE",`EXISTS (${b})`)}catch{}return this},whereDoesntHave(O,I){if(!Z)return this;let K=String(G),M=Z.relations?.[K];if(!M)throw Error(`[query-builder] No relationships defined for table '${K}'`);let C=Object.entries(M).find(([s,$0])=>$0&&typeof $0==="object"&&(O in $0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${K}'`);let[T,k]=C,x=k[O],g=typeof x==="string"?x:x?.model||x?.target||x,B=Z.modelToTable[g]||g,b;if(T==="hasMany"||T==="hasOne"){let s=Z.primaryKeys[K]??"id";b=_X(K,B,s,I)}else if(T==="belongsTo"){let s=Z.primaryKeys[B]??"id";b=v$(K,B,s,I)}else if(T==="belongsToMany"){let s=Z.primaryKeys[K]??"id",$0=Z.primaryKeys[B]??"id";b=b$(K,B,s,$0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${T}' for whereDoesntHave`);R=W`${D()} WHERE NOT EXISTS (${W([b])})`;try{q("WHERE",`NOT EXISTS (${b})`)}catch{}return this},has(O){if(!Z)return this;let I=String(G),K=Z.relations?.[I];if(!K)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(K).find(([b,s])=>s&&typeof s==="object"&&(O in s));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,T]=M,k=T[O],x=typeof k==="string"?k:k?.model||k?.target||k,g=Z.modelToTable[x]||x,B;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";B=_X(I,g,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[g]??"id";B=v$(I,g,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",s=Z.primaryKeys[g]??"id";B=b$(I,g,b,s,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for has`);R=W`${D()} WHERE EXISTS (${W([B])})`;try{q("WHERE",`EXISTS (${B})`)}catch{}return this},doesntHave(O){if(!Z)return this;let I=String(G),K=Z.relations?.[I];if(!K)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(K).find(([b,s])=>s&&typeof s==="object"&&(O in s));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,T]=M,k=T[O],x=typeof k==="string"?k:k?.model||k?.target||k,g=Z.modelToTable[x]||x,B;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";B=_X(I,g,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[g]??"id";B=v$(I,g,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",s=Z.primaryKeys[g]??"id";B=b$(I,g,b,s,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for doesntHave`);R=W`${D()} WHERE NOT EXISTS (${W([B])})`;try{q("WHERE",`NOT EXISTS (${B})`)}catch{}return this},withCount(...O){if(!Z||!O||O.length===0)return this;let I=String(G);for(let K of O){let M=Z.relations?.[I];if(!M)continue;let C=Object.entries(M).find(([P0,r])=>r&&typeof r==="object"&&(K in r));if(!C)continue;let[T,k]=C,x=k[K],g=typeof x==="string"?x:x?.model||x?.target||x,B=Z.modelToTable[g]||g,b=Z.primaryKeys[I]??"id",s;if(T==="hasMany"||T==="hasOne")s=B7(I,B,b);else if(T==="belongsToMany")s=y7(I,B,b,K);else continue;let $0=`${K}_count`;J9(`${s} AS ${$0}`)}return this},withSum(O,I){return f$("SUM",O,I),this},withAvg(O,I){return f$("AVG",O,I),this},withMax(O,I){return f$("MAX",O,I),this},withMin(O,I){return f$("MIN",O,I),this},applyPivotColumns(){return K5(),this},withPivot(O,...I){if(!Z)return this;let K=String(G),M=i(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${K}'`);let C=I&&I.length>0?I:M.hasConfig?M.pivotColumns:[];if(C.length===0)return this;if(v.set(O,C),M.hasConfig)n.add(O);return K5(),this},wherePivot(O,I,K,M){if(!Z)return this;let C=i(O);if(!C)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(C.pivotTable,"wherePivot (pivot table)"),p(I,"wherePivot (column)"),R0(C);let T=M===void 0?"=":String(K),k=M===void 0?K:M,x=y.length+1,g=`${C.pivotTable}.${I} ${T} ${l(x)}`;z0.push(g),y.push(k);let B=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${B} ${g}`,R=null,C.hasConfig)n.add(O);return this},wherePivotIn(O,I,K){if(!Z||!Array.isArray(K)||K.length===0)return this;let M=i(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(M.pivotTable,"wherePivotIn (pivot table)"),p(I,"wherePivotIn (column)"),R0(M);let C=b0(K.length,y.length+1),T=`${M.pivotTable}.${I} IN (${C})`;z0.push(T),y.push(...K);let k=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${k} ${T}`,R=null,M.hasConfig)n.add(O);return this},wherePivotNotIn(O,I,K){if(!Z||!Array.isArray(K)||K.length===0)return this;let M=i(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(M.pivotTable,"wherePivotNotIn (pivot table)"),p(I,"wherePivotNotIn (column)"),R0(M);let C=b0(K.length,y.length+1),T=`${M.pivotTable}.${I} NOT IN (${C})`;z0.push(T),y.push(...K);let k=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${k} ${T}`,R=null,M.hasConfig)n.add(O);return this},wherePivotNull(O,I){if(!Z)return this;let K=i(O);if(!K)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(K.pivotTable,"wherePivotNull (pivot table)"),p(I,"wherePivotNull (column)"),R0(K);let M=`${K.pivotTable}.${I} IS NULL`;z0.push(M);let C=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,R=null,K.hasConfig)n.add(O);return this},wherePivotNotNull(O,I){if(!Z)return this;let K=i(O);if(!K)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);p(K.pivotTable,"wherePivotNotNull (pivot table)"),p(I,"wherePivotNotNull (column)"),R0(K);let M=`${K.pivotTable}.${I} IS NOT NULL`;z0.push(M);let C=o.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,R=null,K.hasConfig)n.add(O);return this},where(O,I,K){let M=()=>o.WHERE.test(F)?"AND":"WHERE";if(typeof O==="string"&&I!==void 0){p(String(O),"where(column)"),f0(I,"where(operator)");let C=String(I).toLowerCase();if(C==="in"||C==="not in"){let k=Array.isArray(K)?K:[K],x=b0(k.length,y.length+1),g=`${String(O)} ${C.toUpperCase()} (${x})`;return z0.push(g),y.push(...k),F=`${F} ${M()} ${g}`,R=null,this}let T=y.length+1;return z0.push(`${String(O)} ${String(I)} ${l(T)}`),y.push(K),F=`${F} ${M()} ${String(O)} ${String(I)} ${l(T)}`,R=null,this}if(Array.isArray(O)){let[C,T,k]=O,x=String(C);p(x,"where(column)");let g=f0(T,"where(operator)");if(g==="in"||g==="not in"){let B=Array.isArray(k)?k:[k],b=b0(B.length,y.length+1);z0.push(`${x} ${g.toUpperCase()} (${b})`),y.push(...B),F=`${F} ${M()} ${x} ${g.toUpperCase()} (${b})`,R=null}else{let B=y.length+1;z0.push(`${x} ${g} ${l(B)}`),y.push(k),F=`${F} ${M()} ${x} ${g} ${l(B)}`,R=null}return this}if(O&&typeof O==="object"&&!p8(O)){let C=O,T=Object.keys(C),k=[];for(let x of T){p(x,"where(column)");let g=C[x];if(Array.isArray(g)){let B=b0(g.length,y.length+1);k.push(`${x} IN (${B})`),z0.push(`${x} IN (${B})`),y.push(...g)}else{let B=y.length+1;k.push(`${x} = ${l(B)}`),z0.push(`${x} = ${l(B)}`),y.push(g)}}if(k.length>0)F=`${F} ${M()} ${k.join(" AND ")}`,R=null;return this}if(p8(O))return z0.push(O.raw),F=`${F} ${M()} ${O.raw}`,R=null,this;return this},whereNull(O){p(String(O),"whereNull(column)");let I=o.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NULL`,R=null,this},whereNotNull(O){p(String(O),"whereNotNull(column)");let I=o.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NOT NULL`,R=null,this},whereBetween(O,I,K){p(String(O),"whereBetween(column)");let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1;return F=`${F} ${M} ${String(O)} BETWEEN ${l(C)} AND ${l(C+1)}`,y.push(I,K),R=null,this},whereExists(O){let I=o.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} EXISTS (${O.toSQL()})`,R=null,this},whereJsonContains(O,I){p(String(O),"whereJsonContains(column)");let K=o.WHERE.test(F)?"AND":"WHERE",M=f.dialect,C=y.length+1;if(M==="postgres"){if(f.sql?.jsonContainsMode==="function")F+=` ${K} jsonb_contains(${O}, ${l(C)})`;else F+=` ${K} ${O} @> ${l(C)}`;y.push(JSON.stringify(I))}else if(I0(M))F+=` ${K} JSON_CONTAINS(${O}, ${l(C)})`,y.push(JSON.stringify(I));else if(Array.isArray(I)){let T=I.map((k,x)=>`EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${l(C+x)})`);F+=` ${K} (${T.join(" AND ")})`;for(let k of I)y.push(k)}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+=` ${K} EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${l(C)})`,y.push(I);return R=null,this},whereJsonPath(O,I,K){if(f0(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=o.WHERE.test(F)?"AND":"WHERE",T=y.length+1;if(M==="postgres")F+=` ${C} ${O} ${I} ${l(T)}`;else if(I0(M))F+=` ${C} JSON_EXTRACT(${O}) ${I} ${l(T)}`;else F+=` ${C} json_extract(${O}) ${I} ${l(T)}`;return y.push(K),R=null,this},whereLike(O,I,K=!1){let M=l(y.length+1);return q("WHERE",`${K?String(O):`LOWER(${String(O)})`} LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},whereILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("WHERE",`${String(O)} ILIKE ${K}`);else q("WHERE",`LOWER(${String(O)}) LIKE LOWER(${K})`);return y.push(I),R=null,this},orWhereLike(O,I,K=!1){let M=l(y.length+1);return q("OR",`${K?String(O):`LOWER(${String(O)})`} LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},orWhereILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("OR",`${String(O)} ILIKE ${K}`);else q("OR",`LOWER(${String(O)}) LIKE LOWER(${K})`);return y.push(I),R=null,this},whereNotLike(O,I,K=!1){let M=l(y.length+1);return q("WHERE",`${K?String(O):`LOWER(${String(O)})`} NOT LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},whereNotILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("WHERE",`${String(O)} NOT ILIKE ${K}`);else q("WHERE",`LOWER(${String(O)}) NOT LIKE LOWER(${K})`);return y.push(I),R=null,this},orWhereNotLike(O,I,K=!1){let M=l(y.length+1);return q("OR",`${K?String(O):`LOWER(${String(O)})`} NOT LIKE ${K?M:`LOWER(${M})`}`),y.push(I),R=null,this},orWhereNotILike(O,I){let K=l(y.length+1);if(f.dialect==="postgres")q("OR",`${String(O)} NOT ILIKE ${K}`);else q("OR",`LOWER(${String(O)}) NOT LIKE LOWER(${K})`);return y.push(I),R=null,this},whereAny(O,I,K){if(O.length===0)return this;let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1,T=O.map((k,x)=>`${k} ${I} ${l(C+x)}`);F+=` ${M} (${T.join(" OR ")})`;for(let k=0;k<O.length;k++)y.push(K);return R=null,this},whereAll(O,I,K){if(O.length===0)return this;let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1,T=O.map((k,x)=>`${k} ${I} ${l(C+x)}`);F+=` ${M} (${T.join(" AND ")})`;for(let k=0;k<O.length;k++)y.push(K);return R=null,this},whereNone(O,I,K){if(O.length===0)return this;let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1,T=O.map((k,x)=>`${k} ${I} ${l(C+x)}`);F+=` ${M} NOT (${T.join(" OR ")})`;for(let k=0;k<O.length;k++)y.push(K);return R=null,this},whereNotBetween(O,I,K){p(String(O),"whereNotBetween(column)");let M=o.WHERE.test(F)?"AND":"WHERE",C=y.length+1;return F+=` ${M} ${O} NOT BETWEEN ${l(C)} AND ${l(C+1)}`,y.push(I,K),R=null,this},whereDate(O,I,K){p(O,"whereDate(column)");let M=K instanceof Date?K.toISOString():typeof K==="string"?K:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof K}`)})(),C=o.WHERE.test(F)?"AND":"WHERE",T=y.length+1;return F+=` ${C} ${O} ${I} ${l(T)}`,y.push(M),R=null,this},whereRaw(O){let I=KX(O,"whereRaw(fragment)"),K=o.WHERE.test(F)?"AND":"WHERE";return F+=` ${K} ${I}`,R=null,this},whereColumn(O,I,K){p(O,"whereColumn(left)"),p(K,"whereColumn(right)");let M=o.WHERE.test(F)?"AND":"WHERE";return F+=` ${M} ${O} ${I} ${K}`,R=null,this},orWhereColumn(O,I,K){return p(O,"orWhereColumn(left)"),p(K,"orWhereColumn(right)"),F+=` OR ${O} ${I} ${K}`,R=null,this},whereIn(O,I){p(String(O),"whereIn(column)");let K=o.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=b0(I.length,y.length+1);F+=` ${K} ${O} IN (${M})`,y.push(...I)}else F+=` ${K} ${O} IN (${String(I.toSQL())})`;return R=null,this},orWhereIn(O,I){if(p(String(O),"orWhereIn(column)"),Array.isArray(I)){let K=b0(I.length,y.length+1);F+=` OR ${O} IN (${K})`,y.push(...I)}else F+=` OR ${O} IN (${String(I.toSQL())})`;return R=null,this},whereNotIn(O,I){p(String(O),"whereNotIn(column)");let K=o.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=b0(I.length,y.length+1);F+=` ${K} ${O} NOT IN (${M})`,y.push(...I)}else F+=` ${K} ${O} NOT IN (${String(I.toSQL())})`;return R=null,this},orWhereNotIn(O,I){if(p(String(O),"orWhereNotIn(column)"),Array.isArray(I)){let K=b0(I.length,y.length+1);F+=` OR ${O} NOT IN (${K})`,y.push(...I)}else F+=` OR ${O} NOT IN (${String(I.toSQL())})`;return R=null,this},whereNested(O){let I=o.WHERE.test(F)?"AND":"WHERE",K=O.toSQL?String(O.toSQL()):String(O);return F+=` ${I} (${K})`,R=null,this},orWhereNested(O){let I=O.toSQL?String(O.toSQL()):String(O);return F+=` OR (${I})`,R=null,this},andWhere(O,I,K){if(typeof O==="string"&&I!==void 0){p(String(O),"andWhere(column)"),f0(I,"andWhere(operator)");let M=y.length+1;return z0.push(`${String(O)} ${String(I)} ${l(M)}`),y.push(K),F=`${F} AND ${String(O)} ${String(I)} ${l(M)}`,R=null,this}if(Array.isArray(O)){let[M,C,T]=O,k=String(M);p(k,"andWhere(column)");let x=f0(C,"andWhere(operator)");if(x==="in"||x==="not in"){let g=Array.isArray(T)?T:[T],B=b0(g.length,y.length+1);z0.push(`${k} ${x.toUpperCase()} (${B})`),y.push(...g),F=`${F} AND ${k} ${x.toUpperCase()} (${B})`,R=null}else{let g=y.length+1;z0.push(`${k} ${x} ${l(g)}`),y.push(T),F=`${F} AND ${k} ${x} ${l(g)}`,R=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let T of M){let k=O[T];if(Array.isArray(k)){let x=b0(k.length,y.length+1);C.push(`${T} IN (${x})`),z0.push(`${T} IN (${x})`),y.push(...k)}else{let x=y.length+1;C.push(`${T} = ${l(x)}`),z0.push(`${T} = ${l(x)}`),y.push(k)}}if(C.length>0)F=`${F} AND ${C.join(" AND ")}`,R=null;return this}if(O&&typeof O.raw<"u")return z0.push(O.raw),F=`${F} AND ${O.raw}`,R=null,this;return this},orWhere(O,I,K){if(typeof O==="string"&&I!==void 0){p(String(O),"orWhere(column)"),f0(I,"orWhere(operator)");let M=y.length+1;return z0.push(`OR ${String(O)} ${String(I)} ${l(M)}`),y.push(K),F=`${F} OR ${String(O)} ${String(I)} ${l(M)}`,R=null,this}if(Array.isArray(O)){let[M,C,T]=O,k=String(M);p(k,"orWhere(column)");let x=f0(C,"orWhere(operator)");if(x==="in"||x==="not in"){let g=Array.isArray(T)?T:[T],B=b0(g.length,y.length+1);z0.push(`OR ${k} ${x.toUpperCase()} (${B})`),y.push(...g),F=`${F} OR ${k} ${x.toUpperCase()} (${B})`,R=null}else{let g=y.length+1;z0.push(`OR ${k} ${x} ${l(g)}`),y.push(T),F=`${F} OR ${k} ${x} ${l(g)}`,R=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let T of M){let k=O[T];if(Array.isArray(k)){let x=b0(k.length,y.length+1);C.push(`${T} IN (${x})`),z0.push(`OR ${T} IN (${x})`),y.push(...k)}else{let x=y.length+1;C.push(`${T} = ${l(x)}`),z0.push(`OR ${T} = ${l(x)}`),y.push(k)}}if(C.length>0)F=`${F} OR ${C.join(" AND ")}`,R=null;return this}if(O&&typeof O.raw<"u")return z0.push(`OR ${O.raw}`),F=`${F} OR ${O.raw}`,R=null,this;return this},orderBy(O,I="asc"){let K=I==="asc"?"ASC":"DESC";return F=o.ORDER_BY.test(F)?`${F}, ${O} ${K}`:`${F} ORDER BY ${O} ${K}`,R=null,this},orderByDesc(O){return F=o.ORDER_BY.test(F)?`${F}, ${O} DESC`:`${F} ORDER BY ${O} DESC`,R=null,this},inRandomOrder(){let O=f.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return F=o.ORDER_BY.test(F)?`${F}, ${O}`:`${F} ORDER BY ${O}`,R=null,this},reorder(O,I="asc"){return F=F.replace(/ORDER BY[\s\S]*$/i,""),F+=` ORDER BY ${O} ${I==="asc"?"ASC":"DESC"}`,R=null,this},latest(O){let I=O??f.timestamps.defaultOrderColumn;return F=o.ORDER_BY.test(F)?`${F}, ${I} DESC`:`${F} ORDER BY ${I} DESC`,R=null,this},oldest(O){let I=O??f.timestamps.defaultOrderColumn;return F=o.ORDER_BY.test(F)?`${F}, ${I} ASC`:`${F} ORDER BY ${I} ASC`,R=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=o.LIMIT.test(F)?F.replace(o.LIMIT,` LIMIT ${O}`):`${F} LIMIT ${O}`,R=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=o.OFFSET.test(F)?F.replace(o.OFFSET,` OFFSET ${O}`):`${F} OFFSET ${O}`,R=null,this},join(O,I,K,M){return p(O,"join(table)"),Q9(I,"join(onLeft)"),Q9(M,"join(onRight)"),f0(K,"join(operator)"),A(`JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},joinSub(O,I,K,M,C){return p(I,"joinSub(alias)"),Q9(K,"joinSub(onLeft)"),Q9(C,"joinSub(onRight)"),f0(M,"joinSub(operator)"),A(`JOIN (${String(O.toSQL())}) AS ${I} ON ${K} ${M} ${C}`),P.add(I),this},innerJoin(O,I,K,M){return p(O,"innerJoin(table)"),Q9(I,"innerJoin(onLeft)"),Q9(M,"innerJoin(onRight)"),f0(K,"innerJoin(operator)"),A(`INNER JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},leftJoin(O,I,K,M){return p(O,"leftJoin(table)"),Q9(I,"leftJoin(onLeft)"),Q9(M,"leftJoin(onRight)"),f0(K,"leftJoin(operator)"),A(`LEFT JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},leftJoinSub(O,I,K,M,C){return p(I,"leftJoinSub(alias)"),Q9(K,"leftJoinSub(onLeft)"),Q9(C,"leftJoinSub(onRight)"),f0(M,"leftJoinSub(operator)"),A(`LEFT JOIN (${String(O.toSQL())}) AS ${I} ON ${K} ${M} ${C}`),P.add(I),this},rightJoin(O,I,K,M){return p(O,"rightJoin(table)"),Q9(I,"rightJoin(onLeft)"),Q9(M,"rightJoin(onRight)"),f0(K,"rightJoin(operator)"),A(`RIGHT JOIN ${O} ON ${I} ${K} ${M}`),P.add(O),this},crossJoin(O){return p(O,"crossJoin(table)"),A(`CROSS JOIN ${O}`),P.add(O),this},crossJoinSub(O,I){return p(I,"crossJoinSub(alias)"),A(`CROSS JOIN (${String(O.toSQL())}) AS ${I}`),P.add(I),this},selectAllRelations(){if(!Y)return this;let O=String(G),I=Object.keys(Y[O]?.columns??{}),K=[];if(I.length>0)K.push(W`${W(O)}.*`);for(let M of P){let C=Object.keys(Y[M]?.columns??{});for(let T of C){let k=f.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${T}`.replace(/_([a-z])/g,(x,g)=>g.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${T}`:`${M}_${T}`;K.push(W`${W(`${M}.${T}`)} AS ${W(k)}`)}}if(K.length>0){let M=I.length>0?`${O}.*`:"",C=[];for(let x of P){let g=Object.keys(Y[x]?.columns??{});for(let B of g){let b=f.aliasing.relationColumnAliasFormat==="camelCase"?`${x}_${B}`.replace(/_([a-z])/g,(s,$0)=>$0.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${x}.${B}`:`${x}_${B}`;C.push(`${x}.${B} AS ${b}`)}}let T=[M,...C].filter(Boolean).join(", "),k=F.indexOf(" FROM ");if(k!==-1)F=`SELECT ${T}${F.substring(k)}`;else F=`SELECT ${T} FROM ${O}`;R=null}return this},groupBy(...O){if(O.length)F=o.GROUP_BY.test(F)?`${F}, ${O.join(", ")}`:`${F} GROUP BY ${O.join(", ")}`,R=null;return this},groupByRaw(O){let I=KX(O,"groupByRaw(fragment)");return F=o.GROUP_BY.test(F)?`${F}, ${I}`:`${F} GROUP BY ${I}`,R=null,this},having(O){let I=/\bHAVING\b/i.test(F)?"AND":"HAVING";if(Array.isArray(O)){let K=y.length+1;F=`${F} ${I} ${O[0]} ${O[1]} ${l(K)}`,y.push(O[2]),R=null}else if(O&&typeof O==="object"&&!("raw"in O)){let K=Object.keys(O),M=K.length;if(M){let C=y.length,T=Array.from({length:M});for(let k=0;k<M;k++){let x=K[k];T[k]=`${x} = ${l(C+k+1)}`,y.push(O[x])}F=`${F} ${I} ${T.join(" AND ")}`,R=null}}else if(O&&typeof O.raw<"u")F+=` ${I} ${O.raw}`,R=null;return this},havingRaw(O){let I=KX(O,"havingRaw(fragment)"),K=/\bHAVING\b/i.test(F)?"AND":"HAVING";return F+=` ${K} ${I}`,R=null,this},orderByRaw(O){let I=KX(O,"orderByRaw(fragment)");return F=o.ORDER_BY.test(F)?`${F}, ${I}`:`${F} ORDER BY ${I}`,R=null,this},union(O){return w("UNION",O),this},unionAll(O){return w("UNION ALL",O),this},intersect(O){return w("INTERSECT",O),this},intersectAll(O){return w("INTERSECT ALL",O),this},except(O){return w("EXCEPT",O),this},exceptAll(O){return w("EXCEPT ALL",O),this},forPage(O,I){let K=Math.max(1,Math.floor(O)),M=Math.max(1,Math.floor(I));return F+=` LIMIT ${M} OFFSET ${(K-1)*M}`,R=null,this},toSQL(){let O=$8(F);return{sql:O,toString:()=>O,execute:()=>D().execute(),values:()=>D().values(),raw:()=>D().raw()}},async value(O){let I=W`${D()} LIMIT 1`,K=await j(I,"select",{signal:N,timeoutMs:H}),[M]=K;return M?.[O]},async pluck(O,I){let K=await j(D(),"select",{signal:N,timeoutMs:H});if(I){let M={};for(let C of K){let T=String(C?.[I]);if(Object.prototype.hasOwnProperty.call(M,T))throw Error(`[query-builder] pluck(${O}, ${I}): duplicate key '${T}' \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[T]=C?.[O]}return M}return K.map((M)=>M?.[O])},async exists(){let O=W`SELECT EXISTS (${D()}) as e`,I=await j(O,"select",{signal:N,timeoutMs:H}),[K]=I;return Boolean(K?.e)},async doesntExist(){return!await this.exists()},async paginate(O,I=1,K={}){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(K.tx){let s=$8(F),$0=[...y],P0=await K.tx.unsafe(`SELECT COUNT(*) as c FROM (${s}) as sub`,$0),r=Number(P0?.[0]?.c??0),S0=Math.max(1,Math.ceil(r/O)),X9=Math.max(1,Math.min(I,S0)),_9=(X9-1)*O;return{data:await K.tx.unsafe(`${s} LIMIT ${O} OFFSET ${_9}`,$0),meta:{perPage:O,page:X9,total:r,lastPage:S0}}}let M=W`SELECT COUNT(*) as c FROM (${D()}) as sub`,C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C,k=Number(T?.c??0),x=Math.max(1,Math.ceil(k/O)),g=Math.max(1,Math.min(I,x)),B=(g-1)*O;return{data:await j(W`${D()} LIMIT ${O} OFFSET ${B}`,"select",{signal:N,timeoutMs:H}),meta:{perPage:O,page:g,total:k,lastPage:x}}},async simplePaginate(O,I=1){let K=Math.max(1,I),M=(K-1)*O,C=await j(W`${D()} LIMIT ${O+1} OFFSET ${M}`,"select",{signal:N,timeoutMs:H}),T=C.length>O;return{data:T?C.slice(0,O):C,meta:{perPage:O,page:K,hasMore:T}}},async cursorPaginate(O,I,K="id",M="asc"){let C=D();if(I!==void 0&&I!==null)if(Array.isArray(K)){let s=K.map((S0)=>W(String(S0))),$0=M==="asc"?W`>`:W`<`,P0=W`(${W(s)})`,r=W`(${W(I)})`;C=W`${C} WHERE ${P0} ${$0} ${r}`}else C=M==="asc"?W`${C} WHERE ${W(String(K))} > ${I}`:W`${C} WHERE ${W(String(K))} < ${I}`;if(Array.isArray(K)){let $0=K.map((P0)=>W`${W(String(P0))} ${M==="asc"?W`ASC`:W`DESC`}`).reduce((P0,r,S0)=>S0===0?r:W`${P0}, ${r}`);C=W`${C} ORDER BY ${$0} LIMIT ${O+1}`}else C=W`${C} ORDER BY ${W(String(K))} ${M==="asc"?W`ASC`:W`DESC`} LIMIT ${O+1}`;let T=await j(C,"select",{signal:N,timeoutMs:H}),k=T.length>O,x=T.slice(0,O),g=x[x.length-1],B=k&&g?Array.isArray(K)?K.map((s)=>g[s]):g[K]:null,b=x.length?Array.isArray(K)?K.map((s)=>x[0]?.[s]):x[0]?.[K]:null;return{data:x,meta:{perPage:O,nextCursor:B??null,prevCursor:b}}},async chunk(O,I){let K=1;while(!0){let{data:M,meta:C}=await this.paginate(O,K);if(M.length===0)break;if(await I(M),K>=C.lastPage)break;K+=1}},async chunkById(O,I="id",K){let M;while(!0){let{data:C,meta:T}=await this.cursorPaginate(O,M,I,"asc");if(C.length===0)break;if(K)await K(C);if(M=T.nextCursor,!M)break}},async eachById(O,I="id",K){await this.chunkById(O,I,async(M)=>{for(let C of M)await K?.(C)})},withTimeout(O){return H=Math.max(1,Math.floor(O)),this},abort(O){return N=O,this},withTrashed(){return S=!0,h=!1,this},onlyTrashed(){S=!0,h=!0;let O=f.softDeletes?.column||"deleted_at",I=(C,T)=>{let k=C.toUpperCase(),x=0;for(let g=0;g<C.length;g++){let B=C[g];if(B==="(")x++;else if(B===")")x--;else if(x===0&&k.substring(g,g+5)==="WHERE"&&(g===0||/\s/.test(C[g-1]??""))&&/\s/.test(C[g+5]??""))return`${C.substring(0,g)}WHERE ${T} AND ${C.substring(g+6)}`}return`${C} WHERE ${T}`},K=`${G}.${O} IS NOT NULL`;F=I(F,K);let M=String(D());return R=W([I(M,K)]),this},scope(O,I){let K=String(G),C=Z?.scopes?.[K]?.[O];if(C)return C(this,I);return this},when(O,I,K){if(O)return I(this);if(K)return K(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 a=O,d=!0,this},async explain(){let O=W`EXPLAIN ${D()}`;return await j(O,"select",{signal:N,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||nX(O));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!I){let T=$._prepareStatement;if(T){let k=T(F);return X0(y.length>0?k.all(...y):k.all())}}if(R=y.length>0?$.unsafe(F,y):$.unsafe(F),!f.softDeletes?.enabled&&!d&&!H&&!N&&!I){let T=D()._stmt,k=D()._params;if(T)return X0(k&&k.length>0?T.all(...k):T.all());return X0(await D().execute())}if(!f.softDeletes?.enabled&&!d&&!H&&!N)return X0(await j(D(),"select"));let K=D();if(f.softDeletes?.enabled&&f.softDeletes.defaultFilter&&!S){let T=f.softDeletes.column,k=String(G);if((Y?Boolean(Y[k]?.columns?.[T]):!0)&&!o.DELETED_AT.test(F))K=W`${D()} WHERE ${W(String(T))} IS ${h?W`NOT NULL`:W`NULL`}`,q("WHERE",`${String(T)} IS ${h?"NOT ":""}NULL`)}let M=d?`${String(K)}\x00${JSON.stringify(y)}`:"";if(d){let T=A$.get(M);if(T)return T}let C=await j(K,"select",{signal:N,timeoutMs:H});if(d)A$.set(M,C,a);return X0(C)},async executeTakeFirst(){let O=await j(D(),"select",{signal:N,timeoutMs:H});return m(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||nX(O));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!I){let C=$._prepareStatement;if(C){let T=F.includes(" LIMIT ")?F:`${F} LIMIT 1`,k=C(T),x=y.length>0?k.all(...y):k.all();return m(x[0])}}let K=await j(W`${D()} LIMIT 1`,"select",{signal:N,timeoutMs:H}),[M]=K;return m(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",K=await j(W`${D()} WHERE ${W(I)} = ${O} LIMIT 1`,"select",{signal:N,timeoutMs:H}),[M]=K;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:N,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),K;if(I)K=`SELECT COUNT(*) as c FROM (${F}) AS _bqb_count_sub`;else if(O!==-1)K=`SELECT COUNT(*) as c${F.substring(O)}`;else K=`SELECT COUNT(*) as c FROM ${G}`;let M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||nX(M));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!C){let g=$._prepareStatement;if(g){let B=g(K),b=y.length>0?B.all(...y):B.all();return Number(b[0]?.c??0)}}let T=y.length>0?$.unsafe(K,y):$.unsafe(K),k=await j(T,"select",{signal:N,timeoutMs:H}),[x]=k;return Number(x?.c??0)},async avg(O){let I=F.indexOf(" FROM "),K=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||nX(M));if(!f.softDeletes?.enabled&&!d&&!H&&!N&&!C){let g=$._prepareStatement;if(g){let B=g(K),b=y.length>0?B.all(...y):B.all();return Number(b[0]?.a??0)}}let T=y.length>0?$.unsafe(K,y):$.unsafe(K),k=await j(T,"select",{signal:N,timeoutMs:H}),[x]=k;return Number(x?.a??0)},async sum(O){let I=F.indexOf(" FROM "),K=I!==-1?`SELECT SUM(${O}) as s${F.substring(I)}`:`SELECT SUM(${O}) as s FROM ${G}`,M=y.length>0?$.unsafe(K,y):$.unsafe(K),C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C;return Number(T?.s??0)},async max(O){let I=F.indexOf(" FROM "),K=I!==-1?`SELECT MAX(${O}) as m${F.substring(I)}`:`SELECT MAX(${O}) as m FROM ${G}`,M=y.length>0?$.unsafe(K,y):$.unsafe(K),C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C;return T?.m},async min(O){let I=F.indexOf(" FROM "),K=I!==-1?`SELECT MIN(${O}) as m${F.substring(I)}`:`SELECT MIN(${O}) as m FROM ${G}`,M=y.length>0?$.unsafe(K,y):$.unsafe(K),C=await j(M,"select",{signal:N,timeoutMs:H}),[T]=C;return T?.m},lockForUpdate(){return F+=" FOR UPDATE",R=null,this},sharedLock(){let O=f.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return F+=` ${O}`,R=null,this},withCTE(O,I){return p(O,"withCTE(name)"),F=`WITH ${O} AS (${String(I.toSQL())}) ${F}`,R=null,this},withRecursive(O,I){return p(O,"withRecursive(name)"),F=`WITH RECURSIVE ${O} AS (${String(I.toSQL())}) ${F}`,R=null,this},execute(){return j(D(),"select",{signal:N,timeoutMs:H})},values(){return D().values()},toParams(){return[...y]},__rawState(){return{sql:$8(F),params:[...y]}},raw(){return D().raw()},get rows(){return},get row(){return},cancel(){try{D().cancel()}catch{}}},{get(O,I,K){let M=Reflect.get(O,I,K);if(M!==void 0)return M;if(typeof I==="string"&&(I.startsWith("where")||I.startsWith("orWhere")||I.startsWith("andWhere"))){let C=I.startsWith("orWhere"),T=I.startsWith("andWhere"),k=`${String(G)}|${I}`,x=U.get(k);if(x===void 0){let B=I.replace(/^(?:or|and)?where/i,"");if(!B)U.set(k,""),x="";else{let b=B.charAt(0).toLowerCase()+B.slice(1),s=B.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),$0=Y?Object.keys(Y[String(G)]?.columns??{}):[];x=[s,b,b.toLowerCase()].find((P0)=>$0.includes(P0))??s,U.set(k,x)}}if(x==="")return()=>K;let g=x;return(B)=>{let b=Array.isArray(B)?W`${W(g)} IN ${W(B)}`:W`${W(g)} = ${B}`;if(R=C?W`${D()} OR ${b}`:T?W`${D()} AND ${b}`:W`${D()} WHERE ${b}`,Array.isArray(B)){let s=b0(B.length,y.length+1);q(C?"OR":T?"AND":"WHERE",`${g} IN (${s})`),y.push(...B)}else{let s=l(y.length+1);q(C?"OR":T?"AND":"WHERE",`${g} = ${s}`),y.push(B)}return K}}return Reflect.get(O,I,K)}})}return{configure(G){return Object.assign(f,G),this},id(G){if(!o.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(!o.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.")}}p(String(J),"selectFromSub(alias)");let F=typeof G.__rawState==="function"?G.__rawState():null,R=G.toSQL(),D=F?.sql??(typeof R==="string"?R:R?.sql??String(R)),q=F?.params??(Array.isArray(R?.values)?R.values:[]),w=`SELECT * FROM (${D}) AS ${String(J)}`,A=(H,N,S,h,d,v,n)=>{let a=!S?"WHERE":n==="WHERE"?"AND":n,u=[...N],i=(X0,R0,z0)=>{p(X0,"selectFromSub where(column)");let y=f0(R0,"selectFromSub where(operator)");if(y==="in"||y==="not in"){let G0=Array.isArray(z0)?z0:[z0],_X=b0(G0.length,u.length+1);return u.push(...G0),`${X0} ${y.toUpperCase()} (${_X})`}let J9=l(u.length+1);return u.push(z0),`${X0} ${y} ${J9}`},m;if(typeof h==="string"&&d!==void 0)m=i(h,d,v);else if(Array.isArray(h)&&h.length===3)m=i(h[0],h[1],h[2]);else if(h&&typeof h==="object")m=Object.entries(h).map(([X0,R0])=>i(X0,"=",R0)).join(" AND ");else return{text:H,params:N};return{text:`${H} ${a} ${m}`,params:u}};function P(H,N,S=!1){let h=()=>N.length>0?$.unsafe(H,N):$.unsafe(H),d={distinct(){return P(H.replace(/^SELECT\s+/i,"SELECT DISTINCT "),N,S)},distinctOn(...v){let n=v.map(String).join(", ");return P(H.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${n}) `),N,S)},selectRaw(v){let n=KX(v,"selectFromSub.selectRaw(fragment)"),a=H.indexOf(" FROM "),u=a!==-1?`${H.slice(0,a)}, ${n}${H.slice(a)}`:`${H}, ${n}`;return P(u,N,S)},where(v,n,a){let u=A(H,N,S,v,n,a,"WHERE");return P(u.text,u.params,!0)},andWhere(v,n,a){let u=A(H,N,S,v,n,a,"AND");return P(u.text,u.params,!0)},orWhere(v,n,a){let u=A(H,N,S,v,n,a,"OR");return P(u.text,u.params,!0)},orderBy(v,n="asc"){p(String(v),"selectFromSub.orderBy(column)");let a=n==="asc"?"ASC":"DESC",u=o.ORDER_BY.test(H)?`${H}, ${v} ${a}`:`${H} ORDER BY ${v} ${a}`;return P(u,N,S)},limit(v){if(!Number.isInteger(v)||v<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${v}`);let n=o.LIMIT.test(H)?H.replace(o.LIMIT,` LIMIT ${v}`):`${H} LIMIT ${v}`;return P(n,N,S)},offset(v){if(!Number.isInteger(v)||v<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${v}`);let n=o.OFFSET.test(H)?H.replace(o.OFFSET,` OFFSET ${v}`):`${H} OFFSET ${v}`;return P(n,N,S)},toSQL(){return E(h(),H)},async execute(){return j(h(),"select")},async executeTakeFirst(){let v=await j(h(),"select");return Array.isArray(v)?v[0]:v},async executeTakeFirstOrThrow(){let v=await j(h(),"select"),n=Array.isArray(v)?v[0]:v;if(!n)throw Error("Record not found");return n},async get(){return j(h(),"select")},async first(){let v=await j(h(),"select");return Array.isArray(v)?v[0]:v},async firstOrFail(){let v=await j(h(),"select"),n=Array.isArray(v)?v[0]:v;if(!n)throw Error("No rows found");return n},async count(){let v=N.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,N):$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),n=await j(v,"select");return Number(n?.[0]?.c??0)},async exists(){let v=N.length>0?$.unsafe(`SELECT EXISTS(${H}) as e`,N):$.unsafe(`SELECT EXISTS(${H}) as e`),n=await j(v,"select");return Boolean(n?.[0]?.e)},async doesntExist(){return!await d.exists()},values(){return h().values()},raw(){return h().raw()},cancel(){try{h().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:(v)=>v(d),when:W("when"),tap:()=>d,dump:()=>d,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>h().simple(),toText:()=>H,toParams:()=>[...N],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 P(w,q)},insertInto(G){let J,W="",F=[],R=f.dialect==="postgres",D=R?(w)=>`"${String(w).replace(/"/g,'""')}"`:I0(f.dialect)?(w)=>`\`${String(w).replace(/`/g,"``")}\``:(w)=>`"${String(w).replace(/"/g,'""')}"`,q=R?(w)=>`$${w+1}`:(w)=>"?";return{values(w){let A=Array.isArray(w)?w:[w],P=A.length;if(P===0)return J=$.unsafe("SELECT 1"),this;let H=A[0],N=Object.keys(H),S=N.length,h=P*S;if(F.length=h,P===1)if(!R){let d=D(N[0]),v="?";F[0]=H[N[0]];for(let n=1;n<S;n++)d+=`,${D(N[n])}`,v+=",?",F[n]=H[N[n]];W=`INSERT INTO ${D(G)}(${d})VALUES(${v})`}else{let d=N.map((v)=>D(v)).join(",");W=`INSERT INTO ${D(G)}(${d})VALUES(`;for(let v=0;v<S;v++){if(v>0)W+=",";W+=q(v),F[v]=H[N[v]]}W+=")"}else{let d=N.map((n)=>D(n)).join(",");W=`INSERT INTO ${D(G)}(${d})VALUES`;let v=0;for(let n=0;n<P;n++){let a=A[n];if(n===0)W+="(";else W+="),(";for(let u=0;u<S;u++){if(u>0)W+=",";W+=q(v),F[v++]=a[N[u]]}}W+=")"}if(!$._prepareStatement)J=$.unsafe(W,F);return this},returning(...w){let A=`${W} RETURNING ${w.join(", ")}`,P=$.unsafe(A,F),H=async()=>{let N=await j(P,"insert");return Array.isArray(N)?N[0]:N};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>E(P,A),execute:()=>j(P,"insert"),get:()=>j(P,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let N=await H();if(!N)throw Error("Insert with RETURNING returned no rows");return N},async executeTakeFirstOrThrow(){let N=await H();if(!N)throw Error("Insert with RETURNING returned no rows");return N}}},toSQL(){if(!J)J=$.unsafe(W,F);return E(J,W)},execute(){let w=f.hooks;if(!(w&&(w.onQueryStart||w.onQueryEnd||w.onQueryError||w.startSpan||w.beforeCreate||w.afterCreate||nX(w)))){let P=$._prepareStatement;if(P){let H=P(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 w=await j(J,"insert");if(!w)throw Error("Insert failed");return w},returningAll(){let w=`${W} RETURNING *`,A=$.unsafe(w,F),P=async()=>{let H=await j(A,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>E(A,w),execute:()=>j(A,"insert"),get:()=>j(A,"insert"),first:P,executeTakeFirst:P,async firstOrFail(){let H=await P();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await P();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(G){let J,W=[],F=(D)=>{let q=String(D);if(I0(f.dialect))return`\`${q.replace(/`/g,"``")}\``;return`"${q.replace(/"/g,'""')}"`},R=`UPDATE ${F(String(G))}`;return{set(D){let q=Object.keys(D),w=q.length,A=Array.from({length:w});for(let P=0;P<w;P++){let H=q[P];A[P]=`${F(H)} = ${l(P+1)}`,W.push(D[H])}return R=`${R} SET ${A.join(", ")}`,J=$.unsafe(R,W),this},where(D,q,w){let A=()=>o.WHERE.test(R)?"AND":"WHERE";if(typeof D==="string"&&q!==void 0){let P=W.length+1;return R=`${R} ${A()} ${F(D)} ${q} ${l(P)}`,W.push(w),J=$.unsafe(R,W),this}if(Array.isArray(D)){let[P,H,N]=D,S=W.length+1;return R=`${R} ${A()} ${F(String(P))} ${String(H)} ${l(S)}`,W.push(N),J=$.unsafe(R,W),this}if(D&&typeof D==="object"&&!("raw"in D)){let P=Object.keys(D),H=P.length,N=W.length,S=Array.from({length:H});for(let h=0;h<H;h++)S[h]=`${F(P[h])} = ${l(N+h+1)}`,W.push(D[P[h]]);R=`${R} ${A()} ${S.join(" AND ")}`,J=$.unsafe(R,W)}return this},returning(...D){let q=`${R} RETURNING ${D.join(", ")}`,w=W.length>0?$.unsafe(q,W):$.unsafe(q),A=async()=>{let H=await j(w,"update");return Array.isArray(H)?H[0]:H},P={where:()=>P,andWhere:()=>P,orWhere:()=>P,orderBy:()=>P,limit:()=>P,offset:()=>P,toSQL:()=>E(w,q),execute:()=>j(w,"update"),get:()=>j(w,"update"),first:A,executeTakeFirst:A,async firstOrFail(){let H=await A();if(!H)throw Error("Update with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await A();if(!H)throw Error("Update with RETURNING returned no rows");return H}};return P},toSQL(){if(!J)J=W.length>0?$.unsafe(R,W):$.unsafe(R);return E(J,R)},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=`${R} RETURNING *`,q=W.length>0?$.unsafe(D,W):$.unsafe(D);return{toSQL:()=>E(q,D),execute:()=>j(q,"update"),async executeTakeFirst(){let w=await j(q,"update");return Array.isArray(w)?w[0]:w},async executeTakeFirstOrThrow(){let w=await j(q,"update"),A=Array.isArray(w)?w[0]:w;if(!A)throw Error("Update with RETURNING failed");return A}}}}},deleteFrom(G){let J=(P)=>{let H=String(P);if(I0(f.dialect))return`\`${H.replace(/`/g,"``")}\``;return`"${H.replace(/"/g,'""')}"`},F=`DELETE FROM ${J(String(G))}`,R=null,D=[],q=null,w=()=>o.WHERE.test(F)?"AND":"WHERE",A=()=>{if(R===null)R=D.length>0?$.unsafe(F,D):$.unsafe(F);return R};return{where(P,H,N){if(q=P,typeof P==="string"&&H!==void 0){let S=D.length+1;return F+=` ${w()} ${J(P)} ${H} ${l(S)}`,D.push(N),R=null,this}if(Array.isArray(P)){let[S,h,d]=P,v=D.length+1;return F+=` ${w()} ${J(String(S))} ${h} ${l(v)}`,D.push(d),R=null,this}if(P&&typeof P==="object"&&!("raw"in P)){let S=Object.keys(P),h=[];for(let d of S){let v=D.length+1;h.push(`${J(d)} = ${l(v)}`),D.push(P[d])}return F+=` ${w()} ${h.join(" AND ")}`,R=null,this}return R=Q({},A(),P),this},returning(...P){let H=`${F} RETURNING ${P.join(", ")}`,N=D.length>0?$.unsafe(H,D):$.unsafe(H),S=async()=>{let d=await j(N,"delete");return Array.isArray(d)?d[0]:d},h={where:()=>h,andWhere:()=>h,orWhere:()=>h,orderBy:()=>h,limit:()=>h,offset:()=>h,toSQL:()=>E(N,H),execute:()=>j(N,"delete"),get:()=>j(N,"delete"),first:S,executeTakeFirst:S,async firstOrFail(){let d=await S();if(!d)throw Error("Delete with RETURNING returned no rows");return d},async executeTakeFirstOrThrow(){let d=await S();if(!d)throw Error("Delete with RETURNING returned no rows");return d}};return h},toSQL(){return E(A(),F)},async execute(){try{await f.hooks?.beforeDelete?.({table:String(G),where:q})}catch(H){throw H}let P=await j(A(),"delete");try{await f.hooks?.afterDelete?.({table:String(G),where:q,result:P})}catch{}return P},async executeTakeFirst(){return{numDeletedRows:await j(A(),"delete")}},async executeTakeFirstOrThrow(){let P=await j(A(),"delete");if(P===0)throw Error("No rows deleted");return{numDeletedRows:P}},returningAll(){let P=`${F} RETURNING *`,H=D.length>0?$.unsafe(P,D):$.unsafe(P);return{toSQL:()=>E(H,P),execute:()=>j(H,"delete"),async executeTakeFirst(){let N=await j(H,"delete");return Array.isArray(N)?N[0]:N},async executeTakeFirstOrThrow(){let N=await j(H,"delete"),S=Array.isArray(N)?N[0]:N;if(!S)throw Error("Delete with RETURNING failed");return S}}}}},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),R=c`SELECT pg_advisory_lock(${F})`;await j(R,"raw");return}if(I0(f.dialect)){let J=`bqb:${String(G)}`,W=c`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 q=0;q<J.length;q++)W=W*31+J.charCodeAt(q)|0;let F=typeof G==="number"?G:Math.abs(W),R=c`SELECT pg_try_advisory_lock(${F}) as ok`,D=await j(R,"raw");return Boolean(D?.[0]?.ok)}if(I0(f.dialect)){let J=`bqb:${String(G)}`,W=c`SELECT GET_LOCK(${J}, 0) AS ok`,F=await j(W,"raw");return Number(F?.[0]?.ok)===1}return!1},unsafe(G,J){return $.unsafe(G,J)},file(G,J){return c.file(G,J)},async reserve(){let G=await c.reserve(),J=H0({sql:G,meta:Z,schema:Y});return J.release=()=>G.release(),J},async close(G){await c.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=c`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((R)=>setTimeout(R,W))}throw Error("Database not ready after waiting")},async transaction(G,J){let F={...X?.txDefaults,...J},R=X?.sql??c,D=X?.inTransaction===!0,q=D&&typeof R?.savepoint==="function"?"savepoint":"begin",w=async(H)=>{F.logger?.({type:"start",attempt:H});let N=Date.now();return await R[q](async(S)=>{let h=H0({sql:S,meta:Z,schema:Y,inTransaction:!0});if(F?.isolation&&!D){let n=F.isolation,a=n==="read committed"?"READ COMMITTED":n==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(f.dialect==="postgres")await S.unsafe(`SET TRANSACTION ISOLATION LEVEL ${a}`);else if(I0(f.dialect))await S.unsafe(`SET TRANSACTION ISOLATION LEVEL ${a}`);else if(n!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${n}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(F?.readOnly)if(f.dialect==="postgres")await S.unsafe("SET TRANSACTION READ ONLY");else if(I0(f.dialect))await S.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(h),v=Date.now()-N;return F.logger?.({type:"commit",attempt:H,durationMs:v}),d})},A=Math.max(0,F?.retries??0),P=0;for(;;)try{let H=await w(P+1);return F?.afterCommit?.(),H}catch(H){let N=d_(H)||p_(H,F.sqlStates);if(P<A&&N){P++,F?.onRetry?.(P,H);let S=u_(P,F.backoff);if(S>0)await c_(S);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=H0({sql:W,meta:Z,schema:Y});return await G(F)})},async beginDistributed(G,J){return await(X?.sql??c).beginDistributed(G,async(R)=>{let D=H0({sql:R,meta:Z,schema:Y});return await J(D)})},async commitDistributed(G){await c.commitDistributed(G)},async rollbackDistributed(G){await c.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:R,params:D}=X8(W),q=t0(String(G)),w=I0(f.dialect)?`INSERT IGNORE INTO ${q} (${F}) VALUES ${R}`:`INSERT INTO ${q} (${F}) VALUES ${R} ON CONFLICT DO NOTHING`;return c.unsafe(w,D).execute()},async insertGetId(G,J,W="id"){let{colsSql:F,valuesSql:R,params:D}=X8([J]),q=t0(String(G));if(I0(f.dialect)){await c.unsafe(`INSERT INTO ${q} (${F}) VALUES ${R}`,D).execute();let[A]=await c.unsafe("SELECT LAST_INSERT_ID() as id").execute();return A?.id}if(f.dialect==="sqlite"){let A=await c.unsafe(`INSERT INTO ${q} (${F}) VALUES ${R}`,D).execute();if(A?.lastInsertRowid!=null)return A.lastInsertRowid;let[P]=await c.unsafe("SELECT last_insert_rowid() as id").execute();return P?.id}let[w]=await c.unsafe(`INSERT INTO ${q} (${F}) VALUES ${R} RETURNING ${t0(String(W))} as id`,D).execute();return w?.id},async updateOrInsert(G,J,W){let F=t0(String(G)),R=Object.keys(J),D=1,q=R.map((S)=>`${t0(S)} = ${l(D++)}`).join(" AND "),w=R.map((S)=>J[S]);if((await c.unsafe(`SELECT 1 FROM ${F} WHERE ${q} LIMIT 1`,w).execute()).length){let S=Object.keys(W),h=1,d=S.map((a)=>`${t0(a)} = ${l(h++)}`).join(", "),v=R.map((a)=>`${t0(a)} = ${l(h++)}`).join(" AND "),n=[...S.map((a)=>W[a]),...R.map((a)=>J[a])];return await c.unsafe(`UPDATE ${F} SET ${d} WHERE ${v}`,n).execute(),!0}let{colsSql:P,valuesSql:H,params:N}=X8([{...J,...W}]);return await c.unsafe(`INSERT INTO ${F} (${P}) VALUES ${H}`,N).execute(),!0},async upsert(G,J,W,F){let R=W.map((d)=>String(d)),D=(F??[]).map((d)=>String(d)),q=J;if(!q.length)return;let{colsSql:w,valuesSql:A,params:P}=X8(q),H=t0(String(G)),N=`INSERT INTO ${H} (${w}) VALUES ${A}`;if(I0(f.dialect)){if(D.length===0)return c.unsafe(`INSERT IGNORE INTO ${H} (${w}) VALUES ${A}`,P).execute();let d=D.map((v)=>`${t0(v)} = VALUES(${t0(v)})`).join(", ");return c.unsafe(`${N} ON DUPLICATE KEY UPDATE ${d}`,P).execute()}let S=R.map(t0).join(", ");if(D.length===0)return c.unsafe(`${N} ON CONFLICT (${S}) DO NOTHING`,P).execute();let h=D.map((d)=>`${t0(d)} = EXCLUDED.${t0(d)}`).join(", ");return c.unsafe(`${N} ON CONFLICT (${S}) DO UPDATE SET ${h}`,P).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 c.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=c`INSERT INTO ${c(String(G))} ${c(J)} RETURNING ${c(String(W))} as id`,[R]=await F.execute();if(console.log("resultId",R),!R?.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(R.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${R.id}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${R.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 R=await this.selectFrom(G).find(F);if(!R)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:R})}catch{}return R}},async createMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),R=F.length,D=J.length,q=Array.from({length:D*R}),w=I0(f.dialect)?(H)=>`\`${String(H).replace(/`/g,"``")}\``:(H)=>`"${String(H).replace(/"/g,'""')}"`,A=`INSERT INTO ${w(String(G))}(${F.map(w).join(",")})VALUES`,P=0;for(let H=0;H<D;H++){if(H>0)A+=",";A+="(";let N=J[H];for(let S=0;S<R;S++){if(S>0)A+=",";A+=l(P+1),q[P++]=N[F[S]]}A+=")"}return $.unsafe(A,q).execute()},async insertMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),R=F.length,D=J.length,q=D*R,w=Array(q),A=f.dialect==="postgres",P;if(!A){let S=Array(R);for(let h=0;h<R;h++)S[h]="?";P=`(${S.join(",")})`}else P="";let H=Array(D+2);H[0]=`INSERT INTO ${G}(${F.join(",")})VALUES`;let N=0;if(!A){for(let S=0;S<D;S++){let h=J[S];H[S+1]=P;for(let d=0;d<R;d++)w[N++]=h[F[d]]}return $.unsafe(H[0]+H.slice(1,D+1).join(","),w).execute()}for(let S=0;S<D;S++){let h=J[S],d=Array(R);for(let v=0;v<R;v++)d[v]=`$${N+1}`,w[N++]=h[F[v]];H[S+1]=`(${d.join(",")})`}return $.unsafe(H[0]+H.slice(1,D+1).join(","),w).execute()},async updateMany(G,J,W){let F=Object.keys(W),R=F.length;if(R===0)return 0;let D=[],q=Array.from({length:R});for(let A=0;A<R;A++)q[A]=`${F[A]}=${l(A+1)}`,D.push(W[F[A]]);let w=`UPDATE ${G} SET ${q.join(",")}`;if(Array.isArray(J))w+=` WHERE ${J[0]}${J[1]}${l(D.length+1)}`,D.push(J[2]);else if(J&&typeof J==="object"&&!("raw"in J)){let A=Object.keys(J),P=A.length;if(P>0){let H=D.length,N=Array.from({length:P});for(let S=0;S<P;S++)N[S]=`${A[S]}=${l(H+S+1)}`,D.push(J[A[S]]);w+=` WHERE ${N.join(" AND ")}`}}return $.unsafe(w,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 q=0;q<F;q++)D[q]=`$${q+1}`;return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${D.join(",")})`,J).execute()}let R=Array(F);for(let D=0;D<F;D++)R[D]="?";return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${R.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 R=Z?.primaryKeys[String(G)]??"id",D=F[R],q=D!=null?await this.selectFrom(G).find(D):await this.selectFrom(G).where(J).first();if(!q)throw Error("updateOrCreate() failed to retrieve updated row");return q}return await this.create(G,{...J,...W})},async count(G,J){let W=J?c(String(J)):c`*`,F=c`SELECT COUNT(${W}) as c FROM ${c(String(G))}`,[R]=await F.execute();return Number(R?.c??0)},async sum(G,J){let W=c`SELECT SUM(${c(String(J))}) as s FROM ${c(String(G))}`,[F]=await W.execute();return Number(F?.s??0)},async avg(G,J){let W=c`SELECT AVG(${c(String(J))}) as a FROM ${c(String(G))}`,[F]=await W.execute();return Number(F?.a??0)},async min(G,J){let W=c`SELECT MIN(${c(String(J))}) as m FROM ${c(String(G))}`,[F]=await W.execute();return F?.m},async max(G,J){let W=c`SELECT MAX(${c(String(J))}) as m FROM ${c(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,R]of Object.entries(J))if(R&&typeof R==="object"&&Object.keys(R).length>0)W[F]=R;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,R]of Object.entries(W))if(R&&typeof R==="object"&&J in R)return F;return null},getRelationshipTarget(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,R]of Object.entries(W))if(R&&typeof R==="object"&&J in R){let D=R[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 n_(){A$.clear()}function i_(X){A$.setMaxSize(X)}var o,q1,P1,A$,rX,l_=500,_Z=e(()=>{c0(),$X(),o={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},q1=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]),P1=new Set,A$=new zU,rX=new Map});async function wG(){console.log("-- Clearing query cache..."),n_(),console.log("-- \u2713 Query cache cleared")}async function qG(){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 PG(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");i_($),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 s_=e(()=>{_Z()});async function r_(){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=H0(),$=o_({input:Z8.stdin,output:Z8.stdout,prompt:"qb> "}),Z="",Y=!1,U=`
79
79
  Available Commands:
80
80
  .help Show this help message
81
81
  .exit Exit the console
@@ -162,15 +162,15 @@ Goodbye!`),Z8.exit(0)}),$.prompt()}async function SG(){return r_()}var a_=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 yG(){return $Q()}var ZQ=e(()=>{c0(),v0()});async function vG(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 c`VACUUM FULL ANALYZE ${c(Y)}`;else await c`VACUUM ANALYZE ${c(Y)}`}else{if(X.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Z)await c`VACUUM FULL`,await c`ANALYZE`;else await c`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(I0($)){if(X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Optimizing table: ${Y}`);await c`OPTIMIZE TABLE ${c(Y)}`,await c`ANALYZE TABLE ${c(Y)}`}else{let Y=SY.env.DB_NAME||"test",U=await c`
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 yG(){return $Q()}var ZQ=e(()=>{c0(),v0()});async function vG(X={}){let $=X.dialect||AY.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 c`VACUUM FULL ANALYZE ${c(Y)}`;else await c`VACUUM ANALYZE ${c(Y)}`}else{if(X.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Z)await c`VACUUM FULL`,await c`ANALYZE`;else await c`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(I0($)){if(X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Optimizing table: ${Y}`);await c`OPTIMIZE TABLE ${c(Y)}`,await c`ANALYZE TABLE ${c(Y)}`}else{let Y=AY.env.DB_NAME||"test",U=await c`
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 c`OPTIMIZE TABLE ${c(Q)}`,await c`ANALYZE TABLE ${c(Q)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(X.verbose)console.log("Running VACUUM on SQLite database...");if(await c`VACUUM`,X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);await c`ANALYZE ${c(Y)}`}else await c`ANALYZE`;if(Z){if(X.verbose)console.log("Running aggressive SQLite optimizations...");await c`PRAGMA optimize`,await c`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 YQ=e(()=>{c0(),$X()});async function fG(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 c`
169
+ `;for(let _ of U){let Q=_.table_name||_.TABLE_NAME;if(X.verbose)console.log(`Optimizing table: ${Q}`);await c`OPTIMIZE TABLE ${c(Q)}`,await c`ANALYZE TABLE ${c(Q)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(X.verbose)console.log("Running VACUUM on SQLite database...");if(await c`VACUUM`,X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);await c`ANALYZE ${c(Y)}`}else await c`ANALYZE`;if(Z){if(X.verbose)console.log("Running aggressive SQLite optimizations...");await c`PRAGMA optimize`,await c`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 YQ=e(()=>{c0(),$X()});async function fG(X={}){let $=X.dialect||kY.env.DB_DIALECT||"postgres";if(X.verbose)console.log(`Wiping all tables from ${$} database...`);try{let Z=[];if($==="postgres")Z=(await c`
170
170
  SELECT tablename
171
171
  FROM pg_tables
172
172
  WHERE schemaname = 'public'
173
- `).map((U)=>U.tablename);else if(I0($)){let Y=AY.env.DB_NAME||"test";Z=(await c`
173
+ `).map((U)=>U.tablename);else if(I0($)){let Y=kY.env.DB_NAME||"test";Z=(await c`
174
174
  SELECT table_name
175
175
  FROM information_schema.tables
176
176
  WHERE table_schema = ${Y}
@@ -234,7 +234,7 @@ Goodbye!`),Z8.exit(0)}),$.prompt()}async function SG(){return r_()}var a_=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),R=W.type.padEnd(G),D=(W.nullable?"YES":"NO").padEnd(10),q=String(W.default||"").padEnd(20),w=[W.isPrimaryKey?"PK":"",W.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${F}${R}${D}${q}${w}`)}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 pG(X,$={}){return zQ(X,$)}var LQ=e(()=>{c0(),v0()});async function cG(X,$={}){let Z=await pX({modelsDir:X}),Y=M7(Z);return console.log(JSON.stringify(Y,null,2)),{models:Z,schema:Y}}var jQ=e(()=>{v0()});function EQ(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 GQ(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 FQ(X){return X.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function zU(X){return FQ(GQ(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(I0($))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 OQ(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,
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),R=W.type.padEnd(G),D=(W.nullable?"YES":"NO").padEnd(10),q=String(W.default||"").padEnd(20),w=[W.isPrimaryKey?"PK":"",W.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${F}${R}${D}${q}${w}`)}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 pG(X,$={}){return zQ(X,$)}var LQ=e(()=>{c0(),v0()});async function cG(X,$={}){let Z=await pX({modelsDir:X}),Y=M7(Z);return console.log(JSON.stringify(Y,null,2)),{models:Z,schema:Y}}var jQ=e(()=>{v0()});function EQ(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 GQ(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 FQ(X){return X.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function LU(X){return FQ(GQ(X))}async function jU(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(I0($))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 OQ(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!`),Z8.exit(0)}),$.prompt()}async function SG(){return r_()}var a_=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 JQ(X,$){let Z=zU(X),Y=$.find((_)=>_.isPrimaryKey)?.name??"id",U=$.map((_)=>{let Q=[`type: '${EQ(_.sqlType)}'`];if(!_.nullable&&!_.isPrimaryKey)Q.push("required: true");return` ${_.name}: { ${Q.join(", ")} },`}).join(`
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 JQ(X,$){let Z=LU(X),Y=$.find((_)=>_.isPrimaryKey)?.name??"id",U=$.map((_)=>{let Q=[`type: '${EQ(_.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!`),Z8.exit(0)}),$.prompt()}async function SG(){return r_()}var a_=e(()=>
252
252
  ${U}
253
253
  },
254
254
  })
255
- `}async function mG(X={}){let $=f.dialect||"postgres",Z=H0(),Y=X.tables?.length?X.tables:await LU(Z,$),U=[];for(let _ of Y){let Q=await OQ(Z,$,_);if(!Q.length)continue;U.push({table:_,modelName:zU(_),primaryKey:Q.find((L)=>L.isPrimaryKey)?.name??"id",columns:Q,source:JQ(_,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(I0($)&&/^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 vX(X){let $=String(X??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function WQ(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:vX(V.on_delete),onUpdate:vX(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 R=Number(V.unique)===1;if(R&&F.length===1)j.add(F[0]);z.push({name:jU(J,$),columns:F,type:R?"unique":"index"})}let E=Z.map((V)=>{let G=String(V.name),J=VQ(Q,G),W=Number(V.pk)>0,F=V.dflt_value,R=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:R,defaultValue:R?Z5(F):void 0,enumValues:J,references:L.get(G)}});return{table:$,columns:E,indexes:z}}function VQ(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 IQ(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,
255
+ `}async function mG(X={}){let $=f.dialect||"postgres",Z=H0(),Y=X.tables?.length?X.tables:await jU(Z,$),U=[];for(let _ of Y){let Q=await OQ(Z,$,_);if(!Q.length)continue;U.push({table:_,modelName:LU(_),primaryKey:Q.find((L)=>L.isPrimaryKey)?.name??"id",columns:Q,source:JQ(_,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(I0($)&&/^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 EU(X,$){let Z=`${$}_`;return X.startsWith(Z)?X.slice(Z.length):X}function vX(X){let $=String(X??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function WQ(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:vX(V.on_delete),onUpdate:vX(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 R=Number(V.unique)===1;if(R&&F.length===1)j.add(F[0]);z.push({name:EU(J,$),columns:F,type:R?"unique":"index"})}let E=Z.map((V)=>{let G=String(V.name),J=VQ(Q,G),W=Number(V.pk)>0,F=V.dflt_value,R=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:R,defaultValue:R?Z5(F):void 0,enumValues:J,references:L.get(G)}});return{table:$,columns:E,indexes:z}}function VQ(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 IQ(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:vX(j.delete_rule),onUpdate:vX(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 RQ(X,$){let Z=await X.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
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:vX(j.delete_rule),onUpdate:vX(j.update_rule)});let{indexes:Q,uniqueColumns:L}=GU($,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 RQ(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:vX(j.delete_rule??j.DELETE_RULE),onUpdate:vX(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=KQ(V),W=String(j.column_key??j.COLUMN_KEY??"").toUpperCase()==="PRI",F=j.column_default??j.COLUMN_DEFAULT,R=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:R,defaultValue:R?Z5(F):void 0,enumValues:G,references:_.get(E)}});return{table:$,columns:z,indexes:Q}}function KQ(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 DQ(X,$={}){let Z=X||f.dialect||"postgres",Y=H0(),_=(($.tables?.length)?$.tables:await LU(Y,Z)).filter((L)=>L!=="migrations"),Q=[];for(let L of _){let z;if(Z==="sqlite")z=await WQ(Y,L);else if(Z==="postgres")z=await IQ(Y,L);else z=await RQ(Y,L);if(z.columns.length>0)Q.push(z)}return{dialect:Z,tables:Q}}var GU=e(()=>{c0(),v0()});function CQ(X){let $=X;while($!==kY($)){if(T1(N1($,"package.json")))return $;$=kY($)}return FU.cwd()}async function lG(X,$={}){let Z=CQ(FU.cwd()),Y=$.dir||N1(Z,"app/Models");if(!T1(Y))MQ(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=N1(Y,Q);if(T1(L))throw console.error(`-- Model already exists: ${L}`),Error(`Model already exists: ${L}`);let j=$.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
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:vX(j.delete_rule??j.DELETE_RULE),onUpdate:vX(j.update_rule??j.UPDATE_RULE)});let{indexes:Q,uniqueColumns:L}=GU($,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=KQ(V),W=String(j.column_key??j.COLUMN_KEY??"").toUpperCase()==="PRI",F=j.column_default??j.COLUMN_DEFAULT,R=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:R,defaultValue:R?Z5(F):void 0,enumValues:G,references:_.get(E)}});return{table:$,columns:z,indexes:Q}}function KQ(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 GU(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:EU(_,X),columns:Q.columns,type:Q.isUnique?"unique":"index",where:Q.where})}return{indexes:Y,uniqueColumns:U}}async function DQ(X,$={}){let Z=X||f.dialect||"postgres",Y=H0(),_=(($.tables?.length)?$.tables:await jU(Y,Z)).filter((L)=>L!=="migrations"),Q=[];for(let L of _){let z;if(Z==="sqlite")z=await WQ(Y,L);else if(Z==="postgres")z=await IQ(Y,L);else z=await RQ(Y,L);if(z.columns.length>0)Q.push(z)}return{dialect:Z,tables:Q}}var FU=e(()=>{c0(),v0()});function CQ(X){let $=X;while($!==xY($)){if(T1(N1($,"package.json")))return $;$=xY($)}return OU.cwd()}async function lG(X,$={}){let Z=CQ(OU.cwd()),Y=$.dir||N1(Z,"app/Models");if(!T1(Y))MQ(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=N1(Y,Q);if(T1(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
 
@@ -310,18 +310,18 @@ export default model
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);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"timestamptz":return"timestamptz";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(`,
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 JU{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"timestamptz":return"timestamptz";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);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=e(()=>{JU=class extends Y5{createTable($){let Z=$.columns.map((Q)=>this.renderColumn(Q)).join(`,
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 WU,BY=e(()=>{WU=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 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"timestamptz":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(`,
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 VU(X){return X==="integer"||X==="bigint"||X==="float"||X==="double"||X==="decimal"}class IU{quoteIdentifier(X){return`"${X.replace(/"/g,'""')}"`}getColumnType(X){if(X.name.endsWith("_id")&&VU(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"timestamptz":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 OU;case"mysql":return new Y5;case"singlestore":return new JU;case"sqlite":return new VU;default:throw Error(`Unsupported dialect: ${X}`)}}var QZ=e(()=>{xY(),xY()}),IU={};i1(IU,{saveMigrationSnapshot:()=>CU,resetDatabase:()=>kQ,generateMigration:()=>wU,executeMigration:()=>AQ,deleteMigrationFiles:()=>qU,copyModelsToGenerated:()=>xQ,clearGeneratedDirectory:()=>PU});function t(X){if(f.verbose)console.log(X)}function U5(X,$){let Z=n0(X,".qb");return n0(Z,`model-snapshot.${$}.json`)}function NQ(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;t("-- Invalid snapshot format, treating as no previous state");return}catch(Y){t(`-- Could not load snapshot, treating as no previous state: ${Y instanceof Error?Y.message:String(Y)}`);return}}function HU(X,$,Z){let Y=U5(X,$),U=n0(X,".qb");if(!d9(U))RU(U,{recursive:!0}),t(`-- Created snapshot directory: ${U}`);let _={plan:Z,hash:Rj(Z),dialect:$,updatedAt:new Date().toISOString()};MU(Y,JSON.stringify(_,null,2)),t(`-- Model snapshot saved to ${Y}`)}function CU(X,$={}){let Z=$.dialect??X.dialect;HU($.workspaceRoot??YX(),Z,X)}function YX(){return y$.cwd()}function SQ(X){let $=TU(X);if(!d9($))RU($,{recursive:!0}),t(`-- Created SQL directory: ${$}`);return $}async function wU(X,$={}){if(!X)X=n0(y$.cwd(),"app/Models");let Z=$.dialect||f.dialect||"postgres",Y=YX(),U=await pX({modelsDir:X}),_=W5(U,{dialect:Z}),Q;if(!$.full)if(Q=NQ(Y,Z),Q)t("-- Comparing with stored model snapshot");else{let G=n0(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)t("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!Q||$.fromDb)try{let W=await DQ(Z),F=new Set(_.tables.map((D)=>D.table)),R=W.tables.filter((D)=>F.has(D.table));if(R.length>0)Q={dialect:W.dialect,tables:R},t(`-- No snapshot; reconciling against live database (${R.length} matching table${R.length===1?"":"s"})`)}catch(W){t(`-- Could not introspect live database, treating as no previous state: ${W instanceof Error?W.message:String(W)}`)}if(!Q)t("-- No previous snapshot found, generating full migration")}else t("-- 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:""}))}:N7(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=qQ(n0(TQ(),"qb-migrate-")),J=n0(G,"migration.sql");try{if(V)MU(J,E),t("-- Migration applied");else t("-- No changes; nothing to apply")}catch(W){throw console.error("-- Migration failed:",W),W}}if(!$.dryRun)HU(Y,Z,_);return{sql:E,sqlStatements:z,hasChanges:V,plan:_,operations:j}}async function AQ(X){if(!X)X=n0(y$.cwd(),"app/Models");let $=YX(),Z=SQ($),Y=f.dialect||"postgres",_=KU(Z).filter((Q)=>Q.endsWith(".sql")).sort();if(_.length===0)return t("-- No migration files found to execute"),!0;t(`-- Found ${_.length} script files to execute`);try{let Q=H0();await BQ(Q,Y);let L=await yQ(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 t("-- No pending migrations to execute"),!0;t(`-- Executing ${E} migrations (${z.length} permanent, ${j.length} transient)`);for(let V of z){let G=n0(Z,V);t(`-- Executing: ${V}`);try{await Q.file(G),await hQ(Q,V,Y),t(`-- \u2713 Migration ${V} executed and recorded`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}for(let V of j){let G=n0(Z,V);t(`-- Executing: ${V} (transient)`);try{await Q.file(G),t(`-- \u2713 Migration ${V} executed (not recorded)`),C8(G),t(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${V}`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}t("-- All migrations executed successfully")}catch(Q){throw console.error("-- Migration execution failed:",Q),Q}return!0}async function kQ(X,$={}){if(!X)X=n0(y$.cwd(),"app/Models");let Z=$.dialect||"postgres",Y=ZX(Z),U=YX();try{let _=Y.dropTable("migrations");try{await dZ(async(z)=>{await z.unsafe(_).execute(),t("-- Dropped migrations table")})}catch(z){console.error(z)}let Q=[],L=[];try{let z=await pX({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)t("-- No tables found to drop");else{t(`-- Dropping ${Q.length} tables: ${Q.join(", ")}`);for(let z of Q.reverse())try{let j=Y.dropTable(z);await dZ(async(E)=>{await E.unsafe(j).execute(),t(`-- Dropped table: ${z}`)})}catch(j){console.error(j),t(`-- Table ${z} may not exist, skipping drop`)}}if(L.length>0){t(`-- Dropping ${L.length} enum types: ${L.join(", ")}`);for(let z of L)try{let j=Y.dropEnumType(z);if(j)await dZ(async(E)=>{await E.unsafe(j).execute(),t(`-- Dropped enum type: ${z}`)})}catch(j){console.error(j),t(`-- Enum type ${z} may not exist, skipping drop`)}}else t("-- No enum types found to drop");if(Q.length>0)try{await qU(X,U,$)}catch(z){console.error(z),t("-- Could not clean up migration files")}else t("-- No models directory found; keeping committed migration files in place");try{await PU(U)}catch(z){console.error(z),t("-- Could not clear generated directory")}return t("-- Database reset completed successfully"),!0}catch(_){return console.error("-- Database reset failed:",_),!1}}async function qU(X,$,Z={}){if(!X)X=n0(y$.cwd(),"app/Models");if(!$)$=YX();let Y=String(Z.dialect||"postgres"),U=U5($,Y);if(d9(U))C8(U),t(`-- Removed model snapshot file: ${U}`);let _=n0(X,`.qb-migrations.${Y}.json`),Q=String(Z.state||_);if(d9(Q))C8(Q),t(`-- Removed legacy migration state file: ${Q}`);let L=TU($);if(d9(L)){let j=KU(L).filter((E)=>E.endsWith(".sql"));for(let E of j){let V=n0(L,E);C8(V),t(`-- Removed migration file: ${E}`)}t(`-- Cleaned up ${j.length} migration files from migrations directory`)}}async function xQ(X,$){}async function PU(X){if(!X)X=YX();let $=n0(X,"generated");if(d9($))try{PQ($,{recursive:!0,force:!0}),t("-- Cleared generated directory")}catch(Z){console.error("-- Failed to clear generated directory:",Z)}}function TU(X){if(!X)X=YX();return n0(X,"database","migrations")}async function BQ(X,$){let Y=ZX($).createMigrationsTable();try{await X.unsafe(Y).execute(),t("-- Migrations table ready")}catch(U){throw console.error("-- Failed to create migrations table:",U),U}}async function yQ(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 hQ(X,$,Z){let Y=ZX(Z);try{t(`-- Recording migration: ${$}`),await X.unsafe(Y.recordMigrationQuery(),[$]).execute(),t(`-- Successfully recorded migration: ${$}`)}catch(U){throw console.error(`-- Failed to record migration ${$}:`,U),U}}var _5=e(()=>{c0(),$X(),QZ(),v0(),GU()});async function tG(X,$={}){return wU(X,$)}var vQ=e(()=>{_5()});function gQ(X){let $=[],Z="",Y=!1,_=X.split(`
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 JU;case"mysql":return new Y5;case"singlestore":return new WU;case"sqlite":return new IU;default:throw Error(`Unsupported dialect: ${X}`)}}var QZ=e(()=>{BY(),BY()}),RU={};i1(RU,{saveMigrationSnapshot:()=>CU,resetDatabase:()=>kQ,generateMigration:()=>wU,executeMigration:()=>AQ,deleteMigrationFiles:()=>qU,copyModelsToGenerated:()=>xQ,clearGeneratedDirectory:()=>PU});function t(X){if(f.verbose)console.log(X)}function _5(X,$){let Z=n0(X,".qb");return n0(Z,`model-snapshot.${$}.json`)}function NQ(X,$){let Z=_5(X,$);if(!v9(Z))return;try{let Y=U5(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;t("-- Invalid snapshot format, treating as no previous state");return}catch(Y){t(`-- Could not load snapshot, treating as no previous state: ${Y instanceof Error?Y.message:String(Y)}`);return}}function HU(X,$,Z){let Y=_5(X,$),U=n0(X,".qb"),_=Rj(Z);if(v9(Y))try{let L=JSON.parse(U5(Y,"utf8"));if(L?.hash===_&&L?.dialect===$&&L?.plan){t("-- Model snapshot unchanged");return}}catch{}if(!v9(U))KU(U,{recursive:!0}),t(`-- Created snapshot directory: ${U}`);let Q={plan:Z,hash:_,dialect:$,updatedAt:new Date().toISOString()};MU(Y,JSON.stringify(Q,null,2)),t(`-- Model snapshot saved to ${Y}`)}function CU(X,$={}){let Z=$.dialect??X.dialect;HU($.workspaceRoot??YX(),Z,X)}function YX(){return y$.cwd()}function SQ(X){let $=TU(X);if(!v9($))KU($,{recursive:!0}),t(`-- Created SQL directory: ${$}`);return $}async function wU(X,$={}){if(!X)X=n0(y$.cwd(),"app/Models");let Z=$.dialect||f.dialect||"postgres",Y=YX(),U=await pX({modelsDir:X}),_=V5(U,{dialect:Z}),Q;if(!$.full)if(Q=NQ(Y,Z),Q)t("-- Comparing with stored model snapshot");else{let G=n0(X,`.qb-migrations.${Z}.json`),J=String($.state||G);if(v9(J))try{let W=U5(J,"utf8"),F=JSON.parse(W);if(Q=F?.plan&&F.plan.tables?F.plan:F?.tables?F:void 0,Q)t("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!Q||$.fromDb)try{let W=await DQ(Z),F=new Set(_.tables.map((D)=>D.table)),R=W.tables.filter((D)=>F.has(D.table));if(R.length>0)Q={dialect:W.dialect,tables:R},t(`-- No snapshot; reconciling against live database (${R.length} matching table${R.length===1?"":"s"})`)}catch(W){t(`-- Could not introspect live database, treating as no previous state: ${W instanceof Error?W.message:String(W)}`)}if(!Q)t("-- No previous snapshot found, generating full migration")}else t("-- Full migration requested, ignoring any previous state");let L=$.full?{statements:I5(_,{dryRun:$.dryRun}),operations:_.tables.map((G)=>({kind:"create_table",table:G.table,destructive:!1,sql:""}))}:N7(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=qQ(n0(TQ(),"qb-migrate-")),J=n0(G,"migration.sql");try{if(V)MU(J,E),t("-- Migration applied");else t("-- No changes; nothing to apply")}catch(W){throw console.error("-- Migration failed:",W),W}}if(!$.dryRun)HU(Y,Z,_);return{sql:E,sqlStatements:z,hasChanges:V,plan:_,operations:j}}async function AQ(X){if(!X)X=n0(y$.cwd(),"app/Models");let $=YX(),Z=SQ($),Y=f.dialect||"postgres",_=DU(Z).filter((Q)=>Q.endsWith(".sql")).sort();if(_.length===0)return t("-- No migration files found to execute"),!0;t(`-- Found ${_.length} script files to execute`);try{let Q=H0();await BQ(Q,Y);let L=await yQ(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 t("-- No pending migrations to execute"),!0;t(`-- Executing ${E} migrations (${z.length} permanent, ${j.length} transient)`);for(let V of z){let G=n0(Z,V);t(`-- Executing: ${V}`);try{await Q.file(G),await hQ(Q,V,Y),t(`-- \u2713 Migration ${V} executed and recorded`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}for(let V of j){let G=n0(Z,V);t(`-- Executing: ${V} (transient)`);try{await Q.file(G),t(`-- \u2713 Migration ${V} executed (not recorded)`),C8(G),t(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${V}`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}t("-- All migrations executed successfully")}catch(Q){throw console.error("-- Migration execution failed:",Q),Q}return!0}async function kQ(X,$={}){if(!X)X=n0(y$.cwd(),"app/Models");let Z=$.dialect||"postgres",Y=ZX(Z),U=YX();try{let _=Y.dropTable("migrations");try{await dZ(async(z)=>{await z.unsafe(_).execute(),t("-- Dropped migrations table")})}catch(z){console.error(z)}let Q=[],L=[];try{let z=await pX({modelsDir:X}),j=V5(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)t("-- No tables found to drop");else{t(`-- Dropping ${Q.length} tables: ${Q.join(", ")}`);for(let z of Q.reverse())try{let j=Y.dropTable(z);await dZ(async(E)=>{await E.unsafe(j).execute(),t(`-- Dropped table: ${z}`)})}catch(j){console.error(j),t(`-- Table ${z} may not exist, skipping drop`)}}if(L.length>0){t(`-- Dropping ${L.length} enum types: ${L.join(", ")}`);for(let z of L)try{let j=Y.dropEnumType(z);if(j)await dZ(async(E)=>{await E.unsafe(j).execute(),t(`-- Dropped enum type: ${z}`)})}catch(j){console.error(j),t(`-- Enum type ${z} may not exist, skipping drop`)}}else t("-- No enum types found to drop");if(Q.length>0)try{await qU(X,U,$)}catch(z){console.error(z),t("-- Could not clean up migration files")}else t("-- No models directory found; keeping committed migration files in place");try{await PU(U)}catch(z){console.error(z),t("-- Could not clear generated directory")}return t("-- Database reset completed successfully"),!0}catch(_){return console.error("-- Database reset failed:",_),!1}}async function qU(X,$,Z={}){if(!X)X=n0(y$.cwd(),"app/Models");if(!$)$=YX();let Y=String(Z.dialect||"postgres"),U=_5($,Y);if(v9(U))C8(U),t(`-- Removed model snapshot file: ${U}`);let _=n0(X,`.qb-migrations.${Y}.json`),Q=String(Z.state||_);if(v9(Q))C8(Q),t(`-- Removed legacy migration state file: ${Q}`);let L=TU($);if(v9(L)){let j=DU(L).filter((E)=>E.endsWith(".sql"));for(let E of j){let V=n0(L,E);C8(V),t(`-- Removed migration file: ${E}`)}t(`-- Cleaned up ${j.length} migration files from migrations directory`)}}async function xQ(X,$){}async function PU(X){if(!X)X=YX();let $=n0(X,"generated");if(v9($))try{PQ($,{recursive:!0,force:!0}),t("-- Cleared generated directory")}catch(Z){console.error("-- Failed to clear generated directory:",Z)}}function TU(X){if(!X)X=YX();return n0(X,"database","migrations")}async function BQ(X,$){let Y=ZX($).createMigrationsTable();try{await X.unsafe(Y).execute(),t("-- Migrations table ready")}catch(U){throw console.error("-- Failed to create migrations table:",U),U}}async function yQ(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 hQ(X,$,Z){let Y=ZX(Z);try{t(`-- Recording migration: ${$}`),await X.unsafe(Y.recordMigrationQuery(),[$]).execute(),t(`-- Successfully recorded migration: ${$}`)}catch(U){throw console.error(`-- Failed to record migration ${$}:`,U),U}}var Q5=e(()=>{c0(),$X(),QZ(),v0(),FU()});async function tG(X,$={}){return wU(X,$)}var vQ=e(()=>{Q5()});function gQ(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 dQ(X,$=f.dialect){let Z=(_)=>I0($)?`\`${_}\``:`"${_}"`,Y=[],U=[];for(let _ of gQ(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(I0($)&&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 pQ(X){let $=X;while($!==BY($)){if(S1(Q5($,"package.json")))return $;$=BY($)}return NU.cwd()}function cQ(X){if(!X)X=pQ(NU.cwd());return Q5(X,"database","migrations")}async function ZF(X={}){let $=X.steps||1,Z=X.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let Y=H0(),U=[];try{U=await Y.unsafe(`
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 dQ(X,$=f.dialect){let Z=(_)=>I0($)?`\`${_}\``:`"${_}"`,Y=[],U=[];for(let _ of gQ(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(I0($)&&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 pQ(X){let $=X;while($!==yY($)){if(S1(z5($,"package.json")))return $;$=yY($)}return NU.cwd()}function cQ(X){if(!X)X=pQ(NU.cwd());return z5(X,"database","migrations")}async function ZF(X={}){let $=X.steps||1,Z=X.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let Y=H0(),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=cQ(),L=!1;for(let z of _)try{let j=Q5(Q,z.migration);if(Z&&S1(j)){let V=bQ(j,"utf8"),{down:G,skipped:J}=dQ(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}`),S1(j))fQ(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 mQ=e(()=>{c0(),v0()});function nQ(X){let $=X;while($!==yY($)){if(SU(AU($,"package.json")))return $;$=yY($)}return kU.cwd()}function iQ(X){if(!X)X=nQ(kU.cwd());return AU(X,"database","migrations")}async function lQ(){let X=f.dialect||"postgres",$=ZX(X),Z=iQ();if(console.log("-- Migration Status"),console.log(`-- Dialect: ${X}`),console.log(`-- SQL directory: ${Z}`),console.log(),!SU(Z))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let U=uQ(Z).filter((_)=>_.endsWith(".sql")).sort();if(U.length===0)return console.log("-- No migration files found"),[];try{let _=H0(),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 QF(){return lQ()}var sQ=e(()=>{c0(),QZ(),v0()});async function EF(X,$={}){let Z=$.dir||hY(rQ.cwd(),"app/Models");try{let Y=oQ(Z),U=Y.find((E)=>{return E.replace(pZ(E),"").toLowerCase()===X.toLowerCase()});if(!U){console.error(`Model "${X}" not found in ${Z}`),console.log(`Available models: ${Y.filter((E)=>[".ts",".js"].includes(pZ(E))).map((E)=>E.replace(pZ(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(`
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=cQ(),L=!1;for(let z of _)try{let j=z5(Q,z.migration);if(Z&&S1(j)){let V=bQ(j,"utf8"),{down:G,skipped:J}=dQ(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}`),S1(j))fQ(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 mQ=e(()=>{c0(),v0()});function nQ(X){let $=X;while($!==hY($)){if(SU(AU($,"package.json")))return $;$=hY($)}return kU.cwd()}function iQ(X){if(!X)X=nQ(kU.cwd());return AU(X,"database","migrations")}async function lQ(){let X=f.dialect||"postgres",$=ZX(X),Z=iQ();if(console.log("-- Migration Status"),console.log(`-- Dialect: ${X}`),console.log(`-- SQL directory: ${Z}`),console.log(),!SU(Z))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let U=uQ(Z).filter((_)=>_.endsWith(".sql")).sort();if(U.length===0)return console.log("-- No migration files found"),[];try{let _=H0(),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 QF(){return lQ()}var sQ=e(()=>{c0(),QZ(),v0()});async function EF(X,$={}){let Z=$.dir||vY(rQ.cwd(),"app/Models");try{let Y=oQ(Z),U=Y.find((E)=>{return E.replace(pZ(E),"").toLowerCase()===X.toLowerCase()});if(!U){console.error(`Model "${X}" not found in ${Z}`),console.log(`Available models: ${Y.filter((E)=>[".ts",".js"].includes(pZ(E))).map((E)=>E.replace(pZ(E),"")).join(", ")}`);return}let Q=await import(vY(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 aQ=()=>{};async function GF(){let $=await H0().ping();return console.log($?"OK":"NOT READY"),$}var tQ=e(()=>{v0()});async function JF(X,$={}){let Z=[];try{let Y=Xz(X),U=[];if(Y.isDirectory())U=eQ(X).filter((z)=>bY(z)===".sql").map((z)=>$z(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 c`EXPLAIN ${c.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}
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 aQ=()=>{};async function GF(){let $=await H0().ping();return console.log($?"OK":"NOT READY"),$}var tQ=e(()=>{v0()});async function JF(X,$={}){let Z=[];try{let Y=Xz(X),U=[];if(Y.isDirectory())U=eQ(X).filter((z)=>fY(z)===".sql").map((z)=>$z(X,z));else if(Y.isFile()&&fY(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=bY(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 c`EXPLAIN ${c.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:bY(L,"utf8").trim(),plan:[],error:z.message}),$.verbose)console.log(` \u2717 Error: ${z.message}
350
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 Zz=e(()=>{$X()});async function RF(X={}){let $=X.dir||Uz(_z.cwd(),"app/Models"),Z=X.format||"mermaid";try{let Y=await pX({modelsDir:$});if(!Y||Object.keys(Y).length===0)return console.error("No models found"),"";let U="";if(Z==="mermaid")U=Qz(Y);else if(Z==="dot")U=zz(Y);else return console.error(`Unsupported format: ${Z}`),"";if(X.output)Yz(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 Qz(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
351
  `)}function zz(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 Lz=e(()=>{v0()});function zZ(X){let $=X;while($!==fY($)){if(c8(m9($,"package.json")))return $;$=fY($)}return h$.cwd()}async function xU(X){if(!c8(X))return console.log(`-- Seeders directory not found: ${X}`),[];let Z=Ez(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 Fz(X={}){let $=zZ(h$.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 xU(Z);if(U.length===0){console.log("-- No seeders found");return}if(Y)console.log(`-- Found ${U.length} seeder(s)`);let _=H0();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 HF(X,$={}){let Z=zZ(h$.cwd()),Y=m9(Z,"database/seeders"),U=$.verbose??!0;if(U)console.log(`-- Running seeder: ${X}`);let Q=(await xU(Y)).find((z)=>z.name===X);if(!Q)throw console.error(`-- Seeder not found: ${X}`),Error(`Seeder not found: ${X}`);let L=H0();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 CF(X){let $=zZ(h$.cwd()),Z=m9($,"database/seeders");if(!c8(Z))jz(Z,{recursive:!0}),console.log(`-- Created seeders directory: ${Z}`);let U=`${X.replace(/Seeder$/i,"")}Seeder`,_=`${U}.ts`,Q=m9(Z,_);if(c8(Q))throw console.error(`-- Seeder already exists: ${Q}`),Error(`Seeder already exists: ${Q}`);let L=`import type { QueryBuilder } from 'bun-query-builder'
352
+ `)}var Lz=e(()=>{v0()});function zZ(X){let $=X;while($!==gY($)){if(c8(m9($,"package.json")))return $;$=gY($)}return h$.cwd()}async function xU(X){if(!c8(X))return console.log(`-- Seeders directory not found: ${X}`),[];let Z=Ez(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 Fz(X={}){let $=zZ(h$.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 xU(Z);if(U.length===0){console.log("-- No seeders found");return}if(Y)console.log(`-- Found ${U.length} seeder(s)`);let _=H0();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 HF(X,$={}){let Z=zZ(h$.cwd()),Y=m9(Z,"database/seeders"),U=$.verbose??!0;if(U)console.log(`-- Running seeder: ${X}`);let Q=(await xU(Y)).find((z)=>z.name===X);if(!Q)throw console.error(`-- Seeder not found: ${X}`),Error(`Seeder not found: ${X}`);let L=H0();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 CF(X){let $=zZ(h$.cwd()),Z=m9($,"database/seeders");if(!c8(Z))jz(Z,{recursive:!0}),console.log(`-- Created seeders directory: ${Z}`);let U=`${X.replace(/Seeder$/i,"")}Seeder`,_=`${U}.ts`,Q=m9(Z,_);if(c8(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
- `;Gz(Q,L),console.log(`-- \u2713 Created seeder: ${Q}`)}async function wF(X={}){let $=zZ(h$.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 Fz({seedersDir:Y,verbose:U}),U)console.log("-- \u2713 Database refreshed successfully")}catch(_){throw console.error("-- \u2717 Database refresh failed:",_),_}}var Oz=e(()=>{v0()});function qF(X,$,Z={}){let Y=pX({modelsDir:X}),U=M7(Y);if(f.debug)f.debug.captureText=!0;let _=H0({schema:U}),Q=_.selectFrom($).limit(Number(Z.limit||10)).toText?.()??"";return console.log(Q||"[query]"),{sql:Q,qb:_,schema:U}}var Jz=e(()=>{c0(),v0()});async function PF(X,$={}){let Z=H0(),Y=$.params?JSON.parse($.params):void 0,U=await Z.unsafe(X,Y);return console.log(JSON.stringify(U)),U}var Wz=e(()=>{v0()});function Iz(X){let $=X;while($!==gY($)){if(Vz(BU($,"package.json")))return $;$=gY($)}return yU.cwd()}async function Rz(X){if(!X)X=BU(Iz(yU.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 pX({modelsDir:X}),U=W5(Y,{dialect:$}),_=H0(),Q=[];if($==="sqlite")Q=(await _.unsafe(`
397
+ `;Gz(Q,L),console.log(`-- \u2713 Created seeder: ${Q}`)}async function wF(X={}){let $=zZ(h$.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(()=>(Q5(),RU));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 Fz({seedersDir:Y,verbose:U}),U)console.log("-- \u2713 Database refreshed successfully")}catch(_){throw console.error("-- \u2717 Database refresh failed:",_),_}}var Oz=e(()=>{v0()});function qF(X,$,Z={}){let Y=pX({modelsDir:X}),U=M7(Y);if(f.debug)f.debug.captureText=!0;let _=H0({schema:U}),Q=_.selectFrom($).limit(Number(Z.limit||10)).toText?.()??"";return console.log(Q||"[query]"),{sql:Q,qb:_,schema:U}}var Jz=e(()=>{c0(),v0()});async function PF(X,$={}){let Z=H0(),Y=$.params?JSON.parse($.params):void 0,U=await Z.unsafe(X,Y);return console.log(JSON.stringify(U)),U}var Wz=e(()=>{v0()});function Iz(X){let $=X;while($!==dY($)){if(Vz(BU($,"package.json")))return $;$=dY($)}return yU.cwd()}async function Rz(X){if(!X)X=BU(Iz(yU.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 pX({modelsDir:X}),U=V5(Y,{dialect:$}),_=H0(),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_%'
@@ -420,12 +420,12 @@ export default class ${U} extends Seeder {
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=(q)=>{return q.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},R=F(J.type),D=F(W.type);if(R!==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 AF(X){return Rz(X)}var Kz=e(()=>{c0(),_Z(),v0()});async function kF(X={}){let $=Number(X.attempts||10),Z=Number(X.delay||100),Y=H0();try{return await Y.waitForReady({attempts:$,delayMs:Z}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var Dz=e(()=>{v0()}),Mz=e(()=>{v_(),s_(),a_(),XQ(),ZQ(),YQ(),UQ(),_Q(),QQ(),LQ(),jQ(),GU(),wQ(),_5(),vQ(),mQ(),sQ(),aQ(),tQ(),Zz(),Lz(),Oz(),Jz(),Wz(),Kz(),Dz()});function iz(X,$){this[X]=IL.bind(null,$)}class k1{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 x1{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 lz(X,$={}){let Z=Object.keys($).sort().map((Y)=>`${Y}:${$[Y]}`).join("|");return Z?`${X}:${Z}`:X}function sz(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function oz(X){return X.getStats().size*2}function rz(X,$={}){let Z=m8.cwd();while(Z.includes("storage"))Z=cY(Z,"..");let Y=cY(Z,X||"");if($?.relative)return Pz(m8.cwd(),Y);return Y}function y0(){if(A9.env.NODE_ENV==="test"||A9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function az(){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 vU{async format(X){let $=await az(),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:HX.pid,hostname:$(),environment:HX.env.NODE_ENV||"development",platform:HX.platform,version:HX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:HX.env.NODE_ENV||HX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class u8{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={...C$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new vU,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??W0.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{...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:C$.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!y0()&&this.config.writeToFile===!0}async writeToFile(X){let $=(async()=>{let Y,U=0,_=3,Q=1000;while(U<_)try{try{try{await kz(this.config.logDirectory,iY.F_OK|iY.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await xz(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(!Y8(this.currentLogFile))await uZ(this.currentLogFile,"",{mode:420});if(Y=nY(this.currentLogFile,"a",420),Az(Y,L,{flag:"a"}),uY(Y),Y!==void 0)mZ(Y),Y=void 0;if((await DX(this.currentLogFile)).size===0){if(await uZ(this.currentLogFile,L,{flag:"w",mode:420}),(await DX(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{mZ(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 MX(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 MX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return MX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(y0())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 cZ(16).toString("hex")}generateKey(){return cZ(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=cZ(16),Y=Tz("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(y0())return;if(!this.shouldWriteToFile())return;let X=await DX(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 U8(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 DX(Z).catch(()=>null))try{if(await lY(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await _8(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 uZ(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 DX(Z).catch(()=>null))await lY(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let U=(await U8(this.config.logDirectory)).filter((_)=>_.startsWith(this.name)).sort((_,Q)=>Q.localeCompare(_));for(let _ of U.slice($.maxFiles))await _8(MX(this.config.logDirectory,_))}}}async compressLogFile(X,$){let Z=mY(X),Y=Sz($),U=sY();await hz(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()})),Y8(this.currentLogFile))try{let X=nY(this.currentLogFile,"r+");uY(X),mZ(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(!y0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await U8(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await _8(MX(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()?J0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||y0())return!1;let X=typeof W0.env.NO_COLOR<"u",$=W0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof W0.stderr<"u"&&W0.stderr.isTTY||typeof W0.stdout<"u"&&W0.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=W0.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(y0())return!1;let X=W0.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=W0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(Bz($)||$.startsWith("./")||$.startsWith("../"))$=yz($);else return null;return Y8($)?$: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?"":lU[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(`
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=(q)=>{return q.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},R=F(J.type),D=F(W.type);if(R!==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 AF(X){return Rz(X)}var Kz=e(()=>{c0(),_Z(),v0()});async function kF(X={}){let $=Number(X.attempts||10),Z=Number(X.delay||100),Y=H0();try{return await Y.waitForReady({attempts:$,delayMs:Z}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var Dz=e(()=>{v0()}),Mz=e(()=>{v_(),s_(),a_(),XQ(),ZQ(),YQ(),UQ(),_Q(),QQ(),LQ(),jQ(),FU(),wQ(),Q5(),vQ(),mQ(),sQ(),aQ(),tQ(),Zz(),Lz(),Oz(),Jz(),Wz(),Kz(),Dz()});function iz(X,$){this[X]=IL.bind(null,$)}class k1{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(!pY(X))return!0;return cY(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=pY(Z)?cY(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 x1{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 lz(X,$={}){let Z=Object.keys($).sort().map((Y)=>`${Y}:${$[Y]}`).join("|");return Z?`${X}:${Z}`:X}function sz(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function oz(X){return X.getStats().size*2}function rz(X,$={}){let Z=m8.cwd();while(Z.includes("storage"))Z=mY(Z,"..");let Y=mY(Z,X||"");if($?.relative)return Pz(m8.cwd(),Y);return Y}function y0(){if(A9.env.NODE_ENV==="test"||A9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function az(){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 vU{async format(X){let $=await az(),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:HX.pid,hostname:$(),environment:HX.env.NODE_ENV||"development",platform:HX.platform,version:HX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:HX.env.NODE_ENV||HX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class u8{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={...C$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new vU,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??W0.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{...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:C$.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!y0()&&this.config.writeToFile===!0}async writeToFile(X){let $=(async()=>{let Y,U=0,_=3,Q=1000;while(U<_)try{try{try{await kz(this.config.logDirectory,lY.F_OK|lY.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await xz(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(!Y8(this.currentLogFile))await uZ(this.currentLogFile,"",{mode:420});if(Y=iY(this.currentLogFile,"a",420),Az(Y,L,{flag:"a"}),nY(Y),Y!==void 0)mZ(Y),Y=void 0;if((await DX(this.currentLogFile)).size===0){if(await uZ(this.currentLogFile,L,{flag:"w",mode:420}),(await DX(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{mZ(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 MX(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 MX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return MX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(y0())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 cZ(16).toString("hex")}generateKey(){return cZ(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=cZ(16),Y=Tz("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=oY(),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(y0())return;if(!this.shouldWriteToFile())return;let X=await DX(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 U8(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 DX(Z).catch(()=>null))try{if(await sY(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await _8(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 uZ(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 DX(Z).catch(()=>null))await sY(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let U=(await U8(this.config.logDirectory)).filter((_)=>_.startsWith(this.name)).sort((_,Q)=>Q.localeCompare(_));for(let _ of U.slice($.maxFiles))await _8(MX(this.config.logDirectory,_))}}}async compressLogFile(X,$){let Z=uY(X),Y=Sz($),U=oY();await hz(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()})),Y8(this.currentLogFile))try{let X=iY(this.currentLogFile,"r+");nY(X),mZ(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(!y0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await U8(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await _8(MX(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()?J0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||y0())return!1;let X=typeof W0.env.NO_COLOR<"u",$=W0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof W0.stderr<"u"&&W0.stderr.isTTY||typeof W0.stdout<"u"&&W0.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=W0.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(y0())return!1;let X=W0.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=W0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(Bz($)||$.startsWith("./")||$.startsWith("../"))$=yz($);else return null;return Y8($)?$: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?"":lU[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(`
424
424
  `);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:J0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!y0()){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
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()&&!y0()&&W0.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()&&!y0()&&W0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,_="info")=>{if(!y0()&&W0.stdout.isTTY)W0.stdout.write(`
427
427
  `);if(this[_==="warning"?"warn":_](U),this.activeProgressBar&&this.shouldStyleConsole()&&!y0()&&W0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?J0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":J0.blue("\u25D0"),tag:Z,message:`${J0.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?J0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":J0.green("\u2713"),tag:j,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!y0())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 u8($,{...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(y0())throw Error("createReadStream is not supported in browser environments");if(!Y8(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=Nz("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 y0()}isServerMode(){return!y0()}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(`
428
+ `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?J0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":J0.green("\u2713"),tag:j,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!y0())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 u8($,{...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(y0())throw Error("createReadStream is not supported in browser environments");if(!Y8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uY(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=Nz("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 y0()}isServerMode(){return!y0()}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
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:J0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:J0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:J0.cyan(E),showTimestamp:!1}))}else if(!y0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
430
430
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(y0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${J0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();W0.stdin.removeListener("data",Z);try{if(typeof W0.stdin.setRawMode==="function")W0.stdin.setRawMode(!1)}catch{}W0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof W0.stdin.setRawMode==="function")W0.stdin.setRawMode(!0)}catch{}W0.stdin.resume(),W0.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?J0.gray(this.formatTag(this.name)):"",L=this.options.showIcons===!1?"":`${J0.blue("\u25D0")} `;console.error(`${L}${Q} ${J0.cyan(Y)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
431
431
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!W0.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,_=J0.green("\u2501".repeat(Y)),Q=J0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?J0.green("\u2713"):J0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${J0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=W0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,W0.stdout.write(X.lastRenderedLine),$)W0.stdout.write(`
@@ -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 XL(X,$){let Z=iU("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function gU(X,$,Z={}){return dU(X,$,Z,new WeakMap)}function dU(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 pU(X,$,U,Y);if(!O9($)||!O9(X))return $;return UL(X,$,Z,Y)}function pU(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 $L(X,$);case"smart":return ZL(X,$,Y);default:return $}return $}function $L(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>B1(U,Y)))Z.push(Y);return Z}function ZL(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(O9($[0])&&O9(X[0]))return YL(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 YL(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 UL(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]=dU(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=pU(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function z5(X,$,Z="replace"){return gU(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function B1(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(!B1(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(!B1(X[U],$[U]))return!1}return!0}return!1}function O9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class jZ{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=bX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!z8(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 w$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new w$(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)bX.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 B$.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(nZ($,`${_}${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 bU(async()=>{return z8(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!z8(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=nZ(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=nZ(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(!z8(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 B$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!vz($))throw new q$($,[{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 q$($,[{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:sU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function _L(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 y1{fileLoader=new jZ;envProcessor=new LZ;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(o0(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}"${_L(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?tX(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=_?tX(X,Z,U):Z,L=[o0(CX(),".config",X),o0(CX(),".config"),CX()];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?tX(X,Y,_):Y;try{let z=o0(Z,"package.json");if(!A1(z))return null;let j={};try{j=JSON.parse(gz(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:tX(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 bX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);bX.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,o0(X,"config"),o0(X,".config"),$?o0(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(o0(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=[o0(CX(),".config",X),o0(CX(),".config"),CX()],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 QL(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 zL(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 LL(X,$,Z="replace"){let Y=new jZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function tX(X,$,Z=!1){let Y=new LZ,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 jL(X){let $=o0(XX.cwd(),X.configDir),Z=o0(XX.cwd(),X.generatedDir),Y=o0(Z,"config-types.ts");if(!A1(oY(Y)))bz(oY(Y),{recursive:!0,mode:511});let U=A1($)?fz($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${xL}
444
+ `;return Z}}function XL(X,$){let Z=iU("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function gU(X,$,Z={}){return dU(X,$,Z,new WeakMap)}function dU(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 pU(X,$,U,Y);if(!O9($)||!O9(X))return $;return UL(X,$,Z,Y)}function pU(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 $L(X,$);case"smart":return ZL(X,$,Y);default:return $}return $}function $L(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>B1(U,Y)))Z.push(Y);return Z}function ZL(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(O9($[0])&&O9(X[0]))return YL(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 YL(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 UL(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]=dU(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=pU(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function L5(X,$,Z="replace"){return gU(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function B1(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(!B1(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(!B1(X[U],$[U]))return!1}return!0}return!1}function O9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class jZ{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=bX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!z8(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 w$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new w$(X,Error("Configuration must export a valid object"),"unknown");let W={config:L5($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)bX.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 B$.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(nZ($,`${_}${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 bU(async()=>{return z8(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!z8(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=nZ(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=nZ(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(!z8(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 j5{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 B$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!vz($))throw new q$($,[{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 q$($,[{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:sU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function _L(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 y1{fileLoader=new jZ;envProcessor=new LZ;validator=new j5;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(o0(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}"${_L(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?tX(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=_?tX(X,Z,U):Z,L=[o0(CX(),".config",X),o0(CX(),".config"),CX()];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?tX(X,Y,_):Y;try{let z=o0(Z,"package.json");if(!A1(z))return null;let j={};try{j=JSON.parse(gz(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:L5(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:tX(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 bX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);bX.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,o0(X,"config"),o0(X,".config"),$?o0(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(o0(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=[o0(CX(),".config",X),o0(CX(),".config"),CX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function tY(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 QL(X){return x9.loadConfig({...X,__strictErrorHandling:!0})}async function E5(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 zL(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"&&tY(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"&&tY($)))return(await x9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function LL(X,$,Z="replace"){let Y=new jZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function tX(X,$,Z=!1){let Y=new LZ,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 jL(X){let $=o0(XX.cwd(),X.configDir),Z=o0(XX.cwd(),X.generatedDir),Y=o0(Z,"config-types.ts");if(!A1(rY(Y)))bz(rY(Y),{recursive:!0,mode:511});let U=A1($)?fz($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${xL}
445
445
  export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
446
- `;dz(Y,_,{mode:438})}function EL(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 GL(X){let $=rY(mz.cwd(),X?.configDir||"./config");function Z(){if(!pz($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=cz($).filter((z)=>U.has(iZ(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=iZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=iZ(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(`,
446
+ `;dz(Y,_,{mode:438})}function EL(X){let $=null,Z=null,Y=()=>{if(!Z)Z=E5(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 GL(X){let $=aY(mz.cwd(),X?.configDir||"./config");function Z(){if(!pz($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=cz($).filter((z)=>U.has(iZ(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=iZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=iZ(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=aY($,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 FL(){if(!z1)z1=await j5({name:"faker",alias:"mock",defaultConfig:$Z});return z1}function AX(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 OL(X){let $=AX(X);if($.region)return[$.normalized,$.language];return[$.language]}function JL(X){return`@mock-locale/${AX(X).packageName}`}function cU(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]=cU(_,U);else Z[Y]=U}return Z}function kX(){let X=hU.cwd(),$=SX(X,"package.json");if(!NX($))return!1;try{let Z=JSON.parse(nz($,"utf-8"));return!!(Z.workspaces||Z.workspace)}catch{return!1}}function mU(){let X=hU.cwd();if(NX(SX(X,"bun.lockb"))||NX(SX(X,"bun.lock")))return"bun";if(NX(SX(X,"pnpm-lock.yaml")))return"pnpm";if(NX(SX(X,"yarn.lock")))return"yarn";if(NX(SX(X,"package-lock.json")))return"npm";return"bun"}function uU(X,$={}){let Z=mU(),{silent:Y=!1}=$;if(!Y)console.log(`
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 FL(){if(!z1)z1=await E5({name:"faker",alias:"mock",defaultConfig:$Z});return z1}function AX(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 OL(X){let $=AX(X);if($.region)return[$.normalized,$.language];return[$.language]}function JL(X){return`@mock-locale/${AX(X).packageName}`}function cU(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]=cU(_,U);else Z[Y]=U}return Z}function kX(){let X=hU.cwd(),$=SX(X,"package.json");if(!NX($))return!1;try{let Z=JSON.parse(nz($,"utf-8"));return!!(Z.workspaces||Z.workspace)}catch{return!1}}function mU(){let X=hU.cwd();if(NX(SX(X,"bun.lockb"))||NX(SX(X,"bun.lock")))return"bun";if(NX(SX(X,"pnpm-lock.yaml")))return"pnpm";if(NX(SX(X,"yarn.lock")))return"yarn";if(NX(SX(X,"package-lock.json")))return"npm";return"bun"}function uU(X,$={}){let Z=mU(),{silent:Y=!1}=$;if(!Y)console.log(`
454
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=uz(_,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.`),kX())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 k$(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 x$(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 WL(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 VL(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 Q${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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({city:$,country:X?.constraints?.country},X.relationships).city||$;if(X?.validation){let Z=k$($,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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({country:$},X.relationships).country||$;if(X?.validation){let Z=k$($,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 z${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 L${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 j${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 E${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 G${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 n8{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 i8{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 l8{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 F${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 s8{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 O${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 o8{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 r8{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 J${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(eU),_=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 a8{random;constructor(X){this.random=X}word(){return this.random.arrayElement(X7)}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,$=`
455
+ \u26A0\uFE0F Package ${X} is already available in the workspace and cannot be installed separately due to a dependency loop.`),kX())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 k$(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 x$(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 WL(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 VL(X,$={}){let Z=X();if($.relationships)return p9(Z,$.relationships);return Z}class G5{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 Q${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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({city:$,country:X?.constraints?.country},X.relationships).city||$;if(X?.validation){let Z=k$($,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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({country:$},X.relationships).country||$;if(X?.validation){let Z=k$($,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 z${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 L${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 j${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 E${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 G${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 n8{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 i8{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 l8{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 F${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 s8{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 O${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 o8{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 r8{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 J${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(eU),_=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 a8{random;constructor(X){this.random=X}word(){return this.random.arrayElement(X7)}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 W${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 t8{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 V${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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({firstName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).firstName||$;if(X?.validation){let Z=k$($,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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({fullName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).fullName||$;if(X?.validation){let Z=k$($,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 I${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 R${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 e8{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 D${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 M${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($7)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(Z7)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(Y7)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(U7)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(_7)}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 H${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 XZ{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==="?")$+=v1[Math.floor(Math.random()*26)];else $+=Y}return $}return X.replace(/[#?]/g,($)=>{if($==="#")return String(this.int(0,9));return this.arrayElement(v1)})}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 EZ{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 XZ(Z),this.person=new V$(this.random,this._locale),this.address=new Q$(this.random,this._locale),this.internet=new J$(this.random,this._locale),this.phone=new I$(this.random,this._locale),this.company=new G$(this.random,this._locale),this.lorem=new a8(this.random),this.date=new i8(this.random),this.number=new t8(this.random),this.string=new e8(this.random),this.color=new j$(this.random,this._locale),this.finance=new l8(this.random),this.helpers=new o8(this.random),this.image=new r8(this.random),this.git=new s8(this.random),this.science=new R$(this.random,this._locale),this.music=new W$(this.random,this._locale),this.database=new n8(this.random),this.food=new F$(this.random,this._locale),this.commerce=new E$(this.random,this._locale),this.book=new L$(this.random,this._locale),this.animal=new z$(this.random,this._locale),this.sport=new K$(this.random,this._locale),this.hacker=new O$(this.random,this._locale),this.system=new D$(this.random,this._locale),this.word=new H$(this.random,this._locale),this.vehicle=new M$(this.random,this._locale)}static async create(X){let $=X?.locale??"en";return await Y9.load($),new EZ(X)}seed(X){return this.random=new XZ(X),Object.assign(this.person,new V$(this.random,this._locale)),Object.assign(this.address,new Q$(this.random,this._locale)),Object.assign(this.internet,new J$(this.random,this._locale)),Object.assign(this.phone,new I$(this.random,this._locale)),Object.assign(this.company,new G$(this.random,this._locale)),Object.assign(this.lorem,new a8(this.random)),Object.assign(this.date,new i8(this.random)),Object.assign(this.number,new t8(this.random)),Object.assign(this.string,new e8(this.random)),Object.assign(this.color,new j$(this.random,this._locale)),Object.assign(this.finance,new l8(this.random)),Object.assign(this.helpers,new o8(this.random)),Object.assign(this.image,new r8(this.random)),Object.assign(this.git,new s8(this.random)),Object.assign(this.science,new R$(this.random,this._locale)),Object.assign(this.music,new W$(this.random,this._locale)),Object.assign(this.database,new n8(this.random)),Object.assign(this.food,new F$(this.random,this._locale)),Object.assign(this.commerce,new E$(this.random,this._locale)),Object.assign(this.book,new L$(this.random,this._locale)),Object.assign(this.animal,new z$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.hacker,new O$(this.random,this._locale)),Object.assign(this.system,new D$(this.random,this._locale)),Object.assign(this.word,new H$(this.random,this._locale)),Object.assign(this.vehicle,new M$(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 V$(this.random,this._locale)),Object.assign(this.address,new Q$(this.random,this._locale)),Object.assign(this.internet,new J$(this.random,this._locale)),Object.assign(this.phone,new I$(this.random,this._locale)),Object.assign(this.company,new G$(this.random,this._locale)),Object.assign(this.food,new F$(this.random,this._locale)),Object.assign(this.animal,new z$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.music,new W$(this.random,this._locale)),Object.assign(this.commerce,new E$(this.random,this._locale)),Object.assign(this.book,new L$(this.random,this._locale)),Object.assign(this.vehicle,new M$(this.random,this._locale)),Object.assign(this.word,new H$(this.random,this._locale)),Object.assign(this.hacker,new O$(this.random,this._locale)),Object.assign(this.system,new D$(this.random,this._locale)),Object.assign(this.color,new j$(this.random,this._locale)),Object.assign(this.science,new R$(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 nU,IL=(X)=>X,RL=(X,$)=>{for(var Z in $)nU(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:iz.bind($,Z)})},C9=(X,$)=>()=>(X&&($=X(X=0)),$),iU,bX,B$,tY,wX,eY,lZ,C$,KL,h0,J0,DL,X6,ML,$6,HL,CL,sZ,wL,Z6,Y6,qL,oZ,PL,TL,NL,SL,AL,w8,lU,kL,U6,xL="0.15.9",BL=()=>{},Z9,q8,w$,rZ,aZ,P8,tZ,eZ,q$,X1,$1,u9,n9,Z1,_6,L8,Y1,sU,U1,j9,x9,Q6,z6,L6,yL=()=>{},_1,Q1,$Z,z1=null,h1,iX,z9,qX,Y9,oU,rU,aU,tU,eU,X7,$7,Z7,Y7,U7,_7,v1,b1,Q7,hL=e(()=>{nU=Object.defineProperty,iU=import.meta.require,wX=C9(()=>{bX=new k1,B$=new x1,tY={createKey:lz,isEquivalent:sz,estimateMemoryUsage:oz}}),U6=C9(()=>{eY=m8.env.CLARITY_LOG_DIR||qz(rz(),"logs"),lZ={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},C$={...lZ},KL=(async()=>{try{let{loadConfig:X}=await Promise.resolve().then(()=>(Q1(),_1)),$=await X({name:"clarity",alias:"logging",defaultConfig:lZ,cwd:m8.cwd()});if($)Object.assign(C$,$)}catch{}return C$})(),h0={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=h0,DL=h0.red,X6=h0.green,ML=h0.yellow,$6=h0.blue,HL=h0.magenta,CL=h0.cyan,sZ=h0.white,wL=h0.gray,Z6=h0.bgRed,Y6=h0.bgYellow,qL=h0.bgGray,oZ=h0.bold,PL=h0.dim,TL=h0.italic,NL=h0.underline,SL=h0.strikethrough,AL=h0.reset,w8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lU={debug:"\uD83D\uDD0D",info:$6("\u2139"),success:X6("\u2713"),warning:Y6(sZ(oZ(" WARN "))),error:Z6(sZ(oZ(" ERROR ")))},kL=new u8("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}`}},q8=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})}},w$=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=$}},rZ=class extends Z9{code="CONFIG_VALIDATION_ERROR";constructor(X,$,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},aZ=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}},P8=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})}},tZ=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}},eZ=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}},q$=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})}},X1=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})}},$1=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 q8(X,$,Z)},configLoad(X,$,Z){return new w$(X,$,Z)},configValidation(X,$,Z){return new rZ(X,$,Z)},configMerge(X,$,Z,Y){return new aZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new P8(X,$,Z,Y)},fileSystem(X,$,Z){return new tZ(X,$,Z)},typeGeneration(X,$,Z){return new eZ(X,$,Z)},schemaValidation(X,$,Z){return new q$(X,$,Z)},browserConfig(X,$,Z,Y){return new X1(X,$,Z,Y)},plugin(X,$,Z){return new $1(X,$,Z)}}}),Z1=C9(()=>{wX(),n9()}),L8=C9(()=>{_6={replace:"replace",concat:"concat",smart:"smart"}}),Y1=C9(()=>{wX(),n9(),L8()}),U1=C9(()=>{wX(),n9(),sU=/^https?:\/\//}),L6=C9(()=>{U6(),BL(),wX(),n9(),Z1(),Y1(),U1(),L8(),j9=new u8("bunfig",{showTags:!0}),x9=new y1,Q6=o0(XX.cwd(),"config"),z6=o0(XX.cwd(),"src/generated")}),_1={},RL(_1,{withErrorRecovery:()=>bU,tryLoadConfig:()=>LL,loadConfigWithResult:()=>QL,loadConfig:()=>j5,isRetryableError:()=>ez,isConfigNotFoundError:()=>tz,isBunfigError:()=>fU,globalPerformanceMonitor:()=>B$,globalCache:()=>bX,getEnvOrDefault:()=>XL,generateConfigTypes:()=>jL,defaultGeneratedDir:()=>z6,defaultConfigDir:()=>Q6,deepMergeWithArrayStrategy:()=>z5,deepMerge:()=>gU,createLibraryConfig:()=>EL,config:()=>zL,bunfigPlugin:()=>GL,applyEnvVarsToConfig:()=>tX,TypeGenerationError:()=>eZ,SchemaValidationError:()=>q$,PluginError:()=>$1,PerformanceMonitor:()=>x1,FileSystemError:()=>tZ,ErrorFactory:()=>u9,EnvVarError:()=>P8,EnvProcessor:()=>LZ,ConfigValidator:()=>L5,ConfigValidationError:()=>rZ,ConfigNotFoundError:()=>q8,ConfigMergeError:()=>aZ,ConfigLoader:()=>y1,ConfigLoadError:()=>w$,ConfigFileLoader:()=>jZ,ConfigCache:()=>k1,CacheUtils:()=>tY,BunfigError:()=>Z9,BrowserConfigError:()=>X1,ArrayMergeStrategies:()=>_6}),Q1=C9(()=>{L6(),n9(),wX(),n9(),yL(),Z1(),Y1(),U1(),L8()}),Q1(),$Z={verbose:!1,locale:"en",autoInstallLocales:!1},h1=$Z,iX={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,qX=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=AX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",iX);return iX}if(z9.has(Z))return z9.get(Z);if(qX.has(Z))return qX.get(Z);let Y=this.loadLocaleWithFallback(Z);qX.set(Z,Y);try{let U=await Y;return z9.set(Z,U),U}finally{qX.delete(Z)}}static loadSync($){let Z=AX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",iX);return iX}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=AX($).normalized;return z9.has(Z)}static async preload($){await Promise.all($.map((Z)=>this.load(Z)))}static clearCache(){z9.clear(),qX.clear()}static async loadLocaleWithFallback($){let Z=OL($);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 cU(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(!kX())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=wz.cwd(),U=Cz(Y,"packages",Z.packageName,"dist","index.js");if(!Hz(U))return null;let _=await import(`file://${U}`);return _[Z.normalized]||_[Z.language]||_.default}catch{return null}}}static async loadLocaleModule($){let Z=JL($),Y=AX($);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(kX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}if(h1.autoInstallLocales)if(console.log(`
458
+ `)}}class W${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 t8{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 V${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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({firstName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).firstName||$;if(X?.validation){let Z=k$($,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)$=x$(this.random,X.weighted);if(X?.relationships)$=p9({fullName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).fullName||$;if(X?.validation){let Z=k$($,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 I${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 R${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 e8{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 D${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 M${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($7)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(Z7)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(Y7)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(U7)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(_7)}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 H${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 XZ{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==="?")$+=v1[Math.floor(Math.random()*26)];else $+=Y}return $}return X.replace(/[#?]/g,($)=>{if($==="#")return String(this.int(0,9));return this.arrayElement(v1)})}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 EZ{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 XZ(Z),this.person=new V$(this.random,this._locale),this.address=new Q$(this.random,this._locale),this.internet=new J$(this.random,this._locale),this.phone=new I$(this.random,this._locale),this.company=new G$(this.random,this._locale),this.lorem=new a8(this.random),this.date=new i8(this.random),this.number=new t8(this.random),this.string=new e8(this.random),this.color=new j$(this.random,this._locale),this.finance=new l8(this.random),this.helpers=new o8(this.random),this.image=new r8(this.random),this.git=new s8(this.random),this.science=new R$(this.random,this._locale),this.music=new W$(this.random,this._locale),this.database=new n8(this.random),this.food=new F$(this.random,this._locale),this.commerce=new E$(this.random,this._locale),this.book=new L$(this.random,this._locale),this.animal=new z$(this.random,this._locale),this.sport=new K$(this.random,this._locale),this.hacker=new O$(this.random,this._locale),this.system=new D$(this.random,this._locale),this.word=new H$(this.random,this._locale),this.vehicle=new M$(this.random,this._locale)}static async create(X){let $=X?.locale??"en";return await Y9.load($),new EZ(X)}seed(X){return this.random=new XZ(X),Object.assign(this.person,new V$(this.random,this._locale)),Object.assign(this.address,new Q$(this.random,this._locale)),Object.assign(this.internet,new J$(this.random,this._locale)),Object.assign(this.phone,new I$(this.random,this._locale)),Object.assign(this.company,new G$(this.random,this._locale)),Object.assign(this.lorem,new a8(this.random)),Object.assign(this.date,new i8(this.random)),Object.assign(this.number,new t8(this.random)),Object.assign(this.string,new e8(this.random)),Object.assign(this.color,new j$(this.random,this._locale)),Object.assign(this.finance,new l8(this.random)),Object.assign(this.helpers,new o8(this.random)),Object.assign(this.image,new r8(this.random)),Object.assign(this.git,new s8(this.random)),Object.assign(this.science,new R$(this.random,this._locale)),Object.assign(this.music,new W$(this.random,this._locale)),Object.assign(this.database,new n8(this.random)),Object.assign(this.food,new F$(this.random,this._locale)),Object.assign(this.commerce,new E$(this.random,this._locale)),Object.assign(this.book,new L$(this.random,this._locale)),Object.assign(this.animal,new z$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.hacker,new O$(this.random,this._locale)),Object.assign(this.system,new D$(this.random,this._locale)),Object.assign(this.word,new H$(this.random,this._locale)),Object.assign(this.vehicle,new M$(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 V$(this.random,this._locale)),Object.assign(this.address,new Q$(this.random,this._locale)),Object.assign(this.internet,new J$(this.random,this._locale)),Object.assign(this.phone,new I$(this.random,this._locale)),Object.assign(this.company,new G$(this.random,this._locale)),Object.assign(this.food,new F$(this.random,this._locale)),Object.assign(this.animal,new z$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.music,new W$(this.random,this._locale)),Object.assign(this.commerce,new E$(this.random,this._locale)),Object.assign(this.book,new L$(this.random,this._locale)),Object.assign(this.vehicle,new M$(this.random,this._locale)),Object.assign(this.word,new H$(this.random,this._locale)),Object.assign(this.hacker,new O$(this.random,this._locale)),Object.assign(this.system,new D$(this.random,this._locale)),Object.assign(this.color,new j$(this.random,this._locale)),Object.assign(this.science,new R$(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 nU,IL=(X)=>X,RL=(X,$)=>{for(var Z in $)nU(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:iz.bind($,Z)})},C9=(X,$)=>()=>(X&&($=X(X=0)),$),iU,bX,B$,eY,wX,X6,lZ,C$,KL,h0,J0,DL,$6,ML,Z6,HL,CL,sZ,wL,Y6,U6,qL,oZ,PL,TL,NL,SL,AL,w8,lU,kL,_6,xL="0.15.9",BL=()=>{},Z9,q8,w$,rZ,aZ,P8,tZ,eZ,q$,X1,$1,u9,n9,Z1,Q6,L8,Y1,sU,U1,j9,x9,z6,L6,j6,yL=()=>{},_1,Q1,$Z,z1=null,h1,iX,z9,qX,Y9,oU,rU,aU,tU,eU,X7,$7,Z7,Y7,U7,_7,v1,b1,Q7,hL=e(()=>{nU=Object.defineProperty,iU=import.meta.require,wX=C9(()=>{bX=new k1,B$=new x1,eY={createKey:lz,isEquivalent:sz,estimateMemoryUsage:oz}}),_6=C9(()=>{X6=m8.env.CLARITY_LOG_DIR||qz(rz(),"logs"),lZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:X6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},C$={...lZ},KL=(async()=>{try{let{loadConfig:X}=await Promise.resolve().then(()=>(Q1(),_1)),$=await X({name:"clarity",alias:"logging",defaultConfig:lZ,cwd:m8.cwd()});if($)Object.assign(C$,$)}catch{}return C$})(),h0={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=h0,DL=h0.red,$6=h0.green,ML=h0.yellow,Z6=h0.blue,HL=h0.magenta,CL=h0.cyan,sZ=h0.white,wL=h0.gray,Y6=h0.bgRed,U6=h0.bgYellow,qL=h0.bgGray,oZ=h0.bold,PL=h0.dim,TL=h0.italic,NL=h0.underline,SL=h0.strikethrough,AL=h0.reset,w8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lU={debug:"\uD83D\uDD0D",info:Z6("\u2139"),success:$6("\u2713"),warning:U6(sZ(oZ(" WARN "))),error:Y6(sZ(oZ(" ERROR ")))},kL=new u8("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}`}},q8=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})}},w$=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=$}},rZ=class extends Z9{code="CONFIG_VALIDATION_ERROR";constructor(X,$,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},aZ=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}},P8=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})}},tZ=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}},eZ=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}},q$=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})}},X1=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})}},$1=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 q8(X,$,Z)},configLoad(X,$,Z){return new w$(X,$,Z)},configValidation(X,$,Z){return new rZ(X,$,Z)},configMerge(X,$,Z,Y){return new aZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new P8(X,$,Z,Y)},fileSystem(X,$,Z){return new tZ(X,$,Z)},typeGeneration(X,$,Z){return new eZ(X,$,Z)},schemaValidation(X,$,Z){return new q$(X,$,Z)},browserConfig(X,$,Z,Y){return new X1(X,$,Z,Y)},plugin(X,$,Z){return new $1(X,$,Z)}}}),Z1=C9(()=>{wX(),n9()}),L8=C9(()=>{Q6={replace:"replace",concat:"concat",smart:"smart"}}),Y1=C9(()=>{wX(),n9(),L8()}),U1=C9(()=>{wX(),n9(),sU=/^https?:\/\//}),j6=C9(()=>{_6(),BL(),wX(),n9(),Z1(),Y1(),U1(),L8(),j9=new u8("bunfig",{showTags:!0}),x9=new y1,z6=o0(XX.cwd(),"config"),L6=o0(XX.cwd(),"src/generated")}),_1={},RL(_1,{withErrorRecovery:()=>bU,tryLoadConfig:()=>LL,loadConfigWithResult:()=>QL,loadConfig:()=>E5,isRetryableError:()=>ez,isConfigNotFoundError:()=>tz,isBunfigError:()=>fU,globalPerformanceMonitor:()=>B$,globalCache:()=>bX,getEnvOrDefault:()=>XL,generateConfigTypes:()=>jL,defaultGeneratedDir:()=>L6,defaultConfigDir:()=>z6,deepMergeWithArrayStrategy:()=>L5,deepMerge:()=>gU,createLibraryConfig:()=>EL,config:()=>zL,bunfigPlugin:()=>GL,applyEnvVarsToConfig:()=>tX,TypeGenerationError:()=>eZ,SchemaValidationError:()=>q$,PluginError:()=>$1,PerformanceMonitor:()=>x1,FileSystemError:()=>tZ,ErrorFactory:()=>u9,EnvVarError:()=>P8,EnvProcessor:()=>LZ,ConfigValidator:()=>j5,ConfigValidationError:()=>rZ,ConfigNotFoundError:()=>q8,ConfigMergeError:()=>aZ,ConfigLoader:()=>y1,ConfigLoadError:()=>w$,ConfigFileLoader:()=>jZ,ConfigCache:()=>k1,CacheUtils:()=>eY,BunfigError:()=>Z9,BrowserConfigError:()=>X1,ArrayMergeStrategies:()=>Q6}),Q1=C9(()=>{j6(),n9(),wX(),n9(),yL(),Z1(),Y1(),U1(),L8()}),Q1(),$Z={verbose:!1,locale:"en",autoInstallLocales:!1},h1=$Z,iX={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,qX=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=AX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",iX);return iX}if(z9.has(Z))return z9.get(Z);if(qX.has(Z))return qX.get(Z);let Y=this.loadLocaleWithFallback(Z);qX.set(Z,Y);try{let U=await Y;return z9.set(Z,U),U}finally{qX.delete(Z)}}static loadSync($){let Z=AX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",iX);return iX}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=AX($).normalized;return z9.has(Z)}static async preload($){await Promise.all($.map((Z)=>this.load(Z)))}static clearCache(){z9.clear(),qX.clear()}static async loadLocaleWithFallback($){let Z=OL($);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 cU(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(!kX())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=wz.cwd(),U=Cz(Y,"packages",Z.packageName,"dist","index.js");if(!Hz(U))return null;let _=await import(`file://${U}`);return _[Z.normalized]||_[Z.language]||_.default}catch{return null}}}static async loadLocaleModule($){let Z=JL($),Y=AX($);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(kX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}if(h1.autoInstallLocales)if(console.log(`
459
459
  \uD83D\uDD0D Locale '${$}' not found. Auto-installing ${Z}...`),uU(Z)){if(kX()&&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(kX()&&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 '${$}': ${_}`)}}},oU=new E5,rU={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<=$}},aU={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"]}}},tU={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}]}},eU=[".","_","-",""],X7=["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"],$7=["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"],Z7=["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"],Y7=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],U7=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],_7=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],v1="abcdefghijklmnopqrstuvwxyz".split(""),b1=new EZ,Q7=b1}),z7={};i1(z7,{validateData:()=>k$,selectWeightedItem:()=>x$,isInWorkspace:()=>kX,installPackage:()=>uU,globalProviderRegistry:()=>oU,getConfig:()=>FL,generateRealisticData:()=>VL,faker:()=>b1,detectPackageManager:()=>mU,defaultConfig:()=>$Z,default:()=>Q7,config:()=>h1,applyRelationships:()=>p9,applyConstraints:()=>WL,WordModule:()=>H$,WeightedSelections:()=>tU,VehicleModule:()=>M$,ValidationRules:()=>rU,SystemModule:()=>D$,StringModule:()=>e8,SportModule:()=>K$,ScienceModule:()=>R$,Random:()=>XZ,PhoneModule:()=>I$,PersonModule:()=>V$,NumberModule:()=>t8,MusicModule:()=>W$,LoremModule:()=>a8,LocaleLoader:()=>Y9,InternetModule:()=>J$,ImageModule:()=>r8,HelpersModule:()=>o8,HackerModule:()=>O$,GitModule:()=>s8,FoodModule:()=>F$,FinanceModule:()=>l8,Faker:()=>EZ,DateModule:()=>i8,DatabaseModule:()=>n8,DataRelationships:()=>aU,DataProviderRegistry:()=>E5,CompanyModule:()=>G$,CommerceModule:()=>E$,ColorModule:()=>j$,BookModule:()=>L$,AnimalModule:()=>z$,AddressModule:()=>Q$});var vL=e(()=>{hL()});function r9(){let X=new Date().toISOString();return I0(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 L7(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(!j8)try{j8=(T8(),n7(W7)).getModel}catch{j8=()=>{return}}return j8(X)}function j6(X){let $=eX.get(X);if($!==void 0)return $;let Z=0,Y=X.replace(/\?/g,()=>`$${++Z}`);if(eX.size>=mL)eX.clear();return eX.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 g1{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 j7{dialect;constructor(X){this.dialect=X}conn(){return hX()}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 E7(X){if(X.database instanceof f1)o9=X.database;else o9=new f1(X.database||":memory:",{create:!0}),e1(o9);P9=null,X$=null}function M0(){if(o9){if(!P9||X$!==o9)P9=new g1(o9),X$=o9,L1="sqlite",j1=null;return P9}let X=f.dialect,$=f.database?.database??null;if(P9&&X$===null&&L1===X&&j1===$)return P9;if(X$=null,L1=X,j1=$,X==="sqlite"){let Z=new f1($||":memory:",{create:!0});e1(Z),P9=new g1(Z)}else P9=new j7(X);return P9}function G7(){let X=M0();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 fX(X){let $=X.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function a9(X){let $=X.traits;return Boolean($?.useTimestamps||$?.timestampable)}function bL(X){let $=d1.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 d1.set(X,Z),Z}function F6(X){let $={};for(let[Z,Y]of Object.entries(X))$[r0(Z)]=Y;return $}function fL(X,$){if(X[$])return X[$];let Z=r0($);if(X[Z])return X[Z];for(let Y of Object.keys(X))if(r0(Y)===Z)return X[Y];return}class e0{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor(X,$={}){this._definition=X,this._attributes=F6({...$}),this._original=null;let Z=bL(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=F7(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 O7(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[r0(X)]}getAttribute(X){return this._attributes[r0(X)]}getAttributes(){return{...this._attributes}}set(X,$){if(this._original===null)this._original={...this._attributes};this._attributes[r0(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=fL($,Z),_=!U&&r0(Z).endsWith("_id");if(U?.fillable&&!U?.guarded||_){if(this._original===null)this._original={...this._attributes};this._attributes[r0(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=M0(),$=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=r0(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=M0(),$=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 e0(this._definition,Y)}async delete(){let X=M0(),$=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),fX(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(!fX(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 M0().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=M0(),$=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 e0(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 r0(X){let $=p1.get(X);if($!==void 0)return $;return $=X.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),p1.set(X,$),$}function i9(X){let $=c1.get(X);if($!==void 0)return $;let Z=r0(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 c1.set(X,$),$}function F7(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 R=typeof F==="string"?F:F?.model||"";if(R&&R.toLowerCase()===$.toLowerCase())return R}return null}if(typeof W==="object"){for(let[F,R]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof R==="string"?R:R?.model||R?.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,R]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:R}}return null}let L=_(X.hasMany);if(L){let F=U9(L)?.getTable?.()||i9(L),R=r0(Z)+"_id";return{type:"hasMany",relatedModelName:L,relatedTable:F,foreignKey:R,localKey:U}}let z=_(X.hasOne);if(z){let F=U9(z)?.getTable?.()||i9(z),R=r0(Z)+"_id";return{type:"hasOne",relatedModelName:z,relatedTable:F,foreignKey:R,localKey:U}}let j=_(X.belongsTo);if(j){let W=U9(j),F=W?.getTable?.()||i9(j),R=W?.getDefinition?.()?.primaryKey||"id",D=r0(j)+"_id";return{type:"belongsTo",relatedModelName:j,relatedTable:F,foreignKey:D,localKey:R}}let E=Q();if(E){let W=typeof E.entry==="object",F=W?E.entry.model:E.entry,D=U9(F)?.getTable?.()||i9(F),q=W?E.entry:null,w,A;if(q?.table)w=q.table;else if(q?.through){A=q.through;let S=U9(q.through);if(!S)throw Error(`[orm] belongsToMany relation '${$}' on '${Z}' references unknown through model '${q.through}'. Make sure '${q.through}' is registered.`);w=S.getTable?.()||S.getDefinition?.()?.table||i9(q.through)}else{let S=Y.endsWith("s")?Y.slice(0,-1):Y,h=D.endsWith("s")?D.slice(0,-1):D;w=[S,h].sort().join("_")}let P=q?.foreignKey||`${Y.endsWith("s")?Y.slice(0,-1):Y}_id`,H=q?.relatedKey||`${D.endsWith("s")?D.slice(0,-1):D}_id`,N=[];if(q?.pivot?.columns)for(let S of Object.keys(q.pivot.columns))N.push(S);if(A){let S=U9(A),h=S?.getDefinition?.()||S?.definition,d=h?.attributes??{},v=h?.primaryKey??"id";for(let n of Object.keys(d)){if(n===P||n===H||n===v)continue;if(!N.includes(n))N.push(n)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:D,foreignKey:P,localKey:U,pivotTable:w,pivotFkParent:P,pivotFkRelated:H,pivotColumns:N,pivotModelName:A,pivotTimestamps:Boolean(q?.pivot?.timestamps)}}let V=(W,F)=>{if(!W||typeof W!=="object"||Array.isArray(W))return null;let R=W[$]??W[Object.keys(W).find((h)=>h.toLowerCase()===$.toLowerCase())??""];if(!R||typeof R!=="object")return null;let{through:D,target:q}=R;if(!D||!q)return null;let w=U9(D),A=w?.getDefinition?.()||w?.definition,P=w?.getTable?.()||A?.table||i9(D),H=A?.primaryKey||"id",S=U9(q)?.getTable?.()||i9(q);return{type:F,relatedModelName:q,relatedTable:S,foreignKey:`${r0(Z)}_id`,localKey:U,throughTable:P,throughForeignKey:`${r0(Z)}_id`,throughLocalKey:H,targetForeignKey:`${gL(P)}_id`}},G=V(X.hasManyThrough,"hasManyThrough");if(G)return G;let J=V(X.hasOneThrough,"hasOneThrough");if(J)return J;return null}function gL(X){return X.endsWith("s")?X.slice(0,-1):X}class O7{_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(L7(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 ${E1}${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(E1))U[L.slice(E1.length)]=z;else if(L!==$&&L!==Z)_[L]=z;let Q=new e0(this._relatedDef,U);return Q.pivot=_,Q})}async get(){let X=M0(),{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=M0(),$=`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=M0(),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 $=M0(),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=M0(),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 $=M0(),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 $=M0(),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(L7(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"||!fX(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 $=M0(),Z=this._definition.primaryKey||"id";for(let Y of this._withRelations){let U=`${this._definition.name}:${Y}`,_=$$.get(U);if(_===void 0){if(_=F7(this._definition,Y),$$.size>=uL)$$.clear();$$.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 e0(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 e0(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 e0(V,F):null)}}if(_.type==="belongsToMany"){let Q=X.map((q)=>q.get(Z)).filter((q)=>q!=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 q of X)q.setRelation(Y,[]);continue}let j=new Set;for(let q of z){let w=q[_.pivotFkRelated];if(w!=null)j.add(w)}let E=[...j],V=U9(_.relatedModelName),G=V?.getDefinition?.()||V?.definition||this._definition,J=G?.primaryKey||"id",W=[];if(E.length>0){let q=E.map(()=>"?").join(", ");W=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${J} IN (${q})`,E)}let F=new Map;for(let q of W)F.set(q[J],q);let R=new Map;for(let q of z){let w=q[_.pivotFkParent];if(!R.has(w))R.set(w,[]);R.get(w).push(q)}let D=new Set([_.pivotFkParent,_.pivotFkRelated]);for(let q of X){let w=q.get(Z),P=(R.get(w)||[]).map((H)=>{let N=F.get(H[_.pivotFkRelated]);if(!N)return null;let S=new e0(G,N),h={};for(let[d,v]of Object.entries(H))if(!D.has(d))h[d]=v;return S.pivot=h,S}).filter((H)=>H!==null);q.setRelation(Y,P)}}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,R=new Map;for(let D of J){let q=E.get(D[_.targetForeignKey]);if(q==null)continue;if(!R.has(q))R.set(q,[]);R.get(q).push(new e0(F,D))}for(let D of X){let q=R.get(D.get(Z))||[];D.setRelation(Y,_.type==="hasManyThrough"?q:q[0]??null)}}}}async get(){let X=M0(),{sql:$,params:Z}=this.buildQuery(),U=(await X.all($,Z)).map((_)=>new e0(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=M0(),$=[],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=M0(),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 $=M0(),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=M0(),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=M0(),$=[],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 $=M0(),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 dL(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=M0(),U=X.primaryKey||"id",_=fX(X)?` AND ${b9} IS NULL`:"",Q=await Y.get(`SELECT * FROM ${X.table} WHERE ${U} = ?${_}`,[Z]);return Q?new e0(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=M0(),U=X.primaryKey||"id",_=fX(X)?` AND ${b9} IS NULL`:"";return(await Y.all(`SELECT * FROM ${X.table} WHERE ${U} IN (${Z.map(()=>"?").join(", ")})${_}`,Z)).map((L)=>new e0(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 e0(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=M0(),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 M0().run(`DELETE FROM ${X.table}`,[])},getDefinition:()=>X,getTable:()=>X.table,make(Z={}){return new e0(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 pL(X){return dL(X)}async function EO(X){let $=M0(),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(fX(X))Y.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${X.table} (${Y.join(", ")})`,[])}function cL(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 GO(X,$,Z){let Y=M0(),U=X.traits?.useSeeder,_=$??(typeof U==="object"&&U?U.count:10);if(!Z)try{let Q=await Promise.resolve().then(()=>(vL(),z7));Z=cL(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,j8=null,eX,mL=500,o9=null,P9=null,X$=null,L1=null,j1=null,b9="deleted_at",E1="__btm_rel__",d1,p1,c1,$$,uL=1000,J7=e(()=>{c0(),$X(),X5(),G5=/^[A-Z_][A-Z0-9_]*$/i,eX=new Map,d1=new WeakMap,p1=new Map,c1=new Map,$$=new Map}),W7={};i1(W7,{registerModel:()=>GZ,registerBrowserModels:()=>aL,hasModel:()=>sL,getModelRegistry:()=>lL,getModel:()=>nL,getAllModels:()=>iL,defineModel:()=>F5,clearModelRegistry:()=>oL});function nL(X){return UX.get(X)}function iL(){return[...UX.values()]}function lL(){return Object.fromEntries(UX)}function sL(X){return UX.has(X)}function oL(){UX.clear()}function GZ(X,$){return UX.set(X,$),$}function rL(){return typeof window<"u"&&typeof document<"u"}function F5(X){let $;if(rL())$=o7(X);else{let Z=pL(X);$=Object.assign(Z,{definition:X,getDefinition:()=>X,getTable:()=>X.table,getName:()=>X.name})}return GZ(X.name,$),$}function aL(X){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...X}}var UX,T8=e(()=>{H6(),J7(),UX=new Map});class dX{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(X){this.driver=gX(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=gX(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 FO(X){return new dX(X)}function OO(X){return new f9(X)}function JO(X){let $=gX(X.config);return{query:()=>new dX(X),item:()=>new f9(X),driver:$,registerEntity:(Z)=>$.registerEntity(Z),buildKey:(Z,Y)=>$.buildPrimaryKey(Z,Y)}}var O5=()=>{};class V7{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 I7{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 R7(this.manager,this.entityName,this.options)}async findAll(){let X=this.manager.typeAttribute??"_type",$=new dX(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 R7{manager;entityName;options;builder;pkValue;skConditions=[];constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z,this.builder=new dX(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 tL(X){return new V7(X)}function eL(X,$,Z){return new I7(X,$,Z)}var Xj,K7=e(()=>{O5(),Xj={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 $j(X){return{models:new Map}}function WO(X){return X}function VO(X){return X}function IO(X){return X}function RO(X){return X}class D7{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=gX($);let Z={tableName:X.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=tL(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 $j({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 eL(this.singleTableManager,X,this.queryBuilderOptions)}query(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new dX(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 KO(X){return new D7(X)}function DO(X){return X.accessPatterns}function MO(X,$="#"){let Z=X.name.toUpperCase(),Y=X.primaryKey??"id";return{name:X.name,pkPattern:`${Z}${$}\${${Y}}`,skPattern:`${Z}${$}\${${Y}}`}}var Zj=e(()=>{O5(),K7()});function M7(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 pX(X){let $=X.cwd??zj.cwd(),Z=X.modelsDir.startsWith("/")?X.modelsDir:`${$}/${X.modelsDir}`,Y={},U=Yj(Z);for(let _ of U){let Q=`${Z}/${_}`;if(Uj(Q).isDirectory())continue;let z=Qj(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=_j(_,z),W=G.name??J;Y[W]={...G,name:W}}return Y}var Lj=()=>{};function m1(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 jj(X){if(!X)return[];return(Array.isArray(X)?X:typeof X==="object"?Object.values(X):[]).map(m1).filter((Z)=>Z!==null)}function Ej(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 R=m1(F);if(R)W[R.model]=R.model}return W}if(typeof J==="object"){for(let[F,R]of Object.entries(J)){let D=m1(R);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 H7=()=>{};function l0(X){if(f.verbose)console.log(X)}function PX(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 Oj(X){let $=X;while($!==J6($)){if(C7(J5($,"package.json")))return $;$=J6($)}return w7.cwd()}function Jj(){let X=Oj(w7.cwd()),$=J5(X,"database","migrations");if(!C7($))Gj($,{recursive:!0}),l0(`-- Created SQL directory: ${$}`);return $}function q7(X,$){if(!X)return!1;let Z=Jj();P$++;let U=`${I5?String(P$).padStart(10,"0"):String(Math.floor(Date.now()/1000)+P$)}-${$}.sql`,_=J5(Z,U);return Fj(_,X),l0(`-- 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 Wj(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 P7(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 Vj(X){if(!X||typeof X!=="object")return;let $=X;if($.name)switch(String($.name).toLowerCase()){case"string":case"text":{let Y=P7($);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"timestamptz":case"timestamp_tz":return"timestamptz";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==="timestamptz"||Z==="timestamp_tz")return"timestamptz";if(Z==="json")return"json"}return}function Ij(X){if(typeof X!=="string")return;switch(X.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function W5(X,$){let Z=Ej(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:PX(j),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let H of Object.keys(V)){let N=V[H],S=PX(H),h=Boolean(N.validation?.rule?.isRequired),d=H===j?!1:N.nullable??!(N.required??h),v,n,a=H===j;if(v=Ij(N.type)??Vj(N.validation?.rule),!v||v==="enum"){let m=Wj(N.validation?.rule);if(m&&m.length>0)v="enum",n=m}if(!v)v=W6(S);if(!v){let m=V6(N.default);if(typeof m==="string")v=m.length>255?"text":"string";else if(typeof m==="number")v=Number.isInteger(m)?"integer":"float";else if(typeof m==="boolean")v="boolean";else if(typeof m==="bigint")v="bigint";else if(m instanceof Date)v="datetime"}if(!v)v=a?"bigint":"string";let u=v==="string"?P7(N.validation?.rule):void 0,i={name:S,type:v,isPrimaryKey:a,isUnique:Boolean(N.unique),isNullable:d,hasDefault:typeof N.default<"u",defaultValue:V6(N.default),enumValues:n,maxLength:typeof u==="number"&&u>0&&u<=255?u:void 0};if(S.endsWith("_id")&&N.foreignKey!==!1)if(typeof N.foreignKey==="object"&&N.foreignKey!==null){let m=N.foreignKey;if(i.references={table:m.table,column:m.column??"id",onDelete:m.onDelete,onUpdate:m.onUpdate},m.nullable!==void 0)i.isNullable=m.nullable}else{let X0=S.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(z0,y,J9)=>J9.toUpperCase()),R0=Z.modelToTable[X0];if(R0){let z0=Z.primaryKeys[R0]??"id";i.references={table:R0,column:z0}}}G.push(i)}let W=jj(L.belongsTo);for(let H of W){let N=H.foreignKey??`${PX(H.model)}_id`;if(G.some((d)=>d.name===N))continue;let S=Z.modelToTable[H.model];if(!S)continue;let h=Z.primaryKeys[S]??"id";G.push({name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:S,column:h,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((N)=>PX(N)),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 w=Array.isArray(L.shardKey)?L.shardKey.map(PX):void 0,A=Array.isArray(L.sortKey)?L.sortKey.map(PX):void 0,P=L.tableKind;Y.push({table:z,columns:G,indexes:J,shardKey:w,sortKey:A,tableKind:P})}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`,q=D.replace(/s$/,""),w=J.table||[E,q].sort().join("_"),A=J.foreignKey||`${E}_id`,P=J.relatedKey||`${q}_id`,H=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:A,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:P,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:D,column:"id"}}];if(W.columns)for(let[h,d]of Object.entries(W.columns)){let v=d,n=W6(h)??"string";H.push({name:h,type:n,isPrimaryKey:!1,isUnique:!1,isNullable:v?.nullable??!1,hasDefault:v?.default!==void 0,defaultValue:v?.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 N=[],S=W.uniques&&W.uniques.length>0?W.uniques:[[A,P]];for(let h=0;h<S.length;h++){let d=S[h];N.push({name:`${w}_${d.join("_")}_unique${h>0?`_${h}`:""}`,columns:[...d],type:"unique"})}_({table:w,columns:H,indexes:N})}}return{dialect:$.dialect,tables:Y}}function V5(X,$={}){P$=0,B9=0,g9=0,I5=!0;let Z=$.dryRun?()=>!1:q7,Y=[],U=ZX(X.dialect),{tables:_,deferredForeignKeys:Q}=T7(X.tables,X.dialect);for(let[z,j]of _.entries()){let E={...j,columns:j.columns.map((F)=>Q.has(BX(j.table,F.name))?{...F,references:void 0}:F)},V=[],G=new Set;for(let F of E.columns)if(F.type==="enum"&&F.enumValues&&F.enumValues.length>0){let R=`${E.table}_${F.name}_type`;if(F.enumTypeName=R,!G.has(R)){let D=U.createEnumType(R,F.enumValues);if(D)V.push(D);G.add(R)}}let J=U.createTable(E);V.push(J);for(let F of E.indexes)V.push(U.createIndex(E.table,F));if(z===_.length-1)for(let F of _)for(let R of F.columns){if(!R.references||!Q.has(BX(F.table,R.name)))continue;let D=U.addForeignKey(F.table,R.name,R.references.table,R.references.column,R.references.onDelete,R.references.onUpdate);if(D)V.push(D)}Y.push(...V);let W=V.join(`
461
+ Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${$}': ${_}`)}}},oU=new G5,rU={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<=$}},aU={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"]}}},tU={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}]}},eU=[".","_","-",""],X7=["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"],$7=["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"],Z7=["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"],Y7=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],U7=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],_7=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],v1="abcdefghijklmnopqrstuvwxyz".split(""),b1=new EZ,Q7=b1}),z7={};i1(z7,{validateData:()=>k$,selectWeightedItem:()=>x$,isInWorkspace:()=>kX,installPackage:()=>uU,globalProviderRegistry:()=>oU,getConfig:()=>FL,generateRealisticData:()=>VL,faker:()=>b1,detectPackageManager:()=>mU,defaultConfig:()=>$Z,default:()=>Q7,config:()=>h1,applyRelationships:()=>p9,applyConstraints:()=>WL,WordModule:()=>H$,WeightedSelections:()=>tU,VehicleModule:()=>M$,ValidationRules:()=>rU,SystemModule:()=>D$,StringModule:()=>e8,SportModule:()=>K$,ScienceModule:()=>R$,Random:()=>XZ,PhoneModule:()=>I$,PersonModule:()=>V$,NumberModule:()=>t8,MusicModule:()=>W$,LoremModule:()=>a8,LocaleLoader:()=>Y9,InternetModule:()=>J$,ImageModule:()=>r8,HelpersModule:()=>o8,HackerModule:()=>O$,GitModule:()=>s8,FoodModule:()=>F$,FinanceModule:()=>l8,Faker:()=>EZ,DateModule:()=>i8,DatabaseModule:()=>n8,DataRelationships:()=>aU,DataProviderRegistry:()=>G5,CompanyModule:()=>G$,CommerceModule:()=>E$,ColorModule:()=>j$,BookModule:()=>L$,AnimalModule:()=>z$,AddressModule:()=>Q$});var vL=e(()=>{hL()});function r9(){let X=new Date().toISOString();return I0(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(!F5.test(X))throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function L7(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||!F5.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(!j8)try{j8=(T8(),n7(W7)).getModel}catch{j8=()=>{return}}return j8(X)}function E6(X){let $=eX.get(X);if($!==void 0)return $;let Z=0,Y=X.replace(/\?/g,()=>`$${++Z}`);if(eX.size>=mL)eX.clear();return eX.set(X,Y),Y}function G6(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 F6(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 g1{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 j7{dialect;constructor(X){this.dialect=X}conn(){return hX()}text(X){return this.dialect==="postgres"?E6(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:G6(Z),lastInsertId:F6(Z)}}async insert(X,$,Z){if(this.dialect==="postgres"){let _=await this.conn().unsafe(`${E6(X)} RETURNING ${Z}`,$),Q=Array.isArray(_)?_[0]:_;return{changes:1,lastInsertId:Q?Q[Z]??null:null}}let Y=await this.conn().unsafe(X,$),U=F6(Y);if(U==null){let _=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);U=(Array.isArray(_)?_[0]:_)?.id??null}return{changes:G6(Y)||1,lastInsertId:U}}}function E7(X){if(X.database instanceof f1)o9=X.database;else o9=new f1(X.database||":memory:",{create:!0}),e1(o9);P9=null,X$=null}function M0(){if(o9){if(!P9||X$!==o9)P9=new g1(o9),X$=o9,L1="sqlite",j1=null;return P9}let X=f.dialect,$=f.database?.database??null;if(P9&&X$===null&&L1===X&&j1===$)return P9;if(X$=null,L1=X,j1=$,X==="sqlite"){let Z=new f1($||":memory:",{create:!0});e1(Z),P9=new g1(Z)}else P9=new j7(X);return P9}function G7(){let X=M0();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 fX(X){let $=X.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function a9(X){let $=X.traits;return Boolean($?.useTimestamps||$?.timestampable)}function bL(X){let $=d1.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 d1.set(X,Z),Z}function O6(X){let $={};for(let[Z,Y]of Object.entries(X))$[r0(Z)]=Y;return $}function fL(X,$){if(X[$])return X[$];let Z=r0($);if(X[Z])return X[Z];for(let Y of Object.keys(X))if(r0(Y)===Z)return X[Y];return}class e0{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor(X,$={}){this._definition=X,this._attributes=O6({...$}),this._original=null;let Z=bL(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=F7(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 O7(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[r0(X)]}getAttribute(X){return this._attributes[r0(X)]}getAttributes(){return{...this._attributes}}set(X,$){if(this._original===null)this._original={...this._attributes};this._attributes[r0(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=fL($,Z),_=!U&&r0(Z).endsWith("_id");if(U?.fillable&&!U?.guarded||_){if(this._original===null)this._original={...this._attributes};this._attributes[r0(Z)]=Y}}return this}forceFill(X){if(this._original===null)this._original={...this._attributes};return Object.assign(this._attributes,O6(X)),this}async save(){let X=M0(),$=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=r0(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=M0(),$=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 e0(this._definition,Y)}async delete(){let X=M0(),$=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),fX(this._definition)){let U=r9();await X.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${$} = ?`,[U,Z]),this._attributes[f9]=U}else await X.run(`DELETE FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);return await Y?.afterDelete?.(this),!0}async restore(){if(!fX(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 M0().run(`UPDATE ${this._definition.table} SET ${f9} = ? WHERE ${X} = ?`,[null,$]),this._attributes[f9]=null,this._original=null,this}trashed(){return this._attributes[f9]!=null}async refresh(){let X=M0(),$=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 e0(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 r0(X){let $=p1.get(X);if($!==void 0)return $;return $=X.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),p1.set(X,$),$}function i9(X){let $=c1.get(X);if($!==void 0)return $;let Z=r0(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 c1.set(X,$),$}function F7(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 R=typeof F==="string"?F:F?.model||"";if(R&&R.toLowerCase()===$.toLowerCase())return R}return null}if(typeof W==="object"){for(let[F,R]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof R==="string"?R:R?.model||R?.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,R]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:R}}return null}let L=_(X.hasMany);if(L){let F=U9(L)?.getTable?.()||i9(L),R=r0(Z)+"_id";return{type:"hasMany",relatedModelName:L,relatedTable:F,foreignKey:R,localKey:U}}let z=_(X.hasOne);if(z){let F=U9(z)?.getTable?.()||i9(z),R=r0(Z)+"_id";return{type:"hasOne",relatedModelName:z,relatedTable:F,foreignKey:R,localKey:U}}let j=_(X.belongsTo);if(j){let W=U9(j),F=W?.getTable?.()||i9(j),R=W?.getDefinition?.()?.primaryKey||"id",D=r0(j)+"_id";return{type:"belongsTo",relatedModelName:j,relatedTable:F,foreignKey:D,localKey:R}}let E=Q();if(E){let W=typeof E.entry==="object",F=W?E.entry.model:E.entry,D=U9(F)?.getTable?.()||i9(F),q=W?E.entry:null,w,A;if(q?.table)w=q.table;else if(q?.through){A=q.through;let S=U9(q.through);if(!S)throw Error(`[orm] belongsToMany relation '${$}' on '${Z}' references unknown through model '${q.through}'. Make sure '${q.through}' is registered.`);w=S.getTable?.()||S.getDefinition?.()?.table||i9(q.through)}else{let S=Y.endsWith("s")?Y.slice(0,-1):Y,h=D.endsWith("s")?D.slice(0,-1):D;w=[S,h].sort().join("_")}let P=q?.foreignKey||`${Y.endsWith("s")?Y.slice(0,-1):Y}_id`,H=q?.relatedKey||`${D.endsWith("s")?D.slice(0,-1):D}_id`,N=[];if(q?.pivot?.columns)for(let S of Object.keys(q.pivot.columns))N.push(S);if(A){let S=U9(A),h=S?.getDefinition?.()||S?.definition,d=h?.attributes??{},v=h?.primaryKey??"id";for(let n of Object.keys(d)){if(n===P||n===H||n===v)continue;if(!N.includes(n))N.push(n)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:D,foreignKey:P,localKey:U,pivotTable:w,pivotFkParent:P,pivotFkRelated:H,pivotColumns:N,pivotModelName:A,pivotTimestamps:Boolean(q?.pivot?.timestamps)}}let V=(W,F)=>{if(!W||typeof W!=="object"||Array.isArray(W))return null;let R=W[$]??W[Object.keys(W).find((h)=>h.toLowerCase()===$.toLowerCase())??""];if(!R||typeof R!=="object")return null;let{through:D,target:q}=R;if(!D||!q)return null;let w=U9(D),A=w?.getDefinition?.()||w?.definition,P=w?.getTable?.()||A?.table||i9(D),H=A?.primaryKey||"id",S=U9(q)?.getTable?.()||i9(q);return{type:F,relatedModelName:q,relatedTable:S,foreignKey:`${r0(Z)}_id`,localKey:U,throughTable:P,throughForeignKey:`${r0(Z)}_id`,throughLocalKey:H,targetForeignKey:`${gL(P)}_id`}},G=V(X.hasManyThrough,"hasManyThrough");if(G)return G;let J=V(X.hasOneThrough,"hasOneThrough");if(J)return J;return null}function gL(X){return X.endsWith("s")?X.slice(0,-1):X}class O7{_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(L7(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 ${E1}${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(E1))U[L.slice(E1.length)]=z;else if(L!==$&&L!==Z)_[L]=z;let Q=new e0(this._relatedDef,U);return Q.pivot=_,Q})}async get(){let X=M0(),{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=M0(),$=`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=M0(),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 $=M0(),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=M0(),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 $=M0(),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 $=M0(),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(L7(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"||!fX(this._definition))return"";return this._trashed==="only"?`${f9} IS NOT NULL`:`${f9} 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 $=M0(),Z=this._definition.primaryKey||"id";for(let Y of this._withRelations){let U=`${this._definition.name}:${Y}`,_=$$.get(U);if(_===void 0){if(_=F7(this._definition,Y),$$.size>=uL)$$.clear();$$.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 e0(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 e0(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 e0(V,F):null)}}if(_.type==="belongsToMany"){let Q=X.map((q)=>q.get(Z)).filter((q)=>q!=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 q of X)q.setRelation(Y,[]);continue}let j=new Set;for(let q of z){let w=q[_.pivotFkRelated];if(w!=null)j.add(w)}let E=[...j],V=U9(_.relatedModelName),G=V?.getDefinition?.()||V?.definition||this._definition,J=G?.primaryKey||"id",W=[];if(E.length>0){let q=E.map(()=>"?").join(", ");W=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${J} IN (${q})`,E)}let F=new Map;for(let q of W)F.set(q[J],q);let R=new Map;for(let q of z){let w=q[_.pivotFkParent];if(!R.has(w))R.set(w,[]);R.get(w).push(q)}let D=new Set([_.pivotFkParent,_.pivotFkRelated]);for(let q of X){let w=q.get(Z),P=(R.get(w)||[]).map((H)=>{let N=F.get(H[_.pivotFkRelated]);if(!N)return null;let S=new e0(G,N),h={};for(let[d,v]of Object.entries(H))if(!D.has(d))h[d]=v;return S.pivot=h,S}).filter((H)=>H!==null);q.setRelation(Y,P)}}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,R=new Map;for(let D of J){let q=E.get(D[_.targetForeignKey]);if(q==null)continue;if(!R.has(q))R.set(q,[]);R.get(q).push(new e0(F,D))}for(let D of X){let q=R.get(D.get(Z))||[];D.setRelation(Y,_.type==="hasManyThrough"?q:q[0]??null)}}}}async get(){let X=M0(),{sql:$,params:Z}=this.buildQuery(),U=(await X.all($,Z)).map((_)=>new e0(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=M0(),$=[],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=M0(),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 $=M0(),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=M0(),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=M0(),$=[],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 $=M0(),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 dL(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=M0(),U=X.primaryKey||"id",_=fX(X)?` AND ${f9} IS NULL`:"",Q=await Y.get(`SELECT * FROM ${X.table} WHERE ${U} = ?${_}`,[Z]);return Q?new e0(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=M0(),U=X.primaryKey||"id",_=fX(X)?` AND ${f9} IS NULL`:"";return(await Y.all(`SELECT * FROM ${X.table} WHERE ${U} IN (${Z.map(()=>"?").join(", ")})${_}`,Z)).map((L)=>new e0(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 e0(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=M0(),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 M0().run(`DELETE FROM ${X.table}`,[])},getDefinition:()=>X,getTable:()=>X.table,make(Z={}){return new e0(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 pL(X){return dL(X)}async function EO(X){let $=M0(),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(fX(X))Y.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${X.table} (${Y.join(", ")})`,[])}function cL(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 GO(X,$,Z){let Y=M0(),U=X.traits?.useSeeder,_=$??(typeof U==="object"&&U?U.count:10);if(!Z)try{let Q=await Promise.resolve().then(()=>(vL(),z7));Z=cL(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 F5,j8=null,eX,mL=500,o9=null,P9=null,X$=null,L1=null,j1=null,f9="deleted_at",E1="__btm_rel__",d1,p1,c1,$$,uL=1000,J7=e(()=>{c0(),$X(),X5(),F5=/^[A-Z_][A-Z0-9_]*$/i,eX=new Map,d1=new WeakMap,p1=new Map,c1=new Map,$$=new Map}),W7={};i1(W7,{registerModel:()=>GZ,registerBrowserModels:()=>aL,hasModel:()=>sL,getModelRegistry:()=>lL,getModel:()=>nL,getAllModels:()=>iL,defineModel:()=>O5,clearModelRegistry:()=>oL});function nL(X){return UX.get(X)}function iL(){return[...UX.values()]}function lL(){return Object.fromEntries(UX)}function sL(X){return UX.has(X)}function oL(){UX.clear()}function GZ(X,$){return UX.set(X,$),$}function rL(){return typeof window<"u"&&typeof document<"u"}function O5(X){let $;if(rL())$=o7(X);else{let Z=pL(X);$=Object.assign(Z,{definition:X,getDefinition:()=>X,getTable:()=>X.table,getName:()=>X.name})}return GZ(X.name,$),$}function aL(X){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...X}}var UX,T8=e(()=>{C6(),J7(),UX=new Map});class dX{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(X){this.driver=gX(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 g9{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(X){this.driver=gX(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 FO(X){return new dX(X)}function OO(X){return new g9(X)}function JO(X){let $=gX(X.config);return{query:()=>new dX(X),item:()=>new g9(X),driver:$,registerEntity:(Z)=>$.registerEntity(Z),buildKey:(Z,Y)=>$.buildPrimaryKey(Z,Y)}}var J5=()=>{};class V7{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 I7{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 g9(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 g9(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 g9(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 g9(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 R7(this.manager,this.entityName,this.options)}async findAll(){let X=this.manager.typeAttribute??"_type",$=new dX(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 R7{manager;entityName;options;builder;pkValue;skConditions=[];constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z,this.builder=new dX(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 tL(X){return new V7(X)}function eL(X,$,Z){return new I7(X,$,Z)}var Xj,K7=e(()=>{J5(),Xj={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 J6(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 $j(X){return{models:new Map}}function WO(X){return X}function VO(X){return X}function IO(X){return X}function RO(X){return X}class D7{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=gX($);let Z={tableName:X.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=tL(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 $j({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 eL(this.singleTableManager,X,this.queryBuilderOptions)}query(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new dX(this.queryBuilderOptions).table(this.config.tableName).entity(X)}item(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new g9(this.queryBuilderOptions).table(this.config.tableName)}buildKey(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=J6(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=J6(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 KO(X){return new D7(X)}function DO(X){return X.accessPatterns}function MO(X,$="#"){let Z=X.name.toUpperCase(),Y=X.primaryKey??"id";return{name:X.name,pkPattern:`${Z}${$}\${${Y}}`,skPattern:`${Z}${$}\${${Y}}`}}var Zj=e(()=>{J5(),K7()});function M7(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 pX(X){let $=X.cwd??zj.cwd(),Z=X.modelsDir.startsWith("/")?X.modelsDir:`${$}/${X.modelsDir}`,Y={},U=Yj(Z);for(let _ of U){let Q=`${Z}/${_}`;if(Uj(Q).isDirectory())continue;let z=Qj(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=_j(_,z),W=G.name??J;Y[W]={...G,name:W}}return Y}var Lj=()=>{};function m1(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 jj(X){if(!X)return[];return(Array.isArray(X)?X:typeof X==="object"?Object.values(X):[]).map(m1).filter((Z)=>Z!==null)}function Ej(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 R=m1(F);if(R)W[R.model]=R.model}return W}if(typeof J==="object"){for(let[F,R]of Object.entries(J)){let D=m1(R);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 H7=()=>{};function l0(X){if(f.verbose)console.log(X)}function PX(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 Oj(X){let $=X;while($!==W6($)){if(C7(W5($,"package.json")))return $;$=W6($)}return w7.cwd()}function Jj(){let X=Oj(w7.cwd()),$=W5(X,"database","migrations");if(!C7($))Gj($,{recursive:!0}),l0(`-- Created SQL directory: ${$}`);return $}function q7(X,$){if(!X)return!1;let Z=Jj();P$++;let U=`${R5?String(P$).padStart(10,"0"):String(Math.floor(Date.now()/1000)+P$)}-${$}.sql`,_=W5(Z,U);return Fj(_,X),l0(`-- Migration file created: ${U}`),B9++,!0}function V6(X){if(X.endsWith("_id"))return"bigint";if(X.endsWith("_at"))return"datetime";if(X.startsWith("is_")||X.startsWith("has_"))return"boolean";return}function I6(X){if(typeof X==="string"||typeof X==="number"||typeof X==="boolean"||typeof X==="bigint"||X instanceof Date)return X;return}function Wj(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 P7(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 Vj(X){if(!X||typeof X!=="object")return;let $=X;if($.name)switch(String($.name).toLowerCase()){case"string":case"text":{let Y=P7($);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"timestamptz":case"timestamp_tz":return"timestamptz";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==="timestamptz"||Z==="timestamp_tz")return"timestamptz";if(Z==="json")return"json"}return}function Ij(X){if(typeof X!=="string")return;switch(X.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function V5(X,$){let Z=Ej(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:PX(j),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let H of Object.keys(V)){let N=V[H],S=PX(H),h=Boolean(N.validation?.rule?.isRequired),d=H===j?!1:N.nullable??!(N.required??h),v,n,a=H===j;if(v=Ij(N.type)??Vj(N.validation?.rule),!v||v==="enum"){let m=Wj(N.validation?.rule);if(m&&m.length>0)v="enum",n=m}if(!v)v=V6(S);if(!v){let m=I6(N.default);if(typeof m==="string")v=m.length>255?"text":"string";else if(typeof m==="number")v=Number.isInteger(m)?"integer":"float";else if(typeof m==="boolean")v="boolean";else if(typeof m==="bigint")v="bigint";else if(m instanceof Date)v="datetime"}if(!v)v=a?"bigint":"string";let u=v==="string"?P7(N.validation?.rule):void 0,i={name:S,type:v,isPrimaryKey:a,isUnique:Boolean(N.unique),isNullable:d,hasDefault:typeof N.default<"u",defaultValue:I6(N.default),enumValues:n,maxLength:typeof u==="number"&&u>0&&u<=255?u:void 0};if(S.endsWith("_id")&&N.foreignKey!==!1)if(typeof N.foreignKey==="object"&&N.foreignKey!==null){let m=N.foreignKey;if(i.references={table:m.table,column:m.column??"id",onDelete:m.onDelete,onUpdate:m.onUpdate},m.nullable!==void 0)i.isNullable=m.nullable}else{let X0=S.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(z0,y,J9)=>J9.toUpperCase()),R0=Z.modelToTable[X0];if(R0){let z0=Z.primaryKeys[R0]??"id";i.references={table:R0,column:z0}}}G.push(i)}let W=jj(L.belongsTo);for(let H of W){let N=H.foreignKey??`${PX(H.model)}_id`;if(G.some((d)=>d.name===N))continue;let S=Z.modelToTable[H.model];if(!S)continue;let h=Z.primaryKeys[S]??"id";G.push({name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:S,column:h,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((N)=>PX(N)),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 w=Array.isArray(L.shardKey)?L.shardKey.map(PX):void 0,A=Array.isArray(L.sortKey)?L.sortKey.map(PX):void 0,P=L.tableKind;Y.push({table:z,columns:G,indexes:J,shardKey:w,sortKey:A,tableKind:P})}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`,q=D.replace(/s$/,""),w=J.table||[E,q].sort().join("_"),A=J.foreignKey||`${E}_id`,P=J.relatedKey||`${q}_id`,H=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:A,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:P,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:D,column:"id"}}];if(W.columns)for(let[h,d]of Object.entries(W.columns)){let v=d,n=V6(h)??"string";H.push({name:h,type:n,isPrimaryKey:!1,isUnique:!1,isNullable:v?.nullable??!1,hasDefault:v?.default!==void 0,defaultValue:v?.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 N=[],S=W.uniques&&W.uniques.length>0?W.uniques:[[A,P]];for(let h=0;h<S.length;h++){let d=S[h];N.push({name:`${w}_${d.join("_")}_unique${h>0?`_${h}`:""}`,columns:[...d],type:"unique"})}_({table:w,columns:H,indexes:N})}}return{dialect:$.dialect,tables:Y}}function I5(X,$={}){P$=0,B9=0,d9=0,R5=!0;let Z=$.dryRun?()=>!1:q7,Y=[],U=ZX(X.dialect),{tables:_,deferredForeignKeys:Q}=T7(X.tables,X.dialect);for(let[z,j]of _.entries()){let E={...j,columns:j.columns.map((F)=>Q.has(BX(j.table,F.name))?{...F,references:void 0}:F)},V=[],G=new Set;for(let F of E.columns)if(F.type==="enum"&&F.enumValues&&F.enumValues.length>0){let R=`${E.table}_${F.name}_type`;if(F.enumTypeName=R,!G.has(R)){let D=U.createEnumType(R,F.enumValues);if(D)V.push(D);G.add(R)}}let J=U.createTable(E);V.push(J);for(let F of E.indexes)V.push(U.createIndex(E.table,F));if(z===_.length-1)for(let F of _)for(let R of F.columns){if(!R.references||!Q.has(BX(F.table,R.name)))continue;let D=U.addForeignKey(F.table,R.name,R.references.table,R.references.column,R.references.onDelete,R.references.onUpdate);if(D)V.push(D)}Y.push(...V);let W=V.join(`
462
462
 
463
- `);Z(W,`create-${E.table}-table`)}if(B9+g9===0)l0("-- Nothing to migrate");else{let z=[];if(B9>0)z.push(`${B9} created`);if(g9>0)z.push(`${g9} updated`);l0(`-- Migration files: ${z.join(", ")}`)}return Y}function BX(X,$){return`${X}\x00${$}`}function T7(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(BX(z.table,j.name))}return U.push(...X.filter((z)=>Q.has(z.table))),{tables:U,deferredForeignKeys:L}}function NO(X){return V5(X).join(`
463
+ `);Z(W,`create-${E.table}-table`)}if(B9+d9===0)l0("-- Nothing to migrate");else{let z=[];if(B9>0)z.push(`${B9} created`);if(d9>0)z.push(`${d9} updated`);l0(`-- Migration files: ${z.join(", ")}`)}return Y}function BX(X,$){return`${X}\x00${$}`}function T7(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(BX(z.table,j.name))}return U.push(...X.filter((z)=>Q.has(z.table))),{tables:U,deferredForeignKeys:L}}function NO(X){return I5(X).join(`
464
464
  `)}function SO(X,$){return Cj(X,$).join(`
465
- `)}function Rj(X){let $=s7("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 E8(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"timestamptz":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 Kj(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 R6(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 Dj(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=R6(X[E],Z),G=_.get(V)??[];G.push(E),_.set(V,G)}for(let E of U){let V=R6($[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 Mj(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 Hj(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 K6(X){let $={};for(let Z of X){let Y=`${Z.type}:${Z.name}:${Z.columns.join(",")}`;$[Y]=Z}return $}function N7(X,$,Z={}){if(!X||X.dialect!==$.dialect){let D=V5($,{dryRun:Z.dryRun}),q=$.tables.map((w)=>({kind:"create_table",table:w.table,destructive:!1,sql:""}));return{statements:D,operations:q}}let Y=Z.applyRenames!==!1,U=Z.dryRun?()=>!1:q7;P$=0,B9=0,g9=0,I5=!1;let _=[],Q=[],L=ZX($.dialect),z=$.dialect,j=I6(X.tables),E=I6($.tables);for(let D of Object.keys(j))if(!E[D]){let q=L.dropTable(D);_.push(q),Q.push({kind:"drop_table",table:D,destructive:!0,sql:q}),U(q,`drop-${D}-table`),l0(`-- Detected dropped table: ${D}`)}let V=Object.keys(E).filter((D)=>!j[D]).map((D)=>E[D]),{tables:G,deferredForeignKeys:J}=T7(V,z);for(let[D,q]of G.entries()){let w={...q,columns:q.columns.map((S)=>J.has(BX(q.table,S.name))?{...S,references:void 0}:S)},A=[],P=new Set;for(let S of w.columns)if(S.type==="enum"&&S.enumValues&&S.enumValues.length>0){let h=`${w.table}_${S.name}_type`;if(S.enumTypeName=h,!P.has(h)){let d=L.createEnumType(h,S.enumValues);if(d)A.push(d);P.add(h)}}let H=L.createTable(w);A.push(H);for(let S of w.indexes){let h=L.createIndex(w.table,S);A.push(h),Q.push({kind:"create_index",table:w.table,column:S.name,destructive:!1,sql:h})}for(let S of q.columns)if(S.references&&!J.has(BX(q.table,S.name)))Q.push({kind:"add_foreign_key",table:q.table,column:S.name,destructive:!1,sql:H});if(D===G.length-1)for(let S of G)for(let h of S.columns){if(!h.references||!J.has(BX(S.table,h.name)))continue;let d=L.addForeignKey(S.table,h.name,h.references.table,h.references.column,h.references.onDelete,h.references.onUpdate);if(!d)continue;A.push(d),Q.push({kind:"add_foreign_key",table:S.table,column:h.name,destructive:!1,sql:d})}_.push(...A),Q.push({kind:"create_table",table:w.table,destructive:!1,sql:H});let N=A.join(`
465
+ `)}function Rj(X){let $=s7("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 R6(X){let $={};for(let Z of X)$[Z.table]=Z;return $}function E8(X){let $={};for(let Z of X)$[Z.name]=Z;return $}function u1(X,$){if($==="sqlite"){if(X.name.endsWith("_id")&&VU(X.type))return"INTEGER";switch(X.type){case"string":case"text":case"date":case"datetime":case"timestamptz":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 Kj(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 Dj(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 Mj(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 Hj(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 D6(X){let $={};for(let Z of X){let Y=`${Z.type}:${Z.name}:${Z.columns.join(",")}`;$[Y]=Z}return $}function N7(X,$,Z={}){if(!X||X.dialect!==$.dialect){let D=I5($,{dryRun:Z.dryRun}),q=$.tables.map((w)=>({kind:"create_table",table:w.table,destructive:!1,sql:""}));return{statements:D,operations:q}}let Y=Z.applyRenames!==!1,U=Z.dryRun?()=>!1:q7;P$=0,B9=0,d9=0,R5=!1;let _=[],Q=[],L=ZX($.dialect),z=$.dialect,j=R6(X.tables),E=R6($.tables);for(let D of Object.keys(j))if(!E[D]){let q=L.dropTable(D);_.push(q),Q.push({kind:"drop_table",table:D,destructive:!0,sql:q}),U(q,`drop-${D}-table`),l0(`-- Detected dropped table: ${D}`)}let V=Object.keys(E).filter((D)=>!j[D]).map((D)=>E[D]),{tables:G,deferredForeignKeys:J}=T7(V,z);for(let[D,q]of G.entries()){let w={...q,columns:q.columns.map((S)=>J.has(BX(q.table,S.name))?{...S,references:void 0}:S)},A=[],P=new Set;for(let S of w.columns)if(S.type==="enum"&&S.enumValues&&S.enumValues.length>0){let h=`${w.table}_${S.name}_type`;if(S.enumTypeName=h,!P.has(h)){let d=L.createEnumType(h,S.enumValues);if(d)A.push(d);P.add(h)}}let H=L.createTable(w);A.push(H);for(let S of w.indexes){let h=L.createIndex(w.table,S);A.push(h),Q.push({kind:"create_index",table:w.table,column:S.name,destructive:!1,sql:h})}for(let S of q.columns)if(S.references&&!J.has(BX(q.table,S.name)))Q.push({kind:"add_foreign_key",table:q.table,column:S.name,destructive:!1,sql:H});if(D===G.length-1)for(let S of G)for(let h of S.columns){if(!h.references||!J.has(BX(S.table,h.name)))continue;let d=L.addForeignKey(S.table,h.name,h.references.table,h.references.column,h.references.onDelete,h.references.onUpdate);if(!d)continue;A.push(d),Q.push({kind:"add_foreign_key",table:S.table,column:h.name,destructive:!1,sql:d})}_.push(...A),Q.push({kind:"create_table",table:w.table,destructive:!1,sql:H});let N=A.join(`
466
466
 
467
- `);U(N,`create-${w.table}-table`)}let W=new Set;for(let D of Object.keys(E)){let q=j[D],w=E[D];if(!q)continue;let A=E8(q.columns),P=E8(w.columns);for(let H of Object.keys(P))if(!A[H]){let N=P[H];if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let S=`${w.table}_${N.name}_type`;if(N.enumTypeName=S,!W.has(S)){let h=L.createEnumType(S,N.enumValues);if(h)_.push(h),Q.push({kind:"create_enum",table:w.table,column:N.name,destructive:!1,sql:h}),U(h,`create-${S}-enum`);W.add(S)}}}}for(let D of Object.keys(E)){let q=j[D],w=E[D];if(!q)continue;let A=E8(q.columns),P=E8(w.columns),H=K6(q.indexes),N=K6(w.indexes),S=[],h=Object.keys(A).filter((i)=>!P[i]),d=Object.keys(P).filter((i)=>!A[i]);if(Y){let i=Dj(A,P,z);S=i.renames,h=i.removed,d=i.added}let v=Object.keys(P).filter((i)=>A[i]&&Kj(A[i],P[i],z)),n=Object.keys(P).filter((i)=>A[i]&&Hj(A[i].references,P[i].references));if(z==="sqlite"){if(v.length>0||n.length>0||h.some((m)=>Mj(q,m))){let m={},X0=new Map(S.map((G0)=>[G0.to,G0.from]));for(let G0 of w.columns)if(A[G0.name])m[G0.name]=G0.name;else if(X0.has(G0.name))m[G0.name]=X0.get(G0.name);let R0=`_qb_tmp_${w.table}`,z0=0;while((j[R0]||E[R0])&&z0<100)z0+=1,R0=`_qb_tmp_${w.table}_${z0}`;let y=L.rebuildTable({target:w,tempName:R0,columnSource:m});_.push(y);let J9=v.some((G0)=>A[G0].type!==P[G0].type);Q.push({kind:"rebuild_table",table:w.table,destructive:h.length>0||J9,sql:y});for(let G0 of S)Q.push({kind:"rename_column",table:w.table,from:G0.from,to:G0.to,destructive:!1,confidence:"high",sql:y});for(let G0 of h)Q.push({kind:"drop_column",table:w.table,column:G0,destructive:!0,sql:y});l0(`-- Detected SQLite table rebuild required: ${w.table}`),U(y,`alter-${w.table}-table`);continue}}let a=[],u=!1;for(let i of Object.keys(H))if(!N[i]){let m=H[i],X0=L.dropIndex(w.table,m.name);a.push(X0),_.push(X0),Q.push({kind:"drop_index",table:w.table,column:m.name,destructive:!1,sql:X0}),l0(`-- Detected dropped index: ${m.name} from ${w.table}`),u=!0}for(let i of S){let m=L.renameColumn(w.table,i.from,i.to);a.push(m),_.push(m),Q.push({kind:"rename_column",table:w.table,from:i.from,to:i.to,destructive:!1,confidence:"high",sql:m}),l0(`-- Detected renamed column: ${w.table}.${i.from} -> ${i.to}`),u=!0}for(let i of h){let m=L.dropColumn(w.table,i);a.push(m),_.push(m),Q.push({kind:"drop_column",table:w.table,column:i,destructive:!0,sql:m}),l0(`-- Detected dropped column: ${w.table}.${i}`),u=!0}for(let i of v){let m=A[i],X0=P[i],R0=L.modifyColumn(w.table,X0);a.push(R0),_.push(R0),Q.push({kind:"modify_column",table:w.table,column:i,destructive:m.type!==X0.type,sql:R0}),l0(`-- Detected column change: ${w.table}.${i} (${m.type} -> ${X0.type})`),u=!0}for(let i of n){let m=P[i];if(!m.references)continue;let X0=L.addForeignKey(w.table,m.name,m.references.table,m.references.column,m.references.onDelete,m.references.onUpdate);if(!X0)continue;a.push(X0),_.push(X0),Q.push({kind:"add_foreign_key",table:w.table,column:i,destructive:!1,sql:X0}),l0(`-- Detected foreign-key change: ${w.table}.${i} -> ${m.references.table}(${m.references.column})`),u=!0}for(let i of d){let m=P[i],X0=L.addColumn(w.table,m);if(a.push(X0),_.push(X0),Q.push({kind:"add_column",table:w.table,column:m.name,destructive:!1,sql:X0}),l0(`-- Detected new column: ${w.table}.${m.name}`),u=!0,m.references){let R0=L.addForeignKey(w.table,m.name,m.references.table,m.references.column,m.references.onDelete,m.references.onUpdate);if(R0)a.push(R0),_.push(R0),Q.push({kind:"add_foreign_key",table:w.table,column:m.name,destructive:!1,sql:R0})}}for(let i of Object.keys(N))if(!H[i]){let m=N[i],X0=L.createIndex(w.table,m);a.push(X0),_.push(X0),Q.push({kind:"create_index",table:w.table,column:m.name,destructive:!1,sql:X0}),l0(`-- Detected new index: ${m.name} in ${w.table}`),u=!0}if(u){let i=a.join(`
467
+ `);U(N,`create-${w.table}-table`)}let W=new Set;for(let D of Object.keys(E)){let q=j[D],w=E[D];if(!q)continue;let A=E8(q.columns),P=E8(w.columns);for(let H of Object.keys(P))if(!A[H]){let N=P[H];if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let S=`${w.table}_${N.name}_type`;if(N.enumTypeName=S,!W.has(S)){let h=L.createEnumType(S,N.enumValues);if(h)_.push(h),Q.push({kind:"create_enum",table:w.table,column:N.name,destructive:!1,sql:h}),U(h,`create-${S}-enum`);W.add(S)}}}}for(let D of Object.keys(E)){let q=j[D],w=E[D];if(!q)continue;let A=E8(q.columns),P=E8(w.columns),H=D6(q.indexes),N=D6(w.indexes),S=[],h=Object.keys(A).filter((i)=>!P[i]),d=Object.keys(P).filter((i)=>!A[i]);if(Y){let i=Dj(A,P,z);S=i.renames,h=i.removed,d=i.added}let v=Object.keys(P).filter((i)=>A[i]&&Kj(A[i],P[i],z)),n=Object.keys(P).filter((i)=>A[i]&&Hj(A[i].references,P[i].references));if(z==="sqlite"){if(v.length>0||n.length>0||h.some((m)=>Mj(q,m))){let m={},X0=new Map(S.map((G0)=>[G0.to,G0.from]));for(let G0 of w.columns)if(A[G0.name])m[G0.name]=G0.name;else if(X0.has(G0.name))m[G0.name]=X0.get(G0.name);let R0=`_qb_tmp_${w.table}`,z0=0;while((j[R0]||E[R0])&&z0<100)z0+=1,R0=`_qb_tmp_${w.table}_${z0}`;let y=L.rebuildTable({target:w,tempName:R0,columnSource:m});_.push(y);let J9=v.some((G0)=>A[G0].type!==P[G0].type);Q.push({kind:"rebuild_table",table:w.table,destructive:h.length>0||J9,sql:y});for(let G0 of S)Q.push({kind:"rename_column",table:w.table,from:G0.from,to:G0.to,destructive:!1,confidence:"high",sql:y});for(let G0 of h)Q.push({kind:"drop_column",table:w.table,column:G0,destructive:!0,sql:y});l0(`-- Detected SQLite table rebuild required: ${w.table}`),U(y,`alter-${w.table}-table`);continue}}let a=[],u=!1;for(let i of Object.keys(H))if(!N[i]){let m=H[i],X0=L.dropIndex(w.table,m.name);a.push(X0),_.push(X0),Q.push({kind:"drop_index",table:w.table,column:m.name,destructive:!1,sql:X0}),l0(`-- Detected dropped index: ${m.name} from ${w.table}`),u=!0}for(let i of S){let m=L.renameColumn(w.table,i.from,i.to);a.push(m),_.push(m),Q.push({kind:"rename_column",table:w.table,from:i.from,to:i.to,destructive:!1,confidence:"high",sql:m}),l0(`-- Detected renamed column: ${w.table}.${i.from} -> ${i.to}`),u=!0}for(let i of h){let m=L.dropColumn(w.table,i);a.push(m),_.push(m),Q.push({kind:"drop_column",table:w.table,column:i,destructive:!0,sql:m}),l0(`-- Detected dropped column: ${w.table}.${i}`),u=!0}for(let i of v){let m=A[i],X0=P[i],R0=L.modifyColumn(w.table,X0);a.push(R0),_.push(R0),Q.push({kind:"modify_column",table:w.table,column:i,destructive:m.type!==X0.type,sql:R0}),l0(`-- Detected column change: ${w.table}.${i} (${m.type} -> ${X0.type})`),u=!0}for(let i of n){let m=P[i];if(!m.references)continue;let X0=L.addForeignKey(w.table,m.name,m.references.table,m.references.column,m.references.onDelete,m.references.onUpdate);if(!X0)continue;a.push(X0),_.push(X0),Q.push({kind:"add_foreign_key",table:w.table,column:i,destructive:!1,sql:X0}),l0(`-- Detected foreign-key change: ${w.table}.${i} -> ${m.references.table}(${m.references.column})`),u=!0}for(let i of d){let m=P[i],X0=L.addColumn(w.table,m);if(a.push(X0),_.push(X0),Q.push({kind:"add_column",table:w.table,column:m.name,destructive:!1,sql:X0}),l0(`-- Detected new column: ${w.table}.${m.name}`),u=!0,m.references){let R0=L.addForeignKey(w.table,m.name,m.references.table,m.references.column,m.references.onDelete,m.references.onUpdate);if(R0)a.push(R0),_.push(R0),Q.push({kind:"add_foreign_key",table:w.table,column:m.name,destructive:!1,sql:R0})}}for(let i of Object.keys(N))if(!H[i]){let m=N[i],X0=L.createIndex(w.table,m);a.push(X0),_.push(X0),Q.push({kind:"create_index",table:w.table,column:m.name,destructive:!1,sql:X0}),l0(`-- Detected new index: ${m.name} in ${w.table}`),u=!0}if(u){let i=a.join(`
468
468
 
469
- `);U(i,`alter-${w.table}-table`)}}if(B9+g9===0)l0("-- Nothing to migrate");else{let D=[];if(B9>0)D.push(`${B9} created`);if(g9>0)D.push(`${g9} updated`);l0(`-- Migration files: ${D.join(", ")}`)}return{statements:_.length===0?["-- No changes detected"]:_,operations:Q}}function Cj(X,$,Z={}){return N7(X,$,Z).statements}var P$=0,B9=0,g9=0,I5=!0,wj=e(()=>{c0(),QZ(),H7()});function AO(X){return X}class qj{get order(){return 100}get description(){return}}function kO(X){return X}var v0=e(async()=>{T8(),T8(),Mz(),H6(),_Z(),T8(),await c0(),QZ(),O5(),K7(),Zj(),j2(),Lj(),H7(),wj(),J7(),X5()});await v0();var A7=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000","PRAGMA wal_autocheckpoint = 1"];function Tj(X){for(let $ of A7)try{X.unsafe($).execute().catch(()=>{})}catch{}}var S7=new WeakSet;function k7(){try{let X=G7?.();if(!X||typeof X.run!=="function"||S7.has(X))return;for(let $ of A7)try{X.run($)}catch{}S7.add(X)}catch{}}function uO(X){E7(X),k7()}function nO(X){let $=H0(X);if(!X?.sql&&f.dialect==="sqlite")Tj($),k7();return $}var Nj=new Map;function iO(X,$){let Z=GZ;if(typeof Z==="function")return Z(X,$);Nj.set(X,$);let Y=typeof $?.getDefinition==="function"?$.getDefinition():$?.definition;if(Y&&typeof Y==="object")F5(Y);return $}var Sj=/^[A-Z_][A-Z0-9_]*$/i;function Aj(X,$={}){if(typeof X!=="string"||X.length===0)return{valid:!1,reason:"empty"};if(X.length>64)return{valid:!1,reason:"too-long"};if(!Sj.test(X))return{valid:!1,reason:"invalid-shape"};if($.allowlist&&!$.allowlist.includes(X))return{valid:!1,reason:"not-in-allowlist"};return{valid:!0}}function lO(X,$={}){let Z=Aj(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 x7=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function kj(X){return typeof X==="string"&&x7.has(X.toLowerCase())}function sO(X,$){if(kj(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 (${[...x7].join(", ")})`)}export{fG as wipeDatabase,kF as waitReady,Rz as validateSchema,Aj as validateIdentifier,PF as unsafe,RO as unmarshallItem,VO as toModelInstance,WO as toDynamoDBItem,SG as tinker,pG as tableInfo,r_ as startConsole,MO as stacksModelToEntity,EQ as sqlTypeToAttr,qF as sql,EF as showModel,i_ as setQueryCacheMaxSize,P_ as setConfig,GO as seedModel,CU as saveMigrationSnapshot,Fz as runSeeders,HF as runSeeder,MG as runBenchmark,T_ as resolveSqlitePragmas,TX as resolvePivot,O6 as resolveKeyPattern,kQ as resetDatabase,DG as resetConnection,RF as relationDiagram,iO as registerModel,aL as registerBrowserModels,CG as raw,JF as queryExplainAll,GF as ping,$j as parseStacksModels,vG as optimizeDatabase,EF as modelShow,zU as modelNameForTable,lQ as migrateStatus,ZF as migrateRollback,nj as migrateModels,QF as migrateList,tG as migrateGenerate,IO as marshallObject,CF as makeSeeder,lG as makeModel,pX as loadModels,HG as iterateAllPivots,kj as isSafeOperator,I0 as isMysqlLike,uj as isDefinitionEqual,pj as isBrowser,mG as introspectDatabase,cG as introspect,zQ as inspectTable,xG as importData,N8 as hashTableDefinition,Rj as hashMigrationPlan,sL as hasModel,b0 as getPlaceholders,l as getPlaceholder,lL as getModelRegistry,nL as getModel,ZX as getDialectDriver,G7 as getDatabase,WG as getConfig,dj as getBrowserConfig,iL as getAllModels,NO as generateSqlString,V5 as generateSql,JQ as generateModelSource,wU as generateMigration,SO as generateDiffSqlString,Cj as generateDiffSql,N7 as generateDiffOperations,RF as generateDiagram,DO as generateAccessPatterns,wF as freshDatabase,dG as file,Z2 as extractTableDefinition,Y2 as extractModelSchema,G6 as extractInsertId,E6 as extractChanges,kG as exportData,JF as explainAllQueries,gG as explain,AQ as executeMigration,L2 as dynamo,BG as dumpDatabase,kO as defineSeeder,AO as defineModels,F5 as defineModel,H1 as defaultConfig,fG as dbWipe,yG as dbStats,vG as dbOptimize,$Q as dbInfo,EO as createTableFromModel,tL as createSingleTableManager,eL as createRepository,nO as createQueryBuilder,pL as createModel,Q2 as createMigrationDriver,KO as createDynamoDBToolingAdapter,FO as createDynamoDBQueryBuilder,OO as createDynamoDBItemBuilder,gX as createDynamoDBDriver,JO as createDynamoDBClient,ij as createDynamo,q6 as createClient,o7 as createBrowserModel,cj as createBrowserDb,U2 as convertSchemaToDefinition,uO as configureOrm,mj as configureModels,gj as configureBrowser,f as config,n_ as clearQueryCache,oL as clearModelRegistry,AF as checkSchema,n1 as canonicalizeDefault,u1 as canonicalStorageType,qG as cacheStats,PG as cacheConfig,wG as cacheClear,Ej as buildSchemaMeta,W5 as buildMigrationPlan,_2 as buildDynamoDBMigrationPlan,M7 as buildDatabaseSchema,M6 as browserQuery,r7 as browserAuth,k7 as bootstrapModelExecutorPragmas,sO as assertSafeOperator,lO as assertSafeIdentifier,Tj as applySqlitePragmas,e1 as applySqliteBootstrapPragmas,I7 as SingleTableRepository,R7 as SingleTableQueryBuilder,Xj as SingleTablePatterns,V7 as SingleTableManager,JU as SingleStoreDriver,qj as Seeder,VU as SQLiteDriver,A7 as SQLITE_BOOTSTRAP_PRAGMAS,nO as QueryBuilder,OU as PostgresDriver,Y5 as MySQLDriver,X2 as Model,K9 as MIGRATIONS_TABLE,A6 as EntityQueryBuilder,D7 as DynamoDBToolingAdapter,dX 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,O7 as BelongsToManyRelationBuilder};
469
+ `);U(i,`alter-${w.table}-table`)}}if(B9+d9===0)l0("-- Nothing to migrate");else{let D=[];if(B9>0)D.push(`${B9} created`);if(d9>0)D.push(`${d9} updated`);l0(`-- Migration files: ${D.join(", ")}`)}return{statements:_.length===0?["-- No changes detected"]:_,operations:Q}}function Cj(X,$,Z={}){return N7(X,$,Z).statements}var P$=0,B9=0,d9=0,R5=!0,wj=e(()=>{c0(),QZ(),H7()});function AO(X){return X}class qj{get order(){return 100}get description(){return}}function kO(X){return X}var v0=e(async()=>{T8(),T8(),Mz(),C6(),_Z(),T8(),await c0(),QZ(),J5(),K7(),Zj(),j2(),Lj(),H7(),wj(),J7(),X5()});await v0();var A7=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000","PRAGMA wal_autocheckpoint = 1"];function Tj(X){for(let $ of A7)try{X.unsafe($).execute().catch(()=>{})}catch{}}var S7=new WeakSet;function k7(){try{let X=G7?.();if(!X||typeof X.run!=="function"||S7.has(X))return;for(let $ of A7)try{X.run($)}catch{}S7.add(X)}catch{}}function uO(X){E7(X),k7()}function nO(X){let $=H0(X);if(!X?.sql&&f.dialect==="sqlite")Tj($),k7();return $}var Nj=new Map;function iO(X,$){let Z=GZ;if(typeof Z==="function")return Z(X,$);Nj.set(X,$);let Y=typeof $?.getDefinition==="function"?$.getDefinition():$?.definition;if(Y&&typeof Y==="object")O5(Y);return $}var Sj=/^[A-Z_][A-Z0-9_]*$/i;function Aj(X,$={}){if(typeof X!=="string"||X.length===0)return{valid:!1,reason:"empty"};if(X.length>64)return{valid:!1,reason:"too-long"};if(!Sj.test(X))return{valid:!1,reason:"invalid-shape"};if($.allowlist&&!$.allowlist.includes(X))return{valid:!1,reason:"not-in-allowlist"};return{valid:!0}}function lO(X,$={}){let Z=Aj(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 x7=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function kj(X){return typeof X==="string"&&x7.has(X.toLowerCase())}function sO(X,$){if(kj(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 (${[...x7].join(", ")})`)}export{fG as wipeDatabase,kF as waitReady,Rz as validateSchema,Aj as validateIdentifier,PF as unsafe,RO as unmarshallItem,VO as toModelInstance,WO as toDynamoDBItem,SG as tinker,pG as tableInfo,r_ as startConsole,MO as stacksModelToEntity,EQ as sqlTypeToAttr,qF as sql,EF as showModel,i_ as setQueryCacheMaxSize,P_ as setConfig,GO as seedModel,CU as saveMigrationSnapshot,Fz as runSeeders,HF as runSeeder,MG as runBenchmark,T_ as resolveSqlitePragmas,TX as resolvePivot,J6 as resolveKeyPattern,kQ as resetDatabase,DG as resetConnection,RF as relationDiagram,iO as registerModel,aL as registerBrowserModels,CG as raw,JF as queryExplainAll,GF as ping,$j as parseStacksModels,vG as optimizeDatabase,EF as modelShow,LU as modelNameForTable,lQ as migrateStatus,ZF as migrateRollback,nj as migrateModels,QF as migrateList,tG as migrateGenerate,IO as marshallObject,CF as makeSeeder,lG as makeModel,pX as loadModels,HG as iterateAllPivots,kj as isSafeOperator,I0 as isMysqlLike,uj as isDefinitionEqual,pj as isBrowser,mG as introspectDatabase,cG as introspect,zQ as inspectTable,xG as importData,N8 as hashTableDefinition,Rj as hashMigrationPlan,sL as hasModel,b0 as getPlaceholders,l as getPlaceholder,lL as getModelRegistry,nL as getModel,ZX as getDialectDriver,G7 as getDatabase,WG as getConfig,dj as getBrowserConfig,iL as getAllModels,NO as generateSqlString,I5 as generateSql,JQ as generateModelSource,wU as generateMigration,SO as generateDiffSqlString,Cj as generateDiffSql,N7 as generateDiffOperations,RF as generateDiagram,DO as generateAccessPatterns,wF as freshDatabase,dG as file,Z2 as extractTableDefinition,Y2 as extractModelSchema,F6 as extractInsertId,G6 as extractChanges,kG as exportData,JF as explainAllQueries,gG as explain,AQ as executeMigration,L2 as dynamo,BG as dumpDatabase,kO as defineSeeder,AO as defineModels,O5 as defineModel,H1 as defaultConfig,fG as dbWipe,yG as dbStats,vG as dbOptimize,$Q as dbInfo,EO as createTableFromModel,tL as createSingleTableManager,eL as createRepository,nO as createQueryBuilder,pL as createModel,Q2 as createMigrationDriver,KO as createDynamoDBToolingAdapter,FO as createDynamoDBQueryBuilder,OO as createDynamoDBItemBuilder,gX as createDynamoDBDriver,JO as createDynamoDBClient,ij as createDynamo,P6 as createClient,o7 as createBrowserModel,cj as createBrowserDb,U2 as convertSchemaToDefinition,uO as configureOrm,mj as configureModels,gj as configureBrowser,f as config,n_ as clearQueryCache,oL as clearModelRegistry,AF as checkSchema,n1 as canonicalizeDefault,u1 as canonicalStorageType,qG as cacheStats,PG as cacheConfig,wG as cacheClear,Ej as buildSchemaMeta,V5 as buildMigrationPlan,_2 as buildDynamoDBMigrationPlan,M7 as buildDatabaseSchema,H6 as browserQuery,r7 as browserAuth,k7 as bootstrapModelExecutorPragmas,sO as assertSafeOperator,lO as assertSafeIdentifier,Tj as applySqlitePragmas,e1 as applySqliteBootstrapPragmas,I7 as SingleTableRepository,R7 as SingleTableQueryBuilder,Xj as SingleTablePatterns,V7 as SingleTableManager,WU as SingleStoreDriver,qj as Seeder,IU as SQLiteDriver,A7 as SQLITE_BOOTSTRAP_PRAGMAS,nO as QueryBuilder,JU as PostgresDriver,Y5 as MySQLDriver,X2 as Model,K9 as MIGRATIONS_TABLE,k6 as EntityQueryBuilder,D7 as DynamoDBToolingAdapter,dX as DynamoDBQueryBuilder,N6 as DynamoDBMigrationTracker,A6 as DynamoDBMigrationDriver,g9 as DynamoDBItemBuilder,w6 as DynamoDBDriverImpl,q6 as DynamoDBClient,UU as DEFAULT_SQLITE_PRAGMAS,y9 as BrowserQueryError,M6 as BrowserQueryBuilder,O7 as BelongsToManyRelationBuilder};