@stacksjs/database 0.70.45 → 0.70.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/dist/auth-tables.d.ts +56 -0
- package/dist/class-seeder.d.ts +49 -0
- package/dist/database.d.ts +3 -2
- package/dist/driver-config.d.ts +30 -1
- package/dist/drivers/dynamodb.d.ts +70 -18
- package/dist/drivers/helpers.d.ts +6 -0
- package/dist/drivers/mysql.d.ts +1 -1
- package/dist/drivers/postgres.d.ts +1 -1
- package/dist/drivers/sqlite.d.ts +6 -9
- package/dist/factory.d.ts +41 -0
- package/dist/fk-audit.d.ts +101 -0
- package/dist/index.d.ts +39 -2
- package/dist/index.js +1140 -1104
- package/dist/migration-lock.d.ts +23 -0
- package/dist/migrations.d.ts +46 -5
- package/dist/notification-tables.d.ts +20 -0
- package/dist/rbac-tables.d.ts +17 -0
- package/dist/seed-scaffold.d.ts +34 -0
- package/dist/seeder.d.ts +59 -0
- package/dist/sql-helpers.d.ts +2 -0
- package/dist/transaction-context.d.ts +52 -0
- package/dist/types.d.ts +82 -0
- package/dist/unique-audit.d.ts +60 -0
- package/dist/utils.d.ts +41 -2
- package/dist/uuid-columns.d.ts +22 -0
- package/package.json +11 -11
package/dist/index.js
CHANGED
|
@@ -1,998 +1,858 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var s_=Object.defineProperty;var l_=($)=>$;function n_($,Z){this[$]=l_.bind(null,Z)}var i_=($,Z)=>{for(var X in Z)s_($,X,{get:Z[X],enumerable:!0,configurable:!0,set:n_.bind(Z,X)})};var t5=($,Z)=>()=>($&&(Z=$($=0)),Z);var H0=import.meta.require;import{existsSync as z7,statSync as U7}from"fs";import{existsSync as FY,mkdirSync as dQ,readdirSync as uQ,readFileSync as VY,writeFileSync as mQ}from"fs";import{homedir as F8}from"os";import{dirname as nQ,resolve as j9}from"path";import r$ from"process";import{existsSync as j7,statSync as E7}from"fs";import{existsSync as uZ,mkdirSync as WY,readdirSync as KY,writeFileSync as IY}from"fs";import{homedir as V8}from"os";import{dirname as O7,resolve as e0}from"path";import z8 from"process";import{join as JY,relative as DY,resolve as Q7}from"path";import o$ from"process";import{existsSync as X2,mkdirSync as _G,readdirSync as YG,writeFileSync as LG}from"fs";import{homedir as e5}from"os";import{dirname as jG,resolve as a0}from"path";import k1 from"process";import{join as RY,relative as SY,resolve as G7}from"path";import a$ from"process";import{existsSync as _2,mkdirSync as FG,readdirSync as VG,writeFileSync as WG}from"fs";import{dirname as IG,resolve as t$}from"path";import mZ from"process";import{Buffer as n9}from"buffer";import{createCipheriv as MY,createDecipheriv as wY,randomBytes as $Z}from"crypto";import{closeSync as ZZ,createReadStream as F7,createWriteStream as HY,existsSync as XZ,fsyncSync as V7,openSync as W7,writeFileSync as qY}from"fs";import{access as TY,constants as K7,mkdir as PY,readdir as _$,rename as I7,stat as W8,unlink as Y$,writeFile as _Z}from"fs/promises";import{join as K8}from"path";import y0 from"process";import{pipeline as NY}from"stream/promises";import{createGzip as J7}from"zlib";import I8 from"process";import A9 from"process";import{Buffer as C9}from"buffer";import{createCipheriv as kY,createDecipheriv as CY,randomBytes as YZ}from"crypto";import{closeSync as LZ,createReadStream as D7,createWriteStream as xY,existsSync as L$,fsyncSync as R7,openSync as S7,writeFileSync as BY}from"fs";import{access as AY,constants as M7,mkdir as yY,readdir as z$,rename as w7,stat as J8,unlink as U$,writeFile as zZ}from"fs/promises";import{isAbsolute as hY,join as D8,resolve as vY}from"path";import X0 from"process";import{pipeline as bY}from"stream/promises";import{createGzip as H7}from"zlib";import R8 from"process";import y9 from"process";import j$ from"process";import{existsSync as E$}from"fs";import{resolve as UZ}from"path";import{existsSync as fY}from"fs";import{existsSync as gY,readdirSync as pY}from"fs";import{extname as jZ,resolve as q7}from"path";import cY from"process";import{join as dY,relative as uY,resolve as T7}from"path";import e$ from"process";import{Buffer as x9}from"buffer";import{createCipheriv as mY,createDecipheriv as sY,randomBytes as EZ}from"crypto";import{closeSync as OZ,createReadStream as P7,createWriteStream as lY,existsSync as O$,fsyncSync as N7,openSync as k7,writeFileSync as nY}from"fs";import{access as iY,constants as C7,mkdir as rY,readdir as Q$,rename as x7,stat as S8,unlink as G$,writeFile as QZ}from"fs/promises";import{isAbsolute as oY,join as M8,resolve as aY}from"path";import _0 from"process";import{pipeline as tY}from"stream/promises";import{createGzip as B7}from"zlib";import w8 from"process";import h9 from"process";import F$ from"process";import{existsSync as V$}from"fs";import{resolve as GZ}from"path";import{existsSync as eY}from"fs";import{Database as kz}from"bun:sqlite";import I$ from"process";import{existsSync as o9,mkdirSync as A2,mkdtempSync as tz,readdirSync as y2,readFileSync as h2,rmSync as ez,unlinkSync as p$,writeFileSync as v2}from"fs";import{tmpdir as $U}from"os";import{join as m0}from"path";import f1 from"process";import{existsSync as SU}from"fs";import{join as MU}from"path";import wU from"process";import{existsSync as GX,statSync as FX}from"fs";import{existsSync as HU,mkdirSync as DF,readdirSync as RF,writeFileSync as SF}from"fs";import{homedir as H8}from"os";import{dirname as HF,resolve as E9}from"path";import U5 from"process";import{join as qU,relative as TU,resolve as VX}from"path";import j5 from"process";import{existsSync as c2,mkdirSync as kF,readdirSync as CF,writeFileSync as xF}from"fs";import{homedir as PZ}from"os";import{dirname as yF,resolve as t0}from"path";import A1 from"process";import{join as PU,relative as NU,resolve as WX}from"path";import E5 from"process";import{existsSync as d2,mkdirSync as gF,readdirSync as pF,writeFileSync as cF}from"fs";import{dirname as uF,resolve as O5}from"path";import X6 from"process";import{Buffer as i9}from"buffer";import{createCipheriv as kU,createDecipheriv as CU,randomBytes as NZ}from"crypto";import{closeSync as kZ,createReadStream as KX,createWriteStream as xU,existsSync as CZ,fsyncSync as IX,openSync as JX,writeFileSync as BU}from"fs";import{access as AU,constants as DX,mkdir as yU,readdir as D$,rename as RX,stat as q8,unlink as R$,writeFile as xZ}from"fs/promises";import{join as T8}from"path";import v0 from"process";import{pipeline as hU}from"stream/promises";import{createGzip as SX}from"zlib";import P8 from"process";import v9 from"process";import{Buffer as B9}from"buffer";import{createCipheriv as vU,createDecipheriv as bU,randomBytes as BZ}from"crypto";import{closeSync as AZ,createReadStream as MX,createWriteStream as fU,existsSync as S$,fsyncSync as wX,openSync as HX,writeFileSync as gU}from"fs";import{access as pU,constants as qX,mkdir as cU,readdir as M$,rename as TX,stat as N8,unlink as w$,writeFile as yZ}from"fs/promises";import{isAbsolute as dU,join as k8,resolve as uU}from"path";import U0 from"process";import{pipeline as mU}from"stream/promises";import{createGzip as PX}from"zlib";import C8 from"process";import b9 from"process";import H$ from"process";import{existsSync as q$}from"fs";import{resolve as hZ}from"path";import{existsSync as sU}from"fs";import{spawnSync as lU}from"child_process";import{existsSync as B8,readFileSync as nU}from"fs";import{join as A8}from"path";import u2 from"process";import{Database as lj}from"bun:sqlite";import{readdirSync as LE,statSync as zE}from"fs";import{basename as UE,extname as jE}from"path";import EE from"process";import{existsSync as H4,mkdirSync as GE,writeFileSync as FE}from"fs";import{dirname as sX,join as N6}from"path";import q4 from"process";function t_($){return this[$]}function ZY($,Z){this[$]=$Y.bind(null,Z)}async function x$(){if(Z0.getToken){let $=Z0.getToken();return $ instanceof Promise?$:$}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function u0(){let $={"Content-Type":"application/json",Accept:"application/json",...Z0.headers},Z=await x$();if(Z)$.Authorization=`Bearer ${Z}`;return $}async function O9($){if($.status===401)throw Z0.onUnauthorized?.(),new c9("Unauthorized",401);if(!$.ok){let X=await $.json().catch(()=>({message:"Request failed"}));throw new c9(X.message||`HTTP ${$.status}`,$.status)}let Z=await $.json();if(Z0.transformResponse)return Z0.transformResponse(Z);return Z}class oX{state;constructor($){this.state={table:$,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...$){return this.state.selectColumns=$,this}where($,Z,X){if(X===void 0)this.state.wheres.push({column:$,operator:"=",value:Z,boolean:"and"});else this.state.wheres.push({column:$,operator:Z,value:X,boolean:"and"});return this}orWhere($,Z,X){if(X===void 0)this.state.wheres.push({column:$,operator:"=",value:Z,boolean:"or"});else this.state.wheres.push({column:$,operator:Z,value:X,boolean:"or"});return this}andWhere($,Z,X){return this.where($,Z,X)}whereNull($){return this.where($,"is",null)}whereNotNull($){return this.where($,"is not",null)}whereIn($,Z){return this.where($,"in",Z)}whereNotIn($,Z){return this.where($,"not in",Z)}orderBy($,Z="asc"){return this.state.orderBy.push({column:$,direction:Z}),this}orderByDesc($){return this.orderBy($,"desc")}latest($="created_at"){return this.orderBy($,"desc")}oldest($="created_at"){return this.orderBy($,"asc")}limit($){return this.state.limitValue=$,this}offset($){return this.state.offsetValue=$,this}skip($){return this.offset($)}take($){return this.limit($)}with(...$){return this.state.withRelations.push(...$),this}buildQueryParams(){let $=new URLSearchParams;for(let Z of this.state.wheres)if(Z.operator==="=")$.append(Z.column,String(Z.value));else if(Z.operator==="in"&&Array.isArray(Z.value))$.append(`${Z.column}[]`,Z.value.join(","));else if(Z.operator==="is"&&Z.value===null)$.append(`filter[${Z.column}][is]`,"null");else if(Z.operator==="is not"&&Z.value===null)$.append(`filter[${Z.column}][is_not]`,"null");else $.append(`filter[${Z.column}][${Z.operator}]`,String(Z.value));if(this.state.orderBy.length>0){let Z=this.state.orderBy.map((X)=>`${X.direction==="desc"?"-":""}${X.column}`).join(",");$.append("sort",Z)}if(this.state.limitValue!==void 0)$.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)$.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))$.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)$.append("include",this.state.withRelations.join(","));return $}buildUrl($){let Z=`${Z0.baseUrl}/${this.state.table}`;if($!==void 0)return`${Z}/${$}`;let _=this.buildQueryParams().toString();return _?`${Z}?${_}`:Z}async get(){let $=this.buildUrl(),Z=await fetch($,{method:"GET",headers:await u0()}),X=await O9(Z);return Array.isArray(X)?X:X.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new c9(`No ${this.state.table} found`,404);return $}async find($){let Z=this.buildUrl($);try{let X=await fetch(Z,{method:"GET",headers:await u0()});if(X.status===404)return null;let _=await O9(X);return"data"in _&&!Array.isArray(_.data)?_.data:_}catch{return null}}async findOrFail($){let Z=await this.find($);if(!Z)throw new c9(`${this.state.table} with id ${$} not found`,404);return Z}async count(){let $=this.buildQueryParams();$.append("count","true");let Z=`${Z0.baseUrl}/${this.state.table}?${$.toString()}`,X=await fetch(Z,{method:"GET",headers:await u0()});return(await O9(X)).count}async exists(){return await this.count()>0}async create($){let Z=`${Z0.baseUrl}/${this.state.table}`,X=Z0.transformRequest?Z0.transformRequest($):$,_=await fetch(Z,{method:"POST",headers:await u0(),body:JSON.stringify(X)}),Y=await O9(_);return"data"in Y&&!Array.isArray(Y.data)?Y.data:Y}async insert($){return this.create($)}async update($,Z){let X=`${Z0.baseUrl}/${this.state.table}/${$}`,_=Z0.transformRequest?Z0.transformRequest(Z):Z,Y=await fetch(X,{method:"PATCH",headers:await u0(),body:JSON.stringify(_)}),L=await O9(Y);return"data"in L&&!Array.isArray(L.data)?L.data:L}async delete($){let Z=`${Z0.baseUrl}/${this.state.table}/${$}`;return(await fetch(Z,{method:"DELETE",headers:await u0()})).ok}async destroy($){return this.delete($)}async paginate($=1,Z=15){this.limit(Z).offset(($-1)*Z);let X=this.buildQueryParams();X.append("paginate","true");let _=`${Z0.baseUrl}/${this.state.table}?${X.toString()}`,Y=await fetch(_,{method:"GET",headers:await u0()});return O9(Y)}toState(){return{...this.state}}}function _Y($){return new oX($)}class v8{_attributes;_definition;constructor($,Z={}){this._definition=$,this._attributes={...Z}}get($){return this._attributes[$]}set($,Z){this._attributes[$]=Z}get attributes(){return{...this._attributes}}get id(){let $=this._definition.primaryKey||"id";return this._attributes[$]}toJSON(){let $=new Set;for(let[X,_]of Object.entries(this._definition.attributes))if(_.hidden)$.add(X);let Z={};for(let[X,_]of Object.entries(this._attributes))if(!$.has(X))Z[X]=_;return Z}}class O0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor($){this._definition=$}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"and"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"and"});return this}orWhere($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"or"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"or"});return this}whereIn($,Z){return this._wheres.push({column:$,operator:"in",value:Z,boolean:"and"}),this}whereNotIn($,Z){return this._wheres.push({column:$,operator:"not in",value:Z,boolean:"and"}),this}whereNull($){return this._wheres.push({column:$,operator:"is",value:null,boolean:"and"}),this}whereNotNull($){return this._wheres.push({column:$,operator:"is not",value:null,boolean:"and"}),this}whereLike($,Z){return this._wheres.push({column:$,operator:"like",value:Z,boolean:"and"}),this}orderBy($,Z="asc"){return this._orderBy.push({column:$,direction:Z}),this}orderByDesc($){return this.orderBy($,"desc")}orderByAsc($){return this.orderBy($,"asc")}limit($){return this._limit=$,this}take($){return this.limit($)}offset($){return this._offset=$,this}skip($){return this.offset($)}select(...$){return this._select=$,this}with(...$){return this._withRelations.push(...$),this}latest($="created_at"){return this.orderByDesc($)}oldest($="created_at"){return this.orderByAsc($)}buildQueryParams(){let $=new URLSearchParams;for(let Z of this._wheres)if(Z.operator==="=")$.append(Z.column,String(Z.value));else if((Z.operator==="in"||Z.operator==="not in")&&Array.isArray(Z.value))$.append(`${Z.column}[]`,Z.value.join(","));else if(Z.operator==="is"&&Z.value===null)$.append(`filter[${Z.column}][is]`,"null");else if(Z.operator==="is not"&&Z.value===null)$.append(`filter[${Z.column}][is_not]`,"null");else $.append(`filter[${Z.column}][${Z.operator}]`,String(Z.value));if(this._orderBy.length>0){let Z=this._orderBy.map((X)=>`${X.direction==="desc"?"-":""}${X.column}`).join(",");$.append("sort",Z)}if(this._limit!==void 0)$.append("limit",String(this._limit));if(this._offset!==void 0)$.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))$.append("fields",this._select.join(","));if(this._withRelations.length>0)$.append("include",this._withRelations.join(","));return $}buildUrl($){let Z=`${Z0.baseUrl}/${this.getTablePath()}`;if($!==void 0)return`${Z}/${$}`;let _=this.buildQueryParams().toString();return _?`${Z}?${_}`:Z}async get(){let $=this.buildUrl(),Z=await fetch($,{method:"GET",headers:await u0()}),X=await O9(Z);return(Array.isArray(X)?X:X.data).map((Y)=>new v8(this._definition,Y))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new c9(`No ${this._definition.name} found`,404);return $}async find($){let Z=this.buildUrl($);try{let X=await fetch(Z,{method:"GET",headers:await u0()});if(X.status===404)return null;let _=await O9(X),Y="data"in _&&!Array.isArray(_.data)?_.data:_;return new v8(this._definition,Y)}catch{return null}}async findOrFail($){let Z=await this.find($);if(!Z)throw new c9(`${this._definition.name} with id ${$} not found`,404);return Z}async count(){let $=this.buildQueryParams();$.append("count","true");let Z=`${Z0.baseUrl}/${this.getTablePath()}?${$.toString()}`,X=await fetch(Z,{method:"GET",headers:await u0()});return(await O9(X)).count}async exists(){return await this.count()>0}async pluck($){return this._select=[$],(await this.get()).map((X)=>X.get($))}async paginate($=1,Z=15){this._limit=Z,this._offset=($-1)*Z;let X=this.buildQueryParams();X.append("paginate","true");let _=`${Z0.baseUrl}/${this.getTablePath()}?${X.toString()}`,Y=await fetch(_,{method:"GET",headers:await u0()}),L=await O9(Y);return{...L,data:L.data.map((z)=>new v8(this._definition,z))}}}function YY($){return new Proxy({query:()=>new O0($),where(X,_,Y){return new O0($).where(X,_,Y)},orWhere(X,_,Y){return new O0($).orWhere(X,_,Y)},whereIn(X,_){return new O0($).whereIn(X,_)},whereNotIn(X,_){return new O0($).whereNotIn(X,_)},whereNull(X){return new O0($).whereNull(X)},whereNotNull(X){return new O0($).whereNotNull(X)},whereLike(X,_){return new O0($).whereLike(X,_)},orderBy(X,_="asc"){return new O0($).orderBy(X,_)},orderByDesc(X){return new O0($).orderByDesc(X)},select(...X){return new O0($).select(...X)},limit:(X)=>new O0($).limit(X),take:(X)=>new O0($).take(X),skip:(X)=>new O0($).skip(X),latest:(X="created_at")=>new O0($).latest(X),oldest:(X="created_at")=>new O0($).oldest(X),async find(X){return new O0($).find(X)},async findOrFail(X){return new O0($).findOrFail(X)},async all(){return new O0($).get()},async first(){return new O0($).first()},async firstOrFail(){return new O0($).firstOrFail()},async count(){return new O0($).count()},async exists(){return new O0($).exists()},async paginate(X,_){return new O0($).paginate(X,_)},async pluck(X){return new O0($).pluck(X)},async create(X){let _=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,Y=`${Z0.baseUrl}/${_}`,L=Z0.transformRequest?Z0.transformRequest(X):X,z=await fetch(Y,{method:"POST",headers:await u0(),body:JSON.stringify(L)}),j=await O9(z),U="data"in j&&!Array.isArray(j.data)?j.data:j;return new v8($,U)},async update(X,_){let Y=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,L=`${Z0.baseUrl}/${Y}/${X}`,z=Z0.transformRequest?Z0.transformRequest(_):_,j=await fetch(L,{method:"PATCH",headers:await u0(),body:JSON.stringify(z)}),U=await O9(j),Q="data"in U&&!Array.isArray(U.data)?U.data:U;return new v8($,Q)},async delete(X){let _=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,Y=`${Z0.baseUrl}/${_}/${X}`;return(await fetch(Y,{method:"DELETE",headers:await u0()})).ok},async destroy(X){return this.delete(X)},getDefinition:()=>$,getTable:()=>$.table},{get(X,_){if(typeof _==="string"&&_.startsWith("where")&&_.length>5){let Y=_.slice(5),L=Y.charAt(0).toLowerCase()+Y.slice(1);if(L in $.attributes||L==="id"||L===$.primaryKey)return(z)=>new O0($).where(L,z)}return Reflect.get(X,_)}})}class tX{config;entityMappings=new Map;constructor($){if(this.config=$,$.entityMappings)for(let Z of $.entityMappings)this.registerEntity(Z)}createTable($){return{...$,billingMode:$.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable($){return{tableName:$}}registerEntity($){this.entityMappings.set($.entityType,$)}getEntityMapping($){return this.entityMappings.get($)}buildPrimaryKey($,Z){let X=this.entityMappings.get($);if(!X)throw Error(`No entity mapping found for type: ${$}`);let _=this.interpolatePattern(X.pkPattern,Z),Y=this.interpolatePattern(X.skPattern,Z);return{pk:_,sk:Y}}parseEntityFromItem($){let Z=$.pk||$.PK;if(!Z)return null;for(let[X,_]of this.entityMappings){let Y=_.pkPattern.split("${")[0];if(Z.startsWith(Y))return{entityType:X,data:this.unmarshall($)}}return null}buildQueryParams($){return{tableName:$.tableName??this.config.tableName??"",keyConditions:$.keyConditions??[],...$}}buildScanParams($){return{tableName:$.tableName??this.config.tableName??"",...$}}buildGetItemParams($){return{tableName:$.tableName??this.config.tableName??"",key:$.key??{},...$}}buildPutItemParams($){return{tableName:$.tableName??this.config.tableName??"",item:$.item??{},...$}}buildUpdateItemParams($){return{tableName:$.tableName??this.config.tableName??"",key:$.key??{},updateExpressions:$.updateExpressions??{},...$}}buildDeleteItemParams($){return{tableName:$.tableName??this.config.tableName??"",key:$.key??{},...$}}buildBatchGetItemParams($){return{requestItems:$.requestItems??{}}}buildBatchWriteItemParams($){return{requestItems:$.requestItems??{}}}buildTransactWriteParams($){return{transactItems:$.transactItems??[],...$}}buildKeyConditionExpression($){return this.buildExpression($,"AND")}buildFilterExpression($){return this.buildExpression($,"AND")}buildUpdateExpression($){let Z={},X={},_=[],Y=0;if($.set&&Object.keys($.set).length>0){let L=[];for(let[z,j]of Object.entries($.set)){let U=`#attr${Y}`,Q=`:val${Y}`;Z[U]=z,X[Q]=this.marshallValue(j),L.push(`${U} = ${Q}`),Y++}_.push(`SET ${L.join(", ")}`)}if($.remove&&$.remove.length>0){let L=[];for(let z of $.remove){let j=`#attr${Y}`;Z[j]=z,L.push(j),Y++}_.push(`REMOVE ${L.join(", ")}`)}if($.add&&Object.keys($.add).length>0){let L=[];for(let[z,j]of Object.entries($.add)){let U=`#attr${Y}`,Q=`:val${Y}`;Z[U]=z,X[Q]=this.marshallValue(j),L.push(`${U} ${Q}`),Y++}_.push(`ADD ${L.join(", ")}`)}if($.delete&&Object.keys($.delete).length>0){let L=[];for(let[z,j]of Object.entries($.delete)){let U=`#attr${Y}`,Q=`:val${Y}`;Z[U]=z,X[Q]=this.marshallValue(j),L.push(`${U} ${Q}`),Y++}_.push(`DELETE ${L.join(", ")}`)}return{expression:_.join(" "),expressionAttributeNames:Z,expressionAttributeValues:X}}buildProjectionExpression($){let Z={},X=[];return $.forEach((_,Y)=>{let L=`#proj${Y}`;Z[L]=_,X.push(L)}),{expression:X.join(", "),expressionAttributeNames:Z}}marshall($){let Z={};for(let[X,_]of Object.entries($))Z[X]=this.marshallValue(_);return Z}unmarshall($){let Z={};for(let[X,_]of Object.entries($))Z[X]=this.unmarshallValue(_);return Z}interpolatePattern($,Z){return $.replace(/\$\{(\w+)\}/g,(X,_)=>{if(!(_ in Z))throw Error(`Missing value for pattern key: ${_}`);return String(Z[_])})}buildExpression($,Z){let X={},_={},Y=[];return $.forEach((L,z)=>{let j=`#attr${z}`;X[j]=L.attribute;let U;switch(L.operator){case"=":case"<":case"<=":case">":case">=":{let Q=`:val${z}`;_[Q]=this.marshallValue(L.value),U=`${j} ${L.operator} ${Q}`;break}case"BETWEEN":{let Q=`:val${z}a`,E=`:val${z}b`;_[Q]=this.marshallValue(L.values?.[0]),_[E]=this.marshallValue(L.values?.[1]),U=`${j} BETWEEN ${Q} AND ${E}`;break}case"begins_with":{let Q=`:val${z}`;_[Q]=this.marshallValue(L.value),U=`begins_with(${j}, ${Q})`;break}case"contains":{let Q=`:val${z}`;_[Q]=this.marshallValue(L.value),U=`contains(${j}, ${Q})`;break}case"attribute_exists":U=`attribute_exists(${j})`;break;case"attribute_not_exists":U=`attribute_not_exists(${j})`;break;case"attribute_type":{let Q=`:val${z}`;_[Q]={S:L.value},U=`attribute_type(${j}, ${Q})`;break}case"IN":{let Q=(L.values??[]).map((E,G)=>`:val${z}_${G}`);L.values?.forEach((E,G)=>{_[`:val${z}_${G}`]=this.marshallValue(E)}),U=`${j} IN (${Q.join(", ")})`;break}default:throw Error(`Unknown operator: ${L.operator}`)}Y.push(U)}),{expression:Y.join(` ${Z} `),expressionAttributeNames:X,expressionAttributeValues:_}}marshallValue($){if($===null||$===void 0)return{NULL:!0};if(typeof $==="string")return{S:$};if(typeof $==="number")return{N:String($)};if(typeof $==="boolean")return{BOOL:$};if($ instanceof Uint8Array||Buffer.isBuffer($))return{B:$};if(Array.isArray($)){if($.length===0)return{L:[]};let Z=typeof $[0],X=$.every((Y)=>typeof Y==="string"),_=$.every((Y)=>typeof Y==="number");if(X)return{SS:$};if(_)return{NS:$.map(String)};return{L:$.map((Y)=>this.marshallValue(Y))}}if(typeof $==="object"){let Z={};for(let[X,_]of Object.entries($))Z[X]=this.marshallValue(_);return{M:Z}}return{S:String($)}}unmarshallValue($){if(!$||typeof $!=="object")return $;if("S"in $)return $.S;if("N"in $)return Number($.N);if("BOOL"in $)return $.BOOL;if("NULL"in $)return null;if("B"in $)return $.B;if("SS"in $)return $.SS;if("NS"in $)return $.NS.map(Number);if("BS"in $)return $.BS;if("L"in $)return $.L.map((Z)=>this.unmarshallValue(Z));if("M"in $){let Z={};for(let[X,_]of Object.entries($.M))Z[X]=this.unmarshallValue(_);return Z}return $}}function UY($){return new tX($)}class $2{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor($,Z,X,_){this.driver=$,this.client=Z,this.tableName=X,this.pkAttribute=_.pkAttribute,this.skAttribute=_.skAttribute,this.entityTypeAttr=_.entityTypeAttribute,this.delimiter=_.keyDelimiter}entity($){return this._entityType=$,this}pk($){return this._pkValue=$,this}get sk(){let $=this;return{equals(Z){return $._skCondition={type:"eq",value:Z},$},beginsWith(Z){return $._skCondition={type:"begins_with",value:Z},$},between(Z,X){return $._skCondition={type:"between",value:Z,value2:X},$},lt(Z){return $._skCondition={type:"lt",value:Z},$},lte(Z){return $._skCondition={type:"lte",value:Z},$},gt(Z){return $._skCondition={type:"gt",value:Z},$},gte(Z){return $._skCondition={type:"gte",value:Z},$}}}index($){return this._indexName=$,this}project(...$){return this._projectionAttrs.push(...$),this}filter($,Z,X){return this._filterConditions.push({attribute:$,operator:Z,value:X}),this}where($,Z){return this.filter($,"=",Z)}whereIn($,Z){return this._filterConditions.push({attribute:$,operator:"IN",values:Z}),this}limit($){return this._limitValue=$,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom($){return this._startKey=$,this}toRequest(){let $={TableName:this.tableName};if(this._indexName)$.IndexName=this._indexName;let Z=[],X={},_={},Y=0;if(this._pkValue){let L=`#pk${Y}`,z=`:pk${Y}`;X[L]=this.pkAttribute,_[z]={S:this._pkValue},Z.push(`${L} = ${z}`),Y++}if(this._skCondition){let L=`#sk${Y}`;switch(X[L]=this.skAttribute,this._skCondition.type){case"eq":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} = ${z}`);break}case"begins_with":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`begins_with(${L}, ${z})`);break}case"between":{let z=`:sk${Y}a`,j=`:sk${Y}b`;_[z]={S:this._skCondition.value},_[j]={S:this._skCondition.value2},Z.push(`${L} BETWEEN ${z} AND ${j}`);break}case"lt":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} < ${z}`);break}case"lte":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} <= ${z}`);break}case"gt":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} > ${z}`);break}case"gte":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} >= ${z}`);break}}Y++}if(Z.length>0)$.KeyConditionExpression=Z.join(" AND ");if(this._filterConditions.length>0){let L=[];for(let z of this._filterConditions){let j=`#flt${Y}`;if(X[j]=z.attribute,z.operator==="IN"&&z.values){let U=z.values.map((Q,E)=>`:flt${Y}_${E}`);z.values.forEach((Q,E)=>{_[`:flt${Y}_${E}`]=this.driver.marshall({v:Q}).v}),L.push(`${j} IN (${U.join(", ")})`)}else{let U=`:flt${Y}`;_[U]=this.driver.marshall({v:z.value}).v,L.push(`${j} ${z.operator} ${U}`)}Y++}$.FilterExpression=L.join(" AND ")}if(this._projectionAttrs.length>0){let L=[];for(let z of this._projectionAttrs){let j=`#proj${Y}`;X[j]=z,L.push(j),Y++}$.ProjectionExpression=L.join(", ")}if(Object.keys(X).length>0)$.ExpressionAttributeNames=X;if(Object.keys(_).length>0)$.ExpressionAttributeValues=_;if(this._limitValue!==void 0)$.Limit=this._limitValue;if($.ScanIndexForward=this._scanForward,this._consistentRead)$.ConsistentRead=!0;if(this._startKey)$.ExclusiveStartKey=this.driver.marshall(this._startKey);return $}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let $=this.toRequest();return((this._pkValue!==void 0?await this.client.query($):await this.client.scan($)).Items??[]).map((_)=>this.driver.unmarshall(_))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let $=[],Z;do{if(Z)this._startKey=Z;let X=this.toRequest(),Y=this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X),L=(Y.Items??[]).map((z)=>this.driver.unmarshall(z));$.push(...L),Z=Y.LastEvaluatedKey?this.driver.unmarshall(Y.LastEvaluatedKey):void 0}while(Z);return $}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let $=this.toRequest();return $.Select="COUNT",(this._pkValue!==void 0?await this.client.query($):await this.client.scan($)).Count??0}}class Z2{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection($){let Z={region:$.region,tableName:$.table,endpoint:$.endpoint,credentials:$.credentials};return this.driver=UY(Z),this.tableName=$.table,this.pkAttribute=$.pkAttribute??"pk",this.skAttribute=$.skAttribute??"sk",this.entityTypeAttr=$.entityTypeAttribute??"_et",this.delimiter=$.keyDelimiter??"#",this}setClient($){return this.client=$,this}registerEntity($){if(this.entityMappings.set($.entityType,$),this.driver)this.driver.registerEntity($);return this}entity($){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new $2(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity($)}async batchWrite($){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 Z=[];for(let X of $)if(X.put){let _={...X.put.item,[this.entityTypeAttr]:X.put.entity};Z.push({PutRequest:{Item:this.driver.marshall(_)}})}else if(X.delete)Z.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:X.delete.pk,[this.skAttribute]:X.delete.sk})}});if(Z.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:Z}})}async transactWrite($){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 Z=[];for(let X of $)if(X.put){let _={...X.put.item,[this.entityTypeAttr]:X.put.entity},Y={Put:{TableName:this.tableName,Item:this.driver.marshall(_)}};if(X.put.condition)Y.Put.ConditionExpression=X.put.condition;Z.push(Y)}else if(X.update){let _={[this.pkAttribute]:X.update.pk};if(X.update.sk)_[this.skAttribute]=X.update.sk;let Y=[],L={},z={},j=0;if(X.update.set){let U=[];for(let[Q,E]of Object.entries(X.update.set)){let G=`#set${j}`,F=`:set${j}`;L[G]=Q,z[F]=this.driver.marshall({v:E}).v,U.push(`${G} = ${F}`),j++}if(U.length>0)Y.push(`SET ${U.join(", ")}`)}if(X.update.add){let U=[];for(let[Q,E]of Object.entries(X.update.add)){let G=`#add${j}`,F=`:add${j}`;L[G]=Q,z[F]={N:String(E)},U.push(`${G} ${F}`),j++}if(U.length>0)Y.push(`ADD ${U.join(", ")}`)}if(X.update.remove&&X.update.remove.length>0){let U=[];for(let Q of X.update.remove){let E=`#rem${j}`;L[E]=Q,U.push(E),j++}Y.push(`REMOVE ${U.join(", ")}`)}Z.push({Update:{TableName:this.tableName,Key:this.driver.marshall(_),UpdateExpression:Y.join(" "),ExpressionAttributeNames:L,ExpressionAttributeValues:z}})}else if(X.delete){let _={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:X.delete.pk,[this.skAttribute]:X.delete.sk})}};if(X.delete.condition)_.Delete.ConditionExpression=X.delete.condition;Z.push(_)}else if(X.conditionCheck)Z.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:X.conditionCheck.pk,[this.skAttribute]:X.conditionCheck.sk}),ConditionExpression:X.conditionCheck.condition}});if(Z.length>0)await this.client.transactWriteItems({TransactItems:Z})}getDriver(){return this.driver}}class Y2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let X=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${X}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,X],[,_])=>X.timestamp.getTime()-_.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let X=0;X<Z;X++)this.cache.delete($[X][0])}set($,Z,X,_){if(!this.options.enabled)return;let Y=this.generateKey($,X),L=_??this.options.ttl,z=this.estimateSize(Z);this.cache.set(Y,{value:Z,timestamp:new Date,ttl:L,hits:0,size:z}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey($,Z),_=this.cache.get(X);if(!_){this.totalMisses++;return}if(this.isExpired(_)){this.cache.delete(X),this.totalMisses++;return}return _.hits++,this.totalHits++,_.value}isFileModified($,Z){try{if(!z7($))return!0;return U7($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let X=this.get($,Z);if(!X)return;if(this.isFileModified(Z,X.fileTimestamp)){this.delete($,Z);return}return X.value}setWithFileCheck($,Z,X,_){try{let Y=z7(X)?U7(X):null,L=Y?Y.mtime:new Date;this.set($,{value:Z,fileTimestamp:L},X,_)}catch{this.set($,Z,X,_)}}delete($,Z){let X=this.generateKey($,Z);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((_,Y)=>_+Y.size,0),X=$.map((_)=>_.timestamp).sort();return{size:Z,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:X[0],newestEntry:X[X.length-1]}}export(){let $={};for(let[Z,X]of this.cache.entries())$[Z]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return $}import($){this.cache.clear();for(let[Z,X]of Object.entries($))if(typeof X==="object"&&X!==null){let _=X;this.cache.set(Z,{value:_.value,timestamp:new Date(_.timestamp),ttl:_.ttl,hits:_.hits,size:_.size})}}}class L2{metrics=[];maxMetrics=1000;async track($,Z,X={}){let _=performance.now(),Y=new Date;try{let L=await Z(),z=performance.now()-_;return this.recordMetric({operation:$,duration:z,timestamp:Y,...X}),L}catch(L){let z=performance.now()-_;throw this.recordMetric({operation:`${$}:error`,duration:z,timestamp:Y,...X}),L}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=Z.map((Y)=>Y.duration),_=X.reduce((Y,L)=>Y+L,0);return{count:Z.length,averageDuration:_/Z.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:_,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function $L($,Z){this[$]=hL.bind(null,Z)}class sZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let X=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${X}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,X],[,_])=>X.timestamp.getTime()-_.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let X=0;X<Z;X++)this.cache.delete($[X][0])}set($,Z,X,_){if(!this.options.enabled)return;let Y=this.generateKey($,X),L=_??this.options.ttl,z=this.estimateSize(Z);this.cache.set(Y,{value:Z,timestamp:new Date,ttl:L,hits:0,size:z}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey($,Z),_=this.cache.get(X);if(!_){this.totalMisses++;return}if(this.isExpired(_)){this.cache.delete(X),this.totalMisses++;return}return _.hits++,this.totalHits++,_.value}isFileModified($,Z){try{if(!j7($))return!0;return E7($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let X=this.get($,Z);if(!X)return;if(this.isFileModified(Z,X.fileTimestamp)){this.delete($,Z);return}return X.value}setWithFileCheck($,Z,X,_){try{let Y=j7(X)?E7(X):null,L=Y?Y.mtime:new Date;this.set($,{value:Z,fileTimestamp:L},X,_)}catch{this.set($,Z,X,_)}}delete($,Z){let X=this.generateKey($,Z);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((_,Y)=>_+Y.size,0),X=$.map((_)=>_.timestamp).sort();return{size:Z,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:X[0],newestEntry:X[X.length-1]}}export(){let $={};for(let[Z,X]of this.cache.entries())$[Z]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return $}import($){this.cache.clear();for(let[Z,X]of Object.entries($))if(typeof X==="object"&&X!==null){let _=X;this.cache.set(Z,{value:_.value,timestamp:new Date(_.timestamp),ttl:_.ttl,hits:_.hits,size:_.size})}}}class lZ{metrics=[];maxMetrics=1000;async track($,Z,X={}){let _=performance.now(),Y=new Date;try{let L=await Z(),z=performance.now()-_;return this.recordMetric({operation:$,duration:z,timestamp:Y,...X}),L}catch(L){let z=performance.now()-_;throw this.recordMetric({operation:`${$}:error`,duration:z,timestamp:Y,...X}),L}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=Z.map((Y)=>Y.duration),_=X.reduce((Y,L)=>Y+L,0);return{count:Z.length,averageDuration:_/Z.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:_,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function ZL($,Z={}){let _=Object.keys(Z).sort().map((Y)=>`${Y}:${Z[Y]}`).join("|");return _?`${$}:${_}`:$}function XL($,Z){try{return JSON.stringify($)===JSON.stringify(Z)}catch{return $===Z}}function _L($){return $.getStats().size*2}function W6($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&K0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&K0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(K0(Z)&&K0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(K0($)&&"arr"in $&&Array.isArray($.arr)&&K0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&K0(Z[0])&&K0($[0])){let _=[...Z];for(let Y of $)if(K0(Y)&&"name"in Y){if(!_.find((z)=>K0(z)&&("name"in z)&&z.name===Y.name))_.push(Y)}else if(K0(Y)&&"path"in Y){if(!_.find((z)=>K0(z)&&("path"in z)&&z.path===Y.path))_.push(Y)}else if(!_.some((L)=>$5(L,Y)))_.push(Y);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}if(!K0(Z)||!K0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let Y=Z[_];if(Y===null||Y===void 0)continue;else if(K0(Y)&&K0(X[_]))X[_]=W6(X[_],Y);else if(Array.isArray(Y)&&Array.isArray(X[_]))if(Y.length>0&&X[_].length>0&&K0(Y[0])&&K0(X[_][0])){let L=[...Y];for(let z of X[_])if(K0(z)&&"name"in z){if(!L.find((U)=>K0(U)&&("name"in U)&&U.name===z.name))L.push(z)}else if(K0(z)&&"path"in z){if(!L.find((U)=>K0(U)&&("path"in U)&&U.path===z.path))L.push(z)}else if(!L.some((j)=>$5(j,z)))L.push(z);X[_]=L}else if(Y.every((L)=>typeof L==="string")&&X[_].every((L)=>typeof L==="string")){let L=[...Y];for(let z of X[_])if(!L.includes(z))L.push(z);X[_]=L}else X[_]=Y;else X[_]=Y}return X}function $5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!$5($[X],Z[X]))return!1;return!0}if(K0($)&&K0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!$5($[Y],Z[Y]))return!1}return!0}return!1}function K0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function YL($,Z){if(!_2($))return null;try{let X=await import($),_=X.default||X;if(typeof _!=="object"||_===null||Array.isArray(_))return null;try{return W6(Z,_)}catch{return null}}catch{return null}}async function LL({name:$="",cwd:Z,defaultConfig:X}){let _=Z||mZ.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],L=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let z of L)for(let j of Y){let U=t$(_,`${z}${j}`),Q=await YL(U,X);if(Q!==null)return Q}try{let z=t$(_,"package.json");if(_2(z)){let U=(await import(z))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return W6(X,U)}catch{}}}catch{}return X}function zL($,Z={}){let X=a$.cwd();while(X.includes("storage"))X=G7(X,"..");let _=G7(X,$||"");if(Z?.relative)return SY(a$.cwd(),_);return _}async function UL(){try{let $=await LL({name:"clarity",defaultConfig:A$,cwd:a$.cwd(),endpoint:"",headers:{}});return{...A$,...$}}catch{return A$}}function S0(){if(A9.env.NODE_ENV==="test"||A9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jL(){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 $=A9.type;if($==="renderer"||$==="worker")return!1;return!!(A9.versions&&(A9.versions.node||A9.versions.bun))}return!1}class z2{async format($){let Z=await jL(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:I8.pid,hostname:Z(),environment:I8.env.NODE_ENV||"development",platform:I8.platform,version:I8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I8.env.NODE_ENV||I8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Z5{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($,Z={}){this.name=$,this.config={...oZ},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new z2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??y0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),L=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,L),this.encryptionKeys.set(Y,{key:L,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...y$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...y$};return{...y$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:oZ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}async writeToFile($){let X=(async()=>{let Y,L=0,z=3,j=1000;while(L<z)try{try{try{await TY(this.config.logDirectory,K7.F_OK|K7.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await PY(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:n9.from($);try{if(!XZ(this.currentLogFile))await _Z(this.currentLogFile,"",{mode:420});if(Y=W7(this.currentLogFile,"a",420),qY(Y,U,{flag:"a"}),V7(Y),Y!==void 0)ZZ(Y),Y=void 0;if((await W8(this.currentLogFile)).size===0){if(await _Z(this.currentLogFile,U,{flag:"w",mode:420}),(await W8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let E=Q;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(L<z-1){let G=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${L+1}/${z}:`,G);let F=j*2**L;await new Promise((O)=>setTimeout(O,F)),L++;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(Y!==void 0)try{ZZ(Y)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(U){if(L===z-1){let E=U,G=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),U}L++;let Q=j*2**(L-1);await new Promise((E)=>setTimeout(E,Q))}})();this.pendingOperations.push(X);let _=this.pendingOperations.length-1;try{await X}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(_,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 K8(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 K8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return K8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(S0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let X=typeof Z.interval==="number"?Z.interval:60,_=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},_)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,X=this.generateKeyId(),_=this.generateKey();this.currentKeyId=X,this.keys.set(X,_),this.encryptionKeys.set(X,{key:_,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,j],[,U])=>U.createdAt.getTime()-j.createdAt.getTime()),L=typeof Z.maxKeys==="number"?Z.maxKeys:1,z=Math.max(1,L);if(Y.length>z)for(let[j]of Y.slice(z))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return $Z(16).toString("hex")}generateKey(){return $Z(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=$Z(16),_=MY("aes-256-gcm",Z,X),Y=n9.concat([_.update($,"utf8"),_.final()]),L=_.getAuthTag();return{encrypted:n9.concat([X,Y,L]),iv:X}}async compressData($){return new Promise((Z,X)=>{let _=J7(),Y=[];_.on("data",(L)=>Y.push(L)),_.on("end",()=>Z(n9.from(n9.concat(Y)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(S0())return;let $=await W8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await _$(this.config.logDirectory),L=Y.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,Q)=>{let E=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),z=L.length>0?Number.parseInt(L[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${X}.${z}`;if(await W8(X).catch(()=>null))try{if(await I7(X,j),Z.compress)try{let U=`${j}.gz`;await this.compressLogFile(j,U),await Y$(j)}catch(U){console.error("Error compressing rotated file:",U)}if(L.length===0&&!Y.some((U)=>U.endsWith(".log.1")))try{let U=`${X}.1`;await _Z(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),L=X.replace(/\.log$/,`-${Y}.log`);if(await W8(X).catch(()=>null))await I7(X,L)}if(this.currentLogFile=_,Z.maxFiles){let L=(await _$(this.config.logDirectory)).filter((z)=>z.startsWith(this.name)).sort((z,j)=>j.localeCompare(z));for(let z of L.slice(Z.maxFiles))await Y$(K8(this.config.logDirectory,z))}}}async compressLogFile($,Z){let X=F7($),_=HY(Z),Y=J7();await NY(X,Y,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);await this.writeToFile(_),console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(Z),console.log(Z);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:$,message:Z,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),XZ(this.currentLogFile))try{let $=W7(this.currentLogFile,"r+");V7($),ZZ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!S0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await _$(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of Z)try{await Y$(K8(this.config.logDirectory,X))}catch(_){console.error(`Failed to delete temp file ${X}:`,_)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?F0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:Y,level:L,showTimestamp:z=!0}=$,j=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(z)O.push(Z);if(L==="warning")O.push("WARN");else if(L==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(Y),O.join(" ")}let U=y0.stdout.columns||120,Q="";if(L==="warning"||L==="error")Q=`${X} ${Y}`;else if(L==="info"||L==="success")Q=`${X} ${_} ${Y}`;else Q=`${X} ${_} ${F0.cyan(Y)}`;if(!z)return Q.trim();let E=j(Q).trim().length,G=j(Z).length,F=Math.max(1,U-2-E-G);return`${Q.trim()}${" ".repeat(F)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(L,z)=>{let j=Number.parseInt(z,10);return j<Z[0].length?String(Z[0][j]):L});let X=/%([sdijfo%])/g,_=0,Y=$.replace(X,(L,z)=>{if(z==="%")return"%";if(_>=Z.length)return L;let j=Z[_++];switch(z){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return L}});if(_<Z.length)Y+=` ${Z.slice(_).map((L)=>typeof L==="object"?JSON.stringify(L,null,2):String(L)).join(" ")}`;return Y}async log($,Z,...X){let _=new Date,Y=this.formatConsoleTimestamp(_),L=this.formatFileTimestamp(_),z,j;if(Z instanceof Error)z=Z.message,j=Z.stack;else z=this.formatMessage(Z,X);if(this.fancy&&!S0()){let Q=w2[$],E=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:F0.gray(z),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:z,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:F0.green(z),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:z,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:z,level:$}),console.error(G),j){let F=j.split(`
|
|
3
|
-
`);for(let O of F)if(O.trim()&&!O.includes(z))console.error(this.formatConsoleMessage({timestamp:Y,message:F0.gray(` ${O}`),level:$,showTimestamp:!1}))}break}}else if(!S0()){if(console.error(`${L} ${this.environment}.${$.toUpperCase()}: ${z}`),j)console.error(j)}if(!this.shouldLog($))return;let U=`${L} ${this.environment}.${$.toUpperCase()}: ${z}
|
|
4
|
-
`;if(j)U+=`${j}
|
|
5
|
-
`;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let Z=performance.now();if(this.fancy&&!S0()){let X=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:F0.blue("\u25D0"),tag:X,message:`${F0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),Y=Math.round(_-Z),L=`${$} completed in ${Y}ms`,z=new Date,j=this.formatConsoleTimestamp(z),Q=`${this.formatFileTimestamp(z)} ${this.environment}.INFO: ${L}`;if(X)Q+=` ${JSON.stringify(X)}`;if(Q+=`
|
|
6
|
-
`,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!S0()){let E=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:F0.green("\u2713"),tag:E,message:`${L}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!S0())console.error(Q.trim());await this.writeToFile(Q)}}async debug($,...Z){await this.log("debug",$,...Z)}async info($,...Z){await this.log("info",$,...Z)}async success($,...Z){await this.log("success",$,...Z)}async warn($,...Z){await this.log("warning",$,...Z)}async error($,...Z){await this.log("error",$,...Z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new Z5(Z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(S0())throw Error("createReadStream is not supported in browser environments");if(!XZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return F7(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=n9.isBuffer($)?$:n9.from($,"base64"),Y=_.slice(0,16),L=_.slice(-16),z=_.slice(16,-16),j=wY("aes-256-gcm",X,Y);return j.setAuthTag(L),n9.concat([j.update(z),j.final()]).toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S0()}isServerMode(){return!S0()}setTestEncryptionKey($,Z){this.currentKeyId=$,this.keys.set($,Z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z);if(this.fancy&&!S0()){let L=$.split(`
|
|
7
|
-
`),z=Math.max(...L.map((E)=>E.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,U=`\u2514${"\u2500".repeat(z)}\u2518`,Q=L.map((E)=>{let G=" ".repeat(z-E.length-2);return`\u2502 ${E}${G} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:F0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:F0.cyan(j)})),Q.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:X,message:F0.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:F0.cyan(U),showTimestamp:!1}))}else if(!S0())console.error(`${_} ${this.environment}.INFO: [BOX] ${$}`);let Y=`${_} ${this.environment}.INFO: [BOX] ${$}
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt($){if(S0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${F0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let Y=_.toString().trim().toLowerCase();y0.stdin.removeListener("data",X);try{if(typeof y0.stdin.setRawMode==="function")y0.stdin.setRawMode(!1)}catch{}y0.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof y0.stdin.setRawMode==="function")y0.stdin.setRawMode(!0)}catch{}y0.stdin.resume(),y0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let z=/%([sdijfo%])/g,j=0;if(X=$.replace(z,(U,Q)=>{if(Q==="%")return"%";if(j>=Z.length)return U;let E=Z[j++];switch(Q){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 U}}),j<Z.length)X+=` ${Z.slice(j).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!S0()){let z=this.options.showTags!==!1&&this.name?F0.gray(this.formatTag(this.name)):"",j=F0.blue("\u25D0");console.error(`${j} ${z} ${F0.cyan(X)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(L)}progress($,Z=""){if(!this.enabled||!this.fancy||S0()||$<=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 X=20;return this.activeProgressBar={total:$,current:0,message:Z,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(z,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,z)),j!==void 0)this.activeProgressBar.message=j;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,z!==void 0)this.activeProgressBar.message=z;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(z,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S0())return;y0.stdout.write(`${"\r".padEnd(y0.stdout.columns||80)}\r`),this.log(j,z),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,Z=!1){if(!this.enabled||!this.fancy||S0()||!y0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),Y=$.barLength-_,L=F0.green("\u2501".repeat(_)),z=F0.gray("\u2501".repeat(Y)),j=`[${L}${z}]`,U=`${X}%`.padStart(4),Q=$.message?` ${$.message}`:"",E=Z||X===100?F0.green("\u2713"):F0.blue("\u25B6"),G=this.options.showTags!==!1&&this.name?` ${F0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${G} ${j} ${U}${Q}`,O=y0.stdout.columns||80,K=" ".repeat(Math.max(0,O-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${K}`,y0.stdout.write($.lastRenderedLine),Z)y0.stdout.write(`
|
|
10
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||S0()||!y0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(S0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await _$(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let L=K8(this.config.logDirectory,_);if($.before)try{if((await W8(L)).mtime>=$.before)continue}catch(z){console.error(`Failed to get stats for file ${L}:`,z);continue}X.push(L)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await Y$(_),console.warn(`Deleted log file: ${_}`)}catch(Y){console.error(`Failed to delete log file ${_}:`,Y)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}function B$($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&j0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&j0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(j0(Z)&&j0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(j0($)&&"arr"in $&&Array.isArray($.arr)&&j0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&j0(Z[0])&&j0($[0])){let _=[...Z];for(let Y of $)if(j0(Y)&&"name"in Y){if(!_.find((z)=>j0(z)&&("name"in z)&&z.name===Y.name))_.push(Y)}else if(j0(Y)&&"path"in Y){if(!_.find((z)=>j0(z)&&("path"in z)&&z.path===Y.path))_.push(Y)}else if(!_.some((L)=>X5(L,Y)))_.push(Y);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}if(!j0(Z)||!j0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let Y=Z[_];if(Y===null||Y===void 0)continue;else if(j0(Y)&&j0(X[_]))X[_]=B$(X[_],Y);else if(Array.isArray(Y)&&Array.isArray(X[_]))if(Y.length>0&&X[_].length>0&&j0(Y[0])&&j0(X[_][0])){let L=[...Y];for(let z of X[_])if(j0(z)&&"name"in z){if(!L.find((U)=>j0(U)&&("name"in U)&&U.name===z.name))L.push(z)}else if(j0(z)&&"path"in z){if(!L.find((U)=>j0(U)&&("path"in U)&&U.path===z.path))L.push(z)}else if(!L.some((j)=>X5(j,z)))L.push(z);X[_]=L}else if(Y.every((L)=>typeof L==="string")&&X[_].every((L)=>typeof L==="string")){let L=[...Y];for(let z of X[_])if(!L.includes(z))L.push(z);X[_]=L}else X[_]=Y;else X[_]=Y}return X}function K6($,Z,X="replace"){if(Z===null||Z===void 0)return $;if(Array.isArray(Z))return X==="replace"?Z:B$($,Z);if(Array.isArray($))return X==="replace"?Z:B$($,Z);if(!j0(Z)||!j0($))return Z;let _={...$};for(let Y of Object.keys(Z)){if(!Object.prototype.hasOwnProperty.call(Z,Y))continue;let L=Z[Y],z=_[Y];if(L===null||L===void 0)continue;if(Array.isArray(L)||Array.isArray(z))if(X==="replace")_[Y]=L;else _[Y]=B$(z,L);else if(j0(L)&&j0(z))_[Y]=K6(z,L,X);else _[Y]=L}return _}function X5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!X5($[X],Z[X]))return!1;return!0}if(j0($)&&j0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!X5($[Y],Z[Y]))return!1}return!0}return!1}function j0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function W$($,Z,X="replace"){if(!X2($))return null;try{let _=await import($),Y=_.default||_;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return K6(Z,Y,X)}catch{return null}}catch{return null}}function EL($,Z,X=!1){if(!$)return Z;let _=$.toUpperCase().replace(/-/g,"_"),Y={...Z};function L(z,j=[]){let U={...z};for(let[Q,E]of Object.entries(z)){let G=[...j,Q],F=(W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${_}_${G.map(F).join("_")}`,K=`${_}_${G.map((W)=>W.toUpperCase()).join("_")}`;if(X)f0.info(`Checking environment variable ${O} for config ${$}.${G.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))U[Q]=L(E,G);else{let W=k1.env[O]||k1.env[K];if(W!==void 0){if(X)f0.info(`Using environment variable ${W?O:K} for config ${$}.${G.join(".")}`);if(typeof E==="number")U[Q]=Number(W);else if(typeof E==="boolean")U[Q]=W.toLowerCase()==="true";else if(Array.isArray(E))try{let w=JSON.parse(W);if(Array.isArray(w))U[Q]=w;else U[Q]=W.split(",").map((J)=>J.trim())}catch{U[Q]=W.split(",").map((w)=>w.trim())}else U[Q]=W}}}return U}return L(Y)}async function OL({name:$="",alias:Z,cwd:X,configDir:_,defaultConfig:Y,verbose:L=!1,checkEnv:z=!0,arrayStrategy:j="replace"}){let U=z&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?EL($,Y,L):Y,Q=X||k1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(L)f0.info(`Loading configuration for "${$}"${Z?` (alias: "${Z}")`:""} from ${Q}`);let G=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),O=Z?[Z,`.${Z}`]:[],K=Z?[`${Z}.config`,`.${Z}.config`]:[],W=Array.from(new Set([Q,a0(Q,"config"),a0(Q,".config"),_?a0(Q,_):void 0].filter(Boolean)));for(let w of W){if(L)f0.info(`Searching for configuration in: ${w}`);let R=[a0(Q,"config"),a0(Q,".config")].concat(_?[a0(Q,_)]:[]).includes(w)?[...G,...F,...O,...K]:[...F,...G,...K,...O];for(let M of R)for(let q of E){let N=a0(w,`${M}${q}`),B=await W$(N,U,j);if(B!==null){if(L)f0.success(`Configuration loaded from: ${N}`);return B}}}if($){let w=a0(e5(),".config",$),J=["config",`${$}.config`];if(Z)J.push(`${Z}.config`);if(L)f0.info(`Checking user config directory: ${w}`);for(let R of J)for(let M of E){let q=a0(w,`${R}${M}`),N=await W$(q,U,j);if(N!==null){if(L)f0.success(`Configuration loaded from user config directory: ${q}`);return N}}}if($){let w=a0(e5(),".config"),J=[`.${$}.config`];if(Z)J.push(`.${Z}.config`);if(L)f0.info(`Checking user config directory for dotfile configs: ${w}`);for(let R of J)for(let M of E){let q=a0(w,`${R}${M}`),N=await W$(q,U,j);if(N!==null){if(L)f0.success(`Configuration loaded from user config directory dotfile: ${q}`);return N}}}if($){let w=e5(),J=[`.${$}.config`,`.${$}`];if(Z)J.push(`.${Z}.config`),J.push(`.${Z}`);if(L)f0.info(`Checking user home directory for dotfile configs: ${w}`);for(let R of J)for(let M of E){let q=a0(w,`${R}${M}`),N=await W$(q,U,j);if(N!==null){if(L)f0.success(`Configuration loaded from user home directory: ${q}`);return N}}}try{let w=a0(Q,"package.json");if(X2(w)){let J=await import(w),R=J[$];if(!R&&Z){if(R=J[Z],R&&L)f0.success(`Using alias "${Z}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(L)f0.success(`Configuration loaded from package.json: ${R===J[$]?$:Z}`);return K6(U,R,j)}catch(M){if(L)f0.warn("Failed to merge package.json config:",M)}}}catch(w){if(L)f0.warn("Failed to load package.json:",w)}if(L)f0.info(`No configuration found for "${$}"${Z?` or alias "${Z}"`:""}, using default configuration with environment variables`);return U}function QL($,Z={}){let X=o$.cwd();while(X.includes("storage"))X=Q7(X,"..");let _=Q7(X,$||"");if(Z?.relative)return DY(o$.cwd(),_);return _}async function GL(){try{let $=await OL({name:"clarity",alias:"logging",defaultConfig:h$,cwd:o$.cwd()});return{...h$,...$||{}}}catch{return h$}}function T0(){if(y9.env.NODE_ENV==="test"||y9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function FL(){if(y9.env.NODE_ENV==="test"||y9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof y9<"u"){let $=y9.type;if($==="renderer"||$==="worker")return!1;return!!(y9.versions&&(y9.versions.node||y9.versions.bun))}return!1}class U2{async format($){let Z=await FL(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:R8.pid,hostname:Z(),environment:R8.env.NODE_ENV||"development",platform:R8.platform,version:R8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R8.env.NODE_ENV||R8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class _5{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,Z={}){this.name=$,this.config={...aZ},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new U2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??X0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),L=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,L),this.encryptionKeys.set(Y,{key:L,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[X]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...v$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...v$};return{...v$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:aZ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile($){let X=(async()=>{let Y,L=0,z=3,j=1000;while(L<z)try{try{try{await AY(this.config.logDirectory,M7.F_OK|M7.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await yY(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:C9.from($);try{if(!L$(this.currentLogFile))await zZ(this.currentLogFile,"",{mode:420});if(Y=S7(this.currentLogFile,"a",420),BY(Y,U,{flag:"a"}),R7(Y),Y!==void 0)LZ(Y),Y=void 0;if((await J8(this.currentLogFile)).size===0){if(await zZ(this.currentLogFile,U,{flag:"w",mode:420}),(await J8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let E=Q;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(L<z-1){let G=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${L+1}/${z}:`,G);let F=j*2**L;await new Promise((O)=>setTimeout(O,F)),L++;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(Y!==void 0)try{LZ(Y)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(U){if(L===z-1){let E=U,G=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),U}L++;let Q=j*2**(L-1);await new Promise((E)=>setTimeout(E,Q))}})();this.pendingOperations.push(X);let _=this.pendingOperations.length-1;try{await X}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(_,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 D8(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 D8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let X=typeof Z.interval==="number"?Z.interval:60,_=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},_)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,X=this.generateKeyId(),_=this.generateKey();this.currentKeyId=X,this.keys.set(X,_),this.encryptionKeys.set(X,{key:_,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,j],[,U])=>U.createdAt.getTime()-j.createdAt.getTime()),L=typeof Z.maxKeys==="number"?Z.maxKeys:1,z=Math.max(1,L);if(Y.length>z)for(let[j]of Y.slice(z))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return YZ(16).toString("hex")}generateKey(){return YZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=YZ(16),_=kY("aes-256-gcm",Z,X),Y=C9.isBuffer($)?$:C9.from($,"utf8"),L=_.update(Y),z=_.final(),j=L.length+z.length,U=_.getAuthTag(),Q=C9.allocUnsafe(16+j+16);return X.copy(Q,0),L.copy(Q,16),z.copy(Q,16+L.length),U.copy(Q,16+j),{encrypted:Q,iv:X}}async compressData($){return new Promise((Z,X)=>{let _=H7(),Y=[];_.on("data",(L)=>Y.push(L)),_.on("end",()=>Z(C9.from(C9.concat(Y)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let $=await J8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await z$(this.config.logDirectory),L=Y.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,Q)=>{let E=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),z=L.length>0?Number.parseInt(L[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${X}.${z}`;if(await J8(X).catch(()=>null))try{if(await w7(X,j),Z.compress)try{let U=`${j}.gz`;await this.compressLogFile(j,U),await U$(j)}catch(U){console.error("Error compressing rotated file:",U)}if(L.length===0&&!Y.some((U)=>U.endsWith(".log.1")))try{let U=`${X}.1`;await zZ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),L=X.replace(/\.log$/,`-${Y}.log`);if(await J8(X).catch(()=>null))await w7(X,L)}if(this.currentLogFile=_,Z.maxFiles){let L=(await z$(this.config.logDirectory)).filter((z)=>z.startsWith(this.name)).sort((z,j)=>j.localeCompare(z));for(let z of L.slice(Z.maxFiles))await U$(D8(this.config.logDirectory,z))}}}async compressLogFile($,Z){let X=D7($),_=xY(Z),Y=H7();await bY(X,Y,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(_);console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),L$(this.currentLogFile))try{let $=S7(this.currentLogFile,"r+");R7($),LZ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await z$(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of Z)try{await U$(D8(this.config.logDirectory,X))}catch(_){console.error(`Failed to delete temp file ${X}:`,_)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Y0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let $=typeof X0.env.NO_COLOR<"u",Z=X0.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof X0.stderr<"u"&&X0.stderr.isTTY||typeof X0.stdout<"u"&&X0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:Y,level:L,showTimestamp:z=!0}=$,j=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(z)O.push(Z);if(L==="warning")O.push("WARN");else if(L==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(Y),O.join(" ")}let U=X0.stdout.columns||120,Q="";if(L==="warning"||L==="error")Q=`${X} ${Y}`;else if(L==="info"||L==="success")Q=`${X} ${_} ${Y}`;else Q=`${X} ${_} ${Y0.cyan(Y)}`;if(!z)return Q.trim();let E=j(Q).trim().length,G=j(Z).length,F=Math.max(1,U-2-E-G);return`${Q.trim()}${" ".repeat(F)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(L,z)=>{let j=Number.parseInt(z,10);return j<Z[0].length?String(Z[0][j]):L});let X=/%([sdijfo%])/g,_=0,Y=$.replace(X,(L,z)=>{if(z==="%")return"%";if(_>=Z.length)return L;let j=Z[_++];switch(z){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return L}});if(_<Z.length)Y+=` ${Z.slice(_).map((L)=>typeof L==="object"?JSON.stringify(L,null,2):String(L)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,_,Y)=>{let L=Y0.underline(Y0.blue(_)),z=this.toAbsoluteFilePath(Y);if(z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(z)}`,U="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${L}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${L}\x1B]8;;\x1B\\`;return L}),Z=Z.replace(/`([^`]+)`/g,(X,_)=>Y0.bgGray(_)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(X,_)=>Y0.bold(_)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,_)=>Y0.italic(_)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,_)=>Y0.italic(_)),Z=Z.replace(/~([^~]+)~/g,(X,_)=>Y0.strikethrough(_)),Z}supportsHyperlinks(){if(T0())return!1;let $=X0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let X=X0.env.HOME||"";if(X)Z=Z.replace(/^~(?=$|\/)/,X)}if(hY(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=vY(Z);else return null;return L$(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,X=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:X}}async log($,Z,...X){let _=new Date,Y=this.formatConsoleTimestamp(_),L=this.formatFileTimestamp(_),z,j;if(Z instanceof Error)z=Z.message,j=Z.stack;else z=this.formatMessage(Z,X);let{consoleText:U,fileText:Q}=this.buildOutputTexts(z);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":H2[$],F=this.options.showTags!==!1&&this.name?Y0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:Y0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:Y0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.error(O),j){let K=j.split(`
|
|
11
|
-
`);for(let W of K)if(W.trim()&&!W.includes(z))console.error(this.formatConsoleMessage({timestamp:Y,message:Y0.gray(` ${W}`),level:$,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${L} ${this.environment}.${$.toUpperCase()}: ${z}`),j)console.error(j)}if(!this.shouldLog($))return;let E=`${L} ${this.environment}.${$.toUpperCase()}: ${Q}
|
|
12
|
-
`;if(j)E+=`${j}
|
|
13
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,Z=""){let X={update:(j,U)=>{},finish:(j)=>{},interrupt:(j,U)=>{}};if(!this.enabled)return X;let _=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:_,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&X0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!T0()&&X0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,U="info")=>{if(!T0()&&X0.stdout.isTTY)X0.stdout.write(`
|
|
14
|
-
`);if(this[U==="warning"?"warn":U](j),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&X0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?Y0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":Y0.blue("\u25D0"),tag:X,message:`${Y0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),Y=Math.round(_-Z),L=`${$} completed in ${Y}ms`,z=new Date,j=this.formatConsoleTimestamp(z),Q=`${this.formatFileTimestamp(z)} ${this.environment}.INFO: ${L}`;if(X)Q+=` ${JSON.stringify(X)}`;if(Q+=`
|
|
15
|
-
`,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?Y0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":Y0.green("\u2713"),tag:E,message:`${L}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!T0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug($,...Z){await this.log("debug",$,...Z)}async info($,...Z){await this.log("info",$,...Z)}async success($,...Z){await this.log("success",$,...Z)}async warn($,...Z){await this.log("warning",$,...Z)}async error($,...Z){await this.log("error",$,...Z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new _5(Z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!L$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return D7(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=C9.isBuffer($)?$:C9.from($,"base64"),Y=_.subarray(0,16),L=_.subarray(_.length-16),z=_.subarray(16,_.length-16),j=CY("aes-256-gcm",X,Y);j.setAuthTag(L);let U=j.update(z),Q=j.final(),E=U.length+Q.length,G=C9.allocUnsafe(E);return U.copy(G,0),Q.copy(G,U.length),G.toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey($,Z){this.currentKeyId=$,this.keys.set($,Z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),{consoleText:Y,fileText:L}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let j=Y.split(`
|
|
16
|
-
`),U=Math.max(...j.map((F)=>F.length))+2,Q=`\u250C${"\u2500".repeat(U)}\u2510`,E=`\u2514${"\u2500".repeat(U)}\u2518`,G=j.map((F)=>{return this.formatConsoleMessage({timestamp:X,message:Y0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:Y0.cyan(Q),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:X,message:Y0.cyan(E),showTimestamp:!1}))}else if(!T0())console.error(`${_} ${this.environment}.INFO: [BOX] ${L}`);let z=`${_} ${this.environment}.INFO: [BOX] ${L}
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}async prompt($){if(T0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${Y0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let Y=_.toString().trim().toLowerCase();X0.stdin.removeListener("data",X);try{if(typeof X0.stdin.setRawMode==="function")X0.stdin.setRawMode(!1)}catch{}X0.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof X0.stdin.setRawMode==="function")X0.stdin.setRawMode(!0)}catch{}X0.stdin.resume(),X0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let U=/%([sdijfo%])/g,Q=0;if(X=$.replace(U,(E,G)=>{if(G==="%")return"%";if(Q>=Z.length)return E;let F=Z[Q++];switch(G){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return E}}),Q<Z.length)X+=` ${Z.slice(Q).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:_,fileText:Y}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?Y0.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${Y0.blue("\u25D0")} `;console.error(`${Q}${U} ${Y0.cyan(_)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!X0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),Y=$.barLength-_,L=Y0.green("\u2501".repeat(_)),z=Y0.gray("\u2501".repeat(Y)),j=`[${L}${z}]`,U=`${X}%`.padStart(4),Q=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":Z||X===100?Y0.green("\u2713"):Y0.blue("\u25B6"),G=this.options.showTags!==!1&&this.name?` ${Y0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${G} ${j} ${U}${Q}`,O=X0.stdout.columns||80,K=" ".repeat(Math.max(0,O-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${K}`,X0.stdout.write($.lastRenderedLine),Z)X0.stdout.write(`
|
|
19
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||T0()||!X0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await z$(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let L=D8(this.config.logDirectory,_);if($.before)try{if((await J8(L)).mtime>=$.before)continue}catch(z){console.error(`Failed to get stats for file ${L}:`,z);continue}X.push(L)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await U$(_),console.warn(`Deleted log file: ${_}`)}catch(Y){console.error(`Failed to delete log file ${_}:`,Y)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function j2($,Z={}){let{maxRetries:X=3,retryDelay:_=1000,isRetryable:Y=()=>!0,fallback:L}=Z,z=Error("Unknown error occurred");for(let j=0;j<=X;j++)try{return await $()}catch(U){if(z=U instanceof Error?U:Error(String(U)),j===X||!Y(z))break;if(_>0)await new Promise((Q)=>setTimeout(Q,_))}if(L!==void 0)return L;throw z instanceof Error?z:Error(`Unknown error: ${String(z)}`)}function E2($){return $ instanceof X9}function VL($){return $ instanceof b$}function WL($){if(E2($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((X)=>$.message.toLowerCase().includes(X.toLowerCase()))}class N5{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,X={}){let{prefix:_,useCamelCase:Y=!0,useBackwardCompatibility:L=!0,customParsers:z={},verbose:j=!1,trackPerformance:U=!0}=X,Q=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let E=_||this.generateEnvPrefix($),G={...Z};return this.processObject(G,[],E,{useCamelCase:Y,useBackwardCompatibility:L,customParsers:z,verbose:j,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return x1.track("applyEnvironmentVariables",Q,{configName:$});return Q()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,X,_){for(let[Y,L]of Object.entries($)){let z=[...Z,Y],j=z.map((E)=>this.formatEnvKey(E,_.useCamelCase)),U=`${X}_${j.join("_")}`,Q=_.useBackwardCompatibility?`${X}_${z.map((E)=>E.toUpperCase()).join("_")}`:null;if(_.verbose);if(typeof L==="object"&&L!==null&&!Array.isArray(L))this.processObject(L,z,X,_);else{let E=j$.env[U]||(Q?j$.env[Q]:void 0);if(E!==void 0){if(_.verbose){let G=j$.env[U]?U:Q}try{$[Y]=this.parseEnvironmentValue(E,typeof L,U,_.customParsers,_.configName)}catch(G){if(G instanceof f$)throw G;throw t9.envVar(U,E,typeof L,_.configName)}}}}}parseEnvironmentValue($,Z,X,_,Y){for(let[L,z]of Object.entries(_))try{return z($)}catch{continue}for(let L of this.defaultParsers)if(L.canParse($,Z))try{return L.parse($)}catch{throw t9.envVar(X,$,`${Z} (via ${L.name} parser)`,Y)}return $}getEnvironmentVariables($){let Z={},X=$.toUpperCase();for(let[_,Y]of Object.entries(j$.env))if(_.startsWith(X)&&Y!==void 0)Z[_]=Y;return Z}validateEnvironmentVariable($,Z,X){let _=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))_.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue($,Z,X,{})}catch(Y){_.push(`Cannot parse value "${Z}" as ${X}: ${Y}`)}return{isValid:_.length===0,errors:_}}generateEnvVarDocs($,Z,X={}){let{prefix:_,format:Y="text"}=X,L=_||this.generateEnvPrefix($),z=[];switch(this.extractEnvVarInfo(Z,[],L,z),Y){case"markdown":return this.formatAsMarkdown(z,$);case"json":return JSON.stringify(z,null,2);default:return this.formatAsText(z,$)}}extractEnvVarInfo($,Z,X,_){for(let[Y,L]of Object.entries($)){let z=[...Z,Y],j=`${X}_${z.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof L==="object"&&L!==null&&!Array.isArray(L))this.extractEnvVarInfo(L,z,X,_);else _.push({key:j,type:Array.isArray(L)?"array":typeof L,description:`Configuration for ${z.join(".")}`,example:this.generateExample(L)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let X=`Environment Variables for ${Z}:
|
|
20
|
-
|
|
21
|
-
`;for(let _ of $)X+=`${_.key}
|
|
22
|
-
`,X+=` Type: ${_.type}
|
|
23
|
-
`,X+=` Description: ${_.description}
|
|
24
|
-
`,X+=` Example: ${_.example}
|
|
25
|
-
|
|
26
|
-
`;return X}formatAsMarkdown($,Z){let X=`# Environment Variables for ${Z}
|
|
27
|
-
|
|
28
|
-
`;X+=`| Variable | Type | Description | Example |
|
|
29
|
-
`,X+=`|----------|------|-------------|----------|
|
|
30
|
-
`;for(let _ of $)X+=`| \`${_.key}\` | ${_.type} | ${_.description} | \`${_.example}\` |
|
|
31
|
-
`;return X}}function KL($,Z){let X=M2("process");if(typeof X>"u"||!X.env)return Z;let _=X.env[$];return _!==void 0?_:Z}function O2($,Z,X={}){return Q2($,Z,X,new WeakMap)}function Q2($,Z,X,_){let{arrayMergeMode:Y="replace",skipNullish:L=!1,customMerger:z}=X;if(Z===null||Z===void 0)return L?$:Z;if(z){let j=z($,Z);if(j!==void 0)return j}if(Array.isArray(Z)||Array.isArray($))return G2($,Z,Y,_);if(!Q9(Z)||!Q9($))return Z;return RL($,Z,X,_)}function G2($,Z,X,_){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(X){case"replace":return Z;case"concat":return IL($,Z);case"smart":return JL($,Z,_);default:return Z}return Z}function IL($,Z){let X=[...Z];for(let _ of $)if(!X.some((Y)=>nZ(Y,_)))X.push(_);return X}function JL($,Z,X){if(Z.length===0)return $;if($.length===0)return Z;if(Q9(Z[0])&&Q9($[0]))return DL($,Z,X);if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}function DL($,Z,X){let _=[...Z];for(let Y of $){if(!Q9(Y)){_.push(Y);continue}let L=["id","name","key","path","type"],z=!1;for(let j of L)if(j in Y){if(_.find((Q)=>Q9(Q)&&(j in Q)&&Q[j]===Y[j])){z=!0;break}}if(!z)_.push(Y)}return _}function RL($,Z,X,_){let Y=Z;if(Q9(Y)&&_.has(Y))return _.get(Y);let L={...$};if(Q9(Y))_.set(Y,L);for(let z in Y){if(!Object.prototype.hasOwnProperty.call(Y,z))continue;let j=Y[z],U=L[z];if(X.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){L[z]=j;continue}if(Q9(j)&&Q9(U))L[z]=Q2(U,j,X,_);else if(Array.isArray(j)||Array.isArray(U))L[z]=G2(U,j,X.arrayMergeMode||"smart",_);else L[z]=j}return L}function I6($,Z,X="replace"){return O2($,Z,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function nZ($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!nZ($[X],Z[X]))return!1;return!0}if(Q9($)&&Q9(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!nZ($[Y],Z[Y]))return!1}return!0}return!1}function Q9($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class k5{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,X={}){let{arrayStrategy:_="replace",useCache:Y=!0,cacheTtl:L,trackPerformance:z=!0,verbose:j=!1}=X;if(Y){let Q=b8.getWithFileCheck("file",$);if(Q){if(j)console.log(`Configuration loaded from cache: ${$}`);return Q}}let U=async()=>{if(!E$($))return null;try{let Q=`?t=${Date.now()}`,E=await import($+Q),G=E.default||E,F="default"in E,O=Object.keys(E).length>0;if(!F&&!O)throw new U1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new U1($,Error("Configuration must export a valid object"),"unknown");let w={config:I6(Z,G,_),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)b8.setWithFileCheck("file",w,$,L);return w}catch(Q){throw Q instanceof Error?t9.configLoad($,Q):t9.configLoad($,Error(String(Q)))}};if(z)return x1.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,Z,X={}){for(let _ of $)try{let Y=await this.loadFromPath(_,Z,X);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(X.verbose)console.warn(`Failed to load config from ${_}:`,Y)}return null}generateConfigPaths($,Z,X){let _=this.generateNamePatterns($,X),Y=[];for(let L of _)for(let z of this.extensions)Y.push(UZ(Z,`${L}${z}`));return Y}generateNamePatterns($,Z){let X=[];if(X.push("config",".config"),$)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(Z){if(X.push(Z,`.${Z}.config`,`${Z}.config`,`.${Z}`),$)X.push(`${$}.${Z}.config`,`.${$}.${Z}.config`)}return X.filter(Boolean)}checkFileAccess($){return j2(async()=>{return E$($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,X){let _=[];if(!E$($))return _;if(Z||X){let Y=this.generateNamePatterns(Z||"",X);for(let L of Y)for(let z of this.extensions){let j=UZ($,`${L}${z}`);if(await this.checkFileAccess(j))_.push(j)}}else try{let{readdirSync:Y}=await import("fs"),L=Y($);for(let z of L)if(this.looksLikeConfigFile(z)){let j=UZ($,z);if(await this.checkFileAccess(j))_.push(j)}}catch{return[]}return _}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((X)=>X.test($))}async validateConfigFile($){let Z=[];try{if(!E$($))return Z.push("Configuration file does not exist"),Z;let X=await import($),_=X.default||X;if(_===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof _!=="object"||_===null)Z.push("Configuration must be an object");else if(Array.isArray(_))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Y}=await import("fs"),L=Y($,"utf8");JSON.parse(L)}catch(Y){Z.push(`Invalid JSON syntax: ${Y}`)}}catch(X){Z.push(`Failed to load configuration file: ${X}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let X=new Map;return await Promise.allSettled($.map(async(_)=>{try{let Y=await this.loadFromPath(_,{},Z);if(Y)X.set(_,Y.config)}catch(Y){if(Z.verbose)console.warn(`Failed to preload ${_}:`,Y)}})),X}}class J6{async validateConfiguration($,Z,X={}){let{stopOnFirstError:_=!1,validateRequired:Y=!0,validateTypes:L=!0,customRules:z=[],trackPerformance:j=!0,verbose:U=!1}=X,Q=async()=>{let E=[],G=[],F={stopOnFirstError:_,validateRequired:Y,validateTypes:L,customRules:z,trackPerformance:j,verbose:U};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,F);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...z],F);else return this.validateWithJSONSchema($,Z,F)}catch(O){return E.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:E,warnings:G}}};if(j)return await x1.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile($,Z,X){try{if(!fY(Z))throw new j1(Z,[{path:"",message:"Schema file does not exist"}]);let _=await import(Z),Y=_.default||_;if(Array.isArray(Y))return this.validateWithRules($,Y,X);else return this.validateWithJSONSchema($,Y,X)}catch(_){throw new j1(Z,[{path:"",message:`Failed to load schema: ${_}`}])}}validateWithJSONSchema($,Z,X){let _=[],Y=[];return this.validateObjectAgainstSchema($,Z,"",_,Y,X),{isValid:_.length===0,errors:_,warnings:Y}}validateObjectAgainstSchema($,Z,X,_,Y,L){if(L.validateTypes&&Z.type){let z=Array.isArray($)?"array":typeof $,j=Array.isArray(Z.type)?Z.type:[Z.type];if(!j.includes(z)){if(_.push({path:X,message:`Expected type ${j.join(" or ")}, got ${z}`,expected:j.join(" or "),actual:z,rule:"type"}),L.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(_.push({path:X,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),L.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)_.push({path:X,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)_.push({path:X,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))_.push({path:X,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)_.push({path:X,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)_.push({path:X,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let z=0;z<$.length;z++){let j=X?`${X}[${z}]`:`[${z}]`;if(this.validateObjectAgainstSchema($[z],Z.items,j,_,Y,L),L.stopOnFirstError&&_.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let z=$;if(L.validateRequired&&Z.required){for(let j of Z.required)if(!(j in z)){if(_.push({path:X?`${X}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),L.stopOnFirstError)return}}if(Z.properties){for(let[j,U]of Object.entries(Z.properties))if(j in z){let Q=X?`${X}.${j}`:j;if(this.validateObjectAgainstSchema(z[j],U,Q,_,Y,L),L.stopOnFirstError&&_.length>0)return}}if(Z.additionalProperties===!1){let j=new Set(Object.keys(Z.properties||{}));for(let U of Object.keys(z))if(!j.has(U))Y.push({path:X?`${X}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,X){let _=[],Y=[];for(let L of Z)try{let z=this.getValueByPath($,L.path),j=this.validateWithRule(z,L,L.path);if(_.push(...j),X.stopOnFirstError&&_.length>0)break}catch(z){_.push({path:L.path,message:`Rule validation failed: ${z}`,rule:"system"})}return{isValid:_.length===0,errors:_,warnings:Y}}validateWithRule($,Z,X){let _=[];if(Z.required&&($===void 0||$===null))return _.push({path:X,message:Z.message||`Property '${X}' is required`,expected:"required",rule:"required"}),_;if($===void 0||$===null)return _;if(Z.type){let Y=Array.isArray($)?"array":typeof $;if(Y!==Z.type)_.push({path:X,message:Z.message||`Expected type ${Z.type}, got ${Y}`,expected:Z.type,actual:Y,rule:"type"})}if(Z.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<Z.min)_.push({path:X,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:Y,rule:"min"})}if(Z.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>Z.max)_.push({path:X,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:Y,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))_.push({path:X,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))_.push({path:X,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let Y=Z.validator($);if(Y)_.push({path:X,message:Z.message||Y,rule:"custom"})}return _}getValueByPath($,Z){if(!Z)return $;let X=Z.split("."),_=$;for(let Y of X)if(_&&typeof _==="object"&&Y in _)_=_[Y];else return;return _}generateRulesFromInterface($){let Z=[],X=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let _ of X){let[,Y,L,z]=_;Z.push({path:Y,required:!L,type:this.mapTypeScriptType(z)})}return Z}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:q2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class iZ{fileLoader=new k5;envProcessor=new N5;validator=new J6;async loadConfig($){let Z=Date.now(),{cache:X,performance:_,schema:Y,validate:L,...z}=$;try{if(X?.enabled){let U=this.checkCache(z.name||"",z);if(U)return U}let j;try{j=await this.loadConfigurationStrategies(z,!0,X)}catch(U){let Q=z.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(Q)throw U;j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`No configuration file found for "${z.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let E=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),G=!E&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),F=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(Q&&(F||E))throw U;if(G&&(!Q||!F))j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Y||L)await this.validateConfiguration(j.config,Y,L,z.name);if(X?.enabled&&j)this.cacheResult(z.name||"",j,X,z);if(_?.enabled){let U={operation:"loadConfig",duration:Date.now()-Z,configName:z.name,timestamp:new Date};if(_.onMetrics)_.onMetrics(U);if(_.slowThreshold&&U.duration>_.slowThreshold)D9.warn(`Slow configuration loading detected: ${U.duration}ms for ${z.name}`);j.metrics=U}return j}catch(j){let U=Date.now()-Z;throw D9.error(`Configuration loading failed after ${U}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies($,Z=!1,X){let{name:_="",alias:Y,cwd:L,configDir:z,defaultConfig:j,checkEnv:U=!0,arrayStrategy:Q="replace",verbose:E=!1}=$,G=L||z8.cwd(),F=[],O=await this.loadLocalConfiguration(_,Y,G,z,j,Q,E,U,X);if(O)return F.push(...this.getLocalSearchPaths(_,Y,G,z)),this.finalizeResult(O,F,U,_,E);let K=await this.loadHomeConfiguration(_,Y,j,Q,E,U);if(K)return F.push(...this.getHomeSearchPaths(_,Y)),this.finalizeResult(K,F,U,_,E);let W=await this.loadPackageJsonConfiguration(_,Y,G,j,Q,E,U);if(W)return F.push(e0(G,"package.json")),this.finalizeResult(W,F,U,_,E);if(F.push(...this.getAllSearchPaths(_,Y,G,z)),Z)throw t9.configNotFound(_,F,Y);return{...await this.applyEnvironmentVariables(_,j,U,E),warnings:[`No configuration file found for "${_}"${Y?` or alias "${Y}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,X,_,Y,L,z,j,U){let Q=j?L1($,Y,z):Y,E=this.getLocalDirectories(X,_);for(let G of E){if(z)D9.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,Z),O=await this.fileLoader.tryLoadFromPaths(F,Q,{arrayStrategy:L,verbose:z,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(z)D9.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,Z,X,_,Y,L){if(!$)return null;let z=L?L1($,X,Y):X,j=[e0(V8(),".config",$),e0(V8(),".config"),V8()];for(let U of j){if(Y)D9.info(`Checking home directory: ${U}`);let Q=this.fileLoader.generateConfigPaths($,U,Z),E=await this.fileLoader.tryLoadFromPaths(Q,z,{arrayStrategy:_,verbose:Y});if(E){if(Y)D9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,Z,X,_,Y,L,z){let j=z?L1($,_,L):_;try{let U=e0(X,"package.json");if(!uZ(U))return null;let Q=await import(U),E=Q[$],G=$;if(!E&&Z)E=Q[Z],G=Z;if(E&&typeof E==="object"&&!Array.isArray(E)){if(L)D9.success(`Configuration loaded from package.json: ${G}`);return{config:I6(j,E,Y),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(L)D9.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,Z,X,_){if(!X||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:L1($,Z,_),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,X,_,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,X,_){let Y=[];if(X){let L=X($);if(L)Y.push(...L)}if(Z){let L=await this.validator.validateConfiguration($,Z);if(!L.isValid)Y.push(...L.errors.map((z)=>z.path?`${z.path}: ${z.message}`:z.message))}if(Y.length>0)throw t9.configValidation(_||"unknown",Y,_)}checkCache($,Z){let X=this.generateCacheKey($,Z);return b8.get(X)||null}cacheResult($,Z,X,_){let Y=this.generateCacheKey($,_);b8.set(Y,Z,void 0,X.ttl)}generateCacheKey($,Z){let X=[$];if(Z.alias)X.push(`alias:${Z.alias}`);if(Z.cwd)X.push(`cwd:${Z.cwd}`);if(Z.configDir)X.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)X.push(`checkEnv:${Z.checkEnv}`);return X.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,e0($,"config"),e0($,".config"),Z?e0($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,X,_){let Y=[];return Y.push(...this.getLocalSearchPaths($,Z,X,_)),Y.push(...this.getHomeSearchPaths($,Z)),Y.push(e0(X,"package.json")),Y}getLocalSearchPaths($,Z,X,_){let Y=this.getLocalDirectories(X,_),L=[];for(let z of Y)L.push(...this.fileLoader.generateConfigPaths($,z,Z));return L}getHomeSearchPaths($,Z){if(!$)return[];let X=[e0(V8(),".config",$),e0(V8(),".config"),V8()],_=[];for(let Y of X)_.push(...this.fileLoader.generateConfigPaths($,Y,Z));return _}async loadConfigWithResult($){return this.loadConfig($)}}function A7($){let X=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),_=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return X||_}async function SL($){return g9.loadConfig({...$,__strictErrorHandling:!0})}async function F2($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},X="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let _;if(X)_=await g9.loadConfig($);else _=await g9.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return _?.config??Z}catch(_){let Y=_ instanceof Error?_.name:"UnknownError",L=_ instanceof Error?_.message:String(_);if(!(Y==="ConfigNotFoundError"||Y==="ConfigLoadError"||Y==="ConfigValidationError"||L.includes("config"))&&$.verbose)D9.warn("Unexpected error loading config, using defaults:",[_ instanceof Error?_:Error(String(_))]);let j=X?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await g9.applyEnvironmentVariables(j.name||"",Z,!0,j.verbose||!1))?.config??Z;return Z}}async function $9($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:Z}=await import("process");try{return(await g9.loadConfig({name:$,cwd:Z(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&A7(X)))return(await g9.applyEnvironmentVariables($,{},!0,!1)).config;throw X}}try{return(await g9.loadConfig({...$,cwd:$.cwd||z8.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&A7(Z)))return(await g9.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw Z}}async function ML($,Z,X="replace"){let _=new k5;try{let Y=await _.loadFromPath($,Z,{arrayStrategy:X,useCache:!1,trackPerformance:!1});return Y?Y.config:null}catch{return null}}function L1($,Z,X=!1){let _=new N5,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function L(z,j=[]){let U={...z};for(let[Q,E]of Object.entries(z)){let G=[...j,Q],F=[`${Y}_${G.join("_").toUpperCase()}`,`${Y}_${G.map((W)=>W.toUpperCase()).join("")}`,`${Y}_${G.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,K;for(let W of F)if(O=z8.env[W],O!==void 0){K=W;break}if(O!==void 0&&K)if(typeof E==="boolean")U[Q]=["true","1","yes"].includes(O.toLowerCase());else if(typeof E==="number"){let W=Number(O);if(!Number.isNaN(W))U[Q]=W}else if(Array.isArray(E))try{U[Q]=JSON.parse(O)}catch{U[Q]=O.split(",").map((W)=>W.trim())}else U[Q]=O;else if(E&&typeof E==="object"&&!Array.isArray(E))U[Q]=L(E,G)}return U}return L(Z)}function wL($){let Z=e0(z8.cwd(),$.configDir),X=e0(z8.cwd(),$.generatedDir),_=e0(X,"config-types.ts");if(!uZ(O7(_)))WY(O7(_),{recursive:!0,mode:511});let Y=uZ(Z)?KY(Z).map((z)=>z.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],L=`// Generated by bunfig v${Oz}
|
|
32
|
-
export type ConfigNames = ${Y.length?`'${Y.join("' | '")}'`:"string"}
|
|
33
|
-
`;IY(_,L,{mode:438})}function HL($){let Z=null,X=null,_=()=>{if(!X)X=F2($).then((L)=>{return Z=L,L},(L)=>{let z="defaultConfig"in $?$.defaultConfig:{};if(Z=z,"verbose"in $&&$.verbose)D9.warn("Config loading failed, using defaults:",[L instanceof Error?L:Error(String(L))]);return z});return X},Y="defaultConfig"in $?$.defaultConfig:{};return Z=Y,_(),new Proxy({},{get(L,z){if(Z)return Z[z];let j=Y[z];return _(),j},has(L,z){return z in(Z||Y)},ownKeys(){return Object.keys(Z||Y)},getOwnPropertyDescriptor(L,z){return Object.getOwnPropertyDescriptor(Z||Y,z)},set(L,z,j){if(!Z)Z={...Y};return Z[z]=j,!0}})}function qL($){let Z=q7(cY.cwd(),$?.configDir||"./config");function X(){if(!gY(Z))return[];let Y=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),L=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],z=pY(Z).filter((U)=>Y.has(jZ(U))).map((U)=>({base:U.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:U})),j=new Map;for(let{base:U,file:Q}of z){let E=jZ(Q).toLowerCase(),G=j.get(U);if(!G){j.set(U,Q);continue}let F=jZ(G).toLowerCase();if(L.indexOf(E)<L.indexOf(F))j.set(U,Q)}return Array.from(j.entries()).map(([U,Q])=>({base:U,file:Q})).sort((U,Q)=>U.base.localeCompare(Q.base))}function _(){let Y=X(),L=Y.map((Q)=>Q.base),z=L.length?L.map((Q)=>`'${Q}'`).join(" | "):"string",j=Y.length?`{
|
|
34
|
-
${Y.map((Q)=>{let E=q7(Z,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${E}').default`}).join(`,
|
|
35
|
-
`)}
|
|
36
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${z}
|
|
37
|
-
export type ConfigByName = ${j}
|
|
38
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
-
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(Y){Y.onResolve({filter:/^virtual:bunfig-types$/},(L)=>{return{path:L.path,namespace:"bunfig-virtual"}}),Y.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:_(),loader:"ts"}})}}}function TL($,Z={}){let X=e$.cwd();while(X.includes("storage"))X=T7(X,"..");let _=T7(X,$||"");if(Z?.relative)return uY(e$.cwd(),_);return _}function P0(){if(h9.env.NODE_ENV==="test"||h9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function PL(){if(h9.env.NODE_ENV==="test"||h9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof h9<"u"){let $=h9.type;if($==="renderer"||$==="worker")return!1;return!!(h9.versions&&(h9.versions.node||h9.versions.bun))}return!1}class V2{async format($){let Z=await PL(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:w8.pid,hostname:Z(),environment:w8.env.NODE_ENV||"development",platform:w8.platform,version:w8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:w8.env.NODE_ENV||w8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Y5{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,Z={}){this.name=$,this.config={...O1},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new V2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),L=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,L),this.encryptionKeys.set(Y,{key:L,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[X]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...g$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...g$};return{...g$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:O1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}shouldWriteToFile(){return!P0()&&this.config.writeToFile===!0}async writeToFile($){let X=(async()=>{let Y,L=0,z=3,j=1000;while(L<z)try{try{try{await iY(this.config.logDirectory,C7.F_OK|C7.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await rY(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x9.from($);try{if(!O$(this.currentLogFile))await QZ(this.currentLogFile,"",{mode:420});if(Y=k7(this.currentLogFile,"a",420),nY(Y,U,{flag:"a"}),N7(Y),Y!==void 0)OZ(Y),Y=void 0;if((await S8(this.currentLogFile)).size===0){if(await QZ(this.currentLogFile,U,{flag:"w",mode:420}),(await S8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let E=Q;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(L<z-1){let G=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${L+1}/${z}:`,G);let F=j*2**L;await new Promise((O)=>setTimeout(O,F)),L++;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(Y!==void 0)try{OZ(Y)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(U){if(L===z-1){let E=U,G=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),U}L++;let Q=j*2**(L-1);await new Promise((E)=>setTimeout(E,Q))}})();this.pendingOperations.push(X);let _=this.pendingOperations.length-1;try{await X}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(_,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 M8(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 M8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return M8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(P0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let X=typeof Z.interval==="number"?Z.interval:60,_=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},_)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,X=this.generateKeyId(),_=this.generateKey();this.currentKeyId=X,this.keys.set(X,_),this.encryptionKeys.set(X,{key:_,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,j],[,U])=>U.createdAt.getTime()-j.createdAt.getTime()),L=typeof Z.maxKeys==="number"?Z.maxKeys:1,z=Math.max(1,L);if(Y.length>z)for(let[j]of Y.slice(z))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return EZ(16).toString("hex")}generateKey(){return EZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=EZ(16),_=mY("aes-256-gcm",Z,X),Y=x9.isBuffer($)?$:x9.from($,"utf8"),L=_.update(Y),z=_.final(),j=L.length+z.length,U=_.getAuthTag(),Q=x9.allocUnsafe(16+j+16);return X.copy(Q,0),L.copy(Q,16),z.copy(Q,16+L.length),U.copy(Q,16+j),{encrypted:Q,iv:X}}async compressData($){return new Promise((Z,X)=>{let _=B7(),Y=[];_.on("data",(L)=>Y.push(L)),_.on("end",()=>Z(x9.from(x9.concat(Y)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(P0())return;if(!this.shouldWriteToFile())return;let $=await S8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await Q$(this.config.logDirectory),L=Y.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,Q)=>{let E=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),z=L.length>0?Number.parseInt(L[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${X}.${z}`;if(await S8(X).catch(()=>null))try{if(await x7(X,j),Z.compress)try{let U=`${j}.gz`;await this.compressLogFile(j,U),await G$(j)}catch(U){console.error("Error compressing rotated file:",U)}if(L.length===0&&!Y.some((U)=>U.endsWith(".log.1")))try{let U=`${X}.1`;await QZ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),L=X.replace(/\.log$/,`-${Y}.log`);if(await S8(X).catch(()=>null))await x7(X,L)}if(this.currentLogFile=_,Z.maxFiles){let L=(await Q$(this.config.logDirectory)).filter((z)=>z.startsWith(this.name)).sort((z,j)=>j.localeCompare(z));for(let z of L.slice(Z.maxFiles))await G$(M8(this.config.logDirectory,z))}}}async compressLogFile($,Z){let X=P7($),_=lY(Z),Y=B7();await tY(X,Y,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(_);console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),O$(this.currentLogFile))try{let $=k7(this.currentLogFile,"r+");N7($),OZ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!P0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await Q$(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of Z)try{await G$(M8(this.config.logDirectory,X))}catch(_){console.error(`Failed to delete temp file ${X}:`,_)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?L0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P0())return!1;let $=typeof _0.env.NO_COLOR<"u",Z=_0.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof _0.stderr<"u"&&_0.stderr.isTTY||typeof _0.stdout<"u"&&_0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:Y,level:L,showTimestamp:z=!0}=$,j=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(z)O.push(Z);if(L==="warning")O.push("WARN");else if(L==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(Y),O.join(" ")}let U=_0.stdout.columns||120,Q="";if(L==="warning"||L==="error")Q=`${X} ${Y}`;else if(L==="info"||L==="success")Q=`${X} ${_} ${Y}`;else Q=`${X} ${_} ${L0.cyan(Y)}`;if(!z)return Q.trim();let E=j(Q).trim().length,G=j(Z).length,F=Math.max(1,U-2-E-G);return`${Q.trim()}${" ".repeat(F)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(L,z)=>{let j=Number.parseInt(z,10);return j<Z[0].length?String(Z[0][j]):L});let X=/%([sdijfo%])/g,_=0,Y=$.replace(X,(L,z)=>{if(z==="%")return"%";if(_>=Z.length)return L;let j=Z[_++];switch(z){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return L}});if(_<Z.length)Y+=` ${Z.slice(_).map((L)=>typeof L==="object"?JSON.stringify(L,null,2):String(L)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,_,Y)=>{let L=L0.underline(L0.blue(_)),z=this.toAbsoluteFilePath(Y);if(z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(z)}`,U="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${L}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${L}\x1B]8;;\x1B\\`;return L}),Z=Z.replace(/`([^`]+)`/g,(X,_)=>L0.bgGray(_)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(X,_)=>L0.bold(_)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,_)=>L0.italic(_)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,_)=>L0.italic(_)),Z=Z.replace(/~([^~]+)~/g,(X,_)=>L0.strikethrough(_)),Z}supportsHyperlinks(){if(P0())return!1;let $=_0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let X=_0.env.HOME||"";if(X)Z=Z.replace(/^~(?=$|\/)/,X)}if(oY(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=aY(Z);else return null;return O$(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,X=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:X}}async log($,Z,...X){if(!this.shouldLog($))return;let _=new Date,Y=this.formatConsoleTimestamp(_),L=this.formatFileTimestamp(_),z,j;if(Z instanceof Error)z=Z.message,j=Z.stack;else z=this.formatMessage(Z,X);let{consoleText:U,fileText:Q}=this.buildOutputTexts(z);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":T2[$],F=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:L0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:L0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.error(O),j){let K=j.split(`
|
|
41
|
-
`);for(let W of K)if(W.trim()&&!W.includes(z))console.error(this.formatConsoleMessage({timestamp:Y,message:L0.gray(` ${W}`),level:$,showTimestamp:!1}))}break}}else if(!P0()){if(console.error(`${L} ${this.environment}.${$.toUpperCase()}: ${z}`),j)console.error(j)}let E=`${L} ${this.environment}.${$.toUpperCase()}: ${Q}
|
|
42
|
-
`;if(j)E+=`${j}
|
|
43
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,Z=""){let X={update:(j,U)=>{},finish:(j)=>{},interrupt:(j,U)=>{}};if(!this.enabled)return X;let _=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:_,lastRenderedLine:""},this.shouldStyleConsole()&&!P0()&&_0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!P0()&&_0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,U="info")=>{if(!P0()&&_0.stdout.isTTY)_0.stdout.write(`
|
|
44
|
-
`);if(this[U==="warning"?"warn":U](j),this.activeProgressBar&&this.shouldStyleConsole()&&!P0()&&_0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":L0.blue("\u25D0"),tag:X,message:`${L0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),Y=Math.round(_-Z),L=`${$} completed in ${Y}ms`,z=new Date,j=this.formatConsoleTimestamp(z),Q=`${this.formatFileTimestamp(z)} ${this.environment}.INFO: ${L}`;if(X)Q+=` ${JSON.stringify(X)}`;if(Q+=`
|
|
45
|
-
`,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":L0.green("\u2713"),tag:E,message:`${L}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!P0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug($,...Z){await this.log("debug",$,...Z)}async info($,...Z){await this.log("info",$,...Z)}async success($,...Z){await this.log("success",$,...Z)}async warn($,...Z){await this.log("warning",$,...Z)}async error($,...Z){await this.log("error",$,...Z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new Y5(Z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(P0())throw Error("createReadStream is not supported in browser environments");if(!O$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return P7(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=x9.isBuffer($)?$:x9.from($,"base64"),Y=_.subarray(0,16),L=_.subarray(_.length-16),z=_.subarray(16,_.length-16),j=sY("aes-256-gcm",X,Y);j.setAuthTag(L);let U=j.update(z),Q=j.final(),E=U.length+Q.length,G=x9.allocUnsafe(E);return U.copy(G,0),Q.copy(G,U.length),G.toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P0()}isServerMode(){return!P0()}setTestEncryptionKey($,Z){this.currentKeyId=$,this.keys.set($,Z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),{consoleText:Y,fileText:L}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let j=Y.split(`
|
|
46
|
-
`),U=Math.max(...j.map((F)=>F.length))+2,Q=`\u250C${"\u2500".repeat(U)}\u2510`,E=`\u2514${"\u2500".repeat(U)}\u2518`,G=j.map((F)=>{return this.formatConsoleMessage({timestamp:X,message:L0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:L0.cyan(Q),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:X,message:L0.cyan(E),showTimestamp:!1}))}else if(!P0())console.error(`${_} ${this.environment}.INFO: [BOX] ${L}`);let z=`${_} ${this.environment}.INFO: [BOX] ${L}
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}async prompt($){if(P0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${L0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let Y=_.toString().trim().toLowerCase();_0.stdin.removeListener("data",X);try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!1)}catch{}_0.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!0)}catch{}_0.stdin.resume(),_0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let U=/%([sdijfo%])/g,Q=0;if(X=$.replace(U,(E,G)=>{if(G==="%")return"%";if(Q>=Z.length)return E;let F=Z[Q++];switch(G){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return E}}),Q<Z.length)X+=` ${Z.slice(Q).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:_,fileText:Y}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${L0.blue("\u25D0")} `;console.error(`${Q}${U} ${L0.cyan(_)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!_0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),Y=$.barLength-_,L=L0.green("\u2501".repeat(_)),z=L0.gray("\u2501".repeat(Y)),j=`[${L}${z}]`,U=`${X}%`.padStart(4),Q=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":Z||X===100?L0.green("\u2713"):L0.blue("\u25B6"),G=this.options.showTags!==!1&&this.name?` ${L0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${G} ${j} ${U}${Q}`,O=_0.stdout.columns||80,K=" ".repeat(Math.max(0,O-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${K}`,_0.stdout.write($.lastRenderedLine),Z)_0.stdout.write(`
|
|
49
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||P0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(P0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await Q$(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let L=M8(this.config.logDirectory,_);if($.before)try{if((await S8(L)).mtime>=$.before)continue}catch(z){console.error(`Failed to get stats for file ${L}:`,z);continue}X.push(L)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await G$(_),console.warn(`Deleted log file: ${_}`)}catch(Y){console.error(`Failed to delete log file ${_}:`,Y)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function NL($,Z={}){let{maxRetries:X=3,retryDelay:_=1000,isRetryable:Y=()=>!0,fallback:L}=Z,z=Error("Unknown error occurred");for(let j=0;j<=X;j++)try{return await $()}catch(U){if(z=U instanceof Error?U:Error(String(U)),j===X||!Y(z))break;if(_>0)await new Promise((Q)=>setTimeout(Q,_))}if(L!==void 0)return L;throw z instanceof Error?z:Error(`Unknown error: ${String(z)}`)}class D6{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,X={}){let{prefix:_,useCamelCase:Y=!0,useBackwardCompatibility:L=!0,customParsers:z={},verbose:j=!1,trackPerformance:U=!0}=X,Q=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let E=_||this.generateEnvPrefix($),G={...Z};return this.processObject(G,[],E,{useCamelCase:Y,useBackwardCompatibility:L,customParsers:z,verbose:j,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return C5.track("applyEnvironmentVariables",Q,{configName:$});return Q()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,X,_){for(let[Y,L]of Object.entries($)){let z=[...Z,Y],j=z.map((E)=>this.formatEnvKey(E,_.useCamelCase)),U=`${X}_${j.join("_")}`,Q=_.useBackwardCompatibility?`${X}_${z.map((E)=>E.toUpperCase()).join("_")}`:null;if(_.verbose);if(typeof L==="object"&&L!==null&&!Array.isArray(L))this.processObject(L,z,X,_);else{let E=F$.env[U]||(Q?F$.env[Q]:void 0);if(E!==void 0){if(_.verbose){let G=F$.env[U]?U:Q}try{$[Y]=this.parseEnvironmentValue(E,typeof L,U,_.customParsers,_.configName)}catch(G){if(G instanceof tZ)throw G;throw U8.envVar(U,E,typeof L,_.configName)}}}}}parseEnvironmentValue($,Z,X,_,Y){for(let[L,z]of Object.entries(_))try{return z($)}catch{continue}for(let L of this.defaultParsers)if(L.canParse($,Z))try{return L.parse($)}catch{throw U8.envVar(X,$,`${Z} (via ${L.name} parser)`,Y)}return $}getEnvironmentVariables($){let Z={},X=$.toUpperCase();for(let[_,Y]of Object.entries(F$.env))if(_.startsWith(X)&&Y!==void 0)Z[_]=Y;return Z}validateEnvironmentVariable($,Z,X){let _=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))_.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue($,Z,X,{})}catch(Y){_.push(`Cannot parse value "${Z}" as ${X}: ${Y}`)}return{isValid:_.length===0,errors:_}}generateEnvVarDocs($,Z,X={}){let{prefix:_,format:Y="text"}=X,L=_||this.generateEnvPrefix($),z=[];switch(this.extractEnvVarInfo(Z,[],L,z),Y){case"markdown":return this.formatAsMarkdown(z,$);case"json":return JSON.stringify(z,null,2);default:return this.formatAsText(z,$)}}extractEnvVarInfo($,Z,X,_){for(let[Y,L]of Object.entries($)){let z=[...Z,Y],j=`${X}_${z.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof L==="object"&&L!==null&&!Array.isArray(L))this.extractEnvVarInfo(L,z,X,_);else _.push({key:j,type:Array.isArray(L)?"array":typeof L,description:`Configuration for ${z.join(".")}`,example:this.generateExample(L)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let X=`Environment Variables for ${Z}:
|
|
50
|
-
|
|
51
|
-
`;for(let _ of $)X+=`${_.key}
|
|
52
|
-
`,X+=` Type: ${_.type}
|
|
53
|
-
`,X+=` Description: ${_.description}
|
|
54
|
-
`,X+=` Example: ${_.example}
|
|
55
|
-
|
|
56
|
-
`;return X}formatAsMarkdown($,Z){let X=`# Environment Variables for ${Z}
|
|
57
|
-
|
|
58
|
-
`;X+=`| Variable | Type | Description | Example |
|
|
59
|
-
`,X+=`|----------|------|-------------|----------|
|
|
60
|
-
`;for(let _ of $)X+=`| \`${_.key}\` | ${_.type} | ${_.description} | \`${_.example}\` |
|
|
61
|
-
`;return X}}function kL($,Z,X={}){return W2($,Z,X,new WeakMap)}function W2($,Z,X,_){let{arrayMergeMode:Y="replace",skipNullish:L=!1,customMerger:z}=X;if(Z===null||Z===void 0)return L?$:Z;if(z){let j=z($,Z);if(j!==void 0)return j}if(Array.isArray(Z)||Array.isArray($))return K2($,Z,Y,_);if(!G9(Z)||!G9($))return Z;return AL($,Z,X,_)}function K2($,Z,X,_){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(X){case"replace":return Z;case"concat":return CL($,Z);case"smart":return xL($,Z,_);default:return Z}return Z}function CL($,Z){let X=[...Z];for(let _ of $)if(!X.some((Y)=>rZ(Y,_)))X.push(_);return X}function xL($,Z,X){if(Z.length===0)return $;if($.length===0)return Z;if(G9(Z[0])&&G9($[0]))return BL($,Z,X);if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}function BL($,Z,X){let _=[...Z];for(let Y of $){if(!G9(Y)){_.push(Y);continue}let L=["id","name","key","path","type"],z=!1;for(let j of L)if(j in Y){if(_.find((Q)=>G9(Q)&&(j in Q)&&Q[j]===Y[j])){z=!0;break}}if(!z)_.push(Y)}return _}function AL($,Z,X,_){let Y=Z;if(G9(Y)&&_.has(Y))return _.get(Y);let L={...$};if(G9(Y))_.set(Y,L);for(let z in Y){if(!Object.prototype.hasOwnProperty.call(Y,z))continue;let j=Y[z],U=L[z];if(X.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){L[z]=j;continue}if(G9(j)&&G9(U))L[z]=W2(U,j,X,_);else if(Array.isArray(j)||Array.isArray(U))L[z]=K2(U,j,X.arrayMergeMode||"smart",_);else L[z]=j}return L}function I2($,Z,X="replace"){return kL($,Z,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function rZ($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!rZ($[X],Z[X]))return!1;return!0}if(G9($)&&G9(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!rZ($[Y],Z[Y]))return!1}return!0}return!1}function G9($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class J2{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,X={}){let{arrayStrategy:_="replace",useCache:Y=!0,cacheTtl:L,trackPerformance:z=!0,verbose:j=!1}=X;if(Y){let Q=C1.getWithFileCheck("file",$);if(Q){if(j)console.log(`Configuration loaded from cache: ${$}`);return Q}}let U=async()=>{if(!V$($))return null;try{let Q=`?t=${Date.now()}`,E=await import($+Q),G=E.default||E,F="default"in E,O=Object.keys(E).length>0;if(!F&&!O)throw new L5($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new L5($,Error("Configuration must export a valid object"),"unknown");let w={config:I2(Z,G,_),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)C1.setWithFileCheck("file",w,$,L);return w}catch(Q){throw Q instanceof Error?U8.configLoad($,Q):U8.configLoad($,Error(String(Q)))}};if(z)return C5.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,Z,X={}){for(let _ of $)try{let Y=await this.loadFromPath(_,Z,X);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(X.verbose)console.warn(`Failed to load config from ${_}:`,Y)}return null}generateConfigPaths($,Z,X){let _=this.generateNamePatterns($,X),Y=[];for(let L of _)for(let z of this.extensions)Y.push(GZ(Z,`${L}${z}`));return Y}generateNamePatterns($,Z){let X=[];if(X.push("config",".config"),$)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);let _=Z===void 0?[]:Array.isArray(Z)?Z:[Z];for(let L of _){if(!L)continue;if(X.push(L,`.${L}.config`,`${L}.config`,`.${L}`),$)X.push(`${$}.${L}.config`,`.${$}.${L}.config`)}let Y=new Set;return X.filter((L)=>{if(!L||Y.has(L))return!1;return Y.add(L),!0})}checkFileAccess($){return NL(async()=>{return V$($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,X){let _=[];if(!V$($))return _;if(Z||X){let Y=this.generateNamePatterns(Z||"",X);for(let L of Y)for(let z of this.extensions){let j=GZ($,`${L}${z}`);if(await this.checkFileAccess(j))_.push(j)}}else try{let{readdirSync:Y}=await import("fs"),L=Y($);for(let z of L)if(this.looksLikeConfigFile(z)){let j=GZ($,z);if(await this.checkFileAccess(j))_.push(j)}}catch{return[]}return _}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((X)=>X.test($))}async validateConfigFile($){let Z=[];try{if(!V$($))return Z.push("Configuration file does not exist"),Z;let X=await import($),_=X.default||X;if(_===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof _!=="object"||_===null)Z.push("Configuration must be an object");else if(Array.isArray(_))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Y}=await import("fs"),L=Y($,"utf8");JSON.parse(L)}catch(Y){Z.push(`Invalid JSON syntax: ${Y}`)}}catch(X){Z.push(`Failed to load configuration file: ${X}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let X=new Map;return await Promise.allSettled($.map(async(_)=>{try{let Y=await this.loadFromPath(_,{},Z);if(Y)X.set(_,Y.config)}catch(Y){if(Z.verbose)console.warn(`Failed to preload ${_}:`,Y)}})),X}}class D2{async validateConfiguration($,Z,X={}){let{stopOnFirstError:_=!1,validateRequired:Y=!0,validateTypes:L=!0,customRules:z=[],trackPerformance:j=!0,verbose:U=!1}=X,Q=async()=>{let E=[],G=[],F={stopOnFirstError:_,validateRequired:Y,validateTypes:L,customRules:z,trackPerformance:j,verbose:U};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,F);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...z],F);else return this.validateWithJSONSchema($,Z,F)}catch(O){return E.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:E,warnings:G}}};if(j)return await C5.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile($,Z,X){try{if(!eY(Z))throw new z5(Z,[{path:"",message:"Schema file does not exist"}]);let _=await import(Z),Y=_.default||_;if(Array.isArray(Y))return this.validateWithRules($,Y,X);else return this.validateWithJSONSchema($,Y,X)}catch(_){throw new z5(Z,[{path:"",message:`Failed to load schema: ${_}`}])}}validateWithJSONSchema($,Z,X){let _=[],Y=[];return this.validateObjectAgainstSchema($,Z,"",_,Y,X),{isValid:_.length===0,errors:_,warnings:Y}}validateObjectAgainstSchema($,Z,X,_,Y,L){if(L.validateTypes&&Z.type){let z=Array.isArray($)?"array":typeof $,j=Array.isArray(Z.type)?Z.type:[Z.type];if(!j.includes(z)){if(_.push({path:X,message:`Expected type ${j.join(" or ")}, got ${z}`,expected:j.join(" or "),actual:z,rule:"type"}),L.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(_.push({path:X,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),L.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)_.push({path:X,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)_.push({path:X,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))_.push({path:X,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)_.push({path:X,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)_.push({path:X,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let z=0;z<$.length;z++){let j=X?`${X}[${z}]`:`[${z}]`;if(this.validateObjectAgainstSchema($[z],Z.items,j,_,Y,L),L.stopOnFirstError&&_.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let z=$;if(L.validateRequired&&Z.required){for(let j of Z.required)if(!(j in z)){if(_.push({path:X?`${X}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),L.stopOnFirstError)return}}if(Z.properties){for(let[j,U]of Object.entries(Z.properties))if(j in z){let Q=X?`${X}.${j}`:j;if(this.validateObjectAgainstSchema(z[j],U,Q,_,Y,L),L.stopOnFirstError&&_.length>0)return}}if(Z.additionalProperties===!1){let j=new Set(Object.keys(Z.properties||{}));for(let U of Object.keys(z))if(!j.has(U))Y.push({path:X?`${X}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,X){let _=[],Y=[];for(let L of Z)try{let z=this.getValueByPath($,L.path),j=this.validateWithRule(z,L,L.path);if(_.push(...j),X.stopOnFirstError&&_.length>0)break}catch(z){_.push({path:L.path,message:`Rule validation failed: ${z}`,rule:"system"})}return{isValid:_.length===0,errors:_,warnings:Y}}validateWithRule($,Z,X){let _=[];if(Z.required&&($===void 0||$===null))return _.push({path:X,message:Z.message||`Property '${X}' is required`,expected:"required",rule:"required"}),_;if($===void 0||$===null)return _;if(Z.type){let Y=Array.isArray($)?"array":typeof $;if(Y!==Z.type)_.push({path:X,message:Z.message||`Expected type ${Z.type}, got ${Y}`,expected:Z.type,actual:Y,rule:"type"})}if(Z.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<Z.min)_.push({path:X,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:Y,rule:"min"})}if(Z.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>Z.max)_.push({path:X,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:Y,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))_.push({path:X,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))_.push({path:X,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let Y=Z.validator($);if(Y)_.push({path:X,message:Z.message||Y,rule:"custom"})}return _}getValueByPath($,Z){if(!Z)return $;let X=Z.split("."),_=$;for(let Y of X)if(_&&typeof _==="object"&&Y in _)_=_[Y];else return;return _}generateRulesFromInterface($){let Z=[],X=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let _ of X){let[,Y,L,z]=_;Z.push({path:Y,required:!L,type:this.mapTypeScriptType(z)})}return Z}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:P2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function yL($){if(!$)return"";let Z=Array.isArray($)?$.filter(Boolean):[$];if(Z.length===0)return"";if(Z.length===1)return` or alias "${Z[0]}"`;return` or aliases ${Z.map((X)=>`"${X}"`).join(", ")}`}class R2{fileLoader=new J2;envProcessor=new D6;validator=new D2;async loadConfig($){let Z=Date.now(),{cache:X,performance:_,schema:Y,validate:L,...z}=$;try{if(X?.enabled){let U=this.checkCache(z.name||"",z);if(U)return U}let j;try{j=await this.loadConfigurationStrategies(z,!0,X)}catch(U){let Q=z.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(Q)throw U;j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`No configuration file found for "${z.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let E=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),G=!E&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),F=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(Q&&(F||E))throw U;if(G&&(!Q||!F))j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Y||L)await this.validateConfiguration(j.config,Y,L,z.name);if(X?.enabled&&j)this.cacheResult(z.name||"",j,X,z);if(_?.enabled){let U={operation:"loadConfig",duration:Date.now()-Z,configName:z.name,timestamp:new Date};if(_.onMetrics)_.onMetrics(U);if(_.slowThreshold&&U.duration>_.slowThreshold)M9.warn(`Slow configuration loading detected: ${U.duration}ms for ${z.name}`);j.metrics=U}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let U=Date.now()-Z;throw M9.error(`Configuration loading failed after ${U}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies($,Z=!1,X){let{name:_="",alias:Y,cwd:L,configDir:z,defaultConfig:j,checkEnv:U=!0,arrayStrategy:Q="replace",verbose:E=!1}=$,G=L||r$.cwd(),F=[],O=await this.loadLocalConfiguration(_,Y,G,z,j,Q,E,U,X);if(O)return F.push(...this.getLocalSearchPaths(_,Y,G,z)),this.finalizeResult(O,F,U,_,E);let K=await this.loadHomeConfiguration(_,Y,j,Q,E,U);if(K)return F.push(...this.getHomeSearchPaths(_,Y)),this.finalizeResult(K,F,U,_,E);let W=await this.loadPackageJsonConfiguration(_,Y,G,j,Q,E,U);if(W)return F.push(j9(G,"package.json")),this.finalizeResult(W,F,U,_,E);if(F.push(...this.getAllSearchPaths(_,Y,G,z)),Z)throw U8.configNotFound(_,F,Y);return{...await this.applyEnvironmentVariables(_,j,U,E),warnings:[`No configuration file found for "${_}"${yL(Y)}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,X,_,Y,L,z,j,U){let Q=j?K$($,Y,z):Y,E=this.getLocalDirectories(X,_);for(let G of E){if(z)M9.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,Z),O=await this.fileLoader.tryLoadFromPaths(F,Q,{arrayStrategy:L,verbose:z,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(z)M9.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,Z,X,_,Y,L){if(!$)return null;let z=L?K$($,X,Y):X,j=[j9(F8(),".config",$),j9(F8(),".config"),F8()];for(let U of j){if(Y)M9.info(`Checking home directory: ${U}`);let Q=this.fileLoader.generateConfigPaths($,U,Z),E=await this.fileLoader.tryLoadFromPaths(Q,z,{arrayStrategy:_,verbose:Y});if(E){if(Y)M9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,Z,X,_,Y,L,z){let j=z?K$($,_,L):_;try{let U=j9(X,"package.json");if(!FY(U))return null;let Q={};try{Q=JSON.parse(VY(U,"utf8"))}catch(F){if(L)M9.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let E=Q[$],G=$;if(!E&&Z){let F=Array.isArray(Z)?Z:[Z];for(let O of F){if(!O)continue;if(Q[O]){E=Q[O],G=O;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(L)M9.success(`Configuration loaded from package.json: ${G}`);return{config:I2(j,E,Y),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(L)M9.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,Z,X,_){if(!X||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:K$($,Z,_),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,X,_,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,X,_){let Y=[];if(X){let L=X($);if(L)Y.push(...L)}if(Z){let L=await this.validator.validateConfiguration($,Z);if(!L.isValid)Y.push(...L.errors.map((z)=>z.path?`${z.path}: ${z.message}`:z.message))}if(Y.length>0)throw U8.configValidation(_||"unknown",Y,_)}checkCache($,Z){let X=this.generateCacheKey($,Z);return C1.get(X)||null}cacheResult($,Z,X,_){let Y=this.generateCacheKey($,_);C1.set(Y,Z,void 0,X.ttl)}generateCacheKey($,Z){let X=[$];if(Z.alias){let _=Array.isArray(Z.alias)?Z.alias.join(","):Z.alias;X.push(`alias:${_}`)}if(Z.cwd)X.push(`cwd:${Z.cwd}`);if(Z.configDir)X.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)X.push(`checkEnv:${Z.checkEnv}`);return X.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,j9($,"config"),j9($,".config"),Z?j9($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,X,_){let Y=[];return Y.push(...this.getLocalSearchPaths($,Z,X,_)),Y.push(...this.getHomeSearchPaths($,Z)),Y.push(j9(X,"package.json")),Y}getLocalSearchPaths($,Z,X,_){let Y=this.getLocalDirectories(X,_),L=[];for(let z of Y)L.push(...this.fileLoader.generateConfigPaths($,z,Z));return L}getHomeSearchPaths($,Z){if(!$)return[];let X=[j9(F8(),".config",$),j9(F8(),".config"),F8()],_=[];for(let Y of X)_.push(...this.fileLoader.generateConfigPaths($,Y,Z));return _}async loadConfigWithResult($){return this.loadConfig($)}}function K$($,Z,X=!1){let _=new D6,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function L(z,j=[]){let U={...z};for(let[Q,E]of Object.entries(z)){let G=[...j,Q],F=[`${Y}_${G.join("_").toUpperCase()}`,`${Y}_${G.map((W)=>W.toUpperCase()).join("")}`,`${Y}_${G.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,K;for(let W of F)if(O=r$.env[W],O!==void 0){K=W;break}if(O!==void 0&&K)if(typeof E==="boolean")U[Q]=["true","1","yes"].includes(O.toLowerCase());else if(typeof E==="number"){let W=Number(O);if(!Number.isNaN(W))U[Q]=W}else if(Array.isArray(E))try{U[Q]=JSON.parse(O)}catch{U[Q]=O.split(",").map((W)=>W.trim())}else U[Q]=O;else if(E&&typeof E==="object"&&!Array.isArray(E))U[Q]=L(E,G)}return U}return L(Z)}function m($){if(b.dialect==="postgres")return`$${$}`;return"?"}function o0($,Z=1){if(b.dialect==="postgres")return Array.from({length:$},(X,_)=>`$${Z+_}`).join(", ");return Array.from({length:$},()=>"?").join(", ")}function d9($){if($9==null||$9.dialect===void 0)$9=E1?{...E1}:{};if(Object.assign($9,$),$.database)$9.database={...$9.database,...$.database};if($.timestamps)$9.timestamps={...$9.timestamps,...$.timestamps};if($.pagination)$9.pagination={...$9.pagination,...$.pagination};if($.softDeletes)$9.softDeletes={...$9.softDeletes,...$.softDeletes};if(jX)Object.assign(jX,$9)}class N2{db;constructor($){this.db=new kz($),this.db.run("PRAGMA journal_mode = WAL")}query($,Z=[]){return this.db.prepare($).all(...Z)}run($,Z=[]){return this.db.prepare($).run(...Z)}close(){this.db.close()}get database(){return this.db}}function EX($){return{__raw:!0,value:$,toString:()=>$}}function Cz($){let Z=[],X="",_=!1,Y=!1,L=!1,z=!1;for(let U=0;U<$.length;U++){let Q=$[U],E=$[U+1];if(!_&&!Y&&!z&&Q==="-"&&E==="-"){L=!0,X+=Q;continue}if(L&&(Q===`
|
|
62
|
-
`||Q==="\r")){L=!1,X+=Q;continue}if(!_&&!Y&&!L&&Q==="/"&&E==="*"){z=!0,X+=Q;continue}if(z&&Q==="*"&&E==="/"){z=!1,X+=Q+E,U++;continue}if(L||z){X+=Q;continue}if(Q==="'"&&!Y){if(_&&E==="'"){X+=Q+E,U++;continue}_=!_,X+=Q;continue}if(Q==='"'&&!_){Y=!Y,X+=Q;continue}if(Q===";"&&!_&&!Y){let G=X.trim();if(G&&!G.startsWith("--"))Z.push(G);X="";continue}X+=Q}let j=X.trim();if(j&&!j.startsWith("--"))Z.push(j);return Z}function OX($){let Z=new N2($);function X(Y,...L){let z=Y[0],j=[];for(let U=0;U<L.length;U++){let Q=L[U];if(Q&&typeof Q==="object"&&(Q.__raw||Q.raw)){let E=Q.__raw?Q.value:typeof Q.raw==="string"?Q.raw:Q.raw();z+=E+(Y[U+1]||"")}else if(Q&&typeof Q==="object"&&"sql"in Q&&"values"in Q)z+=Q.sql+(Y[U+1]||""),j.push(...Q.values);else if(Array.isArray(Q)){let E=Q.map(()=>"?").join(", ");z+=E+(Y[U+1]||""),j.push(...Q)}else z+=`?${Y[U+1]||""}`,j.push(Q)}return{sql:z,values:j,execute:()=>{try{let U=z.trim().toUpperCase();if(U.startsWith("SELECT")||U.startsWith("PRAGMA")){let Q=Z.query(z,j);return Promise.resolve(Q)}else{let Q=Z.run(z,j);return Promise.resolve(Q)}}catch(U){return Promise.reject(U)}},raw:()=>z,toString:()=>z,cancel:()=>{}}}function _(Y,...L){if(Array.isArray(Y)&&"raw"in Y)return X(Y,...L);if(typeof Y==="string")return EX(Y);return X([""])}return _.raw=(Y)=>EX(Y),_.unsafe=(Y,L=[])=>{return{sql:Y,values:L,execute:()=>{try{let z=Y.trim().toUpperCase();if(z.startsWith("SELECT")||z.startsWith("PRAGMA")){let j=Z.query(Y,L);return Promise.resolve(j)}else{let j=Z.run(Y,L);return Promise.resolve(j)}}catch(z){return Promise.reject(z)}},raw:()=>Y,toString:()=>Y,cancel:()=>{}}},_.close=()=>{return Z.close(),Promise.resolve()},_.query=(Y,L)=>{try{let z=Z.query(Y,L||[]);return Promise.resolve(z)}catch(z){return Promise.reject(z)}},_.file=async(Y,L)=>{try{let{readFileSync:z}=await import("fs"),j=z(Y,"utf-8"),U=Cz(j);for(let Q of U){let E=Q.trim();if(!E||E.startsWith("--"))continue;let G=E.toUpperCase();if(G.startsWith("SELECT")||G.startsWith("PRAGMA"))Z.query(Q);else Z.run(Q)}return Promise.resolve([])}catch(z){return Promise.reject(z)}},_._wrapper=Z,_}function xz($,Z){if(Z.url)return Z.url;let{database:X,username:_,password:Y,host:L="localhost",port:z}=Z;switch($){case"postgres":return`postgres://${_}:${Y}@${L}${z?`:${z}`:""}/${X}`;case"mysql":return`mysql://${_}:${Y}@${L}${z?`:${z}`:""}/${X}`;case"sqlite":if(X===":memory:")return":memory:";return X||":memory:";default:throw Error(`Unsupported dialect: ${$}`)}}function Bz(){let $=b.dialect,Z=xz($,b.database);try{if($==="sqlite")return OX(Z);let X=new Nz(Z);if(X&&typeof X.catch==="function")X.catch((_)=>{if(b.verbose&&!_.message.includes("database")&&!_.message.includes("does not exist"))console.warn(`[query-builder] Database connection error: ${_.message}`)});return X}catch(X){if(b.verbose)console.warn(`[query-builder] Failed to create connection: ${X.message}`);try{return OX(":memory:")}catch{return{query:()=>Promise.resolve([]),execute:()=>Promise.resolve([]),close:()=>Promise.resolve()}}}}function B1($=!1){let Z=z1!==null&&(eZ!==b.dialect||$6!==b.database.database);if($||Z||!z1)z1=Bz(),eZ=b.dialect,$6=b.database.database;return z1}function b1(){z1=null,eZ=null,$6=null}async function TZ($){try{return await $(B1())}catch(Z){if(Z?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||Z?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let X=B1(!0);return await $(X)}throw Z}}function Az(){return new Proxy({},{get($,Z){let X=B1(),_=X[Z];if(typeof _==="function")return _.bind(X);return _},apply($,Z,X){return B1()(...X)}})}function hz($){return $.endsWith("s")?$.slice(0,-1):$}function J$($,Z,X,_={}){let Y=_.singularize??hz,z=$.relations?.[Z]?.belongsToMany?.[X];if(z==null)return null;let j=typeof z==="object",U=j?z:null,Q=j?U.model:z,E=$.modelToTable[Q]||Q,G,F;if(U?.table)G=U.table;else if(U?.through){if(F=U.through,G=$.modelToTable[U.through],!G)throw Error(`[query-builder] belongsToMany relation '${X}' on '${Z}' references unknown through model '${U.through}'. Make sure '${U.through}' is registered via defineModels({...}).`)}else{let R=Y(Z),M=Y(E);G=[R,M].sort().join("_")}let O=U?.foreignKey??`${Y(Z)}_id`,K=U?.relatedKey??`${Y(E)}_id`,W={};if(U?.pivot?.columns)Object.assign(W,U.pivot.columns);if(F&&_.models){let R=_.models[F],M=R?.definition??R?.getDefinition?.()??R,q=M?.attributes??{};for(let[N,B]of Object.entries(q)){if(N===O||N===K||N===(M?.primaryKey??"id"))continue;W[N]={default:B?.default,nullable:B?.nullable,validation:B?.validation}}}let w=Boolean(U?.pivot?.timestamps),J=Object.keys(W);return{pivotTable:G,fkParent:O,fkRelated:K,pivotColumns:J,pivotColumnDefs:W,pivotModelName:F,timestamps:w,relatedModelName:Q,relatedTable:E,hasConfig:j}}function QX($){return typeof $==="object"&&$!==null&&"raw"in $&&typeof $.raw==="string"}class k2{cache=new Map;maxSize=100;get($){let Z=this.cache.get($);if(!Z)return null;if(Date.now()>Z.expiresAt)return this.cache.delete($),null;return Z.data}set($,Z,X){if(this.cache.size>=this.maxSize){let _=this.cache.keys().next().value;if(_)this.cache.delete(_)}this.cache.set($,{data:Z,expiresAt:Date.now()+X})}clear(){this.cache.clear()}setMaxSize($){this.maxSize=$}}function vz($){let Z=String($?.message||"").toLowerCase();return Z.includes("deadlock")||Z.includes("serialization failure")||Z.includes("could not serialize access")||Z.includes("deadlock found when trying to get lock")||Z.includes("lock wait timeout exceeded")||Z.includes("database is locked")||Z.includes("busy")}function bz($,Z){if(!Z||Z.length===0)return!1;let X=$&&($.code||$.sqlState||$.sqlstate);if(!X)return!1;return Z.includes(X)}function fz($){return new Promise((Z)=>setTimeout(Z,$))}function gz($,Z){let X=Math.max(1,Z?.baseMs??50),_=Math.max(1,Z?.factor??2),Y=Math.max(X,Z?.maxMs??2000),L=Math.min(Y,X*_**Math.max(0,$-1));if(Z?.jitter){let z=Math.random()*L*0.2;L=L-z/2}return Math.floor(L)}function F9($){let Z=$?.sql??B1(),X=$?.meta,_=$?.schema;function Y(E){if(Array.isArray(E)){let[W,w,J]=E,R=String(W);switch(w){case"in":if(Array.isArray(J)){let M=o0(J.length);return Z.unsafe(`${R} IN (${M})`,J)}return Z.unsafe(`${R} IN (${m(1)})`,[J]);case"not in":if(Array.isArray(J)){let M=o0(J.length);return Z.unsafe(`${R} NOT IN (${M})`,J)}return Z.unsafe(`${R} NOT IN (${m(1)})`,[J]);case"like":return Z.unsafe(`${R} LIKE ${m(1)}`,[J]);case"is":return Z.unsafe(`${R} IS ${J}`);case"is not":return Z.unsafe(`${R} IS NOT ${J}`);case"!=":return Z.unsafe(`${R} <> ${m(1)}`,[J]);case"<":case">":case"<=":case">=":case"=":default:return Z.unsafe(`${R} ${w} ${m(1)}`,[J])}}if("raw"in E)return E.raw;let G=Object.keys(E);if(G.length===0)return Z.unsafe("");let F=[],O=[],K=1;for(let W of G){let w=E[W];if(Array.isArray(w)){let J=o0(w.length,K);F.push(`${W} IN (${J})`),O.push(...w),K+=w.length}else F.push(`${W} = ${m(K++)}`),O.push(w)}return Z.unsafe(F.join(" AND "),O)}function L(E,G,F){if(!F)return G;let O=Y(F);return Z`${G} WHERE ${O}`}function z(E){let G=b.debug?.captureText;if(b.debug)b.debug.captureText=!0;let F=String(E);if(b.debug)b.debug.captureText=G;return F}function j(E,G,F){let O=b.hooks,K=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan),W=F?.timeoutMs&&F.timeoutMs>0||F?.signal;if(!K&&!W)return E.execute();let w=z(E),J=Date.now(),R;try{if(O?.onQueryStart?.({sql:w,kind:G}),O?.startSpan)R=O.startSpan({sql:w,kind:G})}catch{}let M=!1,q=(f,p)=>{if(M)return;M=!0;let c=Date.now()-J;try{if(f)O?.onQueryError?.({sql:w,error:f,durationMs:c,kind:G});else O?.onQueryEnd?.({sql:w,durationMs:c,rowCount:p,kind:G})}catch{}try{R?.end(f)}catch{}},N=E.execute(),B=[N],A;if(F?.timeoutMs&&F.timeoutMs>0){let f=new Promise((p,c)=>{A=setTimeout(()=>{try{E.cancel?.()}catch{}let l=Error(`Query timed out after ${F.timeoutMs}ms`);l.code="EBQBTIMEOUT",c(l)},F.timeoutMs)});B.push(f)}if(F?.signal){if(F.signal.aborted){try{E.cancel?.()}catch{}let p=Error("Query aborted");return p.code="EBQBABORT",q(p),Promise.reject(p)}let f=()=>{try{E.cancel?.()}catch{}};F.signal.addEventListener("abort",f,{once:!0}),N.finally(()=>{F.signal?.removeEventListener("abort",f)})}return Promise.race(B).then((f)=>{clearTimeout(A);let p=Array.isArray(f)?f.length:typeof f==="number"?f:void 0;return q(void 0,p),f}).catch((f)=>{throw clearTimeout(A),q(f),f})}function U(E,G){let F=G??z(E);return{sql:F,toString:()=>F,execute:()=>E.execute(),values:()=>E.values(),raw:()=>E.raw()}}function Q(E,G){let F=Z,O=G&&G.length>0?`SELECT ${G.join(", ")} FROM ${String(E)}`:`SELECT * FROM ${String(E)}`,K=null,W=()=>{if(K===null)K=y.length>0?Z.unsafe(O,y):Z.unsafe(O);return K},w=(V,I)=>{let S=u.WHERE.test(O)?V:"WHERE";O=`${O} ${S} ${I}`},J=new Set,R,M,q=!1,N=!1,B=!1,A=new Map,f=new Set,p=60000,c=(V)=>{if(b.relations.singularizeStrategy==="none")return V;return V.endsWith("s")?V.slice(0,-1):V},l=(V)=>{if(!X)return null;return J$(X,String(E),V,{singularize:c,models:X.models})},r0=(V)=>{if(!V||typeof V!=="object"||f.size===0)return V;let I;for(let D of Object.keys(V))if(D.startsWith("pivot_")){if(!I)I={};I[D.slice(6)]=V[D],delete V[D]}if(I)V.pivot=I;return V},K9=(V)=>{if(f.size===0||!V)return V;if(Array.isArray(V))for(let I=0;I<V.length;I++)r0(V[I]);else r0(V);return V},s9=(V)=>{if(!X)return;if(J.has(V.pivotTable))return;let I=String(E),D=X.primaryKeys[I]??"id";s(V.pivotTable,"wherePivot auto-join (pivot table)"),s(V.fkParent,"wherePivot auto-join (parent FK)"),s(I,"wherePivot auto-join (parent table)"),s(D,"wherePivot auto-join (parent PK)"),K=F`${W()} LEFT JOIN ${F(V.pivotTable)} ON ${F(`${V.pivotTable}.${V.fkParent}`)} = ${F(`${I}.${D}`)}`,O=`${O} LEFT JOIN ${V.pivotTable} ON ${V.pivotTable}.${V.fkParent} = ${I}.${D}`,J.add(V.pivotTable)},W0=[],y=[],s=(V,I)=>{if(!u.IDENTIFIER.test(V)){let D=I?` in ${I}`:"";throw Error(`[query-builder] Invalid identifier${D}: '${V}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}},o5=(V)=>{if(u.SELECT_STAR.test(O))O=O.replace(u.SELECT_STAR,`SELECT *, ${V}`);else if(u.SELECT.test(O))O=O.replace(u.SELECT_FROM,`SELECT $1, ${V} FROM`);let I=String(W());if(u.SELECT_STAR.test(I)){let D=I.replace(u.SELECT_STAR,`SELECT *, ${V}`);K=Z.unsafe(D)}else if(u.SELECT.test(I)){if(u.SELECT_FROM.exec(I)){let S=I.replace(u.SELECT_FROM,`SELECT $1, ${V} FROM`);K=Z.unsafe(S)}}},$$=(V,I,D,S)=>{s(V,"relationship subquery (parent table)"),s(I,"relationship subquery (target table)"),s(D,"relationship subquery (primary key)");let H=`${V.endsWith("s")?V.slice(0,-1):V}_id`;s(H,"relationship subquery (foreign key)");let T=`SELECT 1 FROM ${I} WHERE ${I}.${H} = ${V}.${D}`;if(S){let k=S({where:(h,P,x)=>{return s(h,"relationship subquery condition"),`${I}.${h} ${P} ${typeof x==="string"?`'${x}'`:x}`}});if(k)T+=` AND ${k}`}return T},Z$=(V,I,D,S)=>{s(V,"relationship subquery (parent table)"),s(I,"relationship subquery (target table)"),s(D,"relationship subquery (primary key)");let H=`${I.endsWith("s")?I.slice(0,-1):I}_id`;s(H,"relationship subquery (foreign key)");let T=`SELECT 1 FROM ${I} WHERE ${I}.${D} = ${V}.${H}`;if(S){let k=S({where:(h,P,x)=>{return s(h,"relationship subquery condition"),`${I}.${h} ${P} ${typeof x==="string"?`'${x}'`:x}`}});if(k)T+=` AND ${k}`}return T},X$=(V,I,D,S,H,T)=>{s(V,"relationship subquery (parent table)"),s(I,"relationship subquery (target table)"),s(D,"relationship subquery (primary key)"),s(S,"relationship subquery (target primary key)");let C=T&&X?J$(X,V,T,{singularize:c,models:X.models}):null,k=c(V),h=c(I),P=C?.pivotTable??[k,h].sort().join("_"),x=C?.fkParent??`${k}_id`,d=C?.fkRelated??`${h}_id`;s(P,"relationship subquery (pivot table)"),s(x,"relationship subquery (foreign key A)"),s(d,"relationship subquery (foreign key B)");let r=`SELECT 1 FROM ${P} JOIN ${I} ON ${I}.${S} = ${P}.${d} WHERE ${P}.${x} = ${V}.${D}`;if(H){let o=H({where:(l9,Z1,L8)=>{return s(l9,"relationship subquery condition"),`${I}.${l9} ${Z1} ${typeof L8==="string"?`'${L8}'`:L8}`}});if(o)r+=` AND ${o}`}return r},p_=(V,I,D)=>{s(V,"withCount (parent table)"),s(I,"withCount (target table)"),s(D,"withCount (primary key)");let S=`${V.endsWith("s")?V.slice(0,-1):V}_id`;return s(S,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${I} WHERE ${I}.${S} = ${V}.${D})`},c_=(V,I,D,S)=>{s(V,"withCount (parent table)"),s(I,"withCount (target table)"),s(D,"withCount (primary key)");let H=S&&X?J$(X,V,S,{singularize:c,models:X.models}):null,T=c(V),C=c(I),k=H?.pivotTable??[T,C].sort().join("_"),h=H?.fkParent??`${T}_id`;return s(k,"withCount (pivot table)"),s(h,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${k} WHERE ${k}.${h} = ${V}.${D})`},$7=()=>{if(A.size===0)return;let V=[];for(let[I,D]of A.entries()){let S=l(I);if(!S)continue;for(let T of D)s(T,"withPivot");let H=D.map((T)=>`${S.pivotTable}.${T} AS pivot_${T}`);V.push(...H)}if(V.length>0){let I=V.join(", ");o5(I)}};return new Proxy({distinct(){return O=O.replace(/^SELECT\s+/i,"SELECT DISTINCT "),K=null,this},distinctOn(...V){let I=V.map(String).join(", ");return O=O.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${I}) `),K=null,this},selectRaw(V){let I=O.indexOf(" FROM ");if(I!==-1)O=`${O.substring(0,I)}, ${String(V)}${O.substring(I)}`;else O+=`, ${String(V)}`;return K=null,this},rowNumber(V="row_number",I,D){let S=[];if(I){let k=Array.isArray(I)?I:[I];S.push(`PARTITION BY ${k.join(", ")}`)}if(D&&D.length)S.push(`ORDER BY ${D.map(([k,h])=>`${k} ${h==="desc"?"DESC":"ASC"}`).join(", ")}`);let T=`ROW_NUMBER() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${V}`,C=O.indexOf(" FROM ");if(C!==-1)O=`${O.substring(0,C)}, ${T}${O.substring(C)}`;else O+=`, ${T}`;return K=null,this},denseRank(V="dense_rank",I,D){let S=Array.isArray(I)?I:I?[I]:[],H=[];if(S.length)H.push(`PARTITION BY ${S.join(", ")}`);if(D&&D.length)H.push(`ORDER BY ${D.map(([h,P])=>`${h} ${P==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`DENSE_RANK() ${H.length?`OVER (${H.join(" ")})`:"OVER ()"} AS ${V}`,k=O.indexOf(" FROM ");if(k!==-1)O=`${O.substring(0,k)}, ${C}${O.substring(k)}`;else O+=`, ${C}`;return K=null,this},rank(V="rank",I,D){let S=Array.isArray(I)?I:I?[I]:[],H=[];if(S.length)H.push(`PARTITION BY ${S.join(", ")}`);if(D&&D.length)H.push(`ORDER BY ${D.map(([h,P])=>`${h} ${P==="desc"?"DESC":"ASC"}`).join(", ")}`);let C=`RANK() ${H.length?`OVER (${H.join(" ")})`:"OVER ()"} AS ${V}`,k=O.indexOf(" FROM ");if(k!==-1)O=`${O.substring(0,k)}, ${C}${O.substring(k)}`;else O+=`, ${C}`;return K=null,this},selectAll(){return this},select(V){if(!V||V.length===0)return this;let I=O.indexOf(" FROM ");if(I!==-1)O=`SELECT ${V.join(", ")}${O.substring(I)}`;else O=`SELECT ${V.join(", ")} FROM ${E}`;return this},addSelect(...V){if(!V.length)return this;let I=O.indexOf(" FROM ");if(I!==-1)O=`${O.substring(0,I)}, ${V.join(", ")}${O.substring(I)}`;else O+=`, ${V.join(", ")}`;return K=null,this},with(...V){if(!X||!V||V.length===0)return this;let I=[];for(let P of V){if(!P)continue;if(typeof P==="string")I.push({name:P});else if(typeof P==="object"&&!Array.isArray(P))for(let[x,d]of Object.entries(P))if(typeof d==="function")I.push({name:x,callback:d});else I.push({name:x})}if(I.length===0)return this;let D=b.relations.maxEagerLoad??50;if(I.length>D)throw Error(`[query-builder] Too many relationships to eager load (${I.length}). Maximum allowed: ${D}`);let S=String(E),H=new Set,T=new Set,C=new Map,k=(P)=>{let x=X.relations?.[P];if(!x)return[];return[...Object.keys(x.hasOne||{}),...Object.keys(x.hasMany||{}),...Object.keys(x.belongsTo||{}),...Object.keys(x.belongsToMany||{}),...Object.keys(x.hasOneThrough||{}),...Object.keys(x.hasManyThrough||{}),...Object.keys(x.morphOne||{}),...Object.keys(x.morphMany||{}),...Object.keys(x.morphToMany||{}),...Object.keys(x.morphedByMany||{})]},h=(P,x,d=0,r)=>{let D0=b.relations.maxDepth??10;if(d>=D0)throw Error(`[query-builder] Maximum relationship depth (${D0}) exceeded at '${x}'. Consider using separate queries or increasing maxDepth.`);let o=X.relations?.[P];if(!o)return P;let l9=(i,a)=>{let Q0=i;if(b.softDeletes?.enabled&&b.softDeletes?.defaultFilter){let G0=b.softDeletes.column||"deleted_at";Q0=`${Q0} AND ${a}.${G0} IS NULL`}if(!r)return Q0;let R0={where:(G0,z9,k9)=>{let X1=typeof k9==="string"?`'${k9}'`:String(k9);return`${a}.${G0} ${z9} ${X1}`}};try{let G0=r(R0);if(G0&&typeof G0==="string")return`${Q0} AND ${G0}`}catch{}return Q0},Z1=(i)=>{if(b.softDeletes?.enabled&&b.softDeletes?.defaultFilter){let a=b.softDeletes.column||"deleted_at";return` AND ${i}.${a} IS NULL`}return""},L8=()=>{let i=(R0)=>{let G0=R0?.[x];return G0?X.modelToTable[G0]:void 0},a=(R0)=>{let G0=R0?.[x],z9=typeof G0==="string"?G0:G0?.model;return z9?X.modelToTable[z9]:void 0},Q0=(R0)=>{let G0=R0?.[x];return G0?.target?X.modelToTable[G0.target]:void 0};return i(o?.hasOne)||i(o?.hasMany)||i(o?.belongsTo)||a(o?.belongsToMany)||Q0(o?.hasOneThrough)||Q0(o?.hasManyThrough)||i(o?.morphOne)||i(o?.morphMany)||i(o?.morphToMany)||i(o?.morphedByMany)},Z7=L8()??(X.modelToTable[x]||X.tableToModel[x]?X.modelToTable[x]??x:x),e=String(Z7);if(!Z7||!L8()&&!X.modelToTable[x]&&!X.tableToModel[x]){let i=k(P);if(i.length>0&&!i.includes(x)){let a=` Available relationships: ${i.join(", ")}`;throw Error(`[query-builder] Relationship '${x}' not found on table '${P}'.${a}`)}}if(b.relations.detectCycles!==!1){let i=`${P}->${e}`;if(H.has(i))throw Error(`[query-builder] Circular relationship detected: ${i}. This would cause an infinite loop.`);H.add(i)}if(!e||e===P)return P;let a5=o?.hasOneThrough?.[x]||o?.hasManyThrough?.[x];if(a5){let{through:i,target:a}=a5,Q0=X.modelToTable[i]||i,R0=X.modelToTable[a]||a,G0=X.primaryKeys[P]??"id",z9=X.primaryKeys[Q0]??"id",k9=`${c(P)}_id`,X1=`${c(Q0)}_id`;return K=F`${W()} LEFT JOIN ${F(Q0)} ON ${F(`${Q0}.${k9}`)} = ${F(`${P}.${G0}`)} LEFT JOIN ${F(R0)} ON ${F(`${R0}.${X1}`)} = ${F(`${Q0}.${z9}`)}`,J.add(Q0),J.add(R0),R0}if(Boolean(o?.belongsToMany?.[x])){let i=J$(X,P,x,{singularize:c,models:X.models}),a=i?.pivotTable??[c(P),c(e)].sort().join("_"),Q0=X.primaryKeys[P]??"id",R0=X.primaryKeys[e]??"id",G0=i?.fkParent??`${c(P)}_id`,z9=i?.fkRelated??`${c(e)}_id`;return K=F`${W()} LEFT JOIN ${F(a)} ON ${F(`${a}.${G0}`)} = ${F(`${P}.${Q0}`)} LEFT JOIN ${F(e)} ON ${F(`${e}.${R0}`)} = ${F(`${a}.${z9}`)}`,J.add(a),J.add(e),e}if(Boolean(o?.morphToMany?.[x])){let i=x,a=`${c(e)}_${i}`,Q0=X.primaryKeys[P]??"id",R0=X.primaryKeys[e]??"id",G0=`${i}_type`,z9=`${i}_id`,k9=`${c(e)}_id`;return K=F`${W()} LEFT JOIN ${F(a)} ON ${F(`${a}.${z9}`)} = ${F(`${P}.${Q0}`)} AND ${F(`${a}.${G0}`)} = ${F(X.tableToModel[P]||P)} LEFT JOIN ${F(e)} ON ${F(`${e}.${R0}`)} = ${F(`${a}.${k9}`)}`,J.add(a),J.add(e),e}if(Boolean(o?.morphedByMany?.[x])){let i=o.morphedByMany?.[x]||x,a=X.modelToTable[i]||i,Q0=c(P),R0=`${c(a)}_${Q0}`,G0=X.primaryKeys[P]??"id",z9=X.primaryKeys[a]??"id",k9=`${Q0}_type`,X1=`${Q0}_id`,m_=`${c(a)}_id`;return K=F`${W()} LEFT JOIN ${F(R0)} ON ${F(`${R0}.${m_}`)} = ${F(`${P}.${G0}`)} LEFT JOIN ${F(a)} ON ${F(`${a}.${z9}`)} = ${F(`${R0}.${X1}`)} AND ${F(`${R0}.${k9}`)} = ${F(X.tableToModel[a]||a)}`,J.add(R0),J.add(a),a}if(Boolean(o?.belongsTo?.[x])){let i=`${c(e)}_id`,a=X.primaryKeys[e]??"id";return K=F`${W()} LEFT JOIN ${F(e)} ON ${F(`${P}.${i}`)} = ${F(`${e}.${a}`)}`,J.add(e),e}let d_=Boolean(o?.morphOne?.[x]),u_=Boolean(o?.morphMany?.[x]);if(d_||u_){let i=`${x}_type`,a=`${x}_id`,Q0=X.primaryKeys[P]??"id";return K=F`${W()} LEFT JOIN ${F(e)} ON ${F(`${e}.${a}`)} = ${F(`${P}.${Q0}`)} AND ${F(`${e}.${i}`)} = ${F(X.tableToModel[P]||P)}`,J.add(e),e}let X7=`${c(P)}_id`,_7=X.primaryKeys[P]??"id",Y7=Z1(e);if(Y7){let i=String(W()),a=`${e}.${X7} = ${P}.${_7}${Y7}`;K=F`${F(i)} LEFT JOIN ${F(e)} ON ${F(a)}`}else K=F`${W()} LEFT JOIN ${F(e)} ON ${F(`${e}.${X7}`)} = ${F(`${P}.${_7}`)}`;return J.add(e),e};for(let P of I){let x=P.name.trim();if(P.callback)C.set(x,P.callback);let d=x.split("."),r=S,D0=0;for(let o of d){if(!o||o.trim().length===0)continue;let l9=o.trim(),Z1=C.get(l9);r=h(r,l9,D0,Z1)||r,D0++}T.add(x)}if(A.size>0){let P=[];for(let[x,d]of A.entries()){let r=l(x);if(!r)continue;let D0=d.map((o)=>`${r.pivotTable}.${o} AS pivot_${o}`);P.push(...D0)}if(P.length>0){let x=P.join(", ");o5(x)}}return O=z(W()),this},whereHas(V,I){if(!X)return this;let D=String(E),S=X.relations?.[D];if(!S)throw Error(`[query-builder] No relationships defined for table '${D}'`);let H=Object.entries(S).find(([d,r])=>r&&typeof r==="object"&&(V in r));if(!H)throw Error(`[query-builder] Relationship '${V}' not found on table '${D}'`);let[T,C]=H,k=C[V],h=typeof k==="string"?k:k?.model||k?.target||k,P=X.modelToTable[h]||h,x;if(T==="hasMany"||T==="hasOne"){let d=X.primaryKeys[D]??"id";x=$$(D,P,d,I)}else if(T==="belongsTo"){let d=X.primaryKeys[P]??"id";x=Z$(D,P,d,I)}else if(T==="belongsToMany"){let d=X.primaryKeys[D]??"id",r=X.primaryKeys[P]??"id";x=X$(D,P,d,r,I,V)}else throw Error(`[query-builder] Unsupported relationship type '${T}' for whereHas`);K=F`${W()} WHERE EXISTS (${F([x])})`;try{w("WHERE",`EXISTS (${x})`)}catch{}return this},whereDoesntHave(V,I){if(!X)return this;let D=String(E),S=X.relations?.[D];if(!S)throw Error(`[query-builder] No relationships defined for table '${D}'`);let H=Object.entries(S).find(([d,r])=>r&&typeof r==="object"&&(V in r));if(!H)throw Error(`[query-builder] Relationship '${V}' not found on table '${D}'`);let[T,C]=H,k=C[V],h=typeof k==="string"?k:k?.model||k?.target||k,P=X.modelToTable[h]||h,x;if(T==="hasMany"||T==="hasOne"){let d=X.primaryKeys[D]??"id";x=$$(D,P,d,I)}else if(T==="belongsTo"){let d=X.primaryKeys[P]??"id";x=Z$(D,P,d,I)}else if(T==="belongsToMany"){let d=X.primaryKeys[D]??"id",r=X.primaryKeys[P]??"id";x=X$(D,P,d,r,I,V)}else throw Error(`[query-builder] Unsupported relationship type '${T}' for whereDoesntHave`);K=F`${W()} WHERE NOT EXISTS (${F([x])})`;try{w("WHERE",`NOT EXISTS (${x})`)}catch{}return this},has(V){if(!X)return this;let I=String(E),D=X.relations?.[I];if(!D)throw Error(`[query-builder] No relationships defined for table '${I}'`);let S=Object.entries(D).find(([x,d])=>d&&typeof d==="object"&&(V in d));if(!S)throw Error(`[query-builder] Relationship '${V}' not found on table '${I}'`);let[H,T]=S,C=T[V],k=typeof C==="string"?C:C?.model||C?.target||C,h=X.modelToTable[k]||k,P;if(H==="hasMany"||H==="hasOne"){let x=X.primaryKeys[I]??"id";P=$$(I,h,x)}else if(H==="belongsTo"){let x=X.primaryKeys[h]??"id";P=Z$(I,h,x)}else if(H==="belongsToMany"){let x=X.primaryKeys[I]??"id",d=X.primaryKeys[h]??"id";P=X$(I,h,x,d,void 0,V)}else throw Error(`[query-builder] Unsupported relationship type '${H}' for has`);K=F`${W()} WHERE EXISTS (${F([P])})`;try{w("WHERE",`EXISTS (${P})`)}catch{}return this},doesntHave(V){if(!X)return this;let I=String(E),D=X.relations?.[I];if(!D)throw Error(`[query-builder] No relationships defined for table '${I}'`);let S=Object.entries(D).find(([x,d])=>d&&typeof d==="object"&&(V in d));if(!S)throw Error(`[query-builder] Relationship '${V}' not found on table '${I}'`);let[H,T]=S,C=T[V],k=typeof C==="string"?C:C?.model||C?.target||C,h=X.modelToTable[k]||k,P;if(H==="hasMany"||H==="hasOne"){let x=X.primaryKeys[I]??"id";P=$$(I,h,x)}else if(H==="belongsTo"){let x=X.primaryKeys[h]??"id";P=Z$(I,h,x)}else if(H==="belongsToMany"){let x=X.primaryKeys[I]??"id",d=X.primaryKeys[h]??"id";P=X$(I,h,x,d,void 0,V)}else throw Error(`[query-builder] Unsupported relationship type '${H}' for doesntHave`);K=F`${W()} WHERE NOT EXISTS (${F([P])})`;try{w("WHERE",`NOT EXISTS (${P})`)}catch{}return this},withCount(...V){if(!X||!V||V.length===0)return this;let I=String(E);for(let D of V){let S=X.relations?.[I];if(!S)continue;let H=Object.entries(S).find(([D0,o])=>o&&typeof o==="object"&&(D in o));if(!H)continue;let[T,C]=H,k=C[D],h=typeof k==="string"?k:k?.model||k?.target||k,P=X.modelToTable[h]||h,x=X.primaryKeys[I]??"id",d;if(T==="hasMany"||T==="hasOne")d=p_(I,P,x);else if(T==="belongsToMany")d=c_(I,P,x,D);else continue;let r=`${D}_count`;o5(`${d} AS ${r}`)}return this},applyPivotColumns(){return $7(),this},withPivot(V,...I){if(!X)return this;let D=String(E),S=l(V);if(!S)throw Error(`[query-builder] Relationship '${V}' is not a belongsToMany relationship on table '${D}'`);let H=I&&I.length>0?I:S.hasConfig?S.pivotColumns:[];if(H.length===0)return this;if(A.set(V,H),S.hasConfig)f.add(V);return $7(),this},wherePivot(V,I,D,S){if(!X)return this;let H=l(V);if(!H)throw Error(`[query-builder] Relationship '${V}' is not a belongsToMany relationship on table '${String(E)}'`);s(H.pivotTable,"wherePivot (pivot table)"),s(I,"wherePivot (column)"),s9(H);let T=S===void 0?"=":String(D),C=S===void 0?D:S,k=y.length+1,h=`${H.pivotTable}.${I} ${T} ${m(k)}`;W0.push(h),y.push(C);let P=u.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${P} ${h}`,K=null,H.hasConfig)f.add(V);return this},wherePivotIn(V,I,D){if(!X||!Array.isArray(D)||D.length===0)return this;let S=l(V);if(!S)throw Error(`[query-builder] Relationship '${V}' is not a belongsToMany relationship on table '${String(E)}'`);s(S.pivotTable,"wherePivotIn (pivot table)"),s(I,"wherePivotIn (column)"),s9(S);let H=o0(D.length,y.length+1),T=`${S.pivotTable}.${I} IN (${H})`;W0.push(T),y.push(...D);let C=u.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${C} ${T}`,K=null,S.hasConfig)f.add(V);return this},wherePivotNotIn(V,I,D){if(!X||!Array.isArray(D)||D.length===0)return this;let S=l(V);if(!S)throw Error(`[query-builder] Relationship '${V}' is not a belongsToMany relationship on table '${String(E)}'`);s(S.pivotTable,"wherePivotNotIn (pivot table)"),s(I,"wherePivotNotIn (column)"),s9(S);let H=o0(D.length,y.length+1),T=`${S.pivotTable}.${I} NOT IN (${H})`;W0.push(T),y.push(...D);let C=u.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${C} ${T}`,K=null,S.hasConfig)f.add(V);return this},wherePivotNull(V,I){if(!X)return this;let D=l(V);if(!D)throw Error(`[query-builder] Relationship '${V}' is not a belongsToMany relationship on table '${String(E)}'`);s(D.pivotTable,"wherePivotNull (pivot table)"),s(I,"wherePivotNull (column)"),s9(D);let S=`${D.pivotTable}.${I} IS NULL`;W0.push(S);let H=u.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${H} ${S}`,K=null,D.hasConfig)f.add(V);return this},wherePivotNotNull(V,I){if(!X)return this;let D=l(V);if(!D)throw Error(`[query-builder] Relationship '${V}' is not a belongsToMany relationship on table '${String(E)}'`);s(D.pivotTable,"wherePivotNotNull (pivot table)"),s(I,"wherePivotNotNull (column)"),s9(D);let S=`${D.pivotTable}.${I} IS NOT NULL`;W0.push(S);let H=u.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${H} ${S}`,K=null,D.hasConfig)f.add(V);return this},where(V,I,D){let S=()=>O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";if(typeof V==="string"&&I!==void 0){let H=y.length+1;return W0.push(`${String(V)} ${String(I)} ${m(H)}`),y.push(D),O=`${O} ${S()} ${String(V)} ${String(I)} ${m(H)}`,K=null,this}if(Array.isArray(V)){let[H,T,C]=V,k=String(H),h=String(T);if(h==="in"||h==="not in"){let P=Array.isArray(C)?C:[C],x=o0(P.length,y.length+1);W0.push(`${k} ${h.toUpperCase()} (${x})`),y.push(...P),O=`${O} ${S()} ${k} ${h.toUpperCase()} (${x})`,K=null}else{let P=y.length+1;W0.push(`${k} ${h} ${m(P)}`),y.push(C),O=`${O} ${S()} ${k} ${h} ${m(P)}`,K=null}return this}if(V&&typeof V==="object"&&!QX(V)){let H=V,T=Object.keys(H),C=[];for(let k of T){let h=H[k];if(Array.isArray(h)){let P=o0(h.length,y.length+1);C.push(`${k} IN (${P})`),W0.push(`${k} IN (${P})`),y.push(...h)}else{let P=y.length+1;C.push(`${k} = ${m(P)}`),W0.push(`${k} = ${m(P)}`),y.push(h)}}if(C.length>0)O=`${O} ${S()} ${C.join(" AND ")}`,K=null;return this}if(QX(V))return W0.push(V.raw),O=`${O} ${S()} ${V.raw}`,K=null,this;return this},whereNull(V){let I=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return O=`${O} ${I} ${String(V)} IS NULL`,K=null,this},whereNotNull(V){let I=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return O=`${O} ${I} ${String(V)} IS NOT NULL`,K=null,this},whereBetween(V,I,D){let S=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return y.push(I,D),O=`${O} ${S} ${String(V)} BETWEEN ? AND ?`,K=null,this},whereExists(V){let I=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return O=`${O} ${I} EXISTS (${V.toSQL()})`,K=null,this},whereJsonContains(V,I){let D=u.WHERE.test(O)?"AND":"WHERE",S=y.length+1;return O+=` ${D} ${V} @> ${m(S)}`,y.push(JSON.stringify(I)),K=null,this},whereJsonPath(V,I,D){let S=b.dialect,H=u.WHERE.test(O)?"AND":"WHERE",T=y.length+1;if(S==="postgres")O+=` ${H} ${V} ${I} ${m(T)}`;else if(S==="mysql")O+=` ${H} JSON_EXTRACT(${V}) ${I} ${m(T)}`;else O+=` ${H} json_extract(${V}) ${I} ${m(T)}`;return y.push(D),K=null,this},whereLike(V,I,D=!1){let S=D?F`${F(String(V))} LIKE ${I}`:F`LOWER(${F(String(V))}) LIKE LOWER(${I})`;return K=F`${W()} WHERE ${S}`,w("WHERE",`${D?String(V):`LOWER(${String(V)})`} LIKE ${D?"?":"LOWER(?)"}`),this},whereILike(V,I){if(b.dialect==="postgres")K=F`${W()} WHERE ${F(String(V))} ILIKE ${I}`,w("WHERE",`${String(V)} ILIKE ?`);else{let D=F`LOWER(${F(String(V))}) LIKE LOWER(${I})`;K=F`${W()} WHERE ${D}`,w("WHERE",`LOWER(${String(V)}) LIKE LOWER(?)`)}return this},orWhereLike(V,I,D=!1){let S=D?F`${F(String(V))} LIKE ${I}`:F`LOWER(${F(String(V))}) LIKE LOWER(${I})`;return K=F`${W()} OR ${S}`,w("OR",`${D?String(V):`LOWER(${String(V)})`} LIKE ${D?"?":"LOWER(?)"}`),this},orWhereILike(V,I){if(b.dialect==="postgres")K=F`${W()} OR ${F(String(V))} ILIKE ${I}`,w("OR",`${String(V)} ILIKE ?`);else{let D=F`LOWER(${F(String(V))}) LIKE LOWER(${I})`;K=F`${W()} OR ${D}`,w("OR",`LOWER(${String(V)}) LIKE LOWER(?)`)}return this},whereNotLike(V,I,D=!1){let S=D?F`${F(String(V))} NOT LIKE ${I}`:F`LOWER(${F(String(V))}) NOT LIKE LOWER(${I})`;return K=F`${W()} WHERE ${S}`,w("WHERE",`${D?String(V):`LOWER(${String(V)})`} NOT LIKE ${D?"?":"LOWER(?)"}`),this},whereNotILike(V,I){if(b.dialect==="postgres")K=F`${W()} WHERE ${F(String(V))} NOT ILIKE ${I}`,w("WHERE",`${String(V)} NOT ILIKE ?`);else{let D=F`LOWER(${F(String(V))}) NOT LIKE LOWER(${I})`;K=F`${W()} WHERE ${D}`,w("WHERE",`LOWER(${String(V)}) NOT LIKE LOWER(?)`)}return this},orWhereNotLike(V,I,D=!1){let S=D?F`${F(String(V))} NOT LIKE ${I}`:F`LOWER(${F(String(V))}) NOT LIKE LOWER(${I})`;return K=F`${W()} OR ${S}`,w("OR",`${D?String(V):`LOWER(${String(V)})`} NOT LIKE ${D?"?":"LOWER(?)"}`),this},orWhereNotILike(V,I){if(b.dialect==="postgres")K=F`${W()} OR ${F(String(V))} NOT ILIKE ${I}`,w("OR",`${String(V)} NOT ILIKE ?`);else{let D=F`LOWER(${F(String(V))}) NOT LIKE LOWER(${I})`;K=F`${W()} OR ${D}`,w("OR",`LOWER(${String(V)}) NOT LIKE LOWER(?)`)}return this},whereAny(V,I,D){if(V.length===0)return this;let S=u.WHERE.test(O)?"AND":"WHERE",H=y.length+1,T=V.map((C,k)=>`${C} ${I} ${m(H+k)}`);O+=` ${S} (${T.join(" OR ")})`;for(let C=0;C<V.length;C++)y.push(D);return K=null,this},whereAll(V,I,D){if(V.length===0)return this;let S=u.WHERE.test(O)?"AND":"WHERE",H=y.length+1,T=V.map((C,k)=>`${C} ${I} ${m(H+k)}`);O+=` ${S} (${T.join(" AND ")})`;for(let C=0;C<V.length;C++)y.push(D);return K=null,this},whereNone(V,I,D){if(V.length===0)return this;let S=u.WHERE.test(O)?"AND":"WHERE",H=y.length+1,T=V.map((C,k)=>`${C} ${I} ${m(H+k)}`);O+=` ${S} NOT (${T.join(" OR ")})`;for(let C=0;C<V.length;C++)y.push(D);return K=null,this},whereNotBetween(V,I,D){let S=u.WHERE.test(O)?"AND":"WHERE";return O+=` ${S} ${V} NOT BETWEEN ? AND ?`,y.push(I,D),K=null,this},whereDate(V,I,D){let S=u.WHERE.test(O)?"AND":"WHERE",H=y.length+1;return O+=` ${S} ${V} ${I} ${m(H)}`,y.push(String(D)),K=null,this},whereRaw(V){let I=u.WHERE.test(O)?"AND":"WHERE";return O+=` ${I} ${String(V)}`,K=null,this},whereColumn(V,I,D){let S=u.WHERE.test(O)?"AND":"WHERE";return O+=` ${S} ${V} ${I} ${D}`,K=null,this},orWhereColumn(V,I,D){return O+=` OR ${V} ${I} ${D}`,K=null,this},whereIn(V,I){let D=u.WHERE.test(O)?"AND":"WHERE";if(Array.isArray(I)){let S=o0(I.length,y.length+1);O+=` ${D} ${V} IN (${S})`,y.push(...I)}else O+=` ${D} ${V} IN (${String(I.toSQL())})`;return K=null,this},orWhereIn(V,I){if(Array.isArray(I)){let D=o0(I.length,y.length+1);O+=` OR ${V} IN (${D})`,y.push(...I)}else O+=` OR ${V} IN (${String(I.toSQL())})`;return K=null,this},whereNotIn(V,I){let D=u.WHERE.test(O)?"AND":"WHERE";if(Array.isArray(I)){let S=o0(I.length,y.length+1);O+=` ${D} ${V} NOT IN (${S})`,y.push(...I)}else O+=` ${D} ${V} NOT IN (${String(I.toSQL())})`;return K=null,this},orWhereNotIn(V,I){if(Array.isArray(I)){let D=o0(I.length,y.length+1);O+=` OR ${V} NOT IN (${D})`,y.push(...I)}else O+=` OR ${V} NOT IN (${String(I.toSQL())})`;return K=null,this},whereNested(V){let I=u.WHERE.test(O)?"AND":"WHERE",D=V.toSQL?String(V.toSQL()):String(V);return O+=` ${I} (${D})`,K=null,this},orWhereNested(V){let I=V.toSQL?String(V.toSQL()):String(V);return O+=` OR (${I})`,K=null,this},andWhere(V,I,D){if(typeof V==="string"&&I!==void 0){let S=y.length+1;return W0.push(`${String(V)} ${String(I)} ${m(S)}`),y.push(D),O=`${O} AND ${String(V)} ${String(I)} ${m(S)}`,K=null,this}if(Array.isArray(V)){let[S,H,T]=V,C=String(S),k=String(H);if(k==="in"||k==="not in"){let h=Array.isArray(T)?T:[T],P=o0(h.length,y.length+1);W0.push(`${C} ${k.toUpperCase()} (${P})`),y.push(...h),O=`${O} AND ${C} ${k.toUpperCase()} (${P})`,K=null}else{let h=y.length+1;W0.push(`${C} ${k} ${m(h)}`),y.push(T),O=`${O} AND ${C} ${k} ${m(h)}`,K=null}return this}if(V&&typeof V==="object"&&!("raw"in V)){let S=Object.keys(V),H=[];for(let T of S){let C=V[T];if(Array.isArray(C)){let k=o0(C.length,y.length+1);H.push(`${T} IN (${k})`),W0.push(`${T} IN (${k})`),y.push(...C)}else{let k=y.length+1;H.push(`${T} = ${m(k)}`),W0.push(`${T} = ${m(k)}`),y.push(C)}}if(H.length>0)O=`${O} AND ${H.join(" AND ")}`,K=null;return this}if(V&&typeof V.raw<"u")return W0.push(V.raw),O=`${O} AND ${V.raw}`,K=null,this;return this},orWhere(V,I,D){if(typeof V==="string"&&I!==void 0){let S=y.length+1;return W0.push(`OR ${String(V)} ${String(I)} ${m(S)}`),y.push(D),O=`${O} OR ${String(V)} ${String(I)} ${m(S)}`,K=null,this}if(Array.isArray(V)){let[S,H,T]=V,C=String(S),k=String(H);if(k==="in"||k==="not in"){let h=Array.isArray(T)?T:[T],P=o0(h.length,y.length+1);W0.push(`OR ${C} ${k.toUpperCase()} (${P})`),y.push(...h),O=`${O} OR ${C} ${k.toUpperCase()} (${P})`,K=null}else{let h=y.length+1;W0.push(`OR ${C} ${k} ${m(h)}`),y.push(T),O=`${O} OR ${C} ${k} ${m(h)}`,K=null}return this}if(V&&typeof V==="object"&&!("raw"in V)){let S=Object.keys(V),H=[];for(let T of S){let C=V[T];if(Array.isArray(C)){let k=o0(C.length,y.length+1);H.push(`${T} IN (${k})`),W0.push(`OR ${T} IN (${k})`),y.push(...C)}else{let k=y.length+1;H.push(`${T} = ${m(k)}`),W0.push(`OR ${T} = ${m(k)}`),y.push(C)}}if(H.length>0)O=`${O} OR ${H.join(" AND ")}`,K=null;return this}if(V&&typeof V.raw<"u")return W0.push(`OR ${V.raw}`),O=`${O} OR ${V.raw}`,K=null,this;return this},orderBy(V,I="asc"){let D=I==="asc"?"ASC":"DESC";return O=u.ORDER_BY.test(O)?`${O}, ${V} ${D}`:`${O} ORDER BY ${V} ${D}`,K=null,this},orderByDesc(V){return O=u.ORDER_BY.test(O)?`${O}, ${V} DESC`:`${O} ORDER BY ${V} DESC`,K=null,this},inRandomOrder(){let V=b.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return O=u.ORDER_BY.test(O)?`${O}, ${V}`:`${O} ORDER BY ${V}`,K=null,this},reorder(V,I="asc"){return O=O.replace(/ORDER BY[\s\S]*$/i,""),O+=` ORDER BY ${V} ${I==="asc"?"ASC":"DESC"}`,K=null,this},latest(V){let I=V??b.timestamps.defaultOrderColumn;return O=u.ORDER_BY.test(O)?`${O}, ${I} DESC`:`${O} ORDER BY ${I} DESC`,K=null,this},oldest(V){let I=V??b.timestamps.defaultOrderColumn;return O=u.ORDER_BY.test(O)?`${O}, ${I} ASC`:`${O} ORDER BY ${I} ASC`,K=null,this},limit(V){return O=u.LIMIT.test(O)?O.replace(u.LIMIT,` LIMIT ${V}`):`${O} LIMIT ${V}`,K=null,this},offset(V){return O=u.OFFSET.test(O)?O.replace(u.OFFSET,` OFFSET ${V}`):`${O} OFFSET ${V}`,K=null,this},join(V,I,D,S){return O=`${O} JOIN ${V} ON ${I} ${D} ${S}`,J.add(V),this},joinSub(V,I,D,S,H){return O+=` JOIN (${String(V.toSQL())}) AS ${I} ON ${D} ${S} ${H}`,K=null,J.add(I),this},innerJoin(V,I,D,S){return O=`${O} INNER JOIN ${V} ON ${I} ${D} ${S}`,K=null,J.add(V),this},leftJoin(V,I,D,S){return O=`${O} LEFT JOIN ${V} ON ${I} ${D} ${S}`,K=null,J.add(V),this},leftJoinSub(V,I,D,S,H){return O+=` LEFT JOIN (${String(V.toSQL())}) AS ${I} ON ${D} ${S} ${H}`,K=null,J.add(I),this},rightJoin(V,I,D,S){return O=`${O} RIGHT JOIN ${V} ON ${I} ${D} ${S}`,K=null,J.add(V),this},crossJoin(V){return O=`${O} CROSS JOIN ${V}`,K=null,J.add(V),this},crossJoinSub(V,I){return O+=` CROSS JOIN (${String(V.toSQL())}) AS ${I}`,K=null,J.add(I),this},selectAllRelations(){if(!_)return this;let V=String(E),I=Object.keys(_[V]?.columns??{}),D=[];if(I.length>0)D.push(F`${F(V)}.*`);for(let S of J){let H=Object.keys(_[S]?.columns??{});for(let T of H){let C=b.aliasing.relationColumnAliasFormat==="camelCase"?`${S}_${T}`.replace(/_([a-z])/g,(k,h)=>h.toUpperCase()):b.aliasing.relationColumnAliasFormat==="table.dot.column"?`${S}.${T}`:`${S}_${T}`;D.push(F`${F(`${S}.${T}`)} AS ${F(C)}`)}}if(D.length>0){let S=I.length>0?`${V}.*`:"",H=[];for(let k of J){let h=Object.keys(_[k]?.columns??{});for(let P of h){let x=b.aliasing.relationColumnAliasFormat==="camelCase"?`${k}_${P}`.replace(/_([a-z])/g,(d,r)=>r.toUpperCase()):b.aliasing.relationColumnAliasFormat==="table.dot.column"?`${k}.${P}`:`${k}_${P}`;H.push(`${k}.${P} AS ${x}`)}}let T=[S,...H].filter(Boolean).join(", "),C=O.indexOf(" FROM ");if(C!==-1)O=`SELECT ${T}${O.substring(C)}`;else O=`SELECT ${T} FROM ${V}`;K=null}return this},groupBy(...V){if(V.length)O=u.GROUP_BY.test(O)?`${O}, ${V.join(", ")}`:`${O} GROUP BY ${V.join(", ")}`,K=null;return this},groupByRaw(V){return O=u.GROUP_BY.test(O)?`${O}, ${String(V)}`:`${O} GROUP BY ${String(V)}`,K=null,this},having(V){if(Array.isArray(V)){let I=y.length+1;O=`${O} HAVING ${V[0]} ${V[1]} ${m(I)}`,y.push(V[2]),K=null}else if(V&&typeof V==="object"&&!("raw"in V)){let I=Object.keys(V),D=I.length;if(D){let S=y.length,H=Array.from({length:D});for(let T=0;T<D;T++){let C=I[T];H[T]=`${C} = ${m(S+T+1)}`,y.push(V[C])}O=`${O} HAVING ${H.join(" AND ")}`,K=null}}else if(V&&typeof V.raw<"u")O+=` HAVING ${V.raw}`,K=null;return this},havingRaw(V){return O+=` HAVING ${String(V)}`,K=null,this},orderByRaw(V){return O=u.ORDER_BY.test(O)?`${O}, ${String(V)}`:`${O} ORDER BY ${String(V)}`,K=null,this},union(V){return O+=` UNION ${String(V.toSQL())}`,K=null,this},unionAll(V){return O+=` UNION ALL ${String(V.toSQL())}`,K=null,this},forPage(V,I){let D=Math.max(1,Math.floor(V)),S=Math.max(1,Math.floor(I));return O+=` LIMIT ${S} OFFSET ${(D-1)*S}`,K=null,this},toSQL(){return U(W(),O)},async value(V){let I=F`${W()} LIMIT 1`,D=await j(I,"select",{signal:M,timeoutMs:R}),[S]=D;return S?.[V]},async pluck(V,I){let D=await j(W(),"select",{signal:M,timeoutMs:R});if(I){let S={};for(let H of D)S[String(H?.[I])]=H?.[V];return S}return D.map((S)=>S?.[V])},async exists(){let V=F`SELECT EXISTS (${W()}) as e`,I=await j(V,"select",{signal:M,timeoutMs:R}),[D]=I;return Boolean(D?.e)},async doesntExist(){return!await this.exists()},async paginate(V,I=1){let D=F`SELECT COUNT(*) as c FROM (${W()}) as sub`,S=await j(D,"select",{signal:M,timeoutMs:R}),[H]=S,T=Number(H?.c??0),C=Math.max(1,Math.ceil(T/V)),k=Math.max(1,Math.min(I,C)),h=(k-1)*V;return{data:await j(F`${W()} LIMIT ${V} OFFSET ${h}`,"select",{signal:M,timeoutMs:R}),meta:{perPage:V,page:k,total:T,lastPage:C}}},async simplePaginate(V,I=1){let D=Math.max(1,I),S=(D-1)*V,H=await j(F`${W()} LIMIT ${V+1} OFFSET ${S}`,"select",{signal:M,timeoutMs:R}),T=H.length>V;return{data:T?H.slice(0,V):H,meta:{perPage:V,page:D,hasMore:T}}},async cursorPaginate(V,I,D="id",S="asc"){let H=W();if(I!==void 0&&I!==null)if(Array.isArray(D)){let P=D.map((D0)=>F(String(D0))),x=S==="asc"?F`>`:F`<`,d=F`(${F(P)})`,r=F`(${F(I)})`;H=F`${H} WHERE ${d} ${x} ${r}`}else H=S==="asc"?F`${H} WHERE ${F(String(D))} > ${I}`:F`${H} WHERE ${F(String(D))} < ${I}`;if(Array.isArray(D)){let x=D.map((d)=>F`${F(String(d))} ${S==="asc"?F`ASC`:F`DESC`}`).reduce((d,r,D0)=>D0===0?r:F`${d}, ${r}`);H=F`${H} ORDER BY ${x} LIMIT ${V+1}`}else H=F`${H} ORDER BY ${F(String(D))} ${S==="asc"?F`ASC`:F`DESC`} LIMIT ${V+1}`;let T=await j(H,"select",{signal:M,timeoutMs:R}),C=T.length>V?Array.isArray(D)?D.map((P)=>T[V]?.[P]):T[V]?.[D]:null,k=T.slice(0,V),h=k.length?Array.isArray(D)?D.map((P)=>k[0]?.[P]):k[0]?.[D]:null;return{data:k,meta:{perPage:V,nextCursor:C??null,prevCursor:h}}},async chunk(V,I){let D=1;while(!0){let{data:S}=await this.paginate(V,D);if(S.length===0)break;if(await I(S),S.length<V)break;D+=1}},async chunkById(V,I="id",D){let S;while(!0){let{data:H,meta:T}=await this.cursorPaginate(V,S,I,"asc");if(H.length===0)break;if(D)await D(H);if(S=T.nextCursor,!S)break}},async eachById(V,I="id",D){await this.chunkById(V,I,async(S)=>{for(let H of S)await D?.(H)})},withTimeout(V){return R=Math.max(1,Math.floor(V)),this},abort(V){return M=V,this},withTrashed(){return q=!0,N=!1,this},onlyTrashed(){q=!0,N=!0;let V=b.softDeletes?.column||"deleted_at";if(O.includes("WHERE"))O=O.replace(/WHERE/,`WHERE ${E}.${V} IS NOT NULL AND`);else O=`${O} WHERE ${E}.${V} IS NOT NULL`;let I=String(W());if(I.includes("WHERE")){let D=I.replace(/WHERE/,`WHERE ${E}.${V} IS NOT NULL AND`);K=F([D])}else{let D=`${I} WHERE ${E}.${V} IS NOT NULL`;K=F([D])}return this},scope(V,I){let D=String(E),H=X?.scopes?.[D]?.[V];if(H)return H(this,I);return this},when(V,I,D){if(V)return I(this);if(D)return D(this);return this},tap(V){return V(this),this},dump(){return console.log(String(W())),this},dd(){throw console.log(String(W())),Error("Dump and Die")},cache(V=60000){return p=V,B=!0,this},async explain(){let V=F`EXPLAIN ${W()}`;return await j(V,"select",{signal:M,timeoutMs:R})},simple(){return W().simple()},toText(){return O},async get(){let V=b.hooks,I=V&&(V.onQueryStart||V.onQueryEnd||V.onQueryError||V.startSpan);if(!b.softDeletes?.enabled&&!B&&!R&&!M&&!I){let H=Z._prepareStatement;if(H){let T=H(O);return K9(y.length>0?T.all(...y):T.all())}}if(K=y.length>0?Z.unsafe(O,y):Z.unsafe(O),!b.softDeletes?.enabled&&!B&&!R&&!M&&!I){let H=W()._stmt,T=W()._params;if(H)return K9(T&&T.length>0?H.all(...T):H.all());return K9(await W().execute())}if(!b.softDeletes?.enabled&&!B&&!R&&!M)return K9(await j(W(),"select"));let D=W();if(b.softDeletes?.enabled&&b.softDeletes.defaultFilter&&!q){let H=b.softDeletes.column,T=String(E);if((_?Boolean(_[T]?.columns?.[H]):!0)&&!u.DELETED_AT.test(O))D=F`${W()} WHERE ${F(String(H))} IS ${N?F`NOT NULL`:F`NULL`}`,w("WHERE",`${String(H)} IS ${N?"NOT ":""}NULL`)}if(B){let H=String(D),T=Z6.get(H);if(T)return T}let S=await j(D,"select",{signal:M,timeoutMs:R});if(B){let H=String(D);Z6.set(H,S,p)}return K9(S)},async executeTakeFirst(){let V=await j(W(),"select",{signal:M,timeoutMs:R});return r0(Array.isArray(V)?V[0]:V)},async executeTakeFirstOrThrow(){let V=await this.executeTakeFirst();if(!V)throw Error("Record not found");return V},async first(){let V=b.hooks,I=V&&(V.onQueryStart||V.onQueryEnd||V.onQueryError||V.startSpan);if(!b.softDeletes?.enabled&&!B&&!R&&!M&&!I){let H=Z._prepareStatement;if(H){let T=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,C=H(T),k=y.length>0?C.all(...y):C.all();return r0(k[0])}}let D=await j(F`${W()} LIMIT 1`,"select",{signal:M,timeoutMs:R}),[S]=D;return r0(S)},async firstOrFail(){let V=await this.first();if(!V)throw Error("Record not found");return V},async find(V){let I=X?.primaryKeys[String(E)]??"id",D=await j(F`${W()} WHERE ${F(I)} = ${V} LIMIT 1`,"select",{signal:M,timeoutMs:R}),[S]=D;return S},async findOrFail(V){let I=await this.find(V);if(!I)throw Error("Record not found");return I},async findMany(V){let I=X?.primaryKeys[String(E)]??"id";return await j(F`${W()} WHERE ${F(String(I))} IN ${F(V)}`,"select",{signal:M,timeoutMs:R})},async*lazy(){let V,I=X?.primaryKeys[String(E)]??"id";while(!0){let S=await(V==null?F`${W()} ORDER BY ${F(String(I))} ASC LIMIT 100`:F`${W()} WHERE ${F(String(I))} > ${V} ORDER BY ${F(String(I))} ASC LIMIT 100`).execute();if(S.length===0)break;for(let H of S)yield H;if(V=S[S.length-1]?.[I],V==null)break}},async*lazyById(){let V=X?.primaryKeys[String(E)]??"id",I;while(!0){let S=await(I==null?F`${W()} ORDER BY ${F(String(V))} ASC LIMIT 100`:F`${W()} WHERE ${F(String(V))} > ${I} ORDER BY ${F(String(V))} ASC LIMIT 100`).execute();if(S.length===0)break;for(let H of S)yield H;if(I=S[S.length-1]?.[V],I==null)break}},pipe(V){return V(this)},async count(){let V=O.indexOf(" FROM "),I=V!==-1?`SELECT COUNT(*) as c${O.substring(V)}`:`SELECT COUNT(*) as c FROM ${E}`,D=b.hooks,S=D&&(D.onQueryStart||D.onQueryEnd||D.onQueryError||D.startSpan);if(!b.softDeletes?.enabled&&!B&&!R&&!M&&!S){let k=Z._prepareStatement;if(k){let h=k(I),P=y.length>0?h.all(...y):h.all();return Number(P[0]?.c??0)}}let H=y.length>0?Z.unsafe(I,y):Z.unsafe(I),T=await j(H,"select",{signal:M,timeoutMs:R}),[C]=T;return Number(C?.c??0)},async avg(V){let I=O.indexOf(" FROM "),D=I!==-1?`SELECT AVG(${V}) as a${O.substring(I)}`:`SELECT AVG(${V}) as a FROM ${E}`,S=b.hooks,H=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan);if(!b.softDeletes?.enabled&&!B&&!R&&!M&&!H){let h=Z._prepareStatement;if(h){let P=h(D),x=y.length>0?P.all(...y):P.all();return Number(x[0]?.a??0)}}let T=y.length>0?Z.unsafe(D,y):Z.unsafe(D),C=await j(T,"select",{signal:M,timeoutMs:R}),[k]=C;return Number(k?.a??0)},async sum(V){let I=O.indexOf(" FROM "),D=I!==-1?`SELECT SUM(${V}) as s${O.substring(I)}`:`SELECT SUM(${V}) as s FROM ${E}`,S=y.length>0?Z.unsafe(D,y):Z.unsafe(D),H=await j(S,"select",{signal:M,timeoutMs:R}),[T]=H;return Number(T?.s??0)},async max(V){let I=O.indexOf(" FROM "),D=I!==-1?`SELECT MAX(${V}) as m${O.substring(I)}`:`SELECT MAX(${V}) as m FROM ${E}`,S=y.length>0?Z.unsafe(D,y):Z.unsafe(D),H=await j(S,"select",{signal:M,timeoutMs:R}),[T]=H;return T?.m},async min(V){let I=O.indexOf(" FROM "),D=I!==-1?`SELECT MIN(${V}) as m${O.substring(I)}`:`SELECT MIN(${V}) as m FROM ${E}`,S=y.length>0?Z.unsafe(D,y):Z.unsafe(D),H=await j(S,"select",{signal:M,timeoutMs:R}),[T]=H;return T?.m},lockForUpdate(){return O+=" FOR UPDATE",K=null,this},sharedLock(){let V=b.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return O+=` ${V}`,K=null,this},withCTE(V,I){return O=`WITH ${V} AS (${String(I.toSQL())}) ${O}`,K=null,this},withRecursive(V,I){return O=`WITH RECURSIVE ${V} AS (${String(I.toSQL())}) ${O}`,K=null,this},execute(){return j(W(),"select",{signal:M,timeoutMs:R})},values(){return W().values()},toParams(){return W().values?.()??[]},raw(){return W().raw()},get rows(){return},get row(){return},cancel(){try{W().cancel()}catch{}}},{get(V,I,D){let S=Reflect.get(V,I,D);if(S!==void 0)return S;if(typeof I==="string"&&(I.startsWith("where")||I.startsWith("orWhere")||I.startsWith("andWhere"))){let H=I.startsWith("orWhere"),T=I.startsWith("andWhere"),C=I.replace(/^or?where/i,"").replace(/^andwhere/i,"");if(!C)return()=>D;let k=C.charAt(0).toLowerCase()+C.slice(1),P=((D0)=>D0.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))(C),x=String(E),d=_?Object.keys(_[x]?.columns??{}):[],r=[P,k,k.toLowerCase()].find((D0)=>d.includes(D0))??P;return(D0)=>{let o=Array.isArray(D0)?F`${F(String(r))} IN ${F(D0)}`:F`${F(String(r))} = ${D0}`;K=H?F`${W()} OR ${o}`:T?F`${W()} AND ${o}`:F`${W()} WHERE ${o}`;let l9=Array.isArray(D0)?`${String(r)} IN (?)`:`${String(r)} = ?`;return w(H?"OR":T?"AND":"WHERE",l9),D}}return Reflect.get(V,I,D)}})}return{configure(E){return Object.assign(b,E),this},id(E){if(!u.IDENTIFIER.test(E))throw Error(`[query-builder] Invalid identifier: '${E}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return Z(String(E))},ids(...E){for(let G of E)if(!u.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 Z(E)},select(E,...G){return Q(E,G)},selectFrom(E){return Q(E)},selectFromSub(E,G){let F=Z,O=Z`SELECT * FROM (${E.toSQL()}) AS ${Z(G)}`,K={distinct(){let J=String(O).replace(/^SELECT\s+/i,""),R=F`SELECT DISTINCT ${F``}${F(J)}`;return W(R)},distinctOn(...J){let R=/^SELECT\s+(\S+)\s+FROM/i.exec(String(O)),M=R?`${R[1]} FROM`:String(O),q=F`SELECT DISTINCT ON (${F(J)}) ${F``}${F(M)}`;return W(q)},selectRaw(J){let R=F`${O} , ${J}`;return W(R)},where(J,R,M){let q=w(O,J,R,M,"WHERE");return W(q)},andWhere(J,R,M){let q=w(O,J,R,M,"AND");return W(q)},orWhere(J,R,M){let q=w(O,J,R,M,"OR");return W(q)},orderBy(J,R="asc"){let M=R==="asc"?"ASC":"DESC",q=String(O),N=u.ORDER_BY.test(q)?F.unsafe(`${q}, ${J} ${M}`):F`${O} ORDER BY ${F(J)} ${R==="asc"?F`ASC`:F`DESC`}`;return W(N)},limit(J){let R=String(O),M=u.LIMIT.test(R)?F.unsafe(R.replace(u.LIMIT,` LIMIT ${J}`)):F`${O} LIMIT ${J}`;return W(M)},offset(J){let R=String(O),M=u.OFFSET.test(R)?F.unsafe(R.replace(u.OFFSET,` OFFSET ${J}`)):F`${O} OFFSET ${J}`;return W(M)},toSQL(){return U(O)},async execute(){return j(O,"select")},async executeTakeFirst(){let J=await j(O,"select");return Array.isArray(J)?J[0]:J},async executeTakeFirstOrThrow(){let J=await j(O,"select"),R=Array.isArray(J)?J[0]:J;if(!R)throw Error("Record not found");return R},async get(){return j(O,"select")},async first(){let J=await j(O,"select");return Array.isArray(J)?J[0]:J},async firstOrFail(){let J=await j(O,"select"),R=Array.isArray(J)?J[0]:J;if(!R)throw Error("No rows found");return R},async exists(){let J=F`SELECT EXISTS(${O}) as exists`;return(await j(J,"select"))?.[0]?.exists===!0},async doesntExist(){return!await this.exists()},values(){return O.values()},raw(){return O.raw()},cancel(){try{O.cancel()}catch{}},whereRaw:()=>this,whereColumn:()=>this,orWhereColumn:()=>this,whereIn:()=>this,orWhereIn:()=>this,whereNotIn:()=>this,orWhereNotIn:()=>this,whereLike:()=>this,whereILike:()=>this,orWhereLike:()=>this,orWhereILike:()=>this,whereNotLike:()=>this,whereNotILike:()=>this,orWhereNotLike:()=>this,orWhereNotILike:()=>this,whereAny:()=>this,whereAll:()=>this,whereNone:()=>this,whereNested:()=>this,orWhereNested:()=>this,whereDate:()=>this,whereBetween:()=>this,whereNotBetween:()=>this,whereJsonContains:()=>this,whereJsonPath:()=>this,whereNull:()=>this,whereNotNull:()=>this,whereExists:()=>this,whereJsonDoesntContain:()=>this,whereJsonContainsKey:()=>this,whereJsonDoesntContainKey:()=>this,whereJsonLength:()=>this,join:()=>this,joinSub:()=>this,innerJoin:()=>this,leftJoin:()=>this,leftJoinSub:()=>this,rightJoin:()=>this,crossJoin:()=>this,crossJoinSub:()=>this,groupBy:()=>this,groupByRaw:()=>this,having:()=>this,havingRaw:()=>this,addSelect:()=>this,select:()=>this,selectAll:()=>this,orderByDesc:()=>this,inRandomOrder:()=>this,reorder:()=>this,orderByRaw:()=>this,union:()=>this,unionAll:()=>this,forPage:()=>this,selectAllRelations:()=>this,with:()=>this,value:()=>Promise.resolve(void 0),pluck:()=>Promise.resolve([]),cursorPaginate:()=>Promise.resolve({data:[],meta:{perPage:0,nextCursor:null}}),paginate:()=>Promise.resolve({data:[],meta:{perPage:0,page:1,total:0,lastPage:1}}),simplePaginate:()=>Promise.resolve({data:[],meta:{perPage:0,page:1,hasMore:!1}}),chunk:()=>Promise.resolve(),chunkById:()=>Promise.resolve(),eachById:()=>Promise.resolve(),count:()=>Promise.resolve(0),avg:()=>Promise.resolve(0),sum:()=>Promise.resolve(0),max:()=>Promise.resolve(null),min:()=>Promise.resolve(null),find:()=>Promise.resolve(void 0),findOrFail:()=>Promise.reject(Error("Not found")),findMany:()=>Promise.resolve([]),latest:()=>this,oldest:()=>this,lazy:()=>async function*(){}(),lazyById:()=>async function*(){}(),pipe:(J)=>J(this),when:()=>this,tap:()=>this,dump:()=>this,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>O.simple(),toText:()=>String(O),toParams:()=>O.values?.()??[],withTimeout:()=>this,abort:()=>this,lockForUpdate:()=>this,sharedLock:()=>this,withCTE:()=>this,withRecursive:()=>this,cache:()=>this,clone:()=>this,withTrashed:()=>this,onlyTrashed:()=>this,scope:()=>this,get rows(){return[]},get row(){return}};function W(J){return{...K,toSQL:()=>U(J),execute:()=>j(J,"select"),get:()=>j(J,"select"),first:async()=>{let R=await j(J,"select");return Array.isArray(R)?R[0]:R},firstOrFail:async()=>{let R=await j(J,"select"),M=Array.isArray(R)?R[0]:R;if(!M)throw Error("No rows found");return M},exists:async()=>{let R=F`SELECT EXISTS(${J}) as exists`;return(await j(R,"select"))?.[0]?.exists===!0},doesntExist:async()=>{return!await K.exists()},values:()=>J.values(),raw:()=>J.raw(),cancel:()=>{try{J.cancel()}catch{}},simple:()=>J.simple(),toText:()=>String(J),toParams:()=>J.values?.()??[]}}function w(J,R,M,q,N="WHERE"){if(typeof R==="string"&&M!==void 0){let B=Array.isArray(q)?`${R} IN (?)`:`${R} ${M} ?`;return F`${J} ${F(N)} ${F(B)}`}else if(Array.isArray(R)&&R.length===3){let[B,A,f]=R,p=Array.isArray(f)?`${B} IN (?)`:`${B} ${A} ?`;return F`${J} ${F(N)} ${F(p)}`}else if(typeof R==="object"&&R!==null){let A=Object.entries(R).map(([f,p])=>{let c=Array.isArray(p)?`${f} IN (?)`:`${f} = ?`;return F`${F(c)}`}).reduce((f,p,c)=>c===0?p:F`${f} AND ${p}`);return F`${J} ${F(N)} ${A}`}return J}return K},insertInto(E){let G,F="",O=[],K=b.dialect==="postgres",W=K?(J)=>`"${J}"`:b.dialect==="mysql"?(J)=>`\`${J}\``:(J)=>J,w=K?(J)=>`$${J+1}`:(J)=>"?";return{values(J){let R=Array.isArray(J)?J:[J],M=R.length;if(M===0)return G=Z.unsafe("SELECT 1"),this;let q=R[0],N=Object.keys(q),B=N.length,A=M*B;if(O.length=A,M===1)if(!K){let f=N[0],p="?";O[0]=q[N[0]];for(let c=1;c<B;c++)f+=`,${N[c]}`,p+=",?",O[c]=q[N[c]];F=`INSERT INTO ${E}(${f})VALUES(${p})`}else{let f=N.map((p)=>W(p)).join(",");F=`INSERT INTO ${W(E)}(${f})VALUES(`;for(let p=0;p<B;p++){if(p>0)F+=",";F+=w(p),O[p]=q[N[p]]}F+=")"}else{let f=N.map((c)=>W(c)).join(",");F=`INSERT INTO ${W(E)}(${f})VALUES`;let p=0;for(let c=0;c<M;c++){let l=R[c];if(c===0)F+="(";else F+="),(";for(let r0=0;r0<B;r0++){if(r0>0)F+=",";F+=w(p),O[p++]=l[N[r0]]}}F+=")"}if(!Z._prepareStatement)G=Z.unsafe(F,O);return this},returning(...J){let R=`${F} RETURNING ${J.join(", ")}`,M=Z.unsafe(R,O);return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>U(M,R),execute:()=>j(M,"insert")}},toSQL(){if(!G)G=Z.unsafe(F,O);return U(G,F)},execute(){let J=b.hooks;if(!(J&&(J.onQueryStart||J.onQueryEnd||J.onQueryError||J.startSpan||J.beforeCreate||J.afterCreate))){let M=Z._prepareStatement;if(M){let q=M(F);return O.length>0?q.run(...O):q.run()}}if(!G)G=Z.unsafe(F,O);return j(G,"insert")},async executeTakeFirst(){if(!G)G=Z.unsafe(F,O);return await j(G,"insert")},async executeTakeFirstOrThrow(){if(!G)G=Z.unsafe(F,O);let J=await j(G,"insert");if(!J)throw Error("Insert failed");return J},returningAll(){let J=`${F} RETURNING *`,R=Z.unsafe(J,O);return{toSQL:()=>U(R,J),execute:()=>j(R,"insert"),async executeTakeFirst(){let M=await j(R,"insert");return Array.isArray(M)?M[0]:M},async executeTakeFirstOrThrow(){let M=await j(R,"insert"),q=Array.isArray(M)?M[0]:M;if(!q)throw Error("Insert with RETURNING failed");return q}}}}},updateTable(E){let G,F=[],O=(W)=>{if(b.dialect==="mysql")return`\`${W}\``;return`"${W}"`},K=`UPDATE ${O(String(E))}`;return{set(W){let w=Object.keys(W),J=w.length,R=Array.from({length:J});for(let M=0;M<J;M++){let q=w[M];R[M]=`${O(q)} = ${m(M+1)}`,F.push(W[q])}return K=`${K} SET ${R.join(", ")}`,G=Z.unsafe(K,F),this},where(W,w,J){let R=()=>K.toUpperCase().includes(" WHERE ")?"AND":"WHERE";if(typeof W==="string"&&w!==void 0){let M=F.length+1;return K=`${K} ${R()} ${O(W)} ${w} ${m(M)}`,F.push(J),G=Z.unsafe(K,F),this}if(Array.isArray(W)){let[M,q,N]=W,B=F.length+1;return K=`${K} ${R()} ${O(String(M))} ${String(q)} ${m(B)}`,F.push(N),G=Z.unsafe(K,F),this}if(W&&typeof W==="object"&&!("raw"in W)){let M=Object.keys(W),q=M.length,N=F.length,B=Array.from({length:q});for(let A=0;A<q;A++)B[A]=`${O(M[A])} = ${m(N+A+1)}`,F.push(W[M[A]]);K=`${K} ${R()} ${B.join(" AND ")}`,G=Z.unsafe(K,F)}return this},returning(...W){let w=`${K} RETURNING ${W.join(", ")}`,J=F.length>0?Z.unsafe(w,F):Z.unsafe(w),R={where:()=>R,andWhere:()=>R,orWhere:()=>R,orderBy:()=>R,limit:()=>R,offset:()=>R,toSQL:()=>U(J,w),execute:()=>j(J,"update")};return R},toSQL(){if(!G)G=F.length>0?Z.unsafe(K,F):Z.unsafe(K);return U(G,K)},execute(){return j(G,"update")},async executeTakeFirst(){return{numUpdatedRows:await j(G,"update")}},async executeTakeFirstOrThrow(){let W=await j(G,"update");if(W===0)throw Error("No rows updated");return{numUpdatedRows:W}},returningAll(){let W=`${K} RETURNING *`,w=F.length>0?Z.unsafe(W,F):Z.unsafe(W);return{toSQL:()=>U(w,W),execute:()=>j(w,"update"),async executeTakeFirst(){let J=await j(w,"update");return Array.isArray(J)?J[0]:J},async executeTakeFirstOrThrow(){let J=await j(w,"update"),R=Array.isArray(J)?J[0]:J;if(!R)throw Error("Update with RETURNING failed");return R}}}}},deleteFrom(E){let G=(R)=>{if(b.dialect==="mysql")return`\`${R}\``;return`"${R}"`},O=`DELETE FROM ${G(String(E))}`,K=null,W=[],w=null,J=()=>{if(K===null)K=W.length>0?Z.unsafe(O,W):Z.unsafe(O);return K};return{where(R,M,q){if(w=R,typeof R==="string"&&M!==void 0){let N=W.length+1;return O+=` WHERE ${G(R)} ${M} ${m(N)}`,W.push(q),K=null,this}if(Array.isArray(R)){let[N,B,A]=R,f=W.length+1;return O+=` WHERE ${G(String(N))} ${B} ${m(f)}`,W.push(A),K=null,this}if(R&&typeof R==="object"&&!("raw"in R)){let N=Object.keys(R),B=[];for(let A of N){let f=W.length+1;B.push(`${G(A)} = ${m(f)}`),W.push(R[A])}return O+=` WHERE ${B.join(" AND ")}`,K=null,this}return K=L({},J(),R),this},returning(...R){let M=`${O} RETURNING ${R.join(", ")}`,q=W.length>0?Z.unsafe(M,W):Z.unsafe(M),N={where:()=>N,andWhere:()=>N,orWhere:()=>N,orderBy:()=>N,limit:()=>N,offset:()=>N,toSQL:()=>U(q,M),execute:()=>j(q,"delete")};return N},toSQL(){return U(J(),O)},async execute(){try{await b.hooks?.beforeDelete?.({table:String(E),where:w})}catch(M){throw M}let R=await j(J(),"delete");try{await b.hooks?.afterDelete?.({table:String(E),where:w,result:R})}catch{}return R},async executeTakeFirst(){return{numDeletedRows:await j(J(),"delete")}},async executeTakeFirstOrThrow(){let R=await j(J(),"delete");if(R===0)throw Error("No rows deleted");return{numDeletedRows:R}},returningAll(){let R=`${O} RETURNING *`,M=W.length>0?Z.unsafe(R,W):Z.unsafe(R);return{toSQL:()=>U(M,R),execute:()=>j(M,"delete"),async executeTakeFirst(){let q=await j(M,"delete");return Array.isArray(q)?q[0]:q},async executeTakeFirstOrThrow(){let q=await j(M,"delete"),N=Array.isArray(q)?q[0]:q;if(!N)throw Error("Delete with RETURNING failed");return N}}}}},table(E){let G=this;return{insert(F){return G.insertInto(E).values(F)},update(F){return G.updateTable(E).set(F)},delete(){return G.deleteFrom(E)},select(...F){if(F.length===0)return G.selectFrom(E);return G.select(E,...F)}}},sql:Z,raw(E,...G){return Z(E,...G)},simple(E,...G){return Z(E,...G).simple()},async advisoryLock(E){if(b.dialect!=="postgres")return;let G=String(E),F=7;for(let W=0;W<G.length;W++)F=F*31+G.charCodeAt(W)|0;let O=typeof E==="number"?E:Math.abs(F),K=g`SELECT pg_advisory_lock(${O})`;await j(K,"raw")},async tryAdvisoryLock(E){if(b.dialect!=="postgres")return!1;let G=String(E),F=7;for(let w=0;w<G.length;w++)F=F*31+G.charCodeAt(w)|0;let O=typeof E==="number"?E:Math.abs(F),K=g`SELECT pg_try_advisory_lock(${O}) as ok`,W=await j(K,"raw");return Boolean(W?.[0]?.ok)},unsafe(E,G){return g.unsafe(E,G)},file(E,G){return g.file(E,G)},async reserve(){let E=await g.reserve(),G=F9({sql:E,meta:X,schema:_});return G.release=()=>E.release(),G},async close(E){await g.close(E)},async listen(E,G){},async unlisten(E){},async notify(E,G){},async copyTo(E,G){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(E,G,F){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let E=g`SELECT 1`;return await j(E,"select"),!0}catch{return!1}},async waitForReady(E){let G=Math.max(1,E?.attempts??10),F=Math.max(10,E?.delayMs??100);for(let O=0;O<G;O++){if(await this.ping())return;await new Promise((K)=>setTimeout(K,F))}throw Error("Database not ready after waiting")},async transaction(E,G){let O={...$?.txDefaults,...G},K=async(J)=>{O.logger?.({type:"start",attempt:J});let R=Date.now();return await g.begin(async(M)=>{let q=F9({sql:M,meta:X,schema:_});if(O?.isolation){let A=O.isolation,f=A==="read committed"?g`READ COMMITTED`:A==="repeatable read"?g`REPEATABLE READ`:g`SERIALIZABLE`;await M`${g`SET TRANSACTION ISOLATION LEVEL`} ${f}`.execute()}if(O?.readOnly)try{await M`${g`SET TRANSACTION READ ONLY`}`.execute()}catch{}let N=await E(q),B=Date.now()-R;return O.logger?.({type:"commit",attempt:J,durationMs:B}),N})},W=Math.max(0,O?.retries??0),w=0;for(;;)try{let J=await K(w+1);return O?.afterCommit?.(),J}catch(J){let R=vz(J)||bz(J,O.sqlStates);if(w<W&&R){w++,O?.onRetry?.(w,J);let M=gz(w,O.backoff);if(M>0)await fz(M);continue}try{O.onRollback?.(J)}catch{}try{O.afterRollback?.()}catch{}throw J}},async savepoint(E){let G=Z;if(!G||typeof G.savepoint!=="function")throw Error("savepoint() must be called inside a transaction");return await G.savepoint(async(F)=>{let O=F9({sql:F,meta:X,schema:_});return await E(O)})},async beginDistributed(E,G){return await g.beginDistributed(E,async(O)=>{let K=F9({sql:O,meta:X,schema:_});return await G(K)})},async commitDistributed(E){await g.commitDistributed(E)},async rollbackDistributed(E){await g.rollbackDistributed(E)},setTransactionDefaults(E){$={...$,txDefaults:{...$?.txDefaults,...E}}},transactional(E,G){return(...F)=>{return this.transaction((O)=>E(O,...F),G)}},async insertOrIgnore(E,G){return g`INSERT INTO ${g(String(E))} ${g(G)} ON CONFLICT DO NOTHING`.execute()},async insertGetId(E,G,F="id"){if(b.dialect==="mysql"){let K=await g`INSERT INTO ${g(String(E))} ${g(G)}`.execute();if(K&&typeof K==="object"&&"insertId"in K)return K.insertId;let[W]=await g`SELECT LAST_INSERT_ID() as id`.execute();return W?.id}else{let O=g`INSERT INTO ${g(String(E))} ${g(G)} RETURNING ${g(String(F))} as id`,[K]=await O.execute();return K?.id}},async updateOrInsert(E,G,F){let O=Object.keys(G).map((w)=>g`${g(String(w))} = ${g(G[w])}`);if((await g`SELECT 1 FROM ${g(String(E))} WHERE ${g(O)} LIMIT 1`.execute()).length)return await g`UPDATE ${g(String(E))} SET ${g(F)} WHERE ${g(O)}`.execute(),!0;else return await g`INSERT INTO ${g(String(E))} ${g({...G,...F})}`.execute(),!0},async upsert(E,G,F,O){let K=F.map((J)=>String(J)),W=(O??[]).map((J)=>String(J));return g`INSERT INTO ${g(String(E))} ${g(G)} ON CONFLICT (${g(K)}) DO UPDATE SET ${g(W.reduce((J,R)=>({...J,[R]:g(`EXCLUDED.${R}`)}),{}))}`.execute()},async save(E,G){let F=X?.primaryKeys[String(E)]??"id",O=G[F];if(O!=null)if(await this.selectFrom(E).find(O)){await this.updateTable(E).set(G).where({[F]:O}).execute();let W=await this.selectFrom(E).find(O);if(!W)throw Error("save() failed to retrieve updated row");return W}else return await this.create(E,G);return await this.create(E,G)},async remove(E,G){return await this.deleteFrom(E).where({id:G}).execute()},async find(E,G){return await this.selectFrom(E).find(G)},async findOrFail(E,G){return await this.selectFrom(E).findOrFail(G)},async findMany(E,G){return await this.selectFrom(E).findMany(G)},async latest(E,G){return await this.selectFrom(E).latest(G).first()},async oldest(E,G){return await this.selectFrom(E).oldest(G).first()},skip(E,G){return this.selectFrom(E).offset(G)},async rawQuery(E){let G=Date.now();try{b.hooks?.onQueryStart?.({sql:E,kind:"raw"});let F=await g.unsafe(E);return b.hooks?.onQueryEnd?.({sql:E,durationMs:Date.now()-G,kind:"raw"}),F}catch(F){throw b.hooks?.onQueryError?.({sql:E,error:F,durationMs:Date.now()-G,kind:"raw"}),F}},async create(E,G){let F=X?.primaryKeys[String(E)]??"id";try{await b.hooks?.beforeCreate?.({table:String(E),data:G})}catch(O){throw O}if(b.dialect==="postgres"){let O=g`INSERT INTO ${g(String(E))} ${g(G)} RETURNING ${g(String(F))} as id`,[K]=await O.execute();if(console.log("resultId",K),!K?.id)throw console.error(`create() failed to get insert ID for table ${String(E)}`),console.error("Inserted values:",G),Error(`create() failed to get insert ID for table ${String(E)}`);let W=await this.selectFrom(E).find(K.id);if(!W)throw console.error(`create() failed to retrieve inserted row for table ${String(E)} with id ${K.id}`),console.error("Inserted values:",G),Error(`create() failed to retrieve inserted row for table ${String(E)} with id ${K.id}`);try{await b.hooks?.afterCreate?.({table:String(E),data:G,result:W})}catch{}return W}else{let O=await this.insertGetId(E,G,F);if(O==null)throw Error(`create() failed to get insert ID for table ${String(E)}`);let K=await this.selectFrom(E).find(O);if(!K)throw console.error(`create() failed to retrieve inserted row for table ${String(E)} with id ${O}`),console.error("Inserted values:",G),Error(`create() failed to retrieve inserted row for table ${String(E)} with id ${O}`);try{await b.hooks?.afterCreate?.({table:String(E),data:G,result:K})}catch{}return K}},async createMany(E,G){if(!G?.length)return;let F=G[0],O=Object.keys(F),K=O.length,W=G.length,w=Array.from({length:W*K}),J=`INSERT INTO ${E}(${O.join(",")})VALUES`,R=0;for(let M=0;M<W;M++){if(M>0)J+=",";J+="(";let q=G[M];for(let N=0;N<K;N++){if(N>0)J+=",";J+=m(R+1),w[R++]=q[O[N]]}J+=")"}return Z.unsafe(J,w).execute()},async insertMany(E,G){if(!G?.length)return;let F=G[0],O=Object.keys(F),K=O.length,W=G.length,w=W*K,J=Array(w),R=b.dialect==="postgres",M;if(!R){let B=Array(K);for(let A=0;A<K;A++)B[A]="?";M=`(${B.join(",")})`}else M="";let q=Array(W+2);q[0]=`INSERT INTO ${E}(${O.join(",")})VALUES`;let N=0;if(!R){for(let B=0;B<W;B++){let A=G[B];q[B+1]=M;for(let f=0;f<K;f++)J[N++]=A[O[f]]}return Z.unsafe(q[0]+q.slice(1,W+1).join(","),J).execute()}for(let B=0;B<W;B++){let A=G[B],f=Array(K);for(let p=0;p<K;p++)f[p]=`$${N+1}`,J[N++]=A[O[p]];q[B+1]=`(${f.join(",")})`}return Z.unsafe(q[0]+q.slice(1,W+1).join(","),J).execute()},async updateMany(E,G,F){let O=Object.keys(F),K=O.length;if(K===0)return 0;let W=[],w=Array.from({length:K});for(let R=0;R<K;R++)w[R]=`${O[R]}=${m(R+1)}`,W.push(F[O[R]]);let J=`UPDATE ${E} SET ${w.join(",")}`;if(Array.isArray(G))J+=` WHERE ${G[0]}${G[1]}${m(W.length+1)}`,W.push(G[2]);else if(G&&typeof G==="object"&&!("raw"in G)){let R=Object.keys(G),M=R.length;if(M>0){let q=W.length,N=Array.from({length:M});for(let B=0;B<M;B++)N[B]=`${R[B]}=${m(q+B+1)}`,W.push(G[R[B]]);J+=` WHERE ${N.join(" AND ")}`}}return Z.unsafe(J,W).execute()},async deleteMany(E,G){if(!Array.isArray(G)||G.length===0)return 0;let F=X?.primaryKeys[String(E)]??"id",O=G.length;if(b.dialect==="postgres"){let W=Array(O);for(let w=0;w<O;w++)W[w]=`$${w+1}`;return Z.unsafe(`DELETE FROM ${E} WHERE ${F} IN (${W.join(",")})`,G).execute()}let K=Array(O);for(let W=0;W<O;W++)K[W]="?";return Z.unsafe(`DELETE FROM ${E} WHERE ${F} IN (${K.join(",")})`,G).execute()},async firstOrCreate(E,G,F){let O=await this.selectFrom(E).where(G).first();if(O)return O;return await this.create(E,{...G,...F})},async updateOrCreate(E,G,F){let O=await this.selectFrom(E).where(G).first();if(O){await this.updateTable(E).set(F).where(G).execute();let K=X?.primaryKeys[String(E)]??"id",W=O[K],w=W!=null?await this.selectFrom(E).find(W):await this.selectFrom(E).where(G).first();if(!w)throw Error("updateOrCreate() failed to retrieve updated row");return w}return await this.create(E,{...G,...F})},async count(E,G){let F=G?g(String(G)):g`*`,O=g`SELECT COUNT(${F}) as c FROM ${g(String(E))}`,[K]=await O.execute();return Number(K?.c??0)},async sum(E,G){let F=g`SELECT SUM(${g(String(G))}) as s FROM ${g(String(E))}`,[O]=await F.execute();return Number(O?.s??0)},async avg(E,G){let F=g`SELECT AVG(${g(String(G))}) as a FROM ${g(String(E))}`,[O]=await F.execute();return Number(O?.a??0)},async min(E,G){let F=g`SELECT MIN(${g(String(G))}) as m FROM ${g(String(E))}`,[O]=await F.execute();return O?.m},async max(E,G){let F=g`SELECT MAX(${g(String(G))}) as m FROM ${g(String(E))}`,[O]=await F.execute();return O?.m},getRelationships(E){if(!X?.relations)return{};let G=X.relations[E];if(!G)return{};let F={};for(let[O,K]of Object.entries(G))if(K&&typeof K==="object"&&Object.keys(K).length>0)F[O]=K;return F},hasRelationship(E,G){if(!X?.relations)return!1;let F=X.relations[E];if(!F)return!1;return Object.values(F).some((O)=>O&&typeof O==="object"&&(G in O))},getRelationshipType(E,G){if(!X?.relations)return null;let F=X.relations[E];if(!F)return null;for(let[O,K]of Object.entries(F))if(K&&typeof K==="object"&&G in K)return O;return null},getRelationshipTarget(E,G){if(!X?.relations)return null;let F=X.relations[E];if(!F)return null;for(let[O,K]of Object.entries(F))if(K&&typeof K==="object"&&G in K){let W=K[G];if(typeof W==="string")return X.modelToTable[W]||W;else if(W&&typeof W==="object"){if("model"in W)return X.modelToTable[W.model]||W.model;if("target"in W)return X.modelToTable[W.target]||W.target}}return null}}}class C2{quoteIdentifier($){return`\`${$.replace(/`/g,"``")}\``}getColumnType($){switch($.type){case"string":return"varchar(255)";case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"json":return"json";case"enum":if($.enumValues&&$.enumValues.length>0)return`ENUM(${$.enumValues.map((X)=>`'${X.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType($){return this.getColumnType($)}getAutoIncrementClause($){if($.isPrimaryKey&&($.type==="integer"||$.type==="bigint"))return"auto_increment";return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let Z=$.defaultValue;if(typeof Z==="string"){let X=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],_=Z.toUpperCase();if(X.includes(_))return`default ${_}`;return`default '${Z.replace(/'/g,"''")}'`}else if(typeof Z==="number"||typeof Z==="bigint")return`default ${Z}`;else if(typeof Z==="boolean")return`default ${Z?1:0}`;else if(Z instanceof Date)return`default '${Z.toISOString()}'`;return""}createEnumType($,Z){return""}createTable($){let Z=$.columns.map((X)=>this.renderColumn(X)).join(`,
|
|
63
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
64
|
-
${Z}
|
|
65
|
-
);`}createIndex($,Z){if(Z.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${Z.name}' on table '${$}' uses WHERE clause: ${Z.where}`);let X=Z.type==="unique"?"UNIQUE ":"",_=`${$}_${Z.name}`,Y=Z.columns.map((L)=>this.quoteIdentifier(L)).join(", ");return`CREATE ${X}INDEX ${this.quoteIdentifier(_)} ON ${this.quoteIdentifier($)} (${Y});`}addForeignKey($,Z,X,_,Y,L){let z=`${$}_${Z}_fk`,j=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(z)} FOREIGN KEY (${this.quoteIdentifier(Z)}) REFERENCES ${this.quoteIdentifier(X)}(${this.quoteIdentifier(_)})`;if(Y)j+=` ON DELETE ${Y.toUpperCase()}`;if(L)j+=` ON UPDATE ${L.toUpperCase()}`;return`${j};`}addColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let Y=this.getDefaultValue(Z);if(Y)_.push(Y);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${_.join(" ")};`}modifyColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let Y=this.getDefaultValue(Z);if(Y)_.push(Y);return`ALTER TABLE ${this.quoteIdentifier($)} MODIFY COLUMN ${_.join(" ")};`}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,Z){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(Z)};`}dropIndex($,Z){let X=`${$}_${Z}`;return`DROP INDEX ${this.quoteIdentifier(X)} ON ${this.quoteIdentifier($)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
66
|
-
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
67
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
68
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
69
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn($){let Z=this.getColumnType($),X=[this.quoteIdentifier($.name),Z];if($.isPrimaryKey){X.push("PRIMARY KEY");let Y=this.getAutoIncrementClause($);if(Y)X.push(Y)}if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let _=this.getDefaultValue($);if(_)X.push(_);return X.join(" ")}}class x2{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){switch($.type){case"string":return"varchar(255)";case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"timestamp";case"json":return"jsonb";case"enum":if($.enumValues&&$.enumValues.length>0)return`${$.name}_type`;return"text";default:return"text"}}getPrimaryKeyType($){switch($.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType($)}}getAutoIncrementClause($){return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let Z=$.defaultValue;if(typeof Z==="string"){let X=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],_=Z.toUpperCase();if(X.includes(_))return`default ${_}`;return`default '${Z.replace(/'/g,"''")}'`}else if(typeof Z==="number"||typeof Z==="bigint")return`default ${Z}`;else if(typeof Z==="boolean")return`default ${Z?"true":"false"}`;else if(Z instanceof Date)return`default '${Z.toISOString()}'`;return""}createEnumType($,Z){let X=Z.map((_)=>`'${_.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier($)} AS ENUM (${X});`}createTable($){let Z=$.columns.map((X)=>this.renderColumn(X)).join(`,
|
|
70
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
71
|
-
${Z}
|
|
72
|
-
);`}createIndex($,Z){let X=Z.type==="unique"?"UNIQUE ":"",_=`${$}_${Z.name}`,Y=Z.columns.map((z)=>this.quoteIdentifier(z)).join(", "),L=Z.where?` WHERE ${Z.where}`:"";return`CREATE ${X}INDEX IF NOT EXISTS ${this.quoteIdentifier(_)} ON ${this.quoteIdentifier($)} (${Y})${L};`}addForeignKey($,Z,X,_,Y,L){let z=`${$}_${Z}_fk`,j=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(z)} FOREIGN KEY (${this.quoteIdentifier(Z)}) REFERENCES ${this.quoteIdentifier(X)}(${this.quoteIdentifier(_)})`;if(Y)j+=` ON DELETE ${Y.toUpperCase()}`;if(L)j+=` ON UPDATE ${L.toUpperCase()}`;return`${j};`}addColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let Y=this.getDefaultValue(Z);if(Y)_.push(Y);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${_.join(" ")};`}modifyColumn($,Z){let X=this.getColumnType(Z);return`ALTER TABLE ${this.quoteIdentifier($)} ALTER COLUMN ${this.quoteIdentifier(Z.name)} TYPE ${X} USING ${this.quoteIdentifier(Z.name)}::${X};`}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}dropColumn($,Z){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(Z)};`}dropIndex($,Z){let X=`${$}_${Z}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(X)};`}dropEnumType($){return`DROP TYPE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
73
|
-
id SERIAL PRIMARY KEY,
|
|
74
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
75
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
76
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}renderColumn($){let Z=$.isPrimaryKey?this.getPrimaryKeyType($):this.getColumnType($),X=[this.quoteIdentifier($.name),Z];if($.isPrimaryKey)X.push("PRIMARY KEY");if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let _=this.getDefaultValue($);if(_)X.push(_);return X.join(" ")}}class B2{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){if($.name.endsWith("_id"))return"INTEGER";switch($.type){case"string":return"TEXT";case"text":return"TEXT";case"boolean":return"INTEGER";case"integer":return"INTEGER";case"bigint":return"INTEGER";case"float":return"REAL";case"double":return"REAL";case"decimal":return"REAL";case"date":return"TEXT";case"datetime":return"TEXT";case"json":return"TEXT";case"enum":if($.enumValues&&$.enumValues.length>0){let Z=$.enumValues.map((X)=>`'${X.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier($.name)} IN (${Z}))`}return"TEXT";default:return"TEXT"}}getPrimaryKeyType($){return this.getColumnType($)}getAutoIncrementClause($){if($.isPrimaryKey&&($.type==="integer"||$.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let Z=$.defaultValue;if(typeof Z==="string"){if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(Z.toUpperCase()))return`default ${Z.toUpperCase()}`;return`default '${Z.replace(/'/g,"''")}'`}else if(typeof Z==="number"||typeof Z==="bigint")return`default ${Z}`;else if(typeof Z==="boolean")return`default ${Z?1:0}`;else if(Z instanceof Date)return`default '${Z.toISOString()}'`;return""}createEnumType($,Z){return""}createTable($){let Z=$.columns.map((X)=>this.renderColumn(X)).join(`,
|
|
77
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
78
|
-
${Z}
|
|
79
|
-
);`}createIndex($,Z){let X=Z.type==="unique"?"UNIQUE ":"",_=`${$}_${Z.name}`,Y=Z.columns.map((z)=>this.quoteIdentifier(z)).join(", "),L=Z.where?` WHERE ${Z.where}`:"";return`CREATE ${X}INDEX IF NOT EXISTS ${this.quoteIdentifier(_)} ON ${this.quoteIdentifier($)} (${Y})${L};`}addForeignKey($,Z,X,_,Y,L){let z=`${$}_${Z}_fk`,j=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(z)} FOREIGN KEY (${this.quoteIdentifier(Z)}) REFERENCES ${this.quoteIdentifier(X)}(${this.quoteIdentifier(_)})`;if(Y)j+=` ON DELETE ${Y.toUpperCase()}`;if(L)j+=` ON UPDATE ${L.toUpperCase()}`;return`${j};`}addColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let Y=this.getDefaultValue(Z);if(Y)_.push(Y);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${_.join(" ")};`}modifyColumn($,Z){return`-- SQLite does not support ALTER COLUMN. Manual table recreation needed to change ${this.quoteIdentifier($)}.${this.quoteIdentifier(Z.name)} type`}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,Z){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(Z)};`}dropIndex($,Z){let X=`${$}_${Z}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(X)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
80
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
81
|
-
migration TEXT NOT NULL UNIQUE,
|
|
82
|
-
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
83
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn($){let Z=this.getColumnType($),X=[this.quoteIdentifier($.name),Z];if($.isPrimaryKey){X.push("PRIMARY KEY");let Y=this.getAutoIncrementClause($);if(Y)X.push(Y)}if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let _=this.getDefaultValue($);if(_)X.push(_);return X.join(" ")}}function g8($){switch($){case"postgres":return new x2;case"mysql":return new C2;case"sqlite":return new B2;default:throw Error(`Unsupported dialect: ${$}`)}}function R6($,Z){let X=m0($,".qb");return m0(X,`model-snapshot.${Z}.json`)}function ZU($,Z){let X=R6($,Z);if(!o9(X))return;try{let _=h2(X,"utf8"),Y=JSON.parse(_);if(Y?.plan&&Array.isArray(Y.plan.tables)&&Y.plan.dialect)return Y.plan;if(Array.isArray(Y?.tables)&&Y?.dialect)return Y;console.log("-- Invalid snapshot format, treating as no previous state");return}catch(_){console.log("-- Could not load snapshot, treating as no previous state:",_);return}}function XU($,Z,X){let _=R6($,Z),Y=m0($,".qb");if(!o9(Y))A2(Y,{recursive:!0}),console.log(`-- Created snapshot directory: ${Y}`);let L={plan:X,hash:RE(X),dialect:Z,updatedAt:new Date().toISOString()};v2(_,JSON.stringify(L,null,2)),console.log(`-- Model snapshot saved to ${_}`)}function p8(){return f1.cwd()}function _U($){let Z=g2($);if(!o9(Z))A2(Z,{recursive:!0}),console.log(`-- Created SQL directory: ${Z}`);return Z}async function A5($,Z={}){if(!$)$=m0(f1.cwd(),"app/Models");let X=Z.dialect||b.dialect||"postgres",_=p8(),Y=await w4({modelsDir:$}),L=T4(Y,{dialect:X}),z;if(!Z.full)if(z=ZU(_,X),z)console.log("-- Comparing with stored model snapshot");else{let E=m0($,`.qb-migrations.${X}.json`),G=String(Z.state||E);if(o9(G))try{let F=h2(G,"utf8"),O=JSON.parse(F);if(z=O?.plan&&O.plan.tables?O.plan:O?.tables?O:void 0,z)console.log("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!z)console.log("-- No previous snapshot found, generating full migration")}else console.log("-- Full migration requested, ignoring any previous state");let j=Z.full?P4(L):ME(z,L),U=j.join(`
|
|
84
|
-
`),Q=j.some((E)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(E));if(Z.apply){let E=tz(m0($U(),"qb-migrate-")),G=m0(E,"migration.sql");try{if(Q)v2(G,U),console.log("-- Migration applied");else console.log("-- No changes; nothing to apply")}catch(F){throw console.error("-- Migration failed:",F),F}}return XU(_,X,L),{sql:U,sqlStatements:j,hasChanges:Q,plan:L}}async function S6($){if(!$)$=m0(f1.cwd(),"app/Models");let Z=p8(),X=_U(Z),_=b.dialect||"postgres",L=y2(X).filter((z)=>z.endsWith(".sql")).sort();if(L.length===0)return console.log("-- No migration files found to execute"),!0;console.log(`-- Found ${L.length} script files to execute`);try{let z=F9();await LU(z,_);let j=await zU(z,_),U=[],Q=[];for(let G of L)if(G.includes("alter-")&&G.includes("-table"))Q.push(G);else if(!j.includes(G))U.push(G);let E=U.length+Q.length;if(E===0)return console.log("-- No pending migrations to execute"),!0;console.log(`-- Executing ${E} migrations (${U.length} permanent, ${Q.length} transient)`);for(let G of U){let F=m0(X,G);console.log(`-- Executing: ${G}`);try{await z.file(F),await UU(z,G,_),console.log(`-- \u2713 Migration ${G} executed and recorded`)}catch(O){throw console.error(`-- \u2717 Migration ${G} failed:`,O),O}}for(let G of Q){let F=m0(X,G);console.log(`-- Executing: ${G} (transient)`);try{await z.file(F),console.log(`-- \u2713 Migration ${G} executed (not recorded)`),p$(F),console.log(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${G}`)}catch(O){throw console.error(`-- \u2717 Migration ${G} failed:`,O),O}}console.log("-- All migrations executed successfully")}catch(z){throw console.error("-- Migration execution failed:",z),z}return!0}async function M6($,Z={}){if(!$)$=m0(f1.cwd(),"app/Models");let X=Z.dialect||"postgres",_=g8(X),Y=p8();try{let L=_.dropTable("migrations");try{await TZ(async(U)=>{await U.unsafe(L).execute(),console.log("-- Dropped migrations table")})}catch(U){console.error(U)}let z=[],j=[];try{let U=await w4({modelsDir:$}),Q=T4(U,{dialect:X});z=Q.tables.map((G)=>G.table);let E=new Set;for(let G of Q.tables)for(let F of G.columns)if(F.type==="enum"&&F.enumValues&&F.enumValues.length>0){let O=`${F.name}_type`;E.add(O)}j=Array.from(E)}catch(U){console.error(U),z=[],j=[]}if(z.length===0)console.log("-- No tables found to drop");else{console.log(`-- Dropping ${z.length} tables: ${z.join(", ")}`);for(let U of z.reverse())try{let Q=_.dropTable(U);await TZ(async(E)=>{await E.unsafe(Q).execute(),console.log(`-- Dropped table: ${U}`)})}catch(Q){console.error(Q),console.log(`-- Table ${U} may not exist, skipping drop`)}}if(j.length>0){console.log(`-- Dropping ${j.length} enum types: ${j.join(", ")}`);for(let U of j)try{let Q=_.dropEnumType(U);if(Q)await TZ(async(E)=>{await E.unsafe(Q).execute(),console.log(`-- Dropped enum type: ${U}`)})}catch(Q){console.error(Q),console.log(`-- Enum type ${U} may not exist, skipping drop`)}}else console.log("-- No enum types found to drop");try{await b2($,Y,Z)}catch(U){console.error(U),console.log("-- Could not clean up migration files")}try{await f2(Y)}catch(U){console.error(U),console.log("-- Could not clear generated directory")}return console.log("-- Database reset completed successfully"),!0}catch(L){return console.error("-- Database reset failed:",L),!1}}async function b2($,Z,X={}){if(!$)$=m0(f1.cwd(),"app/Models");if(!Z)Z=p8();let _=String(X.dialect||"postgres"),Y=R6(Z,_);if(o9(Y))p$(Y),console.log(`-- Removed model snapshot file: ${Y}`);let L=m0($,`.qb-migrations.${_}.json`),z=String(X.state||L);if(o9(z))p$(z),console.log(`-- Removed legacy migration state file: ${z}`);let j=g2(Z);if(o9(j)){let Q=y2(j).filter((E)=>E.endsWith(".sql"));for(let E of Q){let G=m0(j,E);p$(G),console.log(`-- Removed migration file: ${E}`)}console.log(`-- Cleaned up ${Q.length} migration files from migrations directory`)}}async function YU($,Z){}async function f2($){if(!$)$=p8();let Z=m0($,"generated");if(o9(Z))try{ez(Z,{recursive:!0,force:!0}),console.log("-- Cleared generated directory")}catch(X){console.error("-- Failed to clear generated directory:",X)}}function g2($){if(!$)$=p8();return m0($,"database","migrations")}async function LU($,Z){let _=g8(Z).createMigrationsTable();try{await $.unsafe(_).execute(),console.log("-- Migrations table ready")}catch(Y){throw console.error("-- Failed to create migrations table:",Y),Y}}async function zU($,Z){let X=g8(Z);try{return(await $.unsafe(X.getExecutedMigrationsQuery()).execute()).map((Y)=>Y.migration)}catch(_){return console.error("-- Failed to get executed migrations:",_),[]}}async function UU($,Z,X){let _=g8(X);try{console.log(`-- Recording migration: ${Z}`),await $.unsafe(_.recordMigrationQuery(),[Z]).execute(),console.log(`-- Successfully recorded migration: ${Z}`)}catch(Y){throw console.error(`-- Failed to record migration ${Z}:`,Y),Y}}class m2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let X=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${X}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,X],[,_])=>X.timestamp.getTime()-_.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let X=0;X<Z;X++)this.cache.delete($[X][0])}set($,Z,X,_){if(!this.options.enabled)return;let Y=this.generateKey($,X),L=_??this.options.ttl,z=this.estimateSize(Z);this.cache.set(Y,{value:Z,timestamp:new Date,ttl:L,hits:0,size:z}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey($,Z),_=this.cache.get(X);if(!_){this.totalMisses++;return}if(this.isExpired(_)){this.cache.delete(X),this.totalMisses++;return}return _.hits++,this.totalHits++,_.value}isFileModified($,Z){try{if(!GX($))return!0;return FX($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let X=this.get($,Z);if(!X)return;if(this.isFileModified(Z,X.fileTimestamp)){this.delete($,Z);return}return X.value}setWithFileCheck($,Z,X,_){try{let Y=GX(X)?FX(X):null,L=Y?Y.mtime:new Date;this.set($,{value:Z,fileTimestamp:L},X,_)}catch{this.set($,Z,X,_)}}delete($,Z){let X=this.generateKey($,Z);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((_,Y)=>_+Y.size,0),X=$.map((_)=>_.timestamp).sort();return{size:Z,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:X[0],newestEntry:X[X.length-1]}}export(){let $={};for(let[Z,X]of this.cache.entries())$[Z]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return $}import($){this.cache.clear();for(let[Z,X]of Object.entries($))if(typeof X==="object"&&X!==null){let _=X;this.cache.set(Z,{value:_.value,timestamp:new Date(_.timestamp),ttl:_.ttl,hits:_.hits,size:_.size})}}}class s2{metrics=[];maxMetrics=1000;async track($,Z,X={}){let _=performance.now(),Y=new Date;try{let L=await Z(),z=performance.now()-_;return this.recordMetric({operation:$,duration:z,timestamp:Y,...X}),L}catch(L){let z=performance.now()-_;throw this.recordMetric({operation:`${$}:error`,duration:z,timestamp:Y,...X}),L}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=Z.map((Y)=>Y.duration),_=X.reduce((Y,L)=>Y+L,0);return{count:Z.length,averageDuration:_/Z.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:_,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function w6($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&I0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&I0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(I0(Z)&&I0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(I0($)&&"arr"in $&&Array.isArray($.arr)&&I0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&I0(Z[0])&&I0($[0])){let _=[...Z];for(let Y of $)if(I0(Y)&&"name"in Y){if(!_.find((L)=>I0(L)&&("name"in L)&&L.name===Y.name))_.push(Y)}else if(I0(Y)&&"path"in Y){if(!_.find((L)=>I0(L)&&("path"in L)&&L.path===Y.path))_.push(Y)}else if(!_.some((L)=>Q5(L,Y)))_.push(Y);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}if(!I0(Z)||!I0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let Y=Z[_];if(Y===null||Y===void 0)continue;else if(I0(Y)&&I0(X[_]))X[_]=w6(X[_],Y);else if(Array.isArray(Y)&&Array.isArray(X[_]))if(Y.length>0&&X[_].length>0&&I0(Y[0])&&I0(X[_][0])){let L=[...Y];for(let z of X[_])if(I0(z)&&"name"in z){if(!L.find((j)=>I0(j)&&("name"in j)&&j.name===z.name))L.push(z)}else if(I0(z)&&"path"in z){if(!L.find((j)=>I0(j)&&("path"in j)&&j.path===z.path))L.push(z)}else if(!L.some((j)=>Q5(j,z)))L.push(z);X[_]=L}else if(Y.every((L)=>typeof L==="string")&&X[_].every((L)=>typeof L==="string")){let L=[...Y];for(let z of X[_])if(!L.includes(z))L.push(z);X[_]=L}else X[_]=Y;else X[_]=Y}return X}function Q5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!Q5($[X],Z[X]))return!1;return!0}if(I0($)&&I0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!Q5($[Y],Z[Y]))return!1}return!0}return!1}function I0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iU($,Z){if(!d2($))return null;try{let X=await import($),_=X.default||X;if(typeof _!=="object"||_===null||Array.isArray(_))return null;try{return w6(Z,_)}catch{return null}}catch{return null}}async function rU({name:$="",cwd:Z,defaultConfig:X}){let _=Z||X6.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],L=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let z of L)for(let j of Y){let U=O5(_,`${z}${j}`),Q=await iU(U,X);if(Q!==null)return Q}try{let z=O5(_,"package.json");if(d2(z)){let j=(await import(z))[$];if(j&&typeof j==="object"&&!Array.isArray(j))try{return w6(X,j)}catch{}}}catch{}return X}function oU($,Z={}){let X=E5.cwd();while(X.includes("storage"))X=WX(X,"..");let _=WX(X,$||"");if(Z?.relative)return NU(E5.cwd(),_);return _}async function aU(){try{let $=await rU({name:"clarity",defaultConfig:d$,cwd:E5.cwd(),endpoint:"",headers:{}});return{...d$,...$}}catch{return d$}}function M0(){if(v9.env.NODE_ENV==="test"||v9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tU(){if(v9.env.NODE_ENV==="test"||v9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v9<"u"){let $=v9.type;if($==="renderer"||$==="worker")return!1;return!!(v9.versions&&(v9.versions.node||v9.versions.bun))}return!1}class l2{async format($){let Z=await tU(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:P8.pid,hostname:Z(),environment:P8.env.NODE_ENV||"development",platform:P8.platform,version:P8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:P8.env.NODE_ENV||P8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class G5{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($,Z={}){this.name=$,this.config={...Y6},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new l2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??v0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),L=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,L),this.encryptionKeys.set(Y,{key:L,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...u$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...u$};return{...u$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:Y6.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}async writeToFile($){let Z=(async()=>{let _,Y=0,L=3,z=1000;while(Y<L)try{try{try{await AU(this.config.logDirectory,DX.F_OK|DX.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await yU(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let j=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:i9.from($);try{if(!CZ(this.currentLogFile))await xZ(this.currentLogFile,"",{mode:420});if(_=JX(this.currentLogFile,"a",420),BU(_,j,{flag:"a"}),IX(_),_!==void 0)kZ(_),_=void 0;if((await q8(this.currentLogFile)).size===0){if(await xZ(this.currentLogFile,j,{flag:"w",mode:420}),(await q8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(U){let Q=U;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(Y<L-1){let E=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${L}:`,E);let G=z*2**Y;await new Promise((F)=>setTimeout(F,G)),Y++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(_!==void 0)try{kZ(_)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(j){if(Y===L-1){let Q=j,E=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),j}Y++;let U=z*2**(Y-1);await new Promise((Q)=>setTimeout(Q,U))}})();this.pendingOperations.push(Z);let X=this.pendingOperations.length-1;try{await Z}catch(_){throw console.error("Debug: [writeToFile] Error in operation:",_),_}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return T8(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 T8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return T8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,X=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((_)=>{console.error("Error rotating keys:",_)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,X),this.encryptionKeys.set(Z,{key:X,createdAt:new Date});let _=Array.from(this.encryptionKeys.entries()).sort(([,z],[,j])=>j.createdAt.getTime()-z.createdAt.getTime()),Y=typeof $.maxKeys==="number"?$.maxKeys:1,L=Math.max(1,Y);if(_.length>L)for(let[z]of _.slice(L))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return NZ(16).toString("hex")}generateKey(){return NZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=NZ(16),_=kU("aes-256-gcm",Z,X),Y=i9.concat([_.update($,"utf8"),_.final()]),L=_.getAuthTag();return{encrypted:i9.concat([X,Y,L]),iv:X}}async compressData($){return new Promise((Z,X)=>{let _=SX(),Y=[];_.on("data",(L)=>Y.push(L)),_.on("end",()=>Z(i9.from(i9.concat(Y)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(M0())return;let $=await q8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await D$(this.config.logDirectory),L=Y.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,Q)=>{let E=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),z=L.length>0?Number.parseInt(L[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${X}.${z}`;if(await q8(X).catch(()=>null))try{if(await RX(X,j),Z.compress)try{let U=`${j}.gz`;await this.compressLogFile(j,U),await R$(j)}catch(U){console.error("Error compressing rotated file:",U)}if(L.length===0&&!Y.some((U)=>U.endsWith(".log.1")))try{let U=`${X}.1`;await xZ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),L=X.replace(/\.log$/,`-${Y}.log`);if(await q8(X).catch(()=>null))await RX(X,L)}if(this.currentLogFile=_,Z.maxFiles){let Y=(await D$(this.config.logDirectory)).filter((L)=>L.startsWith(this.name)).sort((L,z)=>z.localeCompare(L));for(let L of Y.slice(Z.maxFiles))await R$(T8(this.config.logDirectory,L))}}}async compressLogFile($,Z){let X=KX($),_=xU(Z),Y=SX();await hU(X,Y,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);await this.writeToFile(_),console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(Z),console.log(Z);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:$,message:Z,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),CZ(this.currentLogFile))try{let $=JX(this.currentLogFile,"r+");IX($),kZ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await D$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await R$(T8(this.config.logDirectory,Z))}catch(X){console.error(`Failed to delete temp file ${Z}:`,X)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?V0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:Y,level:L,showTimestamp:z=!0}=$,j=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(z)O.push(Z);if(L==="warning")O.push("WARN");else if(L==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(Y),O.join(" ")}let U=v0.stdout.columns||120,Q="";if(L==="warning"||L==="error")Q=`${X} ${Y}`;else if(L==="info"||L==="success")Q=`${X} ${_} ${Y}`;else Q=`${X} ${_} ${V0.cyan(Y)}`;if(!z)return Q.trim();let E=j(Q).trim().length,G=j(Z).length,F=Math.max(1,U-2-E-G);return`${Q.trim()}${" ".repeat(F)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(L,z)=>{let j=Number.parseInt(z,10);return j<Z[0].length?String(Z[0][j]):L});let X=/%([sdijfo%])/g,_=0,Y=$.replace(X,(L,z)=>{if(z==="%")return"%";if(_>=Z.length)return L;let j=Z[_++];switch(z){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return L}});if(_<Z.length)Y+=` ${Z.slice(_).map((L)=>typeof L==="object"?JSON.stringify(L,null,2):String(L)).join(" ")}`;return Y}async log($,Z,...X){let _=new Date,Y=this.formatConsoleTimestamp(_),L=this.formatFileTimestamp(_),z,j;if(Z instanceof Error)z=Z.message,j=Z.stack;else z=this.formatMessage(Z,X);if(this.fancy&&!M0()){let Q=_4[$],E=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:V0.gray(z),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:z,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:V0.green(z),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:z,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:Y,icon:Q,tag:E,message:z,level:$}),console.error(G),j){let F=j.split(`
|
|
85
|
-
`);for(let O of F)if(O.trim()&&!O.includes(z))console.error(this.formatConsoleMessage({timestamp:Y,message:V0.gray(` ${O}`),level:$,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${L} ${this.environment}.${$.toUpperCase()}: ${z}`),j)console.error(j)}if(!this.shouldLog($))return;let U=`${L} ${this.environment}.${$.toUpperCase()}: ${z}
|
|
86
|
-
`;if(j)U+=`${j}
|
|
87
|
-
`;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let Z=performance.now();if(this.fancy&&!M0()){let X=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:V0.blue("\u25D0"),tag:X,message:`${V0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),Y=Math.round(_-Z),L=`${$} completed in ${Y}ms`,z=new Date,j=this.formatConsoleTimestamp(z),U=`${this.formatFileTimestamp(z)} ${this.environment}.INFO: ${L}`;if(X)U+=` ${JSON.stringify(X)}`;if(U+=`
|
|
88
|
-
`,U=U.replace(this.ANSI_PATTERN,""),this.fancy&&!M0()){let Q=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:V0.green("\u2713"),tag:Q,message:`${L}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!M0())console.error(U.trim());await this.writeToFile(U)}}async debug($,...Z){await this.log("debug",$,...Z)}async info($,...Z){await this.log("info",$,...Z)}async success($,...Z){await this.log("success",$,...Z)}async warn($,...Z){await this.log("warning",$,...Z)}async error($,...Z){await this.log("error",$,...Z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new G5(Z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!CZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return KX(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=i9.isBuffer($)?$:i9.from($,"base64"),Y=_.slice(0,16),L=_.slice(-16),z=_.slice(16,-16),j=CU("aes-256-gcm",X,Y);return j.setAuthTag(L),i9.concat([j.update(z),j.final()]).toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey($,Z){this.currentKeyId=$,this.keys.set($,Z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z);if(this.fancy&&!M0()){let L=$.split(`
|
|
89
|
-
`),z=Math.max(...L.map((E)=>E.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,U=`\u2514${"\u2500".repeat(z)}\u2518`,Q=L.map((E)=>{let G=" ".repeat(z-E.length-2);return`\u2502 ${E}${G} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:V0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:V0.cyan(j)})),Q.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:X,message:V0.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:V0.cyan(U),showTimestamp:!1}))}else if(!M0())console.error(`${_} ${this.environment}.INFO: [BOX] ${$}`);let Y=`${_} ${this.environment}.INFO: [BOX] ${$}
|
|
90
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt($){if(M0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${V0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let Y=_.toString().trim().toLowerCase();v0.stdin.removeListener("data",X);try{if(typeof v0.stdin.setRawMode==="function")v0.stdin.setRawMode(!1)}catch{}v0.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof v0.stdin.setRawMode==="function")v0.stdin.setRawMode(!0)}catch{}v0.stdin.resume(),v0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let Y=/%([sdijfo%])/g,L=0;if(X=$.replace(Y,(z,j)=>{if(j==="%")return"%";if(L>=Z.length)return z;let U=Z[L++];switch(j){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return z}}),L<Z.length)X+=` ${Z.slice(L).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}if(this.fancy&&!M0()){let Y=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"",L=V0.blue("\u25D0");console.error(`${L} ${Y} ${V0.cyan(X)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
91
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress($,Z=""){if(!this.enabled||!this.fancy||M0()||$<=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 X=20;return this.activeProgressBar={total:$,current:0,message:Z,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(_,Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||M0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,_)),Y!==void 0)this.activeProgressBar.message=Y;let L=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,L)},finish:(_)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||M0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,_!==void 0)this.activeProgressBar.message=_;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(_,Y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||M0())return;v0.stdout.write(`${"\r".padEnd(v0.stdout.columns||80)}\r`),this.log(Y,_),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,Z=!1){if(!this.enabled||!this.fancy||M0()||!v0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),Y=$.barLength-_,L=V0.green("\u2501".repeat(_)),z=V0.gray("\u2501".repeat(Y)),j=`[${L}${z}]`,U=`${X}%`.padStart(4),Q=$.message?` ${$.message}`:"",E=Z||X===100?V0.green("\u2713"):V0.blue("\u25B6"),G=this.options.showTags!==!1&&this.name?` ${V0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${G} ${j} ${U}${Q}`,O=v0.stdout.columns||80,K=" ".repeat(Math.max(0,O-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${K}`,v0.stdout.write($.lastRenderedLine),Z)v0.stdout.write(`
|
|
92
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||M0()||!v0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await D$(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let Y=T8(this.config.logDirectory,_);if($.before)try{if((await q8(Y)).mtime>=$.before)continue}catch(L){console.error(`Failed to get stats for file ${Y}:`,L);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await R$(_),console.warn(`Deleted log file: ${_}`)}catch(Y){console.error(`Failed to delete log file ${_}:`,Y)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}function c$($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&E0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&E0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(E0(Z)&&E0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(E0($)&&"arr"in $&&Array.isArray($.arr)&&E0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&E0(Z[0])&&E0($[0])){let _=[...Z];for(let Y of $)if(E0(Y)&&"name"in Y){if(!_.find((L)=>E0(L)&&("name"in L)&&L.name===Y.name))_.push(Y)}else if(E0(Y)&&"path"in Y){if(!_.find((L)=>E0(L)&&("path"in L)&&L.path===Y.path))_.push(Y)}else if(!_.some((L)=>F5(L,Y)))_.push(Y);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}if(!E0(Z)||!E0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let Y=Z[_];if(Y===null||Y===void 0)continue;else if(E0(Y)&&E0(X[_]))X[_]=c$(X[_],Y);else if(Array.isArray(Y)&&Array.isArray(X[_]))if(Y.length>0&&X[_].length>0&&E0(Y[0])&&E0(X[_][0])){let L=[...Y];for(let z of X[_])if(E0(z)&&"name"in z){if(!L.find((j)=>E0(j)&&("name"in j)&&j.name===z.name))L.push(z)}else if(E0(z)&&"path"in z){if(!L.find((j)=>E0(j)&&("path"in j)&&j.path===z.path))L.push(z)}else if(!L.some((j)=>F5(j,z)))L.push(z);X[_]=L}else if(Y.every((L)=>typeof L==="string")&&X[_].every((L)=>typeof L==="string")){let L=[...Y];for(let z of X[_])if(!L.includes(z))L.push(z);X[_]=L}else X[_]=Y;else X[_]=Y}return X}function H6($,Z,X="replace"){if(Z===null||Z===void 0)return $;if(Array.isArray(Z))return X==="replace"?Z:c$($,Z);if(Array.isArray($))return X==="replace"?Z:c$($,Z);if(!E0(Z)||!E0($))return Z;let _={...$};for(let Y of Object.keys(Z)){if(!Object.prototype.hasOwnProperty.call(Z,Y))continue;let L=Z[Y],z=_[Y];if(L===null||L===void 0)continue;if(Array.isArray(L)||Array.isArray(z))if(X==="replace")_[Y]=L;else _[Y]=c$(z,L);else if(E0(L)&&E0(z))_[Y]=H6(z,L,X);else _[Y]=L}return _}function F5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!F5($[X],Z[X]))return!1;return!0}if(E0($)&&E0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!F5($[Y],Z[Y]))return!1}return!0}return!1}function E0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function T$($,Z,X="replace"){if(!c2($))return null;try{let _=await import($),Y=_.default||_;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return H6(Z,Y,X)}catch{return null}}catch{return null}}function eU($,Z,X=!1){if(!$)return Z;let _=$.toUpperCase().replace(/-/g,"_"),Y={...Z};function L(z,j=[]){let U={...z};for(let[Q,E]of Object.entries(z)){let G=[...j,Q],F=(W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${_}_${G.map(F).join("_")}`,K=`${_}_${G.map((W)=>W.toUpperCase()).join("_")}`;if(X)g0.info(`Checking environment variable ${O} for config ${$}.${G.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))U[Q]=L(E,G);else{let W=A1.env[O]||A1.env[K];if(W!==void 0){if(X)g0.info(`Using environment variable ${W?O:K} for config ${$}.${G.join(".")}`);if(typeof E==="number")U[Q]=Number(W);else if(typeof E==="boolean")U[Q]=W.toLowerCase()==="true";else if(Array.isArray(E))try{let w=JSON.parse(W);if(Array.isArray(w))U[Q]=w;else U[Q]=W.split(",").map((J)=>J.trim())}catch{U[Q]=W.split(",").map((w)=>w.trim())}else U[Q]=W}}}return U}return L(Y)}async function $j({name:$="",alias:Z,cwd:X,configDir:_,defaultConfig:Y,verbose:L=!1,checkEnv:z=!0,arrayStrategy:j="replace"}){let U=z&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?eU($,Y,L):Y,Q=X||A1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(L)g0.info(`Loading configuration for "${$}"${Z?` (alias: "${Z}")`:""} from ${Q}`);let G=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),O=Z?[Z,`.${Z}`]:[],K=Z?[`${Z}.config`,`.${Z}.config`]:[],W=Array.from(new Set([Q,t0(Q,"config"),t0(Q,".config"),_?t0(Q,_):void 0].filter(Boolean)));for(let w of W){if(L)g0.info(`Searching for configuration in: ${w}`);let J=[t0(Q,"config"),t0(Q,".config")].concat(_?[t0(Q,_)]:[]).includes(w)?[...G,...F,...O,...K]:[...F,...G,...K,...O];for(let R of J)for(let M of E){let q=t0(w,`${R}${M}`),N=await T$(q,U,j);if(N!==null){if(L)g0.success(`Configuration loaded from: ${q}`);return N}}}if($){let w=t0(PZ(),".config",$),J=["config",`${$}.config`];if(Z)J.push(`${Z}.config`);if(L)g0.info(`Checking user config directory: ${w}`);for(let R of J)for(let M of E){let q=t0(w,`${R}${M}`),N=await T$(q,U,j);if(N!==null){if(L)g0.success(`Configuration loaded from user config directory: ${q}`);return N}}}if($){let w=t0(PZ(),".config"),J=[`.${$}.config`];if(Z)J.push(`.${Z}.config`);if(L)g0.info(`Checking user config directory for dotfile configs: ${w}`);for(let R of J)for(let M of E){let q=t0(w,`${R}${M}`),N=await T$(q,U,j);if(N!==null){if(L)g0.success(`Configuration loaded from user config directory dotfile: ${q}`);return N}}}if($){let w=PZ(),J=[`.${$}.config`,`.${$}`];if(Z)J.push(`.${Z}.config`),J.push(`.${Z}`);if(L)g0.info(`Checking user home directory for dotfile configs: ${w}`);for(let R of J)for(let M of E){let q=t0(w,`${R}${M}`),N=await T$(q,U,j);if(N!==null){if(L)g0.success(`Configuration loaded from user home directory: ${q}`);return N}}}try{let w=t0(Q,"package.json");if(c2(w)){let J=await import(w),R=J[$];if(!R&&Z){if(R=J[Z],R&&L)g0.success(`Using alias "${Z}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(L)g0.success(`Configuration loaded from package.json: ${R===J[$]?$:Z}`);return H6(U,R,j)}catch(M){if(L)g0.warn("Failed to merge package.json config:",M)}}}catch(w){if(L)g0.warn("Failed to load package.json:",w)}if(L)g0.info(`No configuration found for "${$}"${Z?` or alias "${Z}"`:""}, using default configuration with environment variables`);return U}function Zj($,Z={}){let X=j5.cwd();while(X.includes("storage"))X=VX(X,"..");let _=VX(X,$||"");if(Z?.relative)return TU(j5.cwd(),_);return _}async function Xj(){try{let $=await $j({name:"clarity",alias:"logging",defaultConfig:m$,cwd:j5.cwd()});return{...m$,...$||{}}}catch{return m$}}function C0(){if(b9.env.NODE_ENV==="test"||b9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _j(){if(b9.env.NODE_ENV==="test"||b9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b9<"u"){let $=b9.type;if($==="renderer"||$==="worker")return!1;return!!(b9.versions&&(b9.versions.node||b9.versions.bun))}return!1}class n2{async format($){let Z=await _j(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:C8.pid,hostname:Z(),environment:C8.env.NODE_ENV||"development",platform:C8.platform,version:C8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:C8.env.NODE_ENV||C8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class V5{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,Z={}){this.name=$,this.config={...L6},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new n2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??U0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),L=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,L),this.encryptionKeys.set(Y,{key:L,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[X]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...s$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...s$};return{...s$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:L6.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}shouldWriteToFile(){return!C0()&&this.config.writeToFile===!0}async writeToFile($){let Z=(async()=>{let _,Y=0,L=3,z=1000;while(Y<L)try{try{try{await pU(this.config.logDirectory,qX.F_OK|qX.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await cU(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let j=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:B9.from($);try{if(!S$(this.currentLogFile))await yZ(this.currentLogFile,"",{mode:420});if(_=HX(this.currentLogFile,"a",420),gU(_,j,{flag:"a"}),wX(_),_!==void 0)AZ(_),_=void 0;if((await N8(this.currentLogFile)).size===0){if(await yZ(this.currentLogFile,j,{flag:"w",mode:420}),(await N8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(U){let Q=U;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(Y<L-1){let E=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${L}:`,E);let G=z*2**Y;await new Promise((F)=>setTimeout(F,G)),Y++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(_!==void 0)try{AZ(_)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(j){if(Y===L-1){let Q=j,E=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),j}Y++;let U=z*2**(Y-1);await new Promise((Q)=>setTimeout(Q,U))}})();this.pendingOperations.push(Z);let X=this.pendingOperations.length-1;try{await Z}catch(_){throw console.error("Debug: [writeToFile] Error in operation:",_),_}finally{this.pendingOperations.splice(X,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return k8(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 k8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return k8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(C0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,X=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((_)=>{console.error("Error rotating keys:",_)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,X),this.encryptionKeys.set(Z,{key:X,createdAt:new Date});let _=Array.from(this.encryptionKeys.entries()).sort(([,z],[,j])=>j.createdAt.getTime()-z.createdAt.getTime()),Y=typeof $.maxKeys==="number"?$.maxKeys:1,L=Math.max(1,Y);if(_.length>L)for(let[z]of _.slice(L))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return BZ(16).toString("hex")}generateKey(){return BZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=BZ(16),_=vU("aes-256-gcm",Z,X),Y=B9.isBuffer($)?$:B9.from($,"utf8"),L=_.update(Y),z=_.final(),j=L.length+z.length,U=_.getAuthTag(),Q=B9.allocUnsafe(16+j+16);return X.copy(Q,0),L.copy(Q,16),z.copy(Q,16+L.length),U.copy(Q,16+j),{encrypted:Q,iv:X}}async compressData($){return new Promise((Z,X)=>{let _=PX(),Y=[];_.on("data",(L)=>Y.push(L)),_.on("end",()=>Z(B9.from(B9.concat(Y)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(C0())return;if(!this.shouldWriteToFile())return;let $=await N8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await M$(this.config.logDirectory),L=Y.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,Q)=>{let E=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),z=L.length>0?Number.parseInt(L[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${X}.${z}`;if(await N8(X).catch(()=>null))try{if(await TX(X,j),Z.compress)try{let U=`${j}.gz`;await this.compressLogFile(j,U),await w$(j)}catch(U){console.error("Error compressing rotated file:",U)}if(L.length===0&&!Y.some((U)=>U.endsWith(".log.1")))try{let U=`${X}.1`;await yZ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),L=X.replace(/\.log$/,`-${Y}.log`);if(await N8(X).catch(()=>null))await TX(X,L)}if(this.currentLogFile=_,Z.maxFiles){let Y=(await M$(this.config.logDirectory)).filter((L)=>L.startsWith(this.name)).sort((L,z)=>z.localeCompare(L));for(let L of Y.slice(Z.maxFiles))await w$(k8(this.config.logDirectory,L))}}}async compressLogFile($,Z){let X=MX($),_=fU(Z),Y=PX();await mU(X,Y,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(_);console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),S$(this.currentLogFile))try{let $=HX(this.currentLogFile,"r+");wX($),AZ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!C0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await M$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await w$(k8(this.config.logDirectory,Z))}catch(X){console.error(`Failed to delete temp file ${Z}:`,X)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?z0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||C0())return!1;let $=typeof U0.env.NO_COLOR<"u",Z=U0.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof U0.stderr<"u"&&U0.stderr.isTTY||typeof U0.stdout<"u"&&U0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:Y,level:L,showTimestamp:z=!0}=$,j=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(z)O.push(Z);if(L==="warning")O.push("WARN");else if(L==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(Y),O.join(" ")}let U=U0.stdout.columns||120,Q="";if(L==="warning"||L==="error")Q=`${X} ${Y}`;else if(L==="info"||L==="success")Q=`${X} ${_} ${Y}`;else Q=`${X} ${_} ${z0.cyan(Y)}`;if(!z)return Q.trim();let E=j(Q).trim().length,G=j(Z).length,F=Math.max(1,U-2-E-G);return`${Q.trim()}${" ".repeat(F)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(L,z)=>{let j=Number.parseInt(z,10);return j<Z[0].length?String(Z[0][j]):L});let X=/%([sdijfo%])/g,_=0,Y=$.replace(X,(L,z)=>{if(z==="%")return"%";if(_>=Z.length)return L;let j=Z[_++];switch(z){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return L}});if(_<Z.length)Y+=` ${Z.slice(_).map((L)=>typeof L==="object"?JSON.stringify(L,null,2):String(L)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,_,Y)=>{let L=z0.underline(z0.blue(_)),z=this.toAbsoluteFilePath(Y);if(z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(z)}`,U="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${L}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${L}\x1B]8;;\x1B\\`;return L}),Z=Z.replace(/`([^`]+)`/g,(X,_)=>z0.bgGray(_)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(X,_)=>z0.bold(_)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,_)=>z0.italic(_)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,_)=>z0.italic(_)),Z=Z.replace(/~([^~]+)~/g,(X,_)=>z0.strikethrough(_)),Z}supportsHyperlinks(){if(C0())return!1;let $=U0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let X=U0.env.HOME||"";if(X)Z=Z.replace(/^~(?=$|\/)/,X)}if(dU(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=uU(Z);else return null;return S$(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,X=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:X}}async log($,Z,...X){let _=new Date,Y=this.formatConsoleTimestamp(_),L=this.formatFileTimestamp(_),z,j;if(Z instanceof Error)z=Z.message,j=Z.stack;else z=this.formatMessage(Z,X);let{consoleText:U,fileText:Q}=this.buildOutputTexts(z);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":Y4[$],F=this.options.showTags!==!1&&this.name?z0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:z0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:z0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Y,icon:G,tag:F,message:U,level:$}),console.error(O),j){let K=j.split(`
|
|
93
|
-
`);for(let W of K)if(W.trim()&&!W.includes(z))console.error(this.formatConsoleMessage({timestamp:Y,message:z0.gray(` ${W}`),level:$,showTimestamp:!1}))}break}}else if(!C0()){if(console.error(`${L} ${this.environment}.${$.toUpperCase()}: ${z}`),j)console.error(j)}if(!this.shouldLog($))return;let E=`${L} ${this.environment}.${$.toUpperCase()}: ${Q}
|
|
94
|
-
`;if(j)E+=`${j}
|
|
95
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,Z=""){let X={update:(Y,L)=>{},finish:(Y)=>{},interrupt:(Y,L)=>{}};if(!this.enabled)return X;let _=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:_,lastRenderedLine:""},this.shouldStyleConsole()&&!C0()&&U0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Y,L)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Y),this.activeProgressBar.total),L!==void 0)this.activeProgressBar.message=L;if(this.shouldStyleConsole()&&!C0()&&U0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Y)},interrupt:(Y,L="info")=>{if(!C0()&&U0.stdout.isTTY)U0.stdout.write(`
|
|
96
|
-
`);if(this[L==="warning"?"warn":L](Y),this.activeProgressBar&&this.shouldStyleConsole()&&!C0()&&U0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?z0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":z0.blue("\u25D0"),tag:X,message:`${z0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),Y=Math.round(_-Z),L=`${$} completed in ${Y}ms`,z=new Date,j=this.formatConsoleTimestamp(z),U=`${this.formatFileTimestamp(z)} ${this.environment}.INFO: ${L}`;if(X)U+=` ${JSON.stringify(X)}`;if(U+=`
|
|
97
|
-
`,U=U.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?z0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":z0.green("\u2713"),tag:Q,message:`${L}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!C0())console.error(U.trim());if(this.shouldWriteToFile())await this.writeToFile(U)}}async debug($,...Z){await this.log("debug",$,...Z)}async info($,...Z){await this.log("info",$,...Z)}async success($,...Z){await this.log("success",$,...Z)}async warn($,...Z){await this.log("warning",$,...Z)}async error($,...Z){await this.log("error",$,...Z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new V5(Z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(C0())throw Error("createReadStream is not supported in browser environments");if(!S$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return MX(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=B9.isBuffer($)?$:B9.from($,"base64"),Y=_.subarray(0,16),L=_.subarray(_.length-16),z=_.subarray(16,_.length-16),j=bU("aes-256-gcm",X,Y);j.setAuthTag(L);let U=j.update(z),Q=j.final(),E=U.length+Q.length,G=B9.allocUnsafe(E);return U.copy(G,0),Q.copy(G,U.length),G.toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return C0()}isServerMode(){return!C0()}setTestEncryptionKey($,Z){this.currentKeyId=$,this.keys.set($,Z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),{consoleText:Y,fileText:L}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let j=Y.split(`
|
|
98
|
-
`),U=Math.max(...j.map((F)=>F.length))+2,Q=`\u250C${"\u2500".repeat(U)}\u2510`,E=`\u2514${"\u2500".repeat(U)}\u2518`,G=j.map((F)=>{return this.formatConsoleMessage({timestamp:X,message:z0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:z0.cyan(Q),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:X,message:z0.cyan(E),showTimestamp:!1}))}else if(!C0())console.error(`${_} ${this.environment}.INFO: [BOX] ${L}`);let z=`${_} ${this.environment}.INFO: [BOX] ${L}
|
|
99
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}async prompt($){if(C0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${z0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let Y=_.toString().trim().toLowerCase();U0.stdin.removeListener("data",X);try{if(typeof U0.stdin.setRawMode==="function")U0.stdin.setRawMode(!1)}catch{}U0.stdin.pause(),console.error(""),Z(Y==="y"||Y==="yes")};try{if(typeof U0.stdin.setRawMode==="function")U0.stdin.setRawMode(!0)}catch{}U0.stdin.resume(),U0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let z=/%([sdijfo%])/g,j=0;if(X=$.replace(z,(U,Q)=>{if(Q==="%")return"%";if(j>=Z.length)return U;let E=Z[j++];switch(Q){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 U}}),j<Z.length)X+=` ${Z.slice(j).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}let{consoleText:_,fileText:Y}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?z0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${z0.blue("\u25D0")} `;console.error(`${j}${z} ${z0.cyan(_)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
100
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!U0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),Y=$.barLength-_,L=z0.green("\u2501".repeat(_)),z=z0.gray("\u2501".repeat(Y)),j=`[${L}${z}]`,U=`${X}%`.padStart(4),Q=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":Z||X===100?z0.green("\u2713"):z0.blue("\u25B6"),G=this.options.showTags!==!1&&this.name?` ${z0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${G} ${j} ${U}${Q}`,O=U0.stdout.columns||80,K=" ".repeat(Math.max(0,O-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${K}`,U0.stdout.write($.lastRenderedLine),Z)U0.stdout.write(`
|
|
101
|
-
`)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||C0()||!U0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(C0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await M$(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let Y=k8(this.config.logDirectory,_);if($.before)try{if((await N8(Y)).mtime>=$.before)continue}catch(L){console.error(`Failed to get stats for file ${Y}:`,L);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await w$(_),console.warn(`Deleted log file: ${_}`)}catch(Y){console.error(`Failed to delete log file ${_}:`,Y)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function Yj($,Z={}){let{maxRetries:X=3,retryDelay:_=1000,isRetryable:Y=()=>!0,fallback:L}=Z,z=Error("Unknown error occurred");for(let j=0;j<=X;j++)try{return await $()}catch(U){if(z=U instanceof Error?U:Error(String(U)),j===X||!Y(z))break;if(_>0)await new Promise((Q)=>setTimeout(Q,_))}if(L!==void 0)return L;throw z instanceof Error?z:Error(`Unknown error: ${String(z)}`)}class q6{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,X={}){let{prefix:_,useCamelCase:Y=!0,useBackwardCompatibility:L=!0,customParsers:z={},verbose:j=!1,trackPerformance:U=!0}=X,Q=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let E=_||this.generateEnvPrefix($),G={...Z};return this.processObject(G,[],E,{useCamelCase:Y,useBackwardCompatibility:L,customParsers:z,verbose:j,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return h5.track("applyEnvironmentVariables",Q,{configName:$});return Q()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,X,_){for(let[Y,L]of Object.entries($)){let z=[...Z,Y],j=z.map((E)=>this.formatEnvKey(E,_.useCamelCase)),U=`${X}_${j.join("_")}`,Q=_.useBackwardCompatibility?`${X}_${z.map((E)=>E.toUpperCase()).join("_")}`:null;if(_.verbose);if(typeof L==="object"&&L!==null&&!Array.isArray(L))this.processObject(L,z,X,_);else{let E=H$.env[U]||(Q?H$.env[Q]:void 0);if(E!==void 0){if(_.verbose){let G=H$.env[U]?U:Q}try{$[Y]=this.parseEnvironmentValue(E,typeof L,U,_.customParsers,_.configName)}catch(G){if(G instanceof z6)throw G;throw j8.envVar(U,E,typeof L,_.configName)}}}}}parseEnvironmentValue($,Z,X,_,Y){for(let[L,z]of Object.entries(_))try{return z($)}catch{continue}for(let L of this.defaultParsers)if(L.canParse($,Z))try{return L.parse($)}catch{throw j8.envVar(X,$,`${Z} (via ${L.name} parser)`,Y)}return $}getEnvironmentVariables($){let Z={},X=$.toUpperCase();for(let[_,Y]of Object.entries(H$.env))if(_.startsWith(X)&&Y!==void 0)Z[_]=Y;return Z}validateEnvironmentVariable($,Z,X){let _=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))_.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue($,Z,X,{})}catch(Y){_.push(`Cannot parse value "${Z}" as ${X}: ${Y}`)}return{isValid:_.length===0,errors:_}}generateEnvVarDocs($,Z,X={}){let{prefix:_,format:Y="text"}=X,L=_||this.generateEnvPrefix($),z=[];switch(this.extractEnvVarInfo(Z,[],L,z),Y){case"markdown":return this.formatAsMarkdown(z,$);case"json":return JSON.stringify(z,null,2);default:return this.formatAsText(z,$)}}extractEnvVarInfo($,Z,X,_){for(let[Y,L]of Object.entries($)){let z=[...Z,Y],j=`${X}_${z.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof L==="object"&&L!==null&&!Array.isArray(L))this.extractEnvVarInfo(L,z,X,_);else _.push({key:j,type:Array.isArray(L)?"array":typeof L,description:`Configuration for ${z.join(".")}`,example:this.generateExample(L)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let X=`Environment Variables for ${Z}:
|
|
102
|
-
|
|
103
|
-
`;for(let _ of $)X+=`${_.key}
|
|
104
|
-
`,X+=` Type: ${_.type}
|
|
105
|
-
`,X+=` Description: ${_.description}
|
|
106
|
-
`,X+=` Example: ${_.example}
|
|
107
|
-
|
|
108
|
-
`;return X}formatAsMarkdown($,Z){let X=`# Environment Variables for ${Z}
|
|
109
|
-
|
|
110
|
-
`;X+=`| Variable | Type | Description | Example |
|
|
111
|
-
`,X+=`|----------|------|-------------|----------|
|
|
112
|
-
`;for(let _ of $)X+=`| \`${_.key}\` | ${_.type} | ${_.description} | \`${_.example}\` |
|
|
113
|
-
`;return X}}function Lj($,Z,X={}){return i2($,Z,X,new WeakMap)}function i2($,Z,X,_){let{arrayMergeMode:Y="replace",skipNullish:L=!1,customMerger:z}=X;if(Z===null||Z===void 0)return L?$:Z;if(z){let j=z($,Z);if(j!==void 0)return j}if(Array.isArray(Z)||Array.isArray($))return r2($,Z,Y,_);if(!V9(Z)||!V9($))return Z;return Ej($,Z,X,_)}function r2($,Z,X,_){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(X){case"replace":return Z;case"concat":return zj($,Z);case"smart":return Uj($,Z,_);default:return Z}return Z}function zj($,Z){let X=[...Z];for(let _ of $)if(!X.some((Y)=>_6(Y,_)))X.push(_);return X}function Uj($,Z,X){if(Z.length===0)return $;if($.length===0)return Z;if(V9(Z[0])&&V9($[0]))return jj($,Z,X);if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let Y of $)if(!_.includes(Y))_.push(Y);return _}return Z}function jj($,Z,X){let _=[...Z];for(let Y of $){if(!V9(Y)){_.push(Y);continue}let L=["id","name","key","path","type"],z=!1;for(let j of L)if(j in Y){if(_.find((U)=>V9(U)&&(j in U)&&U[j]===Y[j])){z=!0;break}}if(!z)_.push(Y)}return _}function Ej($,Z,X,_){let Y=Z;if(V9(Y)&&_.has(Y))return _.get(Y);let L={...$};if(V9(Y))_.set(Y,L);for(let z in Y){if(!Object.prototype.hasOwnProperty.call(Y,z))continue;let j=Y[z],U=L[z];if(X.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){L[z]=j;continue}if(V9(j)&&V9(U))L[z]=i2(U,j,X,_);else if(Array.isArray(j)||Array.isArray(U))L[z]=r2(U,j,X.arrayMergeMode||"smart",_);else L[z]=j}return L}function o2($,Z,X="replace"){return Lj($,Z,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function _6($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!_6($[X],Z[X]))return!1;return!0}if(V9($)&&V9(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let Y of X){if(!Object.prototype.hasOwnProperty.call(Z,Y))return!1;if(!_6($[Y],Z[Y]))return!1}return!0}return!1}function V9($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class a2{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,X={}){let{arrayStrategy:_="replace",useCache:Y=!0,cacheTtl:L,trackPerformance:z=!0,verbose:j=!1}=X;if(Y){let Q=v1.getWithFileCheck("file",$);if(Q){if(j)console.log(`Configuration loaded from cache: ${$}`);return Q}}let U=async()=>{if(!q$($))return null;try{let Q=`?t=${Date.now()}`,E=await import($+Q),G=E.default||E,F="default"in E,O=Object.keys(E).length>0;if(!F&&!O)throw new q5($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new q5($,Error("Configuration must export a valid object"),"unknown");let K={config:o2(Z,G,_),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)v1.setWithFileCheck("file",K,$,L);return K}catch(Q){throw Q instanceof Error?j8.configLoad($,Q):j8.configLoad($,Error(String(Q)))}};if(z)return h5.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,Z,X={}){for(let _ of $)try{let Y=await this.loadFromPath(_,Z,X);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(X.verbose)console.warn(`Failed to load config from ${_}:`,Y)}return null}generateConfigPaths($,Z,X){let _=this.generateNamePatterns($,X),Y=[];for(let L of _)for(let z of this.extensions)Y.push(hZ(Z,`${L}${z}`));return Y}generateNamePatterns($,Z){let X=[];if(X.push("config",".config"),$)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(Z){if(X.push(Z,`.${Z}.config`,`${Z}.config`,`.${Z}`),$)X.push(`${$}.${Z}.config`,`.${$}.${Z}.config`)}return X.filter(Boolean)}checkFileAccess($){return Yj(async()=>{return q$($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,X){let _=[];if(!q$($))return _;if(Z||X){let Y=this.generateNamePatterns(Z||"",X);for(let L of Y)for(let z of this.extensions){let j=hZ($,`${L}${z}`);if(await this.checkFileAccess(j))_.push(j)}}else try{let{readdirSync:Y}=await import("fs"),L=Y($);for(let z of L)if(this.looksLikeConfigFile(z)){let j=hZ($,z);if(await this.checkFileAccess(j))_.push(j)}}catch{return[]}return _}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Z)=>Z.test($))}async validateConfigFile($){let Z=[];try{if(!q$($))return Z.push("Configuration file does not exist"),Z;let X=await import($),_=X.default||X;if(_===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof _!=="object"||_===null)Z.push("Configuration must be an object");else if(Array.isArray(_))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Y}=await import("fs"),L=Y($,"utf8");JSON.parse(L)}catch(Y){Z.push(`Invalid JSON syntax: ${Y}`)}}catch(X){Z.push(`Failed to load configuration file: ${X}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let X=new Map;return await Promise.allSettled($.map(async(_)=>{try{let Y=await this.loadFromPath(_,{},Z);if(Y)X.set(_,Y.config)}catch(Y){if(Z.verbose)console.warn(`Failed to preload ${_}:`,Y)}})),X}}class t2{async validateConfiguration($,Z,X={}){let{stopOnFirstError:_=!1,validateRequired:Y=!0,validateTypes:L=!0,customRules:z=[],trackPerformance:j=!0,verbose:U=!1}=X,Q=async()=>{let E=[],G=[],F={stopOnFirstError:_,validateRequired:Y,validateTypes:L,customRules:z,trackPerformance:j,verbose:U};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,F);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...z],F);else return this.validateWithJSONSchema($,Z,F)}catch(O){return E.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:E,warnings:G}}};if(j)return await h5.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile($,Z,X){try{if(!sU(Z))throw new T5(Z,[{path:"",message:"Schema file does not exist"}]);let _=await import(Z),Y=_.default||_;if(Array.isArray(Y))return this.validateWithRules($,Y,X);else return this.validateWithJSONSchema($,Y,X)}catch(_){throw new T5(Z,[{path:"",message:`Failed to load schema: ${_}`}])}}validateWithJSONSchema($,Z,X){let _=[],Y=[];return this.validateObjectAgainstSchema($,Z,"",_,Y,X),{isValid:_.length===0,errors:_,warnings:Y}}validateObjectAgainstSchema($,Z,X,_,Y,L){if(L.validateTypes&&Z.type){let z=Array.isArray($)?"array":typeof $,j=Array.isArray(Z.type)?Z.type:[Z.type];if(!j.includes(z)){if(_.push({path:X,message:`Expected type ${j.join(" or ")}, got ${z}`,expected:j.join(" or "),actual:z,rule:"type"}),L.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(_.push({path:X,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),L.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)_.push({path:X,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)_.push({path:X,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))_.push({path:X,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)_.push({path:X,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)_.push({path:X,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let z=0;z<$.length;z++){let j=X?`${X}[${z}]`:`[${z}]`;if(this.validateObjectAgainstSchema($[z],Z.items,j,_,Y,L),L.stopOnFirstError&&_.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let z=$;if(L.validateRequired&&Z.required){for(let j of Z.required)if(!(j in z)){if(_.push({path:X?`${X}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),L.stopOnFirstError)return}}if(Z.properties){for(let[j,U]of Object.entries(Z.properties))if(j in z){let Q=X?`${X}.${j}`:j;if(this.validateObjectAgainstSchema(z[j],U,Q,_,Y,L),L.stopOnFirstError&&_.length>0)return}}if(Z.additionalProperties===!1){let j=new Set(Object.keys(Z.properties||{}));for(let U of Object.keys(z))if(!j.has(U))Y.push({path:X?`${X}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,X){let _=[],Y=[];for(let L of Z)try{let z=this.getValueByPath($,L.path),j=this.validateWithRule(z,L,L.path);if(_.push(...j),X.stopOnFirstError&&_.length>0)break}catch(z){_.push({path:L.path,message:`Rule validation failed: ${z}`,rule:"system"})}return{isValid:_.length===0,errors:_,warnings:Y}}validateWithRule($,Z,X){let _=[];if(Z.required&&($===void 0||$===null))return _.push({path:X,message:Z.message||`Property '${X}' is required`,expected:"required",rule:"required"}),_;if($===void 0||$===null)return _;if(Z.type){let Y=Array.isArray($)?"array":typeof $;if(Y!==Z.type)_.push({path:X,message:Z.message||`Expected type ${Z.type}, got ${Y}`,expected:Z.type,actual:Y,rule:"type"})}if(Z.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<Z.min)_.push({path:X,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:Y,rule:"min"})}if(Z.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>Z.max)_.push({path:X,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:Y,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))_.push({path:X,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))_.push({path:X,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let Y=Z.validator($);if(Y)_.push({path:X,message:Z.message||Y,rule:"custom"})}return _}getValueByPath($,Z){if(!Z)return $;let X=Z.split("."),_=$;for(let Y of X)if(_&&typeof _==="object"&&Y in _)_=_[Y];else return;return _}generateRulesFromInterface($){let Z=[],X=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let _ of X){let[,Y,L,z]=_;Z.push({path:Y,required:!L,type:this.mapTypeScriptType(z)})}return Z}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:L4},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class e2{fileLoader=new a2;envProcessor=new q6;validator=new t2;async loadConfig($){let Z=Date.now(),{cache:X,performance:_,schema:Y,validate:L,...z}=$;try{if(X?.enabled){let U=this.checkCache(z.name||"",z);if(U)return U}let j;try{j=await this.loadConfigurationStrategies(z,!0,X)}catch(U){let Q=z.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(Q)throw U;j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`No configuration file found for "${z.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let E=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),G=!E&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),F=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(Q&&(F||E))throw U;if(G&&(!Q||!F))j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else j={...await this.applyEnvironmentVariables(z.name||"",z.defaultConfig,z.checkEnv!==!1,z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Y||L)await this.validateConfiguration(j.config,Y,L,z.name);if(X?.enabled&&j)this.cacheResult(z.name||"",j,X,z);if(_?.enabled){let U={operation:"loadConfig",duration:Date.now()-Z,configName:z.name,timestamp:new Date};if(_.onMetrics)_.onMetrics(U);if(_.slowThreshold&&U.duration>_.slowThreshold)w9.warn(`Slow configuration loading detected: ${U.duration}ms for ${z.name}`);j.metrics=U}return j}catch(j){let U=Date.now()-Z;throw w9.error(`Configuration loading failed after ${U}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies($,Z=!1,X){let{name:_="",alias:Y,cwd:L,configDir:z,defaultConfig:j,checkEnv:U=!0,arrayStrategy:Q="replace",verbose:E=!1}=$,G=L||U5.cwd(),F=[],O=await this.loadLocalConfiguration(_,Y,G,z,j,Q,E,U,X);if(O)return F.push(...this.getLocalSearchPaths(_,Y,G,z)),this.finalizeResult(O,F,U,_,E);let K=await this.loadHomeConfiguration(_,Y,j,Q,E,U);if(K)return F.push(...this.getHomeSearchPaths(_,Y)),this.finalizeResult(K,F,U,_,E);let W=await this.loadPackageJsonConfiguration(_,Y,G,j,Q,E,U);if(W)return F.push(E9(G,"package.json")),this.finalizeResult(W,F,U,_,E);if(F.push(...this.getAllSearchPaths(_,Y,G,z)),Z)throw j8.configNotFound(_,F,Y);return{...await this.applyEnvironmentVariables(_,j,U,E),warnings:[`No configuration file found for "${_}"${Y?` or alias "${Y}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,X,_,Y,L,z,j,U){let Q=j?P$($,Y,z):Y,E=this.getLocalDirectories(X,_);for(let G of E){if(z)w9.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,Z),O=await this.fileLoader.tryLoadFromPaths(F,Q,{arrayStrategy:L,verbose:z,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(z)w9.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,Z,X,_,Y,L){if(!$)return null;let z=L?P$($,X,Y):X,j=[E9(H8(),".config",$),E9(H8(),".config"),H8()];for(let U of j){if(Y)w9.info(`Checking home directory: ${U}`);let Q=this.fileLoader.generateConfigPaths($,U,Z),E=await this.fileLoader.tryLoadFromPaths(Q,z,{arrayStrategy:_,verbose:Y});if(E){if(Y)w9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,Z,X,_,Y,L,z){let j=z?P$($,_,L):_;try{let U=E9(X,"package.json");if(!HU(U))return null;let Q=await import(U),E=Q[$],G=$;if(!E&&Z)E=Q[Z],G=Z;if(E&&typeof E==="object"&&!Array.isArray(E)){if(L)w9.success(`Configuration loaded from package.json: ${G}`);return{config:o2(j,E,Y),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(L)w9.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,Z,X,_){if(!X||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:P$($,Z,_),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,X,_,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,X,_){let Y=[];if(X){let L=X($);if(L)Y.push(...L)}if(Z){let L=await this.validator.validateConfiguration($,Z);if(!L.isValid)Y.push(...L.errors.map((z)=>z.path?`${z.path}: ${z.message}`:z.message))}if(Y.length>0)throw j8.configValidation(_||"unknown",Y,_)}checkCache($,Z){let X=this.generateCacheKey($,Z);return v1.get(X)||null}cacheResult($,Z,X,_){let Y=this.generateCacheKey($,_);v1.set(Y,Z,void 0,X.ttl)}generateCacheKey($,Z){let X=[$];if(Z.alias)X.push(`alias:${Z.alias}`);if(Z.cwd)X.push(`cwd:${Z.cwd}`);if(Z.configDir)X.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)X.push(`checkEnv:${Z.checkEnv}`);return X.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,E9($,"config"),E9($,".config"),Z?E9($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,X,_){let Y=[];return Y.push(...this.getLocalSearchPaths($,Z,X,_)),Y.push(...this.getHomeSearchPaths($,Z)),Y.push(E9(X,"package.json")),Y}getLocalSearchPaths($,Z,X,_){let Y=this.getLocalDirectories(X,_),L=[];for(let z of Y)L.push(...this.fileLoader.generateConfigPaths($,z,Z));return L}getHomeSearchPaths($,Z){if(!$)return[];let X=[E9(H8(),".config",$),E9(H8(),".config"),H8()],_=[];for(let Y of X)_.push(...this.fileLoader.generateConfigPaths($,Y,Z));return _}async loadConfigWithResult($){return this.loadConfig($)}}async function Oj($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},X="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let _;if(X)_=await l$.loadConfig($);else _=await l$.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return _?.config??Z}catch(_){let Y=_ instanceof Error?_.name:"UnknownError",L=_ instanceof Error?_.message:String(_);if(!(Y==="ConfigNotFoundError"||Y==="ConfigLoadError"||Y==="ConfigValidationError"||L.includes("config"))&&$.verbose)w9.warn("Unexpected error loading config, using defaults:",[_ instanceof Error?_:Error(String(_))]);let z=X?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await l$.applyEnvironmentVariables(z.name||"",Z,!0,z.verbose||!1))?.config??Z;return Z}}function P$($,Z,X=!1){let _=new q6,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function L(z,j=[]){let U={...z};for(let[Q,E]of Object.entries(z)){let G=[...j,Q],F=[`${Y}_${G.join("_").toUpperCase()}`,`${Y}_${G.map((W)=>W.toUpperCase()).join("")}`,`${Y}_${G.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,K;for(let W of F)if(O=U5.env[W],O!==void 0){K=W;break}if(O!==void 0&&K)if(typeof E==="boolean")U[Q]=["true","1","yes"].includes(O.toLowerCase());else if(typeof E==="number"){let W=Number(O);if(!Number.isNaN(W))U[Q]=W}else if(Array.isArray(E))try{U[Q]=JSON.parse(O)}catch{U[Q]=O.split(",").map((W)=>W.trim())}else U[Q]=O;else if(E&&typeof E==="object"&&!Array.isArray(E))U[Q]=L(E,G)}return U}return L(Z)}async function Qj(){if(!pZ)pZ=await Oj({name:"mock",alias:"faker",defaultConfig:P5});return pZ}function y8($){let Z=$.replace(/-/g,"_").split("_"),X=Z[0].toLowerCase(),_=Z[1]?.toUpperCase(),Y=_?`${X}-${_.toLowerCase()}`:X;return{full:$,language:X,region:_,packageName:Y,normalized:_?`${X}_${_}`:X}}function Gj($){let Z=y8($);if(Z.region)return[Z.normalized,Z.language];return[Z.language]}function Fj($){return`@mock-locale/${y8($).packageName}`}function $4($,Z){let X={...$};for(let _ in Z){let Y=Z[_],L=$[_];if(Y===void 0)continue;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y)&&typeof L==="object"&&L!==null&&!Array.isArray(L))X[_]=$4(L,Y);else X[_]=Y}return X}function h8(){let $=u2.cwd(),Z=A8($,"package.json");if(!B8(Z))return!1;try{let X=JSON.parse(nU(Z,"utf-8"));return!!(X.workspaces||X.workspace)}catch{return!1}}function Z4(){let $=u2.cwd();if(B8(A8($,"bun.lockb"))||B8(A8($,"bun.lock")))return"bun";if(B8(A8($,"pnpm-lock.yaml")))return"pnpm";if(B8(A8($,"yarn.lock")))return"yarn";if(B8(A8($,"package-lock.json")))return"npm";return"bun"}function X4($,Z={}){let X=Z4(),{silent:_=!1}=Z;if(!_)console.log(`
|
|
114
|
-
\uD83D\uDCE6 Installing ${$} using ${X}...`);let Y={bun:{cmd:"bun",args:["add",$]},npm:{cmd:"npm",args:["install",$]},yarn:{cmd:"yarn",args:["add",$]},pnpm:{cmd:"pnpm",args:["add",$]}},{cmd:L,args:z}=Y[X];try{let j=lU(L,z,{stdio:"pipe",shell:!0}),U=j.stdout?.toString()||"",Q=j.stderr?.toString()||"",E=U+Q;if(!_){if(U)console.log(U);if(Q)console.error(Q)}if(j.status===0){if(!_)console.log(`\u2713 Successfully installed ${$}`);return!0}else{let G=E;if(G.toLowerCase().includes("dependency loop")||G.includes("DependencyLoop")||G.includes("has a dependency loop")||G.includes("An internal error occurred (DependencyLoop)")){if(!_){if(console.log(`
|
|
115
|
-
\u26A0\uFE0F Package ${$} is already available in the workspace and cannot be installed separately due to a dependency loop.`),h8())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!_)console.error(`\u2717 Failed to install ${$}`);return!1}}catch(j){if(!_)console.error(`\u2717 Error installing ${$}:`,j);return!1}}function y1($,Z){let X=[];for(let _ of Z.rules)if(!_.validator($)){let Y=_.errorMessage||`Validation failed for value: ${$}`;if(X.push(Y),Z.strict)throw Error(Y)}return{isValid:X.length===0,errors:X}}function h1($,Z){let{items:X}=Z;if(X.length===0)throw Error("Cannot select from empty weighted items array");let _=X.reduce((z,j)=>z+j.weight,0);if(_<=0)throw Error("Total weight must be greater than 0");let Y=$.number()*_,L=0;for(let z of X)if(L+=z.weight,Y<=L)return z.item;return X[X.length-1].item}function Vj($,Z){return $.filter((X)=>{if(Z.gender&&X.gender&&X.gender!==Z.gender)return!1;if(Z.country){let _=Array.isArray(Z.country)?Z.country:[Z.country];if(X.country&&!_.includes(X.country))return!1}if(Z.region){let _=Array.isArray(Z.region)?Z.region:[Z.region];if(X.region&&!_.includes(X.region))return!1}if(Z.locale&&X.locale&&X.locale!==Z.locale)return!1;if(Z.ageRange&&X.age){let{min:_,max:Y}=Z.ageRange;if(X.age<_||X.age>Y)return!1}for(let[_,Y]of Object.entries(Z))if(_!=="gender"&&_!=="country"&&_!=="region"&&_!=="locale"&&_!=="ageRange"&&X[_]!==void 0){if(!(Array.isArray(Y)?Y:[Y]).includes(X[_]))return!1}return!0})}function a9($,Z){let X={...$};for(let _ of Z){let{field:Y,dependsOn:L,mapping:z}=_;if(X[L]&&z[X[L]])X[Y]=z[X[L]]}return X}function Wj($,Z={}){let X=$();if(Z.relationships)return a9(X,Z.relationships);return X}class T6{providers=new Map;register($){let{category:Z,name:X}=$;if(!this.providers.has(Z))this.providers.set(Z,new Map);this.providers.get(Z).set(X,$)}get($,Z){return this.providers.get($)?.get(Z)}getProvidersInCategory($){let Z=this.providers.get($);return Z?Array.from(Z.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove($,Z){let X=this.providers.get($);if(X)return X.delete(Z);return!1}clear(){this.providers.clear()}}class Q1{random;locale;constructor($,Z){this.random=$,this.locale=Z}street(){let $=this.random.arrayElement(this.locale.address.street),Z=this.streetSuffix();return`${$} ${Z}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress($){let Z=this.buildingNumber(),X=this.street();if($?.useFullAddress)return`${Z} ${X}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${Z} ${X}`}buildingNumber(){let $=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols($)}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 $=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols($)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude($){let Z=$?.min??-90,X=$?.max??90,_=$?.precision??4;return this.random.float(Z,X,_)}longitude($){let Z=$?.min??-180,X=$?.max??180,_=$?.precision??4;return this.random.float(Z,X,_)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced($){let Z;if($?.constraints?.country){let X=$.constraints.country,_=Array.isArray(X)?X:[X];Z=this.city()}else Z=this.city();if($?.weighted)Z=h1(this.random,$.weighted);if($?.relationships)Z=a9({city:Z,country:$?.constraints?.country},$.relationships).city||Z;if($?.validation){let X=y1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.city()}}return Z}countryAdvanced($){let Z;if($?.constraints?.country){let X=$.constraints.country,_=Array.isArray(X)?X:[X];Z=this.random.arrayElement(_)}else Z=this.country();if($?.weighted)Z=h1(this.random,$.weighted);if($?.relationships)Z=a9({country:Z},$.relationships).country||Z;if($?.validation){let X=y1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.country()}}return Z}addressAdvanced($){let Z=this.countryAdvanced($),X=this.cityAdvanced($),_=this.state(),Y=this.stateAbbr(),L=this.zipCode(),z=this.street(),j=this.latitude(),U=this.longitude(),Q={street:z,city:X,state:_,stateAbbr:Y,country:Z,countryCode:this.countryCode(),zipCode:L,latitude:j,longitude:U};if($?.relationships)return a9(Q,$.relationships);return Q}neighborhood($){let Z=$?.size||this.random.int(3,10),X=this.cityAdvanced($),_=this.state(),Y=this.zipCode(),L=[];for(let z=0;z<Z;z++)L.push({street:this.street(),city:X,state:_,zipCode:Y,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 L}}class G1{random;locale;constructor($,Z){this.random=$,this.locale=Z}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let $=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement($)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let $=["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($)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let $=["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($)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let $=["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($)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let $=["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($)}bear(){let $=["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($)}cetacean(){let $=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement($)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let $=["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($)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let $=["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($)}lion(){let $=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement($)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let $=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement($)}snake(){let $=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement($)}}class F1{random;locale;constructor($,Z){this.random=$,this.locale=Z}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let $=["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($)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let $=["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($)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let $=["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($)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let $=["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($)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let $=["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($)}isbn(){if(this.random.boolean(0.5)){let L=Array.from({length:9},()=>this.random.int(0,9)),z=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${L.slice(0,1).join("")}-${L.slice(1,4).join("")}-${L.slice(4,9).join("")}-${z}`}let $="978",Z=this.random.int(0,9),X=Array.from({length:3},()=>this.random.int(0,9)).join(""),_=Array.from({length:5},()=>this.random.int(0,9)).join(""),Y=this.random.int(0,9);return`${$}-${Z}-${X}-${_}-${Y}`}format(){let $=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement($)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let $=["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($)}}class V1{random;locale;constructor($,Z){this.random=$,this.locale=Z}hex($){let Z=$?.prefix??"#",X=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return Z+X}rgb($){let Z=this.random.int(0,255),X=this.random.int(0,255),_=this.random.int(0,255);if($?.alpha){let Y=this.random.float(0,1,2);if($?.format==="array")return[Z,X,_,Y];return`rgba(${Z}, ${X}, ${_}, ${Y})`}if($?.format==="array")return[Z,X,_];return`rgb(${Z}, ${X}, ${_})`}hsl($){let Z=this.random.int(0,360),X=this.random.int(0,100),_=this.random.int(0,100);if($?.alpha){let Y=this.random.float(0,1,2);if($?.format==="array")return[Z,X,_,Y];return`hsla(${Z}, ${X}%, ${_}%, ${Y})`}if($?.format==="array")return[Z,X,_];return`hsl(${Z}, ${X}%, ${_}%)`}css($){let Z=$?.format??this.random.arrayElement(["hex","rgb","hsl"]);if(Z==="hex")return this.hex();if(Z==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let $=["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($)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class W1{random;locale;constructor($,Z){this.random=$,this.locale=Z}product(){let $=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"],Z=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],X=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($)} ${this.random.arrayElement(Z)} ${this.random.arrayElement(X)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let $=["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($)}price($){let Z=$?.min??1,X=$?.max??1000,_=$?.dec??2,Y=$?.symbol??"",L=this.random.float(Z,X,_);return Y+L.toFixed(_)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let $=["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($)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let $=["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($)}productDescription(){let $=["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}."],Z=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],X=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement($).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement(Z)).replace("{benefit}",this.random.arrayElement(X))}review(){let $=["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($)}discountCode(){let $=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],Z=this.random.int(10,99);return`${this.random.arrayElement($)}${Z}`}sku(){let $=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),Z=this.random.int(1e4,99999),X=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${$}-${Z}-${X}`}}class K1{random;locale;constructor($,Z){this.random=$,this.locale=Z}name(){let $=this.random.arrayElement(this.locale.company.name??["Company"]),Z=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${$} ${Z}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let $=this.random.arrayElement(this.locale.company.adjective??["innovative"]),Z=this.random.arrayElement(this.locale.company.descriptor??["digital"]),X=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${Z} ${X}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let $=this.buzzword(),Z=this.random.arrayElement(this.locale.company.descriptor??["digital"]),X=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${Z} ${X}`}}class W5{random;constructor($){this.random=$}engine(){let $=["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($)}type(){let $=["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($)}collation(){let $=["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($)}column(){let $=["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($)}table(){let $=["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($)}mongodbObjectId(){let $="";for(let Z=0;Z<24;Z++)$+="0123456789abcdef"[this.random.int(0,15)];return $}constraint(){let $=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement($)}queryType(){let $=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement($)}connectionString($){let Z=$?.engine??this.engine().toLowerCase().replace(/ /g,""),X="user",_="password",Y="localhost",L=this.random.int(3000,9999),z=this.table(),j={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[Z]||"jdbc";if(Z==="mongodb")return`${j}://user:password@localhost:${L}/${z}`;return`${j}://user:password@localhost:${L}/${z}`}}class K5{random;constructor($){this.random=$}past($){let Z=$?.years??1,X=$?.to??new Date,_=$?.from??new Date(X.getTime()-Z*365*24*60*60*1000);return this.between({from:_,to:X})}future($){let Z=$?.years??1,X=$?.from??new Date,_=$?.to??new Date(X.getTime()+Z*365*24*60*60*1000);return this.between({from:X,to:_})}between($){let Z=$.from??new Date(Date.now()-31536000000),X=$.to??new Date,_=Z.getTime(),Y=X.getTime(),L=this.random.int(_,Y);return new Date(L)}recent($){let Z=$?.days??1,X=new Date,_=new Date(X.getTime()-Z*24*60*60*1000);return this.between({from:_,to:X})}soon($){let Z=$?.days??1,X=new Date,_=new Date(X.getTime()+Z*24*60*60*1000);return this.between({from:X,to:_})}month(){let $=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement($)}weekday(){let $=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement($)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween($){return this.between($)}}class I5{random;constructor($){this.random=$}amount($){let Z=$?.min??0,X=$?.max??1e4,_=$?.dec??2,Y=$?.symbol??"",L=this.random.float(Z,X,_);return Y+L.toFixed(_)}account($=8){let Z="";for(let X=0;X<$;X++)Z+=this.random.int(0,9);return Z}accountName(){let $=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement($)} Account`}routingNumber(){return this.account(9)}creditCardNumber($){let Z=$?.formatted??!0,X=$?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),_="",Y=16;switch(X){case"visa":_="4",Y=16;break;case"mastercard":_=`5${this.random.int(1,5)}`,Y=16;break;case"amex":_=`3${this.random.arrayElement(["4","7"])}`,Y=15;break;case"discover":_="6011",Y=16;break}let L=_;while(L.length<Y)L+=this.random.int(0,9);if(Z){if(X==="amex")return`${L.slice(0,4)}-${L.slice(4,10)}-${L.slice(10)}`;return L.match(/.{1,4}/g)?.join("-")??L}return L}cvv(){return this.account(3)}iban($){let Z=$?.countryCode??"GB",X=$?.formatted??!1,_=this.random.int(10,99).toString(),Y="WEST",L=this.account(14),z=Z+_+"WEST"+L;if(X)return z.match(/.{1,4}/g)?.join(" ")??z;return z}bic(){let $="";for(let Z=0;Z<4;Z++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let Z=0;Z<2;Z++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let Z=0;Z<2;Z++)$+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(X,_)=>_.toString())]);return $}bitcoin(){let $=this.random.arrayElement(["1","3"]);for(let Z=0;Z<33;Z++)$+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return $}ethereum(){let $="0x";for(let Z=0;Z<40;Z++)$+="0123456789abcdef"[this.random.int(0,15)];return $}currencyCode(){let $=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement($)}currencyName(){let $=["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($)}currencySymbol(){let $=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement($)}transactionType(){let $=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement($)}}class I1{random;locale;constructor($,Z){this.random=$,this.locale=Z}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let $=["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($)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let $=["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($)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let $=["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($)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let $=["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($)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let $=["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($)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let $=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement($)}seafood(){let $=["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($)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let $=["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($)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let $=["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($)}description(){let $=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],Z=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement($)} ${this.random.arrayElement(Z)}`}}class J5{random;constructor($){this.random=$}branch(){let $=["feature","bugfix","hotfix","refactor","chore","docs","test"],Z=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],X=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],_=this.random.arrayElement($),Y=this.random.arrayElement(Z),L=this.random.arrayElement(X);return`${_}/${Y}-${L}`}commitMessage(){let $=["feat","fix","docs","style","refactor","test","chore","perf"],Z=["api","ui","auth","db","config","deps","core","utils"],X=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],_=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],Y=this.random.arrayElement($),L=this.random.boolean(0.5)?`(${this.random.arrayElement(Z)})`:"",z=this.random.arrayElement(X),j=this.random.arrayElement(_);return`${Y}${L}: ${z} ${j}`}commitSha($){let Z=$?.short?7:40,X="0123456789abcdef",_="";for(let Y=0;Y<Z;Y++)_+="0123456789abcdef"[this.random.int(0,15)];return _}commitEntry(){let $=this.commitSha({short:!0}),Z=this.commitMessage();return`${$} ${Z}`}commitAuthor($){let Z=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],X=$?.name??this.random.arrayElement(Z),_=$?.email??`${X.toLowerCase().replace(" ",".")}@example.com`;return`${X} <${_}>`}remote($){let Z=$?.protocol??this.random.arrayElement(["https","ssh"]),X=$?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),_=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),Y=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),L={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if(Z==="ssh")return`git@${L[X]}:${_}/${Y}.git`;return`https://${L[X]}/${_}/${Y}.git`}tag(){let $=this.random.int(0,5),Z=this.random.int(0,20),X=this.random.int(0,50),_=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${$}.${Z}.${X}${_}`}}class J1{random;locale;constructor($,Z){this.random=$,this.locale=Z}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let $=["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($)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let $=["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($)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let $=["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($)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let $=["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($)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let $=["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($)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let $=["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($).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 D5{random;constructor($){this.random=$}randomElement($){return this.random.arrayElement($)}arrayElement($){return this.random.arrayElement($)}arrayElements($,Z){return this.random.arrayElements($,Z)}shuffle($){return this.random.shuffle($)}numerify($){return $.replace(/#/g,()=>String(this.random.int(0,9)))}lexify($){return $.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify($){return this.numerify(this.lexify($))}replaceSymbols($){return this.random.replaceSymbols($)}boolean($=0.5){return this.random.boolean($)}objectKey($){let Z=Object.keys($);return this.random.arrayElement(Z)}objectValue($){let Z=this.objectKey($);return $[Z]}multiple($,Z=3){return Array.from({length:Z},$)}maybe($,Z=0.5){return this.random.boolean(Z)?$():void 0}unique($,Z=50){let X=new Set,_=0;while(_<Z){let Y=$();if(!X.has(Y))return X.add(Y),Y;_++}throw Error(`Failed to generate unique value after ${Z} retries`)}replaceCreditCardSymbols($="####-####-####-####",Z="#"){return this.random.replaceCreditCardSymbols($,Z)}regexify($){return $.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,X)=>{return""})}}class R5{random;constructor($){this.random=$}url($){let Z=$?.width??640,X=$?.height??480;return`https://via.placeholder.com/${Z}x${X}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr($){let Z=$?.width??640,X=$?.height??480,_=$?.category??"";if(_)return`https://loremflickr.com/${Z}/${X}/${_}`;return`https://loremflickr.com/${Z}/${X}`}urlPicsumPhotos($){let Z=$?.width??640,X=$?.height??480,_=`https://picsum.photos/${Z}/${X}`;if($?.grayscale)_+="?grayscale";if($?.blur)_+=$?.grayscale?`&blur=${$.blur}`:`?blur=${$.blur}`;return _}dataUri($){let Z=$?.width??640,X=$?.height??480,_=$?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),Y=`<svg xmlns="http://www.w3.org/2000/svg" width="${Z}" height="${X}"><rect width="${Z}" height="${X}" fill="#${_}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(Y)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let $=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement($)}imageType(){let $=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement($)}}class D1{random;locale;domainWordsCache=null;constructor($,Z){this.random=$,this.locale=Z}getDomainWords(){if(!this.domainWordsCache){let $=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=$.map((Z)=>Z.toLowerCase().replace(/[^a-z0-9]/g,"")).filter((Z)=>Z.length>0)}return this.domainWordsCache}email($){let Z;if($?.firstName)Z=$.firstName.toLowerCase();else{let z=this.locale.person.firstNameMale.length,j=this.locale.person.firstNameFemale.length,U=this.locale.person.firstNameNeutral?.length||0,Q=z+j+U,E=this.random.int(0,Q-1);if(E<z)Z=this.locale.person.firstNameMale[E].toLowerCase();else if(E<z+j)Z=this.locale.person.firstNameFemale[E-z].toLowerCase();else Z=this.locale.person.firstNameNeutral[E-z-j].toLowerCase()}let X=$?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),_=$?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),Y=this.random.arrayElement(O4),L=this.random.arrayElement(this.getDomainWords());return`${Z}${Y}${X}@${L}.${_}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let $=this.locale.person.firstNameMale.length,Z=this.locale.person.firstNameFemale.length,X=this.locale.person.firstNameNeutral?.length||0,_=$+Z+X,Y=this.random.int(0,_-1),L;if(Y<$)L=this.locale.person.firstNameMale[Y].toLowerCase();else if(Y<$+Z)L=this.locale.person.firstNameFemale[Y-$].toLowerCase();else L=this.locale.person.firstNameNeutral[Y-$-Z].toLowerCase();let z=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),j=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),U=[".","_",""],Q=this.random.arrayElement(U);return`${L}${Q}${z}@${j}`}username($){let Z;if($?.firstName)Z=$.firstName.toLowerCase();else{let Y=this.locale.person.firstNameMale.length,L=this.locale.person.firstNameFemale.length,z=this.locale.person.firstNameNeutral?.length||0,j=Y+L+z,U=this.random.int(0,j-1);if(U<Y)Z=this.locale.person.firstNameMale[U].toLowerCase();else if(U<Y+L)Z=this.locale.person.firstNameFemale[U-Y].toLowerCase();else Z=this.locale.person.firstNameNeutral[U-Y-L].toLowerCase()}let X=$?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),_=[`${Z}${X}`,`${Z}_${X}`,`${Z}.${X}`,`${Z}${this.random.int(10,999)}`,`${Z}_${X}${this.random.int(10,99)}`];return this.random.arrayElement(_)}password($){let Z=$?.length??12,X=$?.memorable??!1,_=$?.prefix??"";if(X){let z=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],j=[];for(let U=0;U<3;U++)j.push(this.random.arrayElement(z));return _+j.join("-")+this.random.int(10,999)}let Y="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",L=_;for(let z=_.length;z<Z;z++)L+=Y[this.random.int(0,Y.length-1)];return L}url($){let Z=$?.protocol??this.random.arrayElement(["http","https"]),X=$?.domain??this.domainName();return`${Z}://${X}`}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 $=[];for(let Z=0;Z<8;Z++)$.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return $.join(":")}mac($=":"){let Z=[];for(let X=0;X<6;X++)Z.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return Z.join($)}userAgent(){let $=["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($)}slug($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return Z.join("-").toLowerCase()}ip(){return this.ipv4()}}class S5{random;constructor($){this.random=$}word(){return this.random.arrayElement(Q4)}words($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.word());return Z.join(" ")}sentence($){let Z=$??this.random.int(3,10),X=this.words(Z);return`${X.charAt(0).toUpperCase()+X.slice(1)}.`}sentences($=3,Z=" "){let X=[];for(let _=0;_<$;_++)X.push(this.sentence());return X.join(Z)}paragraph($){let Z=$??this.random.int(3,7);return this.sentences(Z)}paragraphs($=3,Z=`
|
|
116
|
-
|
|
117
|
-
`){let X=[];for(let _=0;_<$;_++)X.push(this.paragraph());return X.join(Z)}text($){let Z=$??200,X="";while(X.length<Z)X+=`${this.paragraph()} `;return X.trim().slice(0,Z)}slug($=3){return this.words($).replace(/ /g,"-")}lines($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.sentence());return Z.join(`
|
|
118
|
-
`)}}class R1{random;locale;constructor($,Z){this.random=$,this.locale=Z}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let $=["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($)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let $=["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($)}albumName(){let $=["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($)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let $=["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($)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let $=["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($)}note(){let $=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement($)}chord(){let $=this.note(),Z=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${$}${Z}`}tempo(){return this.random.int(60,200)}key(){let $=this.note(),Z=this.random.arrayElement(["Major","Minor"]);return`${$} ${Z}`}timeSignature(){let $=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement($)}}class M5{random;constructor($){this.random=$}int($){let Z=$?.min??0,X=$?.max??100;return this.random.int(Z,X)}float($){let Z=$?.min??0,X=$?.max??1,_=$?.precision??2;return this.random.float(Z,X,_)}bigInt($){let Z=$?.min??0n,X=($?.max??1000000n)-Z+1n,_=BigInt(Math.floor(this.random.number()*Number(X)));return Z+_}binary($){let Z=$?.length??8,X="";for(let _=0;_<Z;_++)X+=this.random.int(0,1);return X}octal($){let Z=$?.length??3,X="";for(let _=0;_<Z;_++)X+=this.random.int(0,7);return X}hex($){let Z=$?.length??6,X="0123456789ABCDEF",_="";for(let Y=0;Y<Z;Y++)_+="0123456789ABCDEF"[this.random.int(0,15)];return _}randomNumber($){return this.int($)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class S1{random;locale;constructor($,Z){this.random=$,this.locale=Z}firstName($){if($?.gender==="male")return this.firstNameMale();if($?.gender==="female")return this.firstNameFemale();if($?.gender==="neutral")return this.firstNameNeutral();let Z=this.locale.person.firstNameMale.length,X=this.locale.person.firstNameFemale.length,_=this.locale.person.firstNameNeutral?.length||0,Y=Z+X+_,L=this.random.int(0,Y-1);if(L<Z)return this.locale.person.firstNameMale[L];if(L<Z+X)return this.locale.person.firstNameFemale[L-Z];return this.locale.person.firstNameNeutral[L-Z-X]}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 $=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement($)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName($){if(!$)return`${this.firstName()} ${this.lastName()}`;let Z=this.firstName({gender:$.gender}),X=this.lastName();if($.prefix&&$.suffix)return`${this.prefix()} ${Z} ${X} ${this.suffix()}`;if($.prefix)return`${this.prefix()} ${Z} ${X}`;if($.suffix)return`${Z} ${X} ${this.suffix()}`;return`${Z} ${X}`}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($){let Z;if($?.constraints)Z=this.firstName({gender:$.constraints.gender});else Z=this.firstName({gender:$?.gender});if($?.weighted)Z=h1(this.random,$.weighted);if($?.relationships)Z=a9({firstName:Z,gender:$?.gender||$?.constraints?.gender},$.relationships).firstName||Z;if($?.validation){let X=y1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.firstName({gender:$?.gender||$?.constraints?.gender})}}return Z}fullNameAdvanced($){let Z;if($?.constraints)Z=this.fullName({gender:$.constraints.gender,prefix:$.prefix,suffix:$.suffix});else Z=this.fullName($);if($?.weighted)Z=h1(this.random,$.weighted);if($?.relationships)Z=a9({fullName:Z,gender:$?.gender||$?.constraints?.gender},$.relationships).fullName||Z;if($?.validation){let X=y1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.fullName({gender:$?.gender||$?.constraints?.gender,prefix:$?.prefix,suffix:$?.suffix})}}return Z}profile($){let Z=$?.constraints?.gender||$?.gender||this.gender(),X=this.firstNameAdvanced({...$,gender:Z}),_=this.lastName(),Y=`${X} ${_}`,L={firstName:X,lastName:_,fullName:Y,gender:Z,jobTitle:this.jobTitle(),age:$?.constraints?.ageRange?this.random.int($.constraints.ageRange.min,$.constraints.ageRange.max):this.random.int(18,80)};if($?.relationships)return a9(L,$.relationships);return L}family($){let Z=$?.size||this.random.int(2,6),X=this.lastName(),_=["parent","parent","child","child","child","grandparent"],Y=[];for(let L=0;L<Z;L++){let z=_[L]||"relative",j=z==="parent"||z==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",U=this.firstNameAdvanced({...$,gender:j,constraints:{...$?.constraints,gender:j}});Y.push({firstName:U,lastName:X,fullName:`${U} ${X}`,gender:j,relationship:z})}return{members:Y,lastName:X}}}class M1{random;locale;constructor($,Z){this.random=$,this.locale=Z}number($){let Z=$??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols(Z)}phoneNumber($){return this.number($)}}class w1{random;locale;constructor($,Z){this.random=$,this.locale=Z}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let $=["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($)}chemicalElementSymbol(){let $=["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($)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let $=["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($)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let $=["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($)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let $=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement($)}dnaSequence($=12){let Z=["A","T","C","G"],X="";for(let _=0;_<$;_++)X+=this.random.arrayElement(Z);return X}rnaSequence($=12){let Z=["A","U","C","G"],X="";for(let _=0;_<$;_++)X+=this.random.arrayElement(Z);return X}hypothesis(){let $=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],Z=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement($)}, then ${this.random.arrayElement(Z)}`}}class H1{random;locale;constructor($,Z){this.random=$,this.locale=Z}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let $=["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($)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let $=["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($)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let $=["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($)}position(){let $=["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($)}event(){let $=["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($)}league(){let $=["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($)}quote(){let $=["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($)}equipment(){let $=["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($)}}class w5{random;constructor($){this.random=$}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let $="0123456789abcdef",Z="";for(let X=0;X<36;X++)if(X===8||X===13||X===18||X===23)Z+="-";else if(X===14)Z+="4";else if(X===19){let _=this.random.int(0,15);Z+=$[_&3|8]}else Z+=$[this.random.int(0,15)];return Z}nanoid($=21){let Z="";for(let X=0;X<$;X++)Z+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return Z}alpha($){let Z=$?.length??10,X=$?.casing??"mixed",_="abcdefghijklmnopqrstuvwxyz",Y="ABCDEFGHIJKLMNOPQRSTUVWXYZ",L="";if(X==="lower")L="abcdefghijklmnopqrstuvwxyz";else if(X==="upper")L="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else L="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let z="";for(let j=0;j<Z;j++)z+=L[this.random.int(0,L.length-1)];return z}alphanumeric($){let Z=$?.length??10,X=$?.casing??"mixed",_="abcdefghijklmnopqrstuvwxyz",Y="ABCDEFGHIJKLMNOPQRSTUVWXYZ",L="0123456789",z="0123456789";if(X==="lower")z+="abcdefghijklmnopqrstuvwxyz";else if(X==="upper")z+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let j="";for(let U=0;U<Z;U++)j+=z[this.random.int(0,z.length-1)];return j}numeric($=10){if(!this.random.isSeeded()){let X="";for(let _=0;_<$;_++)X+=Math.floor(Math.random()*10);return X}let Z="";for(let X=0;X<$;X++)Z+=this.random.int(0,9);return Z}sample($=10){return this.alphanumeric({length:$})}symbol($=5){let Z="";for(let X=0;X<$;X++)Z+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return Z}hexadecimal($){let Z=$?.length??6,X=$?.prefix??"",_="0123456789abcdef",Y=X;for(let L=0;L<Z;L++)Y+="0123456789abcdef"[this.random.int(0,15)];return Y}}class q1{random;locale;constructor($,Z){this.random=$,this.locale=Z}fileName($){let Z;if(this.locale?.system?.fileName)Z=this.locale.system.fileName;else Z=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let X=this.random.arrayElement(Z),_=$?.extension??this.fileExtension();return`${X}.${_}`}fileExtension(){let $=["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($)}commonFileName(){let $=["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($)}mimeType(){let $=["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($)}commonMimeType(){let $=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement($)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let $=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement($)}directoryPath(){let $=["/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($)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let $=this.random.int(0,10),Z=this.random.int(0,20),X=this.random.int(0,50);return`${$}.${Z}.${X}`}networkInterface(){let $=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement($)}cron(){let $=this.random.boolean(0.5)?"*":this.random.int(0,59),Z=this.random.boolean(0.5)?"*":this.random.int(0,23),X=this.random.boolean(0.5)?"*":this.random.int(1,31),_=this.random.boolean(0.5)?"*":this.random.int(1,12),Y=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${$} ${Z} ${X} ${_} ${Y}`}}class T1{random;locale;constructor($,Z){this.random=$,this.locale=Z}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(G4)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(F4)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(V4)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(W4)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(K4)}vin(){let $="";for(let Z=0;Z<17;Z++)$+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return $}registration(){let $=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement($).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let $=this.random.int(2000,2024),Z=this.manufacturer(),X=this.model();return`${$} ${Z} ${X}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let $=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement($)}}class P1{random;locale;constructor($,Z){this.random=$,this.locale=Z}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let $=["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($)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let $=["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($)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let $=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement($)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let $=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement($)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let $=["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($)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let $=["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($)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let $=["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($)}sample(){let $=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],Z=this.random.arrayElement($);return this[Z]()}words($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.sample());return Z.join(" ")}}class H5{seed;constructor($){this.seed=$}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($=0,Z=100){return Math.floor(this.number()*(Z-$+1))+$}float($=0,Z=1,X=2){let _=this.number()*(Z-$)+$;return Number.parseFloat(_.toFixed(X))}arrayElement($){if($.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return $[Math.floor(Math.random()*$.length)];return $[this.int(0,$.length-1)]}arrayElements($,Z){if($.length===0)return[];let X=Z??this.int(1,$.length);return[...$].sort(()=>this.number()-0.5).slice(0,Math.min(X,$.length))}shuffle($){let Z=[...$];for(let X=Z.length-1;X>0;X--){let _=this.int(0,X);[Z[X],Z[_]]=[Z[_],Z[X]]}return Z}boolean($=0.5){return this.number()<$}replaceSymbols($){if(this.seed===void 0){let Z="";for(let X=0;X<$.length;X++){let _=$[X];if(_==="#")Z+="0123456789"[Math.floor(Math.random()*10)];else if(_==="?")Z+=j6[Math.floor(Math.random()*26)];else Z+=_}return Z}return $.replace(/[#?]/g,(Z)=>{if(Z==="#")return String(this.int(0,9));return this.arrayElement(j6)})}replaceCreditCardSymbols($="####-####-####-####",Z="#"){return $.replace(new RegExp(Z,"g"),()=>String(this.int(0,9)))}weightedArrayElement($){if($.length===0)throw Error("Cannot pick from empty weighted items array");let Z=$.reduce((Y,L)=>Y+L.weight,0);if(Z<=0)throw Error("Total weight must be greater than 0");let X=this.number()*Z,_=0;for(let Y of $)if(_+=Y.weight,X<=_)return Y.item;return $[$.length-1].item}weightedArrayElements($,Z,X=!1){if($.length===0)return[];let _=Z??this.int(1,$.length),Y=[],L=[...$];for(let z=0;z<_&&L.length>0;z++){let j=this.weightedArrayElement(L);if(Y.push(j),!X){let U=L.findIndex((Q)=>Q.item===j);if(U!==-1)L.splice(U,1)}}return Y}weightedBoolean($=0.5){return this.number()<$}weightedInt($,Z,X){let _=Z-$+1;if(X){if(X.length!==_)throw Error("Weights array length must match the range size");let Y=X.map((L,z)=>({item:$+z,weight:L}));return this.weightedArrayElement(Y)}return this.int($,Z)}}class y5{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($){let Z=$?.locale??"en",X=$?.seed;if(this._autoInstallLocales=$?.autoInstallLocales??!1,Z!=="en"&&!_9.isCached(Z))console.warn(`[ts-mocker] Locale '${Z}' requires async loading. Use 'await Faker.create({ locale: "${Z}" })' for better performance. Falling back to English.`),this._locale=_9.loadSync("en");else this._locale=_9.loadSync(Z);this.random=new H5(X),this.person=new S1(this.random,this._locale),this.address=new Q1(this.random,this._locale),this.internet=new D1(this.random,this._locale),this.phone=new M1(this.random,this._locale),this.company=new K1(this.random,this._locale),this.lorem=new S5(this.random),this.date=new K5(this.random),this.number=new M5(this.random),this.string=new w5(this.random),this.color=new V1(this.random,this._locale),this.finance=new I5(this.random),this.helpers=new D5(this.random),this.image=new R5(this.random),this.git=new J5(this.random),this.science=new w1(this.random,this._locale),this.music=new R1(this.random,this._locale),this.database=new W5(this.random),this.food=new I1(this.random,this._locale),this.commerce=new W1(this.random,this._locale),this.book=new F1(this.random,this._locale),this.animal=new G1(this.random,this._locale),this.sport=new H1(this.random,this._locale),this.hacker=new J1(this.random,this._locale),this.system=new q1(this.random,this._locale),this.word=new P1(this.random,this._locale),this.vehicle=new T1(this.random,this._locale)}static async create($){let Z=$?.locale??"en";return await _9.load(Z),new y5($)}seed($){return this.random=new H5($),Object.assign(this.person,new S1(this.random,this._locale)),Object.assign(this.address,new Q1(this.random,this._locale)),Object.assign(this.internet,new D1(this.random,this._locale)),Object.assign(this.phone,new M1(this.random,this._locale)),Object.assign(this.company,new K1(this.random,this._locale)),Object.assign(this.lorem,new S5(this.random)),Object.assign(this.date,new K5(this.random)),Object.assign(this.number,new M5(this.random)),Object.assign(this.string,new w5(this.random)),Object.assign(this.color,new V1(this.random,this._locale)),Object.assign(this.finance,new I5(this.random)),Object.assign(this.helpers,new D5(this.random)),Object.assign(this.image,new R5(this.random)),Object.assign(this.git,new J5(this.random)),Object.assign(this.science,new w1(this.random,this._locale)),Object.assign(this.music,new R1(this.random,this._locale)),Object.assign(this.database,new W5(this.random)),Object.assign(this.food,new I1(this.random,this._locale)),Object.assign(this.commerce,new W1(this.random,this._locale)),Object.assign(this.book,new F1(this.random,this._locale)),Object.assign(this.animal,new G1(this.random,this._locale)),Object.assign(this.sport,new H1(this.random,this._locale)),Object.assign(this.hacker,new J1(this.random,this._locale)),Object.assign(this.system,new q1(this.random,this._locale)),Object.assign(this.word,new P1(this.random,this._locale)),Object.assign(this.vehicle,new T1(this.random,this._locale)),this}async setLocale($){return this._locale=await _9.load($),this.reinitializeLocaleModules(),this}setLocaleSync($){if(!_9.isCached($)&&$!=="en")return console.warn(`[ts-mocker] Locale '${$}' is not loaded. Use 'await faker.setLocale("${$}")' or preload it first.`),this;return this._locale=_9.loadSync($),this.reinitializeLocaleModules(),this}async preloadLocales($){return await _9.preload($),this}reinitializeLocaleModules(){Object.assign(this.person,new S1(this.random,this._locale)),Object.assign(this.address,new Q1(this.random,this._locale)),Object.assign(this.internet,new D1(this.random,this._locale)),Object.assign(this.phone,new M1(this.random,this._locale)),Object.assign(this.company,new K1(this.random,this._locale)),Object.assign(this.food,new I1(this.random,this._locale)),Object.assign(this.animal,new G1(this.random,this._locale)),Object.assign(this.sport,new H1(this.random,this._locale)),Object.assign(this.music,new R1(this.random,this._locale)),Object.assign(this.commerce,new W1(this.random,this._locale)),Object.assign(this.book,new F1(this.random,this._locale)),Object.assign(this.vehicle,new T1(this.random,this._locale)),Object.assign(this.word,new P1(this.random,this._locale)),Object.assign(this.hacker,new J1(this.random,this._locale)),Object.assign(this.system,new q1(this.random,this._locale)),Object.assign(this.color,new V1(this.random,this._locale)),Object.assign(this.science,new w1(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return _9.getAvailableLocales()}static isLocaleLoaded($){return _9.isCached($)}static async preloadLocales($){await _9.preload($)}name(){return this.person.name()}email(){return this.internet.email()}}function H9($){if(!N$)try{N$=(i$(),e_(S4)).getModel}catch{N$=()=>{return}}return N$($)}function J0(){if(!cZ)cZ=new lj(":memory:",{create:!0});return cZ}function nj($){let Z=new Set,X=$.belongsToMany;if(!X)return Z;if(Array.isArray(X)){for(let _ of X)if(typeof _==="string")Z.add(_.toLowerCase());else if(_&&typeof _==="object"&&_.model)Z.add(_.model.toLowerCase())}else if(typeof X==="object")for(let _ of Object.keys(X))Z.add(_);return Z}class Y9{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor($,Z={}){this._definition=$,this._attributes={...Z},this._original=null;let X=nj($);if(X.size===0)return;let _=this;return new Proxy(this,{get(Y,L,z){if(typeof L==="string"&&X.has(L)&&!(L in Y))return()=>{let j=J4($,L);if(!j||j.type!=="belongsToMany")throw Error(`[orm] relation '${L}' did not resolve to a belongsToMany on '${$.name}'`);let U=H9(j.relatedModelName),Q=U?.getDefinition?.()||U?.definition;if(!Q)throw Error(`[orm] related model '${j.relatedModelName}' is not registered`);return new D4(_,$,j,Q)};return Reflect.get(Y,L,z)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get($){let Z=this._definition.get?.[$];if(Z)try{let X=Z(this._attributes);if(X!==void 0)return X}catch{}return this._attributes[$]}getAttribute($){return this._attributes[$]}getAttributes(){return{...this._attributes}}set($,Z){if(this._original===null)this._original={...this._attributes};this._attributes[$]=Z}only($){let Z={};for(let X of $)Z[X]=this._attributes[X];return Z}except($){let Z=new Set($.map((_)=>_)),X={};for(let _ of Object.keys(this._attributes))if(!Z.has(_))X[_]=this._attributes[_];return X}getRelation($){return this._relations[$]}setRelation($,Z){this._relations[$]=Z}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let $=this._definition.primaryKey||"id";return this._attributes[$]}isDirty($){if(this._original===null)return!1;if($)return this._attributes[$]!==this._original[$];return Object.keys(this._attributes).some((Z)=>this._attributes[Z]!==this._original[Z])}isClean($){return!this.isDirty($)}getOriginal($){return this.getOriginalAttributes()[$]}getChanges(){if(this._original===null)return{};let $={};for(let Z of Object.keys(this._attributes))if(this._attributes[Z]!==this._original[Z])$[Z]=this._attributes[Z];return $}fill($){let Z=this._definition.attributes;for(let[X,_]of Object.entries($)){let Y=Z[X];if(Y?.fillable&&!Y?.guarded)this._attributes[X]=_}return this}forceFill($){return Object.assign(this._attributes,$),this}save(){let $=J0(),Z=this._definition.primaryKey||"id",X=this._definition.hooks,_=this._definition.set||{};for(let[Y,L]of Object.entries(_))if(this.isDirty(Y))this._attributes[Y]=L(this._attributes);if(this._attributes[Z]){X?.beforeUpdate?.(this,this.getChanges());let Y=this.getChanges(),L=Object.keys(Y);if(L.length>0){let z=L.map((U)=>`${U} = ?`).join(", "),j=[...Object.values(Y),this._attributes[Z]];if(this._definition.traits?.useTimestamps){let U=new Date().toISOString();$.run(`UPDATE ${this._definition.table} SET ${z}, updated_at = ? WHERE ${Z} = ?`,[...Object.values(Y),U,this._attributes[Z]])}else $.run(`UPDATE ${this._definition.table} SET ${z} WHERE ${Z} = ?`,j)}X?.afterUpdate?.(this)}else{let Y=this._definition.attributes,L={};for(let[Q,E]of Object.entries(Y))if(E.fillable&&this._attributes[Q]!==void 0)L[Q]=this._attributes[Q];if(this._definition.traits?.useTimestamps){let Q=new Date().toISOString();L.created_at=Q,L.updated_at=Q}if(this._definition.traits?.useUuid&&!L.uuid)L.uuid=crypto.randomUUID();X?.beforeCreate?.(L);let z=Object.keys(L),j=z.map(()=>"?").join(", "),U=$.run(`INSERT INTO ${this._definition.table} (${z.join(", ")}) VALUES (${j})`,Object.values(L));for(let[Q,E]of Object.entries(L))this._attributes[Q]=E;this._attributes[Z]=U.lastInsertRowid,X?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}update($){return this.fill($),this.save()}fresh(){let $=J0(),Z=this._definition.primaryKey||"id",X=this._attributes[Z];if(X==null)return null;let _=$.query(`SELECT * FROM ${this._definition.table} WHERE ${Z} = ?`).get(X);if(!_)return null;return new Y9(this._definition,_)}delete(){let $=J0(),Z=this._definition.primaryKey||"id",X=this._attributes[Z],_=this._definition.hooks;if(!X)throw Error("Cannot delete a model without a primary key");if(_?.beforeDelete?.(this),this._definition.traits?.useSoftDeletes)$.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${Z} = ?`,[new Date().toISOString(),X]);else $.run(`DELETE FROM ${this._definition.table} WHERE ${Z} = ?`,[X]);return _?.afterDelete?.(this),!0}refresh(){let $=J0(),Z=this._definition.primaryKey||"id",X=this._attributes[Z];if(!X)throw Error("Cannot refresh a model without a primary key");let _=$.query(`SELECT * FROM ${this._definition.table} WHERE ${Z} = ?`).get(X);if(!_)return null;return this._attributes=_,this._original=null,this}replicate(){let $=this._definition.primaryKey||"id",Z={...this._attributes};return delete Z[$],delete Z.uuid,delete Z.created_at,delete Z.updated_at,new Y9(this._definition,Z)}toArray(){let $={...this._attributes};for(let[Z,X]of Object.entries(this._relations))if(Array.isArray(X))$[Z]=X.map((_)=>_.toArray());else if(X)$[Z]=X.toArray();else $[Z]=null;return $}toJSON(){let $=new Set;for(let[X,_]of Object.entries(this._definition.attributes))if(_.hidden)$.add(X);let Z={};for(let[X,_]of Object.entries(this._attributes))if(!$.has(X))Z[X]=_;for(let[X,_]of Object.entries(this._relations))if(Array.isArray(_))Z[X]=_.map((Y)=>Y.toJSON());else if(_)Z[X]=_.toJSON();else Z[X]=null;return Z}}function n$($){let Z=O6.get($);if(Z!==void 0)return Z;return Z=$.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),O6.set($,Z),Z}function Y1($){let Z=Q6.get($);if(Z!==void 0)return Z;let X=n$($);if(X.endsWith("y")&&!X.endsWith("ay")&&!X.endsWith("ey")&&!X.endsWith("oy")&&!X.endsWith("uy"))Z=X.slice(0,-1)+"ies";else if(X.endsWith("s")||X.endsWith("x")||X.endsWith("ch")||X.endsWith("sh"))Z=`${X}es`;else Z=`${X}s`;return Q6.set($,Z),Z}function J4($,Z){let{name:X,table:_}=$,Y=$.primaryKey||"id";function L(G){if(!G)return null;if(Array.isArray(G)){for(let F of G){let O=typeof F==="string"?F:F?.model||"";if(O&&O.toLowerCase()===Z.toLowerCase())return O}return null}if(typeof G==="object"){for(let[F,O]of Object.entries(G))if(F===Z||F.toLowerCase()===Z.toLowerCase())return typeof O==="string"?O:O?.model||O?.target||F}return null}function z(){let G=$.belongsToMany;if(!G)return null;if(Array.isArray(G)){for(let F of G)if(typeof F==="string"){if(F.toLowerCase()===Z.toLowerCase())return{entry:F}}else if(F&&typeof F==="object"&&F.model){if(F.model.toLowerCase()===Z.toLowerCase())return{entry:F}}return null}if(typeof G==="object"){for(let[F,O]of Object.entries(G))if(F===Z||F.toLowerCase()===Z.toLowerCase())return{entry:O}}return null}let j=L($.hasMany);if(j){let F=H9(j)?.getTable?.()||Y1(j),O=n$(X)+"_id";return{type:"hasMany",relatedModelName:j,relatedTable:F,foreignKey:O,localKey:Y}}let U=L($.hasOne);if(U){let F=H9(U)?.getTable?.()||Y1(U),O=n$(X)+"_id";return{type:"hasOne",relatedModelName:U,relatedTable:F,foreignKey:O,localKey:Y}}let Q=L($.belongsTo);if(Q){let G=H9(Q),F=G?.getTable?.()||Y1(Q),O=G?.getDefinition?.()?.primaryKey||"id",K=n$(Q)+"_id";return{type:"belongsTo",relatedModelName:Q,relatedTable:F,foreignKey:K,localKey:O}}let E=z();if(E){let G=typeof E.entry==="object",F=G?E.entry.model:E.entry,K=H9(F)?.getTable?.()||Y1(F),W=G?E.entry:null,w,J;if(W?.table)w=W.table;else if(W?.through){J=W.through;let N=H9(W.through);if(!N)throw Error(`[orm] belongsToMany relation '${Z}' on '${X}' references unknown through model '${W.through}'. Make sure '${W.through}' is registered.`);w=N.getTable?.()||N.getDefinition?.()?.table||Y1(W.through)}else{let N=_.endsWith("s")?_.slice(0,-1):_,B=K.endsWith("s")?K.slice(0,-1):K;w=[N,B].sort().join("_")}let R=W?.foreignKey||`${_.endsWith("s")?_.slice(0,-1):_}_id`,M=W?.relatedKey||`${K.endsWith("s")?K.slice(0,-1):K}_id`,q=[];if(W?.pivot?.columns)for(let N of Object.keys(W.pivot.columns))q.push(N);if(J){let N=H9(J),B=N?.getDefinition?.()||N?.definition,A=B?.attributes??{},f=B?.primaryKey??"id";for(let p of Object.keys(A)){if(p===R||p===M||p===f)continue;if(!q.includes(p))q.push(p)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:K,foreignKey:R,localKey:Y,pivotTable:w,pivotFkParent:R,pivotFkRelated:M,pivotColumns:q,pivotModelName:J,pivotTimestamps:Boolean(W?.pivot?.timestamps)}}return null}class D4{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor($,Z,X,_){this._parent=$,this._parentDef=Z,this._resolved=X,this._relatedDef=_}get parentId(){let $=this._parentDef.primaryKey||"id";return this._parent.get($)}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($,Z,X){if(X===void 0)this._wheres.push({sql:`${this.relatedTable}.${$} = ?`,params:[Z]});else this._wheres.push({sql:`${this.relatedTable}.${$} ${String(Z)} ?`,params:[X]});return this}wherePivot($,Z,X){if(X===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${$} = ?`,params:[Z]});else this._pivotWheres.push({sql:`${this.pivotTable}.${$} ${String(Z)} ?`,params:[X]});return this}wherePivotIn($,Z){if(!Z.length)return this;let X=Z.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IN (${X})`,params:[...Z]}),this}wherePivotNotIn($,Z){if(!Z.length)return this;let X=Z.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} NOT IN (${X})`,params:[...Z]}),this}wherePivotNull($){return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IS NULL`,params:[]}),this}wherePivotNotNull($){return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IS NOT NULL`,params:[]}),this}orderBy($,Z="asc"){return this._orderBy.push(`${$} ${Z.toUpperCase()}`),this}limit($){return this._limit=$,this}offset($){return this._offset=$,this}buildSelect(){let $=[],Z=`SELECT ${this.relatedTable}.*, ${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} = ?`,$.push(this.parentId);for(let X of this._pivotWheres)Z+=` AND ${X.sql}`,$.push(...X.params);for(let X of this._wheres)Z+=` AND ${X.sql}`,$.push(...X.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:$}}hydrateRows($){let Z=new Set(Object.keys(this._relatedDef.attributes??{}));Z.add(this.relatedPk),Z.add("created_at"),Z.add("updated_at"),Z.add("deleted_at");let X=this.fkParent,_=this.fkRelated;return $.map((Y)=>{let L={},z={};for(let[U,Q]of Object.entries(Y)){if(U===X||U===_)continue;if(Z.has(U))L[U]=Q;else z[U]=Q}L[this.relatedPk]=Y[this.relatedPk];let j=new Y9(this._relatedDef,L);return j.pivot=z,j})}get(){let $=J0(),{sql:Z,params:X}=this.buildSelect(),_=$.query(Z).all(...X);return this.hydrateRows(_)}first(){return this._limit=1,this.get()[0]}count(){let $=J0(),Z=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,X=[this.parentId];for(let _ of this._pivotWheres)Z+=` AND ${_.sql}`,X.push(..._.params);return $.query(Z).get(...X).count}exists(){return this.count()>0}now(){return new Date().toISOString()}attach($,Z={}){let X=J0(),_=Array.isArray($)?$:[$];if(_.length===0)return 0;let Y=this._resolved.pivotTimestamps?this.now():null,L=0;for(let z of _){let j={[this.fkParent]:this.parentId,[this.fkRelated]:z,...Z};if(Y){if(j.created_at===void 0)j.created_at=Y;if(j.updated_at===void 0)j.updated_at=Y}let U=Object.keys(j),Q=U.map(()=>"?").join(", "),E=`INSERT INTO ${this.pivotTable} (${U.join(", ")}) VALUES (${Q})`,G=U.map((F)=>j[F]);X.run(E,G),L++}return L}detach($){let Z=J0(),X=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,_=[this.parentId];if($!==void 0&&$!==null){let Y=Array.isArray($)?$:[$];if(Y.length===0)return 0;let L=Y.map(()=>"?").join(", ");X+=` AND ${this.fkRelated} IN (${L})`,_.push(...Y)}return Z.run(X,_).changes}updateExistingPivot($,Z){let X=J0(),_={...Z};if(this._resolved.pivotTimestamps&&_.updated_at===void 0)_.updated_at=this.now();let Y=Object.keys(_);if(Y.length===0)return 0;let L=Y.map((U)=>`${U} = ?`).join(", "),z=`UPDATE ${this.pivotTable} SET ${L} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,j=[...Y.map((U)=>_[U]),this.parentId,$];return X.run(z,j).changes}sync($){let Z=J0(),X=new Map;for(let Q of $)if(Q!=null&&typeof Q==="object"&&"id"in Q){let{id:E,...G}=Q;X.set(E,G)}else X.set(Q,{});let _=Z.query(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`).all(this.parentId),Y=new Set(_.map((Q)=>Q[this.fkRelated])),L=[],z=[],j=[],U=[...Y].filter((Q)=>!X.has(Q));if(U.length>0)this.detach(U),z.push(...U);for(let[Q,E]of X)if(!Y.has(Q))this.attach(Q,E),L.push(Q);else if(Object.keys(E).length>0)this.updateExistingPivot(Q,E),j.push(Q);return{attached:L,detached:z,updated:j}}toggle($){let Z=J0(),X=Array.isArray($)?$:[$];if(X.length===0)return{attached:[],detached:[]};let _=X.map(()=>"?").join(", "),Y=Z.query(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${_})`).all(this.parentId,...X),L=new Set(Y.map((U)=>U[this.fkRelated])),z=X.filter((U)=>!L.has(U)),j=X.filter((U)=>L.has(U));if(z.length>0)this.attach(z);if(j.length>0)this.detach(j);return{attached:z,detached:j}}}class t{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor($){this._definition=$}where($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"and"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"and"});return this}orWhere($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"or"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"or"});return this}whereIn($,Z){return this._wheres.push({column:$,operator:"in",value:Z,boolean:"and"}),this}orWhereIn($,Z){return this._wheres.push({column:$,operator:"in",value:Z,boolean:"or"}),this}whereNotIn($,Z){return this._wheres.push({column:$,operator:"not in",value:Z,boolean:"and"}),this}orWhereNotIn($,Z){return this._wheres.push({column:$,operator:"not in",value:Z,boolean:"or"}),this}whereNull($){return this._wheres.push({column:$,operator:"=",value:null,boolean:"and"}),this}orWhereNull($){return this._wheres.push({column:$,operator:"=",value:null,boolean:"or"}),this}whereNotNull($){return this._wheres.push({column:$,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull($){return this._wheres.push({column:$,operator:"!=",value:null,boolean:"or"}),this}whereLike($,Z){return this._wheres.push({column:$,operator:"like",value:Z,boolean:"and"}),this}orWhereLike($,Z){return this._wheres.push({column:$,operator:"like",value:Z,boolean:"or"}),this}whereNotLike($,Z){return this._wheres.push({column:$,operator:"not like",value:Z,boolean:"and"}),this}orWhereNotLike($,Z){return this._wheres.push({column:$,operator:"not like",value:Z,boolean:"or"}),this}whereRaw($,...Z){return this._wheres.push({raw:$,rawParams:Z,boolean:"and"}),this}orWhereRaw($,...Z){return this._wheres.push({raw:$,rawParams:Z,boolean:"or"}),this}whereGroup($){return this._addGroup("and",$)}orWhereGroup($){return this._addGroup("or",$)}_addGroup($,Z){let X=new t(this._definition);if(Z(X),X._wheres.length===0)return this;let _=[],Y=X.buildWhereClauses(_);if(!Y)return this;return this._wheres.push({raw:`(${Y})`,rawParams:_,boolean:$}),this}whereBetween($,Z){return this._wheres.push({column:$,operator:">=",value:Z[0],boolean:"and"}),this._wheres.push({column:$,operator:"<=",value:Z[1],boolean:"and"}),this}whereNotBetween($,Z){return this._wheres.push({column:$,operator:"<",value:Z[0],boolean:"and"}),this._wheres.push({column:$,operator:">",value:Z[1],boolean:"or"}),this}when($,Z){if($)return Z(this);return this}orderBy($,Z="asc"){return this._orderBy.push({column:$,direction:Z}),this}orderByDesc($){return this.orderBy($,"desc")}orderByAsc($){return this.orderBy($,"asc")}limit($){return this._limit=$,this}take($){return this.limit($)}offset($){return this._offset=$,this}skip($){return this.offset($)}select(...$){return this._select=$,this}with(...$){return this._withRelations=$,this}getWithRelations(){return this._withRelations}buildWhereClauses($){let Z=[];for(let X=0;X<this._wheres.length;X++){let _=this._wheres[X],Y;if(_.raw){if(Y=_.raw,_.rawParams&&_.rawParams.length>0)$.push(..._.rawParams)}else if(_.value===null)Y=_.operator==="="?`${_.column} IS NULL`:`${_.column} IS NOT NULL`;else if(_.operator==="in"||_.operator==="not in"){let L=_.value;Y=`${_.column} ${_.operator.toUpperCase()} (${L.map(()=>"?").join(", ")})`,$.push(...L)}else Y=`${_.column} ${_.operator} ?`,$.push(_.value);Z.push(X===0?Y:`${_.boolean.toUpperCase()} ${Y}`)}return Z.join(" ")}buildQuery(){let $=[],Z=`SELECT ${this._select.join(", ")} FROM ${this._definition.table}`;if(this._wheres.length>0)Z+=` WHERE ${this.buildWhereClauses($)}`;if(this._orderBy.length>0)Z+=` ORDER BY ${this._orderBy.map((X)=>`${X.column} ${X.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Z+=` OFFSET ${this._offset}`;return{sql:Z,params:$}}toSql(){return this.buildQuery()}eagerLoadRelations($){if($.length===0||this._withRelations.length===0)return;let Z=J0(),X=this._definition.primaryKey||"id";for(let _ of this._withRelations){let Y=`${this._definition.name}:${_}`,L=G6.get(Y);if(L===void 0)L=J4(this._definition,_),G6.set(Y,L);if(!L)continue;if(L.type==="hasMany"||L.type==="hasOne"){let z=$.map((G)=>G.get(X)).filter((G)=>G!=null);if(z.length===0)continue;let j=z.map(()=>"?").join(", "),U=Z.query(`SELECT * FROM ${L.relatedTable} WHERE ${L.foreignKey} IN (${j})`).all(...z),Q=H9(L.relatedModelName),E=Q?.getDefinition?.()||Q?.definition||this._definition;if(L.type==="hasMany"){let G=new Map;for(let F of U){let O=F[L.foreignKey];if(!G.has(O))G.set(O,[]);G.get(O).push(F)}for(let F of $){let O=G.get(F.get(X))||[];F.setRelation(_,O.map((K)=>new Y9(E,K)))}}else{let G=new Map;for(let F of U)G.set(F[L.foreignKey],F);for(let F of $){let O=G.get(F.get(X));F.setRelation(_,O?new Y9(E,O):null)}}}if(L.type==="belongsTo"){let z=$.map((O)=>O._attributes[L.foreignKey]).filter((O)=>O!=null),j=[...new Set(z)];if(j.length===0)continue;let U=j.map(()=>"?").join(", "),Q=Z.query(`SELECT * FROM ${L.relatedTable} WHERE ${L.localKey} IN (${U})`).all(...j),E=H9(L.relatedModelName),G=E?.getDefinition?.()||E?.definition||this._definition,F=new Map;for(let O of Q)F.set(O[L.localKey],O);for(let O of $){let K=O._attributes[L.foreignKey],W=F.get(K);O.setRelation(_,W?new Y9(G,W):null)}}if(L.type==="belongsToMany"){let z=$.map((J)=>J.get(X)).filter((J)=>J!=null);if(z.length===0)continue;if(!L.pivotTable||!L.pivotFkParent||!L.pivotFkRelated)continue;let j=z.map(()=>"?").join(", "),U=Z.query(`SELECT * FROM ${L.pivotTable} WHERE ${L.pivotFkParent} IN (${j})`).all(...z);if(U.length===0){for(let J of $)J.setRelation(_,[]);continue}let Q=[...new Set(U.map((J)=>J[L.pivotFkRelated]))].filter((J)=>J!=null),E=H9(L.relatedModelName),G=E?.getDefinition?.()||E?.definition||this._definition,F=G?.primaryKey||"id",O=[];if(Q.length>0){let J=Q.map(()=>"?").join(", ");O=Z.query(`SELECT * FROM ${L.relatedTable} WHERE ${F} IN (${J})`).all(...Q)}let K=new Map;for(let J of O)K.set(J[F],J);let W=new Map;for(let J of U){let R=J[L.pivotFkParent];if(!W.has(R))W.set(R,[]);W.get(R).push(J)}let w=new Set([L.pivotFkParent,L.pivotFkRelated]);for(let J of $){let R=J.get(X),q=(W.get(R)||[]).map((N)=>{let B=K.get(N[L.pivotFkRelated]);if(!B)return null;let A=new Y9(G,B),f={};for(let[p,c]of Object.entries(N))if(!w.has(p))f[p]=c;return A.pivot=f,A}).filter((N)=>N!==null);J.setRelation(_,q)}}}}get(){let $=J0(),{sql:Z,params:X}=this.buildQuery(),Y=$.query(Z).all(...X).map((L)=>new Y9(this._definition,L));if(this._withRelations.length>0)this.eagerLoadRelations(Y);return Y}first(){return this._limit=1,this.get()[0]}firstOrFail(){let $=this.first();if(!$)throw Error(`No ${this._definition.name} found`);return $}last(){let $=this._definition.primaryKey||"id";return this._orderBy=[{column:$,direction:"desc"}],this._limit=1,this.get()[0]}count(){let $=J0(),Z=[],X=`SELECT COUNT(*) as count FROM ${this._definition.table}`;if(this._wheres.length>0)X+=` WHERE ${this.buildWhereClauses(Z)}`;return $.query(X).get(...Z).count}exists(){return this.count()>0}doesntExist(){return this.count()===0}sole(){this._limit=2;let $=this.get();if($.length===0)throw Error(`No ${this._definition.name} found`);if($.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return $[0]}increment($,Z=1){let X=J0(),_=[Z],Y=`UPDATE ${this._definition.table} SET ${$} = ${$} + ?`;if(this._definition.traits?.useTimestamps)Y+=", updated_at = ?",_.push(new Date().toISOString());if(this._wheres.length>0){let L=this.buildWhereClauses(_);Y+=` WHERE ${L}`}return X.run(Y,_).changes}decrement($,Z=1){return this.increment($,-Z)}chunk($,Z){let X=0;while(!0){let _=new t(this._definition);_._wheres=[...this._wheres],_._orderBy=[...this._orderBy],_._select=[...this._select],_._withRelations=[...this._withRelations],_._limit=$,_._offset=X*$;let Y=_.get();if(Y.length===0)break;if(Z(Y)===!1)break;if(Y.length<$)break;X++}}paginate($=1,Z=15){let X=this.count(),_=Math.ceil(X/Z);this._limit=Z,this._offset=($-1)*Z;let Y=this.get();return{data:Y,total:X,page:$,perPage:Z,lastPage:_,hasMorePages:$<_,isEmpty:Y.length===0,from:Y.length>0?($-1)*Z+1:null,to:Y.length>0?($-1)*Z+Y.length:null}}pluck($){let Z=J0(),X=[],_=`SELECT ${$} FROM ${this._definition.table}`;if(this._wheres.length>0)_+=` WHERE ${this.buildWhereClauses(X)}`;if(this._orderBy.length>0)_+=` ORDER BY ${this._orderBy.map((L)=>`${L.column} ${L.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)_+=` LIMIT ${this._limit}`;if(this._offset!==void 0)_+=` OFFSET ${this._offset}`;return Z.query(_).all(...X).map((L)=>L[$])}aggregate($,Z){let X=J0(),_=[],Y=`SELECT ${$}(${Z}) as v FROM ${this._definition.table}`;if(this._wheres.length>0)Y+=` WHERE ${this.buildWhereClauses(_)}`;return X.query(Y).get(..._)?.v??null}max($){return this.aggregate("MAX",$)}min($){return this.aggregate("MIN",$)}avg($){return this.aggregate("AVG",$)||0}sum($){return this.aggregate("SUM",$)||0}delete(){let $=J0(),Z=[],X=`DELETE FROM ${this._definition.table}`;if(this._wheres.length>0)X+=` WHERE ${this.buildWhereClauses(Z)}`;return $.run(X,Z).changes}update($){let Z=J0(),X=Object.entries($),_=X.map(([z])=>`${z} = ?`).join(", "),Y=X.map(([,z])=>z);if(this._definition.traits?.useTimestamps)Y.push(new Date().toISOString());let L=`UPDATE ${this._definition.table} SET ${_}${this._definition.traits?.useTimestamps?", updated_at = ?":""}`;if(this._wheres.length>0)L+=` WHERE ${this.buildWhereClauses(Y)}`;return Z.run(L,Y).changes}}function ij($){let Z={query:()=>new t($),where(X,_,Y){return new t($).where(X,_,Y)},orWhere(X,_,Y){return new t($).orWhere(X,_,Y)},whereIn(X,_){return new t($).whereIn(X,_)},whereNotIn(X,_){return new t($).whereNotIn(X,_)},whereNull(X){return new t($).whereNull(X)},whereNotNull(X){return new t($).whereNotNull(X)},whereLike(X,_){return new t($).whereLike(X,_)},orderBy(X,_="asc"){return new t($).orderBy(X,_)},orderByDesc(X){return new t($).orderByDesc(X)},select(...X){return new t($).select(...X)},with(...X){return new t($).with(...X)},limit:(X)=>new t($).limit(X),take:(X)=>new t($).take(X),skip:(X)=>new t($).skip(X),find(X){let _=J0(),Y=$.primaryKey||"id",L=`SELECT * FROM ${$.table} WHERE ${Y} = ?`,z=F6.get(L);if(!z)z=_.prepare(L),F6.set(L,z);let j=z.get(X);return j?new Y9($,j):void 0},findOrFail(X){let _=Z.find(X);if(!_)throw Error(`${$.name} with id ${X} not found`);return _},findMany(X){let _=J0(),Y=$.primaryKey||"id";return _.query(`SELECT * FROM ${$.table} WHERE ${Y} IN (${X.map(()=>"?").join(", ")})`).all(...X).map((z)=>new Y9($,z))},all:()=>new t($).get(),first:()=>new t($).first(),firstOrFail:()=>new t($).firstOrFail(),last:()=>new t($).last(),count:()=>new t($).count(),exists:()=>new t($).exists(),doesntExist:()=>new t($).doesntExist(),paginate:(X,_)=>new t($).paginate(X,_),whereBetween(X,_){return new t($).whereBetween(X,_)},whereNotBetween(X,_){return new t($).whereNotBetween(X,_)},create(X){let _=new Y9($,X);return _.save(),_},createMany(X){return X.map((_)=>this.create(_))},updateOrCreate(X,_){let Y=new t($);for(let[z,j]of Object.entries(X))Y=Y.where(z,j);let L=Y.first();if(L)return L.update(_),L;return this.create({...X,..._})},firstOrCreate(X,_){let Y=new t($);for(let[z,j]of Object.entries(X))Y=Y.where(z,j);return Y.first()||this.create({...X,..._})},destroy(X){let _=J0(),Y=$.primaryKey||"id";return _.run(`DELETE FROM ${$.table} WHERE ${Y} = ?`,[X]).changes>0},remove(X){return this.destroy(X)},truncate(){J0().run(`DELETE FROM ${$.table}`)},getDefinition:()=>$,getTable:()=>$.table,make(X={}){return new Y9($,X)},latest:(X="created_at")=>new t($).orderByDesc(X),oldest:(X="created_at")=>new t($).orderBy(X,"asc"),max:(X)=>new t($).max(X),min:(X)=>new t($).min(X),avg:(X)=>new t($).avg(X),sum:(X)=>new t($).sum(X),pluck(X){return new t($).pluck(X)}};return new Proxy(Z,{get(X,_){if(typeof _==="string"&&_.startsWith("where")&&_.length>5){let Y=_.slice(5),L=Y.charAt(0).toLowerCase()+Y.slice(1);if(L in $.attributes||L==="id"||L===$.primaryKey)return(z)=>new t($).where(L,z)}return Reflect.get(X,_)}})}function rj($){return E8.get($)}function oj(){return[...E8.values()]}function aj(){return Object.fromEntries(E8)}function tj($){return E8.has($)}function ej(){E8.clear()}function $E(){return typeof window<"u"&&typeof document<"u"}function ZE($){let Z;if($E())Z=YY($);else{let X=ij($);Z=Object.assign(X,{definition:$,getDefinition:()=>$,getTable:()=>$.table,getName:()=>$.name})}return E8.set($.name,Z),Z}function XE($){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...$}}async function w4($){let Z=$.cwd??EE.cwd(),X=$.modelsDir.startsWith("/")?$.modelsDir:`${Z}/${$.modelsDir}`,_={},Y=LE(X);for(let L of Y){let z=`${X}/${L}`;if(zE(z).isDirectory())continue;let U=jE(z);if(![".ts",".mts",".cts",".js",".mjs",".cjs"].includes(U))continue;let Q=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,E=await import(`${z}${Q}`),G=E.default??E,F=G.definition??G.getDefinition?.()??G,O=UE(L,U),K=F.name??O;_[K]={...F,name:K}}return _}function QE($){let Z={},X={},_={},Y={},L={};for(let z of Object.keys($)){let j=$[z],U=j.definition??j.getDefinition?.()??j,Q=U.table||`${String(U.name).toLowerCase()}s`;Z[z]=Q,X[Q]=z,_[Q]=U.primaryKey??"id";let E=(O)=>{if(!O)return{};if(Array.isArray(O)){let K={};for(let W of O)K[W]=W;return K}return O},G=(O)=>{if(!O)return{};if(Array.isArray(O)){let K={};for(let W of O)if(typeof W==="string")K[W]=W;else if(W&&typeof W==="object"&&typeof W.model==="string")K[W.model]=W;return K}return O},F=(O)=>{if(!O)return{};return O};if(Y[Q]={hasOne:E(U.hasOne),hasMany:E(U.hasMany),belongsTo:E(U.belongsTo),belongsToMany:G(U.belongsToMany),hasOneThrough:F(U.hasOneThrough),hasManyThrough:F(U.hasManyThrough),morphOne:E(U.morphOne),morphMany:E(U.morphMany),morphTo:U.morphTo,morphToMany:E(U.morphToMany),morphedByMany:E(U.morphedByMany)},U.scopes&&typeof U.scopes==="object"){L[Q]={};for(let O of Object.keys(U.scopes)){let K=U.scopes[O];if(typeof K==="function")L[Q][O]=K}}}return{modelToTable:Z,tableToModel:X,primaryKeys:_,relations:Y,scopes:L,models:$}}function k$($){return $.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 VE($){let Z=$;while(Z!==sX(Z)){if(H4(N6(Z,"package.json")))return Z;Z=sX(Z)}return q4.cwd()}function WE(){let $=VE(q4.cwd()),Z=N6($,"database","migrations");if(!H4(Z))GE(Z,{recursive:!0}),console.log(`-- Created SQL directory: ${Z}`);return Z}function f9($,Z){if(!$)return!1;let X=WE();N1++;let Y=`${k6?String(N1).padStart(10,"0"):String(Math.floor(Date.now()/1000)+N1)}-${Z}.sql`,L=N6(X,Y);return FE(L,$),console.log(`-- Migration file created: ${Y}`),p9++,!0}function lX($){if($.endsWith("_id"))return"bigint";if($.endsWith("_at"))return"datetime";if($.startsWith("is_")||$.startsWith("has_"))return"boolean";return}function nX($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="bigint"||$ instanceof Date)return $;return}function KE($){if($&&typeof $==="object"&&"name"in $){let Z=$;if(Z.name==="enum"||Z.getRules&&Array.isArray(Z.getRules())){if(Z.enumValues&&Array.isArray(Z.enumValues))return Z.enumValues.map((X)=>String(X));if(Z._values&&Array.isArray(Z._values))return Z._values.map((X)=>String(X));if(Z.values&&Array.isArray(Z.values))return Z.values.map((X)=>String(X))}}if($&&typeof $==="object"){let Z=$,X=Z.allowedValues||Z.enumValues||Z._values||Z.values;if(Array.isArray(X)&&X.length>0)return X.map((_)=>String(_))}return}function IE($){if(!$?.rules||!Array.isArray($.rules))return;for(let Z of $.rules)if(Z?.name==="max"||Z?.name==="maxLength"){if(Z.params&&typeof Z.params.max==="number")return Z.params.max;if(Array.isArray(Z.args)&&typeof Z.args[0]==="number")return Z.args[0];if(typeof Z.value==="number")return Z.value;if(typeof Z.expectedValue==="number")return Z.expectedValue}return}function JE($){if(!$||typeof $!=="object")return;let Z=$;if(Z.name)switch(String(Z.name).toLowerCase()){case"string":case"text":{let _=IE(Z);return _&&_>255?"text":"string"}case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"json":return"json";case"enum":return"enum"}if(Z.type){let X=String(Z.type).toLowerCase();if(X==="string"||X==="text")return"string";if(X==="integer"||X==="int")return"integer";if(X==="bigint")return"bigint";if(X==="float")return"float";if(X==="number")return"integer";if(X==="boolean")return"boolean";if(X==="date")return"date";if(X==="datetime")return"datetime";if(X==="json")return"json"}return}function DE($){if(!$)return[];if(Array.isArray($))return $;if(typeof $==="object")return Object.values($);return[]}function T4($,Z){let X=QE($),_=[];for(let z of Object.keys($)){let j=$[z],U=j.table||`${String(j.name).toLowerCase()}s`,Q=j.primaryKey??"id",E=j.autoIncrement!==!1,G=j.attributes??{},F=[],O=[];if(!G[Q])F.push({name:k$(Q),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let M of Object.keys(G)){let q=G[M],N=k$(M),B=!0,A,f,p=M===Q;if(A=JE(q.validation?.rule),!A||A==="enum"){let l=KE(q.validation?.rule);if(l&&l.length>0)A="enum",f=l}if(!A)A=lX(N);if(!A){let l=nX(q.default);if(typeof l==="string")A=l.length>255?"text":"string";else if(typeof l==="number")A=Number.isInteger(l)?"integer":"float";else if(typeof l==="boolean")A="boolean";else if(typeof l==="bigint")A="bigint";else if(l instanceof Date)A="datetime"}if(!A)A=p?"bigint":"string";let c={name:N,type:A,isPrimaryKey:p,isUnique:Boolean(q.unique),isNullable:!0,hasDefault:typeof q.default<"u",defaultValue:nX(q.default),enumValues:f};if(N.endsWith("_id")&&q.foreignKey!==!1)if(typeof q.foreignKey==="object"&&q.foreignKey!==null){let l=q.foreignKey;if(c.references={table:l.table,column:l.column??"id",onDelete:l.onDelete,onUpdate:l.onUpdate},l.nullable!==void 0)c.isNullable=l.nullable}else{let r0=N.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(s9,W0,y)=>y.toUpperCase()),K9=X.modelToTable[r0];if(K9){let s9=X.primaryKeys[K9]??"id";c.references={table:K9,column:s9}}}F.push(c)}let K=DE(j.belongsTo);for(let M of K){let q=`${k$(M)}_id`;if(F.some((A)=>A.name===q))continue;let N=X.modelToTable[M];if(!N)continue;let B=X.primaryKeys[N]??"id";F.push({name:q,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:N,column:B}})}let W=j.traits;if(W?.useTimestamps??W?.timestampable??!1){if(!F.some((M)=>M.name==="created_at"))F.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"});if(!F.some((M)=>M.name==="updated_at"))F.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(W?.useSoftDeletes??W?.softDeletable??!1){if(!F.some((M)=>M.name==="deleted_at"))F.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(W?.useUuid??!1){if(!F.some((M)=>M.name==="uuid"))F.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let M of j.indexes??[])O.push({name:M.name,columns:M.columns.map((q)=>k$(q)),type:M.unique?"unique":"index",where:M.where});for(let M of F)if(M.isUnique&&!M.isPrimaryKey)O.push({name:`${U}_${M.name}_unique`,columns:[M.name],type:"unique"});_.push({table:U,columns:F,indexes:O})}let Y=new Set(_.map((z)=>z.table));function L(z){if(!Y.has(z.table))Y.add(z.table),_.push(z)}for(let z of Object.keys($)){let j=$[z],U=j?.traits??{},Q=j.table||`${String(j.name).toLowerCase()}s`,E=Q.replace(/s$/,"");if(U.likeable){let G=typeof U.likeable==="object"?U.likeable:{},F=G.table||`${Q}_likes`,O=G.foreignKey||`${E}_id`;L({table:F,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:O,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:Q,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:`${F}_user_target_unique`,columns:["user_id",O],type:"unique"}]})}if(U.taggable)L({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(U.categorizable)L({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"}]}),L({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 z of Object.keys($)){let j=$[z],U=j?.belongsToMany;if(!U||typeof U!=="object"||Array.isArray(U))continue;let Q=j.table||`${String(j.name).toLowerCase()}s`,E=Q.replace(/s$/,"");for(let[G,F]of Object.entries(U)){let O=F;if(!O||typeof O!=="object")continue;if(O.through)continue;let K=O.pivot;if(!K||!K.columns&&!K.timestamps&&!K.uniques)continue;let W=O.model,J=$[W]?.table||`${String(W).toLowerCase()}s`,R=J.replace(/s$/,""),M=O.table||[E,R].sort().join("_"),q=O.foreignKey||`${E}_id`,N=O.relatedKey||`${R}_id`,B=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:q,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:Q,column:"id"}},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:J,column:"id"}}];if(K.columns)for(let[p,c]of Object.entries(K.columns)){let l=c,r0=lX(p)??"string";B.push({name:p,type:r0,isPrimaryKey:!1,isUnique:!1,isNullable:l?.nullable??!1,hasDefault:l?.default!==void 0,defaultValue:l?.default})}if(K.timestamps)B.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}),B.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let A=[],f=K.uniques&&K.uniques.length>0?K.uniques:[[q,N]];for(let p=0;p<f.length;p++){let c=f[p];A.push({name:`${M}_${c.join("_")}_unique${p>0?`_${p}`:""}`,columns:[...c],type:"unique"})}L({table:M,columns:B,indexes:A})}}return{dialect:Z.dialect,tables:_}}function P4($){N1=0,p9=0,r9=0,k6=!0;let Z=[],X=g8($.dialect);for(let Y of $.tables){let L=[],z=new Set;for(let Q of Y.columns)if(Q.type==="enum"&&Q.enumValues&&Q.enumValues.length>0){let E=`${Q.name}_type`;if(!z.has(E)){let G=X.createEnumType(E,Q.enumValues);if(G)L.push(G);z.add(E)}}let j=X.createTable(Y);L.push(j),Z.push(...L);let U=L.join(`
|
|
119
|
-
|
|
120
|
-
`);f9(U,`create-${Y.table}-table`)}for(let Y of $.tables)for(let L of Y.columns)if(L.references){let z=X.addForeignKey(Y.table,L.name,L.references.table,L.references.column,L.references.onDelete,L.references.onUpdate);Z.push(z),f9(z,`alter-${Y.table}-${L.name}`)}for(let Y of $.tables)for(let L of Y.indexes){let z=X.createIndex(Y.table,L);Z.push(z),f9(z,`create-${L.name}-index-in-${Y.table}`)}if(p9+r9===0)console.log("-- Nothing to migrate");else{let Y=[];if(p9>0)Y.push(`${p9} created`);if(r9>0)Y.push(`${r9} updated`);console.log(`-- Migration files: ${Y.join(", ")}`)}return Z}function RE($){let Z=XY("crypto");function X(Y){if(Y==null||typeof Y!=="object"||Y instanceof Date)return Y;if(Array.isArray(Y))return Y.map((z)=>X(z));let L={};for(let z of Object.keys(Y).sort())L[z]=X(Y[z]);return L}let _=JSON.stringify(X($));return Z.createHash("sha256").update(_).digest("hex")}function iX($){let Z={};for(let X of $)Z[X.table]=X;return Z}function C$($){let Z={};for(let X of $)Z[X.name]=X;return Z}function SE($,Z){if($.type!==Z.type)return!0;if($.isNullable!==Z.isNullable)return!0;if($.hasDefault!==Z.hasDefault)return!0;if($.defaultValue!==Z.defaultValue)return!0;if($.isUnique!==Z.isUnique)return!0;if($.type==="enum"&&Z.type==="enum"){let X=($.enumValues||[]).sort().join(","),_=(Z.enumValues||[]).sort().join(",");if(X!==_)return!0}return!1}function rX($){let Z={};for(let X of $){let _=`${X.type}:${X.name}:${X.columns.join(",")}`;Z[_]=X}return Z}function ME($,Z){if(!$||$.dialect!==Z.dialect)return P4(Z);N1=0,p9=0,r9=0,k6=!1;let X=[],_=g8(Z.dialect),Y=iX($.tables),L=iX(Z.tables);for(let U of Object.keys(Y))if(!L[U]){let Q=_.dropTable(U);X.push(Q),f9(Q,`drop-${U}-table`),console.log(`-- Detected dropped table: ${U}`)}for(let U of Object.keys(L))if(!Y[U]){let Q=L[U],E=[],G=new Set;for(let K of Q.columns)if(K.type==="enum"&&K.enumValues&&K.enumValues.length>0){let W=`${K.name}_type`;if(!G.has(W)){let w=_.createEnumType(W,K.enumValues);if(w)E.push(w);G.add(W)}}let F=_.createTable(Q);E.push(F),X.push(...E);let O=E.join(`
|
|
121
|
-
|
|
122
|
-
`);f9(O,`create-${Q.table}-table`)}for(let U of Object.keys(L))if(!Y[U]){let Q=L[U];for(let E of Q.indexes){let G=_.createIndex(Q.table,E);X.push(G),f9(G,`create-${E.name}-index-in-${Q.table}`)}}for(let U of Object.keys(L))if(!Y[U]){let Q=L[U];for(let E of Q.columns)if(E.references){let G=_.addForeignKey(Q.table,E.name,E.references.table,E.references.column,E.references.onDelete,E.references.onUpdate);X.push(G),f9(G,`alter-${Q.table}-${E.name}`)}}let z=new Set;for(let U of Object.keys(L)){let Q=Y[U],E=L[U];if(!Q)continue;let G=C$(Q.columns),F=C$(E.columns);for(let O of Object.keys(F))if(!G[O]){let K=F[O];if(K.type==="enum"&&K.enumValues&&K.enumValues.length>0){let W=`${K.name}_type`;if(!z.has(W)){let w=_.createEnumType(W,K.enumValues);if(w)X.push(w),f9(w,`create-${W}-enum`);z.add(W)}}}}for(let U of Object.keys(L)){let Q=Y[U],E=L[U];if(!Q)continue;let G=C$(Q.columns),F=C$(E.columns),O=rX(Q.indexes),K=rX(E.indexes),W=[],w=!1;for(let J of Object.keys(O))if(!K[J]){let R=O[J],M=_.dropIndex(E.table,R.name);W.push(M),X.push(M),console.log(`-- Detected dropped index: ${R.name} from ${E.table}`),w=!0}for(let J of Object.keys(G))if(!F[J]){let R=_.dropColumn(E.table,J);W.push(R),X.push(R),console.log(`-- Detected dropped column: ${E.table}.${J}`),w=!0}for(let J of Object.keys(F))if(G[J]&&F[J]){let R=G[J],M=F[J];if(SE(R,M)){let q=_.modifyColumn(E.table,M);W.push(q),X.push(q),console.log(`-- Detected column type change: ${E.table}.${J} (${R.type} -> ${M.type})`),w=!0}}for(let J of Object.keys(F))if(!G[J]){let R=F[J],M=_.addColumn(E.table,R);if(W.push(M),X.push(M),console.log(`-- Detected new column: ${E.table}.${R.name}`),w=!0,R.references){let q=_.addForeignKey(E.table,R.name,R.references.table,R.references.column,R.references.onDelete,R.references.onUpdate);W.push(q),X.push(q)}}for(let J of Object.keys(K))if(!O[J]){let R=K[J],M=_.createIndex(E.table,R);W.push(M),X.push(M),console.log(`-- Detected new index: ${R.name} in ${E.table}`),w=!0}if(w){let J=W.join(`
|
|
123
|
-
|
|
124
|
-
`);f9(J,`alter-${E.table}-table`)}}if(p9+r9===0)console.log("-- Nothing to migrate");else{let U=[];if(p9>0)U.push(`${p9} created`);if(r9>0)U.push(`${r9} updated`);console.log(`-- Migration files: ${U.join(", ")}`)}if(X.length===0)return["-- No changes detected"];return X}var dZ,r_,o_,a_,e_=($)=>{var Z=(L7??=new WeakMap).get($),X;if(Z)return Z;if(Z=dZ({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var _ of r_($))if(!a_.call(Z,_))dZ(Z,_,{get:t_.bind($,_),enumerable:!(X=o_($,_))||X.enumerable})}return L7.set($,Z),Z},L7,$Y=($)=>$,V6=($,Z)=>{for(var X in Z)dZ($,X,{get:Z[X],enumerable:!0,configurable:!0,set:ZY.bind(Z,X)})},n=($,Z)=>()=>($&&(Z=$($=0)),Z),XY,Z0,c9,LY,zY,aX,jY,EY,eX=()=>{},OY,QY,GY,C1,C5,S2,hL=($)=>$,vL=($,Z)=>{for(var X in Z)S2($,X,{get:Z[X],enumerable:!0,configurable:!0,set:$L.bind(Z,X)})},bL=($,Z)=>()=>($&&(Z=$($=0)),Z),FZ,M2,b8,x1,y7,fL,gL,h7,A$,oZ,h0,F0,pL,v7,cL,b7,dL,uL,VZ,mL,f7,g7,WZ,sL,lL,nL,iL,y$,w2,rL,f0,oL,aL,p7,h$,aZ,N0,Y0,tL,c7,eL,d7,$z,Zz,KZ,Xz,u7,m7,_z,IZ,Yz,Lz,zz,Uz,jz,v$,H2,Ez,Oz="0.15.6",X9,b$,U1,JZ,DZ,f$,RZ,SZ,j1,MZ,wZ,t9,s7,q2,D9,g9,l7,n7,i7,r7,E1,O1,Qz,k0,L0,Gz,o7,Fz,a7,Vz,Wz,HZ,Kz,t7,e7,Iz,qZ,Jz,Dz,Rz,Sz,Mz,g$,T2,wz,I9,$X,L5,ZX,XX,tZ,_X,YX,z5,LX,zX,U8,P2,M9,Hz,qz,Tz,Pz,UX,b,jX=null,q9,Nz,z1=null,eZ=null,$6=null,g,f8,yz,u,Z6,x5,pz,cz,dz,uz,mz,sz,lz,nz,iz,rz,oz=()=>{},B5=()=>{},az,p2,jU,EU,OU,QU=()=>{},GU,FU,VU,WU,KU,IU,JU,DU,RU,v1,h5,Kj,Ij,NX,d$,Y6,b0,V0,Jj,kX,Dj,CX,Rj,Sj,vZ,Mj,xX,BX,bZ,wj,Hj,qj,Tj,u$,_4,Pj,g0,Nj,kj,AX,m$,L6,x0,z0,Cj,yX,xj,hX,Bj,Aj,fZ,yj,vX,bX,hj,gZ,vj,bj,fj,gj,pj,s$,Y4,cj,J9,fX,q5,gX,pX,z6,cX,dX,T5,uX,mX,j8,L4,w9,l$,dj,uj,P5,pZ=null,U6,_1,U9,x8,_9,z4,U4,j4,E4,O4,Q4,G4,F4,V4,W4,K4,j6,E6,I4,mj,sj,DV,N$=null,cZ=null,O6,Q6,G6,F6,R4,S4,E8,i$,P6=()=>{},_E,M4,YE,OE=()=>{},N1=0,p9=0,r9=0,k6=!0,wE,A0;var g1=t5(async()=>{dZ=Object.defineProperty,r_=Object.getOwnPropertyNames,o_=Object.getOwnPropertyDescriptor,a_=Object.prototype.hasOwnProperty;XY=import.meta.require;aX=n(()=>{Z0={baseUrl:""},c9=class extends Error{status;constructor(Z,X){super(Z);this.name="BrowserQueryError",this.status=X}},LY={async login($){let Z=await fetch(`${Z0.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...Z0.headers},body:JSON.stringify($)});if(!Z.ok){let Y=await Z.json().catch(()=>({message:"Login failed"}));throw new c9(Y.message||"Login failed",Z.status)}let X=await Z.json(),_=X.data||X;if(typeof localStorage<"u"&&_.token)localStorage.setItem("auth_token",_.token);return _},async register($){let Z=await fetch(`${Z0.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...Z0.headers},body:JSON.stringify($)});if(!Z.ok){let Y=await Z.json().catch(()=>({message:"Registration failed"}));throw new c9(Y.message||"Registration failed",Z.status)}let X=await Z.json(),_=X.data||X;if(typeof localStorage<"u"&&_.token)localStorage.setItem("auth_token",_.token);return _},async logout(){if(await x$())try{await fetch(`${Z0.baseUrl}/logout`,{method:"POST",headers:await u0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await x$())return null;try{let Z=await fetch(`${Z0.baseUrl}/user`,{method:"GET",headers:await u0()});if(Z.status===401)return Z0.onUnauthorized?.(),null;if(!Z.ok)return null;let X=await Z.json();return X.user||X}catch{return null}},async check(){return await this.user()!==null},getToken:x$},zY=_Y});EY=n(()=>{jY={region:process.env.AWS_REGION??"us-east-1"}}),OY=n(()=>{eX()});GY=n(()=>{EY(),OY(),eX(),QY=new Z2});Pz=n(()=>{C1=new Y2,C5=new L2,S2=Object.defineProperty,FZ={},vL(FZ,{withErrorRecovery:()=>j2,tryLoadConfig:()=>ML,loadConfigWithResult:()=>SL,loadConfig:()=>F2,isRetryableError:()=>WL,isConfigNotFoundError:()=>VL,isBunfigError:()=>E2,globalPerformanceMonitor:()=>x1,globalCache:()=>b8,getEnvOrDefault:()=>KL,generateConfigTypes:()=>wL,defaultGeneratedDir:()=>n7,defaultConfigDir:()=>l7,deepMergeWithArrayStrategy:()=>I6,deepMerge:()=>O2,createLibraryConfig:()=>HL,config:()=>$9,bunfigPlugin:()=>qL,applyEnvVarsToConfig:()=>L1,TypeGenerationError:()=>SZ,SchemaValidationError:()=>j1,PluginError:()=>wZ,PerformanceMonitor:()=>lZ,FileSystemError:()=>RZ,ErrorFactory:()=>t9,EnvVarError:()=>f$,EnvProcessor:()=>N5,ConfigValidator:()=>J6,ConfigValidationError:()=>JZ,ConfigNotFoundError:()=>b$,ConfigMergeError:()=>DZ,ConfigLoader:()=>iZ,ConfigLoadError:()=>U1,ConfigFileLoader:()=>k5,ConfigCache:()=>sZ,CacheUtils:()=>y7,BunfigError:()=>X9,BrowserConfigError:()=>MZ,ArrayMergeStrategies:()=>s7}),i7=bL(async()=>{M2=import.meta.require,b8=new sZ,x1=new lZ,y7={createKey:ZL,isEquivalent:XL,estimateMemoryUsage:_L},fL=t$(mZ.cwd(),"config"),gL=t$(mZ.cwd(),"src/generated"),h7=a$.env.CLARITY_LOG_DIR||RY(zL(),"logs"),A$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:h7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},oZ=await UL(),h0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},F0=h0,pL=h0.red,v7=h0.green,cL=h0.yellow,b7=h0.blue,dL=h0.magenta,uL=h0.cyan,VZ=h0.white,mL=h0.gray,f7=h0.bgRed,g7=h0.bgYellow,WZ=h0.bold,sL=h0.dim,lL=h0.italic,nL=h0.underline,iL=h0.reset,y$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w2={debug:"\uD83D\uDD0D",info:b7("\u2139"),success:v7("\u2713"),warning:g7(VZ(WZ(" WARN "))),error:f7(VZ(WZ(" ERROR ")))},rL=new Z5("stacks"),f0=new Z5("bunfig",{showTags:!0}),oL=a0(k1.cwd(),"config"),aL=a0(k1.cwd(),"src/generated"),p7=o$.env.CLARITY_LOG_DIR||JY(QL(),"logs"),h$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:p7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},aZ=await GL(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Y0=N0,tL=N0.red,c7=N0.green,eL=N0.yellow,d7=N0.blue,$z=N0.magenta,Zz=N0.cyan,KZ=N0.white,Xz=N0.gray,u7=N0.bgRed,m7=N0.bgYellow,_z=N0.bgGray,IZ=N0.bold,Yz=N0.dim,Lz=N0.italic,zz=N0.underline,Uz=N0.strikethrough,jz=N0.reset,v$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},H2={debug:"\uD83D\uDD0D",info:d7("\u2139"),success:c7("\u2713"),warning:m7(KZ(IZ(" WARN "))),error:u7(KZ(IZ(" ERROR ")))},Ez=new _5("stacks"),X9=class extends Error{timestamp;context;constructor(Z,X={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,_])=>`${X}: ${_}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},b$=class extends X9{code="CONFIG_NOT_FOUND";constructor(Z,X,_){let Y=_?` or alias "${_}"`:"";super(`Configuration "${Z}"${Y} not found`,{configName:Z,alias:_,searchPaths:X,searchPathCount:X.length})}},U1=class extends X9{code="CONFIG_LOAD_ERROR";constructor(Z,X,_){super(`Failed to load configuration from "${Z}": ${X.message}`,{configPath:Z,configName:_,originalError:X.name,originalMessage:X.message});this.cause=X}},JZ=class extends X9{code="CONFIG_VALIDATION_ERROR";constructor(Z,X,_){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},DZ=class extends X9{code="CONFIG_MERGE_ERROR";constructor(Z,X,_,Y){super(`Failed to merge configuration from "${Z}" with "${X}": ${_.message}`,{sourcePath:Z,targetPath:X,configName:Y,originalError:_.name,originalMessage:_.message});this.cause=_}},f$=class extends X9{code="ENV_VAR_ERROR";constructor(Z,X,_,Y){super(`Failed to parse environment variable "${Z}" with value "${X}" as ${_}`,{envKey:Z,envValue:X,expectedType:_,configName:Y})}},RZ=class extends X9{code="FILE_SYSTEM_ERROR";constructor(Z,X,_){super(`File system ${Z} failed for "${X}": ${_.message}`,{operation:Z,path:X,originalError:_.name,originalMessage:_.message});this.cause=_}},SZ=class extends X9{code="TYPE_GENERATION_ERROR";constructor(Z,X,_){super(`Failed to generate types from "${Z}" to "${X}": ${_.message}`,{configDir:Z,outputPath:X,originalError:_.name,originalMessage:_.message});this.cause=_}},j1=class extends X9{code="SCHEMA_VALIDATION_ERROR";constructor(Z,X,_){super(`Schema validation failed${_?` for config "${_}"`:""}`,{schemaPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},MZ=class extends X9{code="BROWSER_CONFIG_ERROR";constructor(Z,X,_,Y){super(`Failed to fetch configuration from "${Z}": ${X} ${_}`,{endpoint:Z,status:X,statusText:_,configName:Y})}},wZ=class extends X9{code="PLUGIN_ERROR";constructor(Z,X,_){super(`Plugin "${Z}" failed during ${X}: ${_.message}`,{pluginName:Z,operation:X,originalError:_.name,originalMessage:_.message});this.cause=_}},t9={configNotFound($,Z,X){return new b$($,Z,X)},configLoad($,Z,X){return new U1($,Z,X)},configValidation($,Z,X){return new JZ($,Z,X)},configMerge($,Z,X,_){return new DZ($,Z,X,_)},envVar($,Z,X,_){return new f$($,Z,X,_)},fileSystem($,Z,X){return new RZ($,Z,X)},typeGeneration($,Z,X){return new SZ($,Z,X)},schemaValidation($,Z,X){return new j1($,Z,X)},browserConfig($,Z,X,_){return new MZ($,Z,X,_)},plugin($,Z,X){return new wZ($,Z,X)}},s7={replace:"replace",concat:"concat",smart:"smart"},q2=/^https?:\/\//,D9=new _5("bunfig",{showTags:!0}),g9=new iZ,l7=e0(z8.cwd(),"config"),n7=e0(z8.cwd(),"src/generated")}),r7=e$.env.CLARITY_LOG_DIR||dY(TL(),"logs"),E1={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:r7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},O1={...E1},Qz=(async()=>{try{let{loadConfig:$}=await i7().then(()=>FZ),Z=await $({name:"clarity",alias:"logging",defaultConfig:E1,cwd:e$.cwd()});if(Z)Object.assign(O1,Z)}catch{}return O1})(),k0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},L0=k0,Gz=k0.red,o7=k0.green,Fz=k0.yellow,a7=k0.blue,Vz=k0.magenta,Wz=k0.cyan,HZ=k0.white,Kz=k0.gray,t7=k0.bgRed,e7=k0.bgYellow,Iz=k0.bgGray,qZ=k0.bold,Jz=k0.dim,Dz=k0.italic,Rz=k0.underline,Sz=k0.strikethrough,Mz=k0.reset,g$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},T2={debug:"\uD83D\uDD0D",info:a7("\u2139"),success:o7("\u2713"),warning:e7(HZ(qZ(" WARN "))),error:t7(HZ(qZ(" ERROR ")))},wz=new Y5("stacks"),I9=class extends Error{timestamp;context;constructor(Z,X={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,_])=>`${X}: ${_}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},$X=class extends I9{code="CONFIG_NOT_FOUND";constructor(Z,X,_){let Y=_===void 0?[]:Array.isArray(_)?_.filter(Boolean):[_],L="";if(Y.length===1)L=` or alias "${Y[0]}"`;else if(Y.length>1)L=` or aliases ${Y.map((z)=>`"${z}"`).join(", ")}`;super(`Configuration "${Z}"${L} not found`,{configName:Z,alias:_,searchPaths:X,searchPathCount:X.length})}},L5=class extends I9{code="CONFIG_LOAD_ERROR";constructor(Z,X,_){super(`Failed to load configuration from "${Z}": ${X.message}`,{configPath:Z,configName:_,originalError:X.name,originalMessage:X.message});this.cause=X}},ZX=class extends I9{code="CONFIG_VALIDATION_ERROR";constructor(Z,X,_){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},XX=class extends I9{code="CONFIG_MERGE_ERROR";constructor(Z,X,_,Y){super(`Failed to merge configuration from "${Z}" with "${X}": ${_.message}`,{sourcePath:Z,targetPath:X,configName:Y,originalError:_.name,originalMessage:_.message});this.cause=_}},tZ=class extends I9{code="ENV_VAR_ERROR";constructor(Z,X,_,Y){super(`Failed to parse environment variable "${Z}" with value "${X}" as ${_}`,{envKey:Z,envValue:X,expectedType:_,configName:Y})}},_X=class extends I9{code="FILE_SYSTEM_ERROR";constructor(Z,X,_){super(`File system ${Z} failed for "${X}": ${_.message}`,{operation:Z,path:X,originalError:_.name,originalMessage:_.message});this.cause=_}},YX=class extends I9{code="TYPE_GENERATION_ERROR";constructor(Z,X,_){super(`Failed to generate types from "${Z}" to "${X}": ${_.message}`,{configDir:Z,outputPath:X,originalError:_.name,originalMessage:_.message});this.cause=_}},z5=class extends I9{code="SCHEMA_VALIDATION_ERROR";constructor(Z,X,_){super(`Schema validation failed${_?` for config "${_}"`:""}`,{schemaPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},LX=class extends I9{code="BROWSER_CONFIG_ERROR";constructor(Z,X,_,Y){super(`Failed to fetch configuration from "${Z}": ${X} ${_}`,{endpoint:Z,status:X,statusText:_,configName:Y})}},zX=class extends I9{code="PLUGIN_ERROR";constructor(Z,X,_){super(`Plugin "${Z}" failed during ${X}: ${_.message}`,{pluginName:Z,operation:X,originalError:_.name,originalMessage:_.message});this.cause=_}},U8={configNotFound($,Z,X){return new $X($,Z,X)},configLoad($,Z,X){return new L5($,Z,X)},configValidation($,Z,X){return new ZX($,Z,X)},configMerge($,Z,X,_){return new XX($,Z,X,_)},envVar($,Z,X,_){return new tZ($,Z,X,_)},fileSystem($,Z,X){return new _X($,Z,X)},typeGeneration($,Z,X){return new YX($,Z,X)},schemaValidation($,Z,X){return new z5($,Z,X)},browserConfig($,Z,X,_){return new LX($,Z,X,_)},plugin($,Z,X){return new zX($,Z,X)}},P2=/^https?:\/\//,M9=new Y5("bunfig",{showTags:!0}),Hz=new R2,qz=j9(r$.cwd(),"config"),Tz=j9(r$.cwd(),"src/generated")});q9=n(()=>{Pz(),UX={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}},b={...UX}}),{SQL:Nz}=globalThis.Bun;f8=n(()=>{if(q9(),g=Az(),typeof I$<"u"&&I$.on){if(!I$.listeners("unhandledRejection").find((Z)=>Z.name==="sqlConnectionErrorHandler")){let Z=function(X){if(X&&(X.message?.includes("database")||X.message?.includes("does not exist")||X.code==="ERR_POSTGRES_SERVER_ERROR"||X.code==="3D000"));};Object.defineProperty(Z,"name",{value:"sqlConnectionErrorHandler"}),I$.on("unhandledRejection",Z)}}}),yz=n(()=>{f8(),A0()});x5=n(()=>{q9(),f8(),u={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},Z6=new k2}),pz=n(()=>{x5()}),cz=n(()=>{A0()}),dz=n(()=>{q9(),x5()}),uz=n(()=>{q9(),A0()}),mz=n(()=>{f8()}),sz=n(()=>{f8()}),lz=n(()=>{A0()}),nz=n(()=>{A0()}),iz=n(()=>{q9(),A0()}),rz=n(()=>{A0()});az={};V6(az,{resetDatabase:()=>M6,generateMigration:()=>A5,executeMigration:()=>S6,deleteMigrationFiles:()=>b2,copyModelsToGenerated:()=>YU,clearGeneratedDirectory:()=>f2});p2=n(()=>{q9(),f8(),B5(),A0()}),jU=n(()=>{p2()}),EU=n(()=>{A0()}),OU=n(()=>{q9(),B5(),A0()}),GU=n(()=>{A0()}),FU=n(()=>{f8()}),VU=n(()=>{A0()}),WU=n(()=>{A0()}),KU=n(()=>{q9(),A0()}),IU=n(()=>{A0()}),JU=n(()=>{q9(),x5(),A0()}),DU=n(()=>{A0()}),RU=n(()=>{yz(),pz(),cz(),dz(),uz(),mz(),sz(),lz(),nz(),iz(),rz(),oz(),p2(),jU(),EU(),OU(),QU(),GU(),FU(),VU(),WU(),KU(),IU(),JU(),DU()});mj=n(async()=>{v1=new m2,h5=new s2,Kj=O5(X6.cwd(),"config"),Ij=O5(X6.cwd(),"src/generated"),NX=E5.env.CLARITY_LOG_DIR||PU(oU(),"logs"),d$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:NX,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Y6=await aU(),b0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},V0=b0,Jj=b0.red,kX=b0.green,Dj=b0.yellow,CX=b0.blue,Rj=b0.magenta,Sj=b0.cyan,vZ=b0.white,Mj=b0.gray,xX=b0.bgRed,BX=b0.bgYellow,bZ=b0.bold,wj=b0.dim,Hj=b0.italic,qj=b0.underline,Tj=b0.reset,u$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_4={debug:"\uD83D\uDD0D",info:CX("\u2139"),success:kX("\u2713"),warning:BX(vZ(bZ(" WARN "))),error:xX(vZ(bZ(" ERROR ")))},Pj=new G5("stacks"),g0=new G5("bunfig",{showTags:!0}),Nj=t0(A1.cwd(),"config"),kj=t0(A1.cwd(),"src/generated"),AX=j5.env.CLARITY_LOG_DIR||qU(Zj(),"logs"),m$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:AX,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},L6=await Xj(),x0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},z0=x0,Cj=x0.red,yX=x0.green,xj=x0.yellow,hX=x0.blue,Bj=x0.magenta,Aj=x0.cyan,fZ=x0.white,yj=x0.gray,vX=x0.bgRed,bX=x0.bgYellow,hj=x0.bgGray,gZ=x0.bold,vj=x0.dim,bj=x0.italic,fj=x0.underline,gj=x0.strikethrough,pj=x0.reset,s$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Y4={debug:"\uD83D\uDD0D",info:hX("\u2139"),success:yX("\u2713"),warning:bX(fZ(gZ(" WARN "))),error:vX(fZ(gZ(" ERROR ")))},cj=new V5("stacks"),J9=class extends Error{timestamp;context;constructor(Z,X={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,_])=>`${X}: ${_}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},fX=class extends J9{code="CONFIG_NOT_FOUND";constructor(Z,X,_){let Y=_?` or alias "${_}"`:"";super(`Configuration "${Z}"${Y} not found`,{configName:Z,alias:_,searchPaths:X,searchPathCount:X.length})}},q5=class extends J9{code="CONFIG_LOAD_ERROR";constructor(Z,X,_){super(`Failed to load configuration from "${Z}": ${X.message}`,{configPath:Z,configName:_,originalError:X.name,originalMessage:X.message});this.cause=X}},gX=class extends J9{code="CONFIG_VALIDATION_ERROR";constructor(Z,X,_){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},pX=class extends J9{code="CONFIG_MERGE_ERROR";constructor(Z,X,_,Y){super(`Failed to merge configuration from "${Z}" with "${X}": ${_.message}`,{sourcePath:Z,targetPath:X,configName:Y,originalError:_.name,originalMessage:_.message});this.cause=_}},z6=class extends J9{code="ENV_VAR_ERROR";constructor(Z,X,_,Y){super(`Failed to parse environment variable "${Z}" with value "${X}" as ${_}`,{envKey:Z,envValue:X,expectedType:_,configName:Y})}},cX=class extends J9{code="FILE_SYSTEM_ERROR";constructor(Z,X,_){super(`File system ${Z} failed for "${X}": ${_.message}`,{operation:Z,path:X,originalError:_.name,originalMessage:_.message});this.cause=_}},dX=class extends J9{code="TYPE_GENERATION_ERROR";constructor(Z,X,_){super(`Failed to generate types from "${Z}" to "${X}": ${_.message}`,{configDir:Z,outputPath:X,originalError:_.name,originalMessage:_.message});this.cause=_}},T5=class extends J9{code="SCHEMA_VALIDATION_ERROR";constructor(Z,X,_){super(`Schema validation failed${_?` for config "${_}"`:""}`,{schemaPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},uX=class extends J9{code="BROWSER_CONFIG_ERROR";constructor(Z,X,_,Y){super(`Failed to fetch configuration from "${Z}": ${X} ${_}`,{endpoint:Z,status:X,statusText:_,configName:Y})}},mX=class extends J9{code="PLUGIN_ERROR";constructor(Z,X,_){super(`Plugin "${Z}" failed during ${X}: ${_.message}`,{pluginName:Z,operation:X,originalError:_.name,originalMessage:_.message});this.cause=_}},j8={configNotFound($,Z,X){return new fX($,Z,X)},configLoad($,Z,X){return new q5($,Z,X)},configValidation($,Z,X){return new gX($,Z,X)},configMerge($,Z,X,_){return new pX($,Z,X,_)},envVar($,Z,X,_){return new z6($,Z,X,_)},fileSystem($,Z,X){return new cX($,Z,X)},typeGeneration($,Z,X){return new dX($,Z,X)},schemaValidation($,Z,X){return new T5($,Z,X)},browserConfig($,Z,X,_){return new uX($,Z,X,_)},plugin($,Z,X){return new mX($,Z,X)}},L4=/^https?:\/\//,w9=new V5("bunfig",{showTags:!0}),l$=new e2,dj=E9(U5.cwd(),"config"),uj=E9(U5.cwd(),"src/generated"),P5={verbose:!1,locale:"en",autoInstallLocales:!1},U6=P5,_1={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"]}},U9=new Map,x8=new Map,_9=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(Z){let X=y8(Z).normalized;if(X==="en"){if(!U9.has("en"))U9.set("en",_1);return _1}if(U9.has(X))return U9.get(X);if(x8.has(X))return x8.get(X);let _=this.loadLocaleWithFallback(X);x8.set(X,_);try{let Y=await _;return U9.set(X,Y),Y}finally{x8.delete(X)}}static loadSync(Z){let X=y8(Z).normalized;if(X==="en"){if(!U9.has("en"))U9.set("en",_1);return _1}if(U9.has(X))return U9.get(X);throw Error(`Locale '${Z}' is not loaded. Please use async loading with faker.setLocale('${Z}') or preload it.`)}static isCached(Z){let X=y8(Z).normalized;return U9.has(X)}static async preload(Z){await Promise.all(Z.map((X)=>this.load(X)))}static clearCache(){U9.clear(),x8.clear()}static async loadLocaleWithFallback(Z){let X=Gj(Z);for(let _=0;_<X.length;_++){let Y=X[_],L=_===0&&X.length>1,z=!L;try{if(L){let j=await this.loadLocaleModule(Y),U=X[1];try{let Q=await this.loadLocaleModule(U);return $4(Q,j)}catch{return j}}else return await this.loadLocaleModule(Y)}catch(j){if(_===X.length-1)throw j;continue}}throw Error(`Failed to load locale '${Z}' with fallback chain: ${X.join(" \u2192 ")}`)}static async tryWorkspaceImport(Z,X){if(!h8())return null;try{let _=await import(`../../${X.packageName}/dist/index.js`);return _[X.normalized]||_[X.language]||_.default}catch{try{let _=wU.cwd(),Y=MU(_,"packages",X.packageName,"dist","index.js");if(!SU(Y))return null;let L=await import(`file://${Y}`);return L[X.normalized]||L[X.language]||L.default}catch{return null}}}static async loadLocaleModule(Z){let X=Fj(Z),_=y8(Z);try{let Y=await import(X);return Y[_.normalized]||Y[_.language]||Y.default}catch(Y){let L=Y instanceof Error?Y.message:String(Y);if(L.includes("Cannot find")||L.includes("not found")||L.includes("ModuleNotFound")){if(h8()&&X.startsWith("@mock-locale/")){let z=await this.tryWorkspaceImport(Z,_);if(z)return z}if(U6.autoInstallLocales)if(console.log(`
|
|
125
|
-
\uD83D\uDD0D Locale '${Z}' not found. Auto-installing ${X}...`),X4(X)){if(h8()&&X.startsWith("@mock-locale/")){let z=await this.tryWorkspaceImport(Z,_);if(z)return z}try{let z=await import(X);return z[_.normalized]||z[_.language]||z.default}catch(z){if(h8()&&X.startsWith("@mock-locale/")){let j=await this.tryWorkspaceImport(Z,_);if(j)return j;throw Error(`Locale '${Z}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${X.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${Z}' after installation: ${z instanceof Error?z.message:String(z)}`)}}else throw Error(`Failed to auto-install locale '${Z}'. Please install manually with: bun add ${X}`);throw Error(`Locale '${Z}' is not installed. Install it with: bun add ${X}
|
|
126
|
-
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}
|
|
127
|
-
Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${Z}': ${L}`)}}},z4=new T6,U4={email:($)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test($)},phone:($)=>{let Z=/^\+?[1-9]\d{0,15}$/,X=$.replace(/[\s\-()]/g,"");return X.length>=7&&Z.test(X)},name:($)=>{return/^[a-z\s\-']+$/i.test($)&&$.length>=2&&$.length<=50},age:($)=>{return Number.isInteger($)&&$>=0&&$<=150},url:($)=>{try{let Z=new URL($);return $.startsWith("http://")||$.startsWith("https://")}catch{return!1}},regex:($)=>(Z)=>{return $.test(Z)},length:($,Z)=>(X)=>{return X.length>=$&&X.length<=Z},range:($,Z)=>(X)=>{return X>=$&&X<=Z}},j4={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"]}}},E4={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}]}},O4=[".","_","-",""],Q4=["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"],G4=["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"],F4=["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"],V4=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],W4=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],K4=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],j6="abcdefghijklmnopqrstuvwxyz".split(""),E6=new y5,I4=E6}),sj={};V6(sj,{validateData:()=>y1,selectWeightedItem:()=>h1,isInWorkspace:()=>h8,installPackage:()=>X4,globalProviderRegistry:()=>z4,getConfig:()=>Qj,generateRealisticData:()=>Wj,faker:()=>E6,detectPackageManager:()=>Z4,defaultConfig:()=>P5,default:()=>I4,config:()=>U6,applyRelationships:()=>a9,applyConstraints:()=>Vj,WordModule:()=>P1,WeightedSelections:()=>E4,VehicleModule:()=>T1,ValidationRules:()=>U4,SystemModule:()=>q1,StringModule:()=>w5,SportModule:()=>H1,ScienceModule:()=>w1,Random:()=>H5,PhoneModule:()=>M1,PersonModule:()=>S1,NumberModule:()=>M5,MusicModule:()=>R1,LoremModule:()=>S5,LocaleLoader:()=>_9,InternetModule:()=>D1,ImageModule:()=>R5,HelpersModule:()=>D5,HackerModule:()=>J1,GitModule:()=>J5,FoodModule:()=>I1,FinanceModule:()=>I5,Faker:()=>y5,DateModule:()=>K5,DatabaseModule:()=>W5,DataRelationships:()=>j4,DataProviderRegistry:()=>T6,CompanyModule:()=>K1,CommerceModule:()=>W1,ColorModule:()=>V1,BookModule:()=>F1,AnimalModule:()=>G1,AddressModule:()=>Q1});DV=n(async()=>{await mj()});R4=n(()=>{O6=new Map,Q6=new Map,G6=new Map,F6=new Map}),S4={};V6(S4,{registerBrowserModels:()=>XE,hasModel:()=>tj,getModelRegistry:()=>aj,getModel:()=>rj,getAllModels:()=>oj,defineModel:()=>ZE,clearModelRegistry:()=>ej});i$=n(()=>{aX(),R4(),E8=new Map}),M4=n(()=>{P6(),_E={simpleEntity:($,Z="id")=>({name:$,pkPattern:`${$.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]}),oneToMany:($,Z,X="id",_="id")=>({parent:{name:$,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:"METADATA",keyFields:[X]},child:{name:Z,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:`${Z.toUpperCase()}#\${${_}}`,keyFields:[X,_]}}),manyToMany:($,Z,X="id",_="relatedId")=>({entity:{name:$,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:"METADATA",keyFields:[X]},relation:{name:Z,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:`${Z.toUpperCase()}#\${${_}}`,keyFields:[X,_],indexes:[{name:"GSI1",pkPattern:`${$.toUpperCase()}#\${${_}}`,skPattern:`${Z.toUpperCase()}#\${${X}}`}]}}),hierarchical:($,Z="rootId",X="path")=>({name:$,pkPattern:`ROOT#\${${Z}}`,skPattern:`PATH#\${${X}}`,keyFields:[Z,X]})}}),YE=n(()=>{P6(),M4()});wE=n(()=>{B5()}),A0=n(async()=>{i$(),i$(),RU(),aX(),x5(),i$(),await q9(),B5(),P6(),M4(),YE(),GY(),OE(),wE(),R4()});await A0()});function $8($,Z){let X=Z??{};switch($){case"sqlite":return{database:X.DB_DATABASE_PATH||C6.sqlitePath,prefix:""};case"mysql":return{database:X.DB_DATABASE||C6.default,host:X.DB_HOST||"127.0.0.1",port:X.DB_PORT||k4.mysql,username:X.DB_USERNAME||C4.mysql,password:X.DB_PASSWORD||"",prefix:""};case"postgres":return{database:X.DB_DATABASE||C6.default,host:X.DB_HOST||"127.0.0.1",port:X.DB_PORT||k4.postgres,username:X.DB_USERNAME||C4.postgres,password:X.DB_PASSWORD||"",prefix:""};default:return{database:":memory:"}}}var AV="127.0.0.1",k4,C6,C4,yV,hV;var v5=t5(()=>{k4={mysql:3306,postgres:5432,sqlite:0},C6={default:"stacks",sqlitePath:"database/stacks.sqlite",sqliteTestingPath:"database/stacks_testing.sqlite"},C4={mysql:"root",postgres:"postgres",sqlite:""},yV={host:"localhost",port:6379},hV={region:"us-east-1"}});var O8={};i_(O8,{setConfig:()=>d9,initializeDbConfig:()=>y4,ensureDatabaseConfigLoaded:()=>A6,db:()=>v});import{env as d1}from"@stacksjs/env";function y4($){if($?.app?.env)x4=$.app.env;if($?.database?.default)B4=$.database.default;if($?.database)A4=$.database;B6()}function h4(){return x4}function v4(){return B4}function yE(){return A4}function hE(){let $=v4();if($==="sqlite")return"sqlite";if($==="mysql")return"mysql";if($==="postgres")return"postgres";return"sqlite"}function vE(){let $=v4(),Z=yE(),X=h4();if($==="sqlite"){let _=X!=="testing"?"database/stacks.sqlite":"database/stacks_testing.sqlite";return{database:Z.connections?.sqlite?.database??_}}if($==="mysql")return{database:Z.connections?.mysql?.name||"stacks",host:Z.connections?.mysql?.host??"127.0.0.1",username:Z.connections?.mysql?.username??"root",password:Z.connections?.mysql?.password??"",port:Z.connections?.mysql?.port??3306};if($==="postgres"){let _=Z.connections?.postgres?.name??"stacks";return{database:X==="testing"?`${_}_testing`:_,host:Z.connections?.postgres?.host??"127.0.0.1",username:Z.connections?.postgres?.username??"",password:Z.connections?.postgres?.password??"",port:Z.connections?.postgres?.port??5432}}return{database:":memory:"}}function B6(){let $=hE(),Z=vE();d9({dialect:$,database:Z,verbose:h4()!=="production",timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}})}function b4(){if(!x6)x6=(async()=>{try{let{config:$}=await import("@stacksjs/config");if($)y4($),b5=null}catch{}})();return x6}async function A6(){await b4()}function bE(){if(!b5)B6(),b5=F9();return b5}var AE,p1,c1,x4,B4,A4,b5=null,x6=null,v;var p0=t5(async()=>{v5();await g1();AE=$8("sqlite",d1),p1=$8("mysql",d1),c1=$8("postgres",d1),x4=d1.APP_ENV||"local",B4=d1.DB_CONNECTION||"sqlite",A4={connections:{sqlite:{database:AE.database,prefix:""},mysql:{name:p1.database,host:p1.host,username:p1.username,password:p1.password,port:p1.port,prefix:""},postgres:{name:c1.database,host:c1.host,username:c1.username,password:c1.password,port:c1.port,prefix:""}}};B6();b4();v=new Proxy({},{get($,Z){let X=bE(),_=X[Z];if(typeof _==="function")return _.bind(X);return _}})});await g1();import{env as L9}from"@stacksjs/env";class e9{_queryBuilder=null;_options;_initialized=!1;constructor($){this._options={verbose:!1,timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0},...$}}get driver(){return this._options.driver}get connection(){return this._options.connection}get isInitialized(){return this._initialized}get query(){if(!this._queryBuilder)this.initialize();return this._queryBuilder}initialize(){if(this._initialized)return;d9({dialect:this._options.driver,database:this._options.connection,verbose:this._options.verbose,timestamps:this._options.timestamps,softDeletes:this._options.softDeletes,hooks:this._options.hooks}),this._queryBuilder=F9(),this._initialized=!0}switchDriver($,Z){this.close(),this._options.driver=$,this._options.connection=Z,this._initialized=!1,this.initialize()}close(){if(this._queryBuilder&&typeof this._queryBuilder.close==="function")this._queryBuilder.close();this._queryBuilder=null,this._initialized=!1}static fromConfig($,Z){let X=$.default,_;switch(X){case"sqlite":{_={database:Z==="testing"?$.connections.sqlite?.database?.replace(".sqlite","_testing.sqlite")||"database/stacks_testing.sqlite":$.connections.sqlite?.database||"database/stacks.sqlite"};break}case"mysql":{let Y=$.connections.mysql;_={database:Y?.name||"stacks",host:Y?.host||"127.0.0.1",port:Y?.port||3306,username:Y?.username||"root",password:Y?.password||""};break}case"postgres":{let Y=$.connections.postgres,L=Y?.name||"stacks";_={database:Z==="testing"?`${L}_testing`:L,host:Y?.host||"127.0.0.1",port:Y?.port||5432,username:Y?.username||"",password:Y?.password||""};break}default:_={database:":memory:"}}return new e9({driver:X,connection:_,verbose:Z!=="production"})}static fromEnv(){let $=L9.DB_CONNECTION||"sqlite",Z;switch($){case"sqlite":Z={database:L9.DB_DATABASE||"database/stacks.sqlite"};break;case"mysql":Z={database:L9.DB_DATABASE||"stacks",host:L9.DB_HOST||"127.0.0.1",port:L9.DB_PORT||3306,username:L9.DB_USERNAME||"root",password:L9.DB_PASSWORD||""};break;case"postgres":Z={database:L9.DB_DATABASE||"stacks",host:L9.DB_HOST||"127.0.0.1",port:L9.DB_PORT||5432,username:L9.DB_USERNAME||"",password:L9.DB_PASSWORD||""};break;default:Z={database:":memory:"}}return new e9({driver:$,connection:Z,verbose:L9.APP_ENV!=="prod"})}}function HE($){return new e9($)}function qE($,Z){return new e9({driver:"sqlite",connection:{database:$},...Z})}function TE($,Z){return new e9({driver:"postgres",connection:$,...Z})}function PE($,Z){return new e9({driver:"mysql",connection:$,...Z})}import{env as B0}from"@stacksjs/env";var N4={sqlite:{database:"database/stacks.sqlite",prefix:""},mysql:{name:"stacks",host:"127.0.0.1",port:3306,username:"root",password:"",prefix:"",charset:"utf8mb4",collation:"utf8mb4_unicode_ci"},postgres:{name:"stacks",host:"127.0.0.1",port:5432,username:"postgres",password:"",prefix:"",schema:"public"},browser:{}};function NE($,Z){switch($){case"sqlite":{let X=Z;if(X.database===":memory:")return":memory:";return`sqlite://${X.database}`}case"mysql":{let X=Z,{name:_,host:Y="127.0.0.1",port:L=3306,username:z="root",password:j=""}=X;return`mysql://${z}:${j}@${Y}:${L}/${_}`}case"postgres":{let X=Z,{name:_,host:Y="127.0.0.1",port:L=5432,username:z="postgres",password:j=""}=X;return`postgres://${z}:${j}@${Y}:${L}/${_}`}default:throw Error(`Unsupported driver: ${$}`)}}function kE($,Z){let X=[];switch($){case"sqlite":{if(!Z.database)X.push("SQLite requires a database path");break}case"mysql":{if(!Z.name)X.push("MySQL requires a database name");break}case"postgres":{if(!Z.name)X.push("PostgreSQL requires a database name");break}default:X.push(`Unsupported driver: ${$}`)}return{valid:X.length===0,errors:X}}function CE($,Z){return{...N4[$],...Z}}function xE($){switch($){case"sqlite":return{database:B0.DB_DATABASE||"database/stacks.sqlite",prefix:B0.DB_PREFIX||""};case"mysql":return{name:B0.DB_DATABASE||"stacks",host:B0.DB_HOST||"127.0.0.1",port:B0.DB_PORT??3306,username:B0.DB_USERNAME||"root",password:B0.DB_PASSWORD||"",prefix:B0.DB_PREFIX||""};case"postgres":return{name:B0.DB_DATABASE||"stacks",host:B0.DB_HOST||"127.0.0.1",port:B0.DB_PORT??5432,username:B0.DB_USERNAME||"postgres",password:B0.DB_PASSWORD||"",prefix:B0.DB_PREFIX||"",schema:B0.DB_SCHEMA||"public"};default:throw Error(`Unsupported driver: ${$}`)}}function BE(){if(B0.DB_CONNECTION)return B0.DB_CONNECTION;if(B0.DATABASE_URL?.startsWith("postgres"))return"postgres";if(B0.DATABASE_URL?.startsWith("mysql"))return"mysql";return"sqlite"}p0();function u1($,...Z){let X=[],_=[];for(let Y=0;Y<$.length;Y++)if(X.push($[Y]),Y<Z.length)if(Z[Y]&&typeof Z[Y]==="object"&&"raw"in Z[Y])X.push(Z[Y].raw);else X.push("?"),_.push(Z[Y]);return{sql:X.join(""),parameters:_}}u1.raw=function(Z){return{raw:Z}};u1.ref=function(Z){return{raw:Z}};v5();await __promiseAll([g1(),p0()]);import{existsSync as y6,readdirSync as h6,readFileSync as f4,unlinkSync as fE,writeFileSync as g4}from"fs";import{join as Q8}from"path";import{log as T9}from"@stacksjs/logging";import{err as f5,handleError as g5,ok as c8}from"@stacksjs/error-handling";import{path as v6}from"@stacksjs/path";import{env as p5}from"@stacksjs/env";var $0={info:(...$)=>typeof T9?.info==="function"?T9.info(...$):console.log(...$),success:($)=>typeof T9?.success==="function"?T9.success($):console.log($),warn:($)=>typeof T9?.warn==="function"?T9.warn($):console.warn($),error:(...$)=>typeof T9?.error==="function"?T9.error(...$):console.error(...$),debug:(...$)=>typeof T9?.debug==="function"?T9.debug(...$):console.debug(...$)},gE=p5.DB_CONNECTION||"sqlite",pE=$8("sqlite",p5),m1=$8("mysql",p5),s1=$8("postgres",p5),l1={default:gE,connections:{sqlite:{database:pE.database,prefix:""},mysql:{name:m1.database,host:m1.host,username:m1.username,password:m1.password,port:m1.port,prefix:""},postgres:{name:s1.database,host:s1.host,username:s1.username,password:s1.password,port:s1.port,prefix:""}}};function cE(){return l1.default||"sqlite"}function d8(){let $=cE();if($==="sqlite")return"sqlite";if($==="mysql")return"mysql";if($==="postgres")return"postgres";return"sqlite"}function c5(){let $=d8(),Z=l1.connections[$];d9({dialect:$,database:{database:Z?.name||Z?.database||"stacks",host:Z?.host||"localhost",port:Z?.port||($==="postgres"?5432:$==="mysql"?3306:0),username:Z?.username||"",password:Z?.password||""}}),b1()}function p4(){let $=v6.userModelsPath();return{modelsDir:$,skip:!y6($)}}function dE(){let $=Q8(process.cwd(),"database","migrations"),Z;try{Z=h6($).filter((G)=>G.endsWith(".sql"))}catch{return}let X=[],_=(G,F,O)=>{$0.info(`Dropping no-op migration (${O}): ${G}`);try{fE(F)}catch{}X.push(G)},Y=/^\s*ALTER\s+TABLE\s+.+\s+ADD\s+CONSTRAINT\s+/i,L=/^\s*CREATE\s+UNIQUE\s+INDEX\s+/i,z=/^\s*ALTER\s+TABLE\s+["']?(\w+)["']?\s+DROP\s+COLUMN\s+["']?(\w+)["']?\s*$/i,j=/^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i,U=new Map;for(let G of Z){let F=G.match(/^\d+-create-(\w+)-table\.sql$/);if(!F||!F[1])continue;let O=F[1],K=U.get(O);if(!K||G<K)U.set(O,G)}let Q=Q8(process.cwd(),l1.connections.sqlite.database||"stacks.db"),E=null;if(y6(Q))try{let{Database:G}=H0("bun:sqlite");E=new G(Q,{readonly:!0})}catch{}for(let G of Z){$0.debug(`[migration] Running: ${G}`);let F=Q8($,G),K=f4(F,"utf-8").split(";").map((q)=>q.trim()).filter((q)=>q.length>0&&!q.startsWith("--"));if(K.length===0)continue;let W=K[0],w=W?W.match(j):null;if(w&&w[1]){let q=w[1],N=U.get(q);if(N&&N!==G){_(G,F,`duplicate create-table for "${q}" (kept ${N})`);continue}}if(K.every((q)=>Y.test(q))){_(G,F,"SQLite does not support ALTER TABLE ADD CONSTRAINT");continue}if(K.every((q)=>L.test(q))){_(G,F,"unique constraint already inline on table");continue}if(K.some((q)=>z.test(q))){let q=!1,N=[];for(let B of K){let A=B.match(z);if(A&&A[1]&&A[2]){let f=A[1],p=A[2];if(!E){$0.info(`Skipping DROP COLUMN "${p}" \u2014 no database exists yet: ${G}`),q=!0;continue}try{let c=f.replace(/[^a-zA-Z0-9_]/g,""),l=E.prepare(`PRAGMA table_info("${c}")`).all();if(l.length===0){$0.info(`Skipping DROP COLUMN "${p}" \u2014 table "${f}" does not exist yet: ${G}`),q=!0;continue}if(!l.some((K9)=>K9.name===p)){$0.info(`Skipping DROP COLUMN "${p}" from "${f}" \u2014 column does not exist: ${G}`),q=!0;continue}}catch{$0.info(`Skipping DROP COLUMN "${p}" \u2014 table "${f}" not found: ${G}`),q=!0;continue}}N.push(B)}if(q){if(N.length===0)_(G,F,"columns already absent from table");else g4(F,`${N.join(`;
|
|
2
|
+
var v6=Object.defineProperty;var f6=(Z)=>Z;function b6(Z,Y){this[Z]=f6.bind(null,Y)}var p6=(Z,Y)=>{for(var $ in Y)v6(Z,$,{get:Y[$],enumerable:!0,configurable:!0,set:b6.bind(Y,$)})};var sZ=(Z,Y)=>()=>(Z&&(Y=Z(Z=0)),Y);var p=import.meta.require;function o(Z,Y){let $=Y??{};switch(Z){case"sqlite":return{database:$.DB_DATABASE_PATH||GZ.sqlitePath,prefix:""};case"mysql":return{database:$.DB_DATABASE||GZ.default,host:$.DB_HOST||"127.0.0.1",port:$.DB_PORT||rZ.mysql,username:$.DB_USERNAME||nZ.mysql,password:$.DB_PASSWORD||"",prefix:""};case"postgres":return{database:$.DB_DATABASE||GZ.default,host:$.DB_HOST||"127.0.0.1",port:$.DB_PORT||rZ.postgres,username:$.DB_USERNAME||nZ.postgres,password:$.DB_PASSWORD||"",prefix:""};default:return{database:":memory:"}}}var k0="127.0.0.1",rZ,GZ,nZ,N0,y0;var rY=sZ(()=>{rZ={mysql:3306,postgres:5432,sqlite:0},GZ={default:"stacks",sqlitePath:"database/stacks.sqlite",sqliteTestingPath:"database/stacks_testing.sqlite"},nZ={mysql:"root",postgres:"postgres",sqlite:""},N0={host:"localhost",port:6379},y0={region:"us-east-1"}});var u={};p6(u,{setConfig:()=>oZ,initializeDbConfig:()=>Z4,ensureDatabaseConfigLoaded:()=>_Z,db:()=>V,applySqlitePragmas:()=>W7,acquireDbConfigLock:()=>e6,SQLITE_BOOTSTRAP_PRAGMAS:()=>OZ});import{AsyncLocalStorage as a6}from"async_hooks";import{createQueryBuilder as o6,setConfig as oZ}from"@stacksjs/query-builder";import{env as xY}from"@stacksjs/env";import{applySqlitePragmas as W7,SQLITE_BOOTSTRAP_PRAGMAS as OZ}from"@stacksjs/query-builder";function e6(){let Z=()=>{},Y=new Promise((J)=>{Z=J}),$=zZ.then(()=>Z);return zZ=zZ.then(()=>Y),$}function Z4(Z){if(Z?.app?.env)tZ=Z.app.env;if(Z?.database?.default)eZ=Z.database.default;if(Z?.database)Y4=Z.database;QZ(),QY=null}function $4(){return tZ}function J4(){return eZ}function Y7(){return Y4}function X4(){let Z=J4();if(Z==="sqlite")return"sqlite";if(Z==="mysql")return"mysql";if(Z==="singlestore")return"singlestore";if(Z==="postgres")return"postgres";return"sqlite"}function Z7(){let Z=J4(),Y=Y7(),$=$4();if(Z==="sqlite"){let J=$!=="testing"?"database/stacks.sqlite":"database/stacks_testing.sqlite";return{database:Y.connections?.sqlite?.database??J}}if(Z==="mysql")return{database:Y.connections?.mysql?.name||"stacks",host:Y.connections?.mysql?.host??"127.0.0.1",username:Y.connections?.mysql?.username??"root",password:Y.connections?.mysql?.password??"",port:Y.connections?.mysql?.port??3306};if(Z==="singlestore")return{database:Y.connections?.singlestore?.name||"stacks",host:Y.connections?.singlestore?.host??"127.0.0.1",username:Y.connections?.singlestore?.username??"root",password:Y.connections?.singlestore?.password??"",port:Y.connections?.singlestore?.port??3306};if(Z==="postgres"){let J=Y.connections?.postgres?.name??"stacks";return{database:$==="testing"?`${J}_testing`:J,host:Y.connections?.postgres?.host??"127.0.0.1",username:Y.connections?.postgres?.username??"",password:Y.connections?.postgres?.password??"",port:Y.connections?.postgres?.port??5432}}return{database:":memory:"}}function QZ(){let Z=X4(),Y=Z7();oZ({dialect:Z,database:Y,verbose:$4()!=="production",timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},softDeletes:{enabled:!0,column:"deleted_at",defaultFilter:!0}})}function W4(){if(!UZ)UZ=(async()=>{try{let{config:Z,overridesReady:Y}=await import("@stacksjs/config");if(await Y,Z)Z4(Z),QY=null}catch{}})();return UZ}async function _Z(){await W4()}function $7(Z){if(iZ.getStore())return Z();let Y=aZ.then(()=>iZ.run(!0,Z));return aZ=Y.then(()=>{return},()=>{return}),Y}function J7(Z){let Y=Z.transaction.bind(Z);Z.transaction=(...$)=>$7(()=>Y(...$))}function X7(){if(!QY){if(QZ(),QY=o6(),X4()==="sqlite")J7(QY)}return QY}var t6,DY,qY,tZ,eZ,Y4,zZ,QY=null,UZ=null,iZ,aZ,V;var F=sZ(()=>{rY();t6=o("sqlite",xY),DY=o("mysql",xY),qY=o("postgres",xY),tZ=xY.APP_ENV||"local",eZ=xY.DB_CONNECTION||"sqlite",Y4={connections:{sqlite:{database:t6.database,prefix:""},mysql:{name:DY.database,host:DY.host,username:DY.username,password:DY.password,port:DY.port,prefix:""},postgres:{name:qY.database,host:qY.host,username:qY.username,password:qY.password,port:qY.port,prefix:""}}},zZ=Promise.resolve();QZ();iZ=new a6,aZ=Promise.resolve();W4();V=new Proxy({},{get(Z,Y){let $=X7(),J=$[Y];if(typeof J==="function")return J.bind($);return J}})});import{createQueryBuilder as C6,setConfig as c6}from"@stacksjs/query-builder";import{env as C}from"@stacksjs/env";class a{_queryBuilder=null;_options;_initialized=!1;constructor(Z){this._options={verbose:!1,timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0},...Z}}get driver(){return this._options.driver}get connection(){return this._options.connection}get isInitialized(){return this._initialized}get query(){if(!this._queryBuilder)this.initialize();return this._queryBuilder}initialize(){if(this._initialized)return;c6({dialect:this._options.driver,database:this._options.connection,verbose:this._options.verbose,timestamps:this._options.timestamps,softDeletes:this._options.softDeletes,hooks:this._options.hooks}),this._queryBuilder=C6(),this._initialized=!0}switchDriver(Z,Y){this.close(),this._options.driver=Z,this._options.connection=Y,this._initialized=!1,this.initialize()}async close(){if(this._queryBuilder&&typeof this._queryBuilder.close==="function")await this._queryBuilder.close();this._queryBuilder=null,this._initialized=!1}static fromConfig(Z,Y){let $=Z.default,J;switch($){case"sqlite":{J={database:Y==="testing"?Z.connections.sqlite?.database?.replace(".sqlite","_testing.sqlite")||"database/stacks_testing.sqlite":Z.connections.sqlite?.database||"database/stacks.sqlite"};break}case"mysql":{let X=Z.connections.mysql;J={database:X?.name||"stacks",host:X?.host||"127.0.0.1",port:X?.port||3306,username:X?.username||"root",password:X?.password||""};break}case"singlestore":{let X=Z.connections.singlestore;J={database:X?.name||"stacks",host:X?.host||"127.0.0.1",port:X?.port||3306,username:X?.username||"root",password:X?.password||""};break}case"postgres":{let X=Z.connections.postgres,W=X?.name||"stacks";J={database:Y==="testing"?`${W}_testing`:W,host:X?.host||"127.0.0.1",port:X?.port||5432,username:X?.username||"",password:X?.password||""};break}case"dynamodb":throw Error("[database] DB_CONNECTION=dynamodb is not a SQL driver. Use the entity-style `dynamo.entity(...)` API for DynamoDB access, or set DB_CONNECTION to sqlite/mysql/postgres for SQL workloads.");default:throw Error(`[database] Unknown DB_CONNECTION "${String($)}". Allowed values: sqlite, mysql, postgres.`)}return new a({driver:$,connection:J,verbose:Y!=="production"})}static fromEnv(){let Z=C.DB_CONNECTION||"sqlite",Y;switch(Z){case"sqlite":Y={database:C.DB_DATABASE||"database/stacks.sqlite"};break;case"mysql":case"singlestore":Y={database:C.DB_DATABASE||"stacks",host:C.DB_HOST||"127.0.0.1",port:C.DB_PORT||3306,username:C.DB_USERNAME||"root",password:C.DB_PASSWORD||""};break;case"postgres":Y={database:C.DB_DATABASE||"stacks",host:C.DB_HOST||"127.0.0.1",port:C.DB_PORT||5432,username:C.DB_USERNAME||"",password:C.DB_PASSWORD||""};break;default:Y={database:":memory:"}}return new a({driver:Z,connection:Y,verbose:C.APP_ENV!=="prod"})}}function u6(Z){return new a(Z)}function g6(Z,Y){return new a({driver:"sqlite",connection:{database:Z},...Y})}function d6(Z,Y){return new a({driver:"postgres",connection:Z,...Y})}function m6(Z,Y){return new a({driver:"mysql",connection:Z,...Y})}import{env as S}from"@stacksjs/env";var lZ={sqlite:{database:"database/stacks.sqlite",prefix:""},mysql:{name:"stacks",host:"127.0.0.1",port:3306,username:"root",password:"",prefix:"",charset:"utf8mb4",collation:"utf8mb4_unicode_ci"},singlestore:{name:"stacks",host:"127.0.0.1",port:3306,username:"root",password:"",prefix:"",charset:"utf8mb4",ssl:!1},postgres:{name:"stacks",host:"127.0.0.1",port:5432,username:"postgres",password:"",prefix:"",schema:"public"},browser:{}};function s6(Z,Y){switch(Z){case"sqlite":{let $=Y;if($.database===":memory:")return":memory:";return`sqlite://${$.database}`}case"mysql":{let $=Y,{name:J,host:X="127.0.0.1",port:W=3306,username:H="root",password:G=""}=$;return`mysql://${H}:${G}@${X}:${W}/${J}`}case"singlestore":{let $=Y,{name:J,host:X="127.0.0.1",port:W=3306,username:H="root",password:G=""}=$;return`mysql://${H}:${G}@${X}:${W}/${J}`}case"postgres":{let $=Y,{name:J,host:X="127.0.0.1",port:W=5432,username:H="postgres",password:G=""}=$;return`postgres://${H}:${G}@${X}:${W}/${J}`}default:throw Error(`Unsupported driver: ${Z}`)}}function l6(Z,Y){let $=[];switch(Z){case"sqlite":{if(!Y.database)$.push("SQLite requires a database path");break}case"mysql":{if(!Y.name)$.push("MySQL requires a database name");break}case"singlestore":{if(!Y.name)$.push("SingleStore requires a database name");break}case"postgres":{if(!Y.name)$.push("PostgreSQL requires a database name");break}default:$.push(`Unsupported driver: ${Z}`)}return{valid:$.length===0,errors:$}}function r6(Z,Y){return{...lZ[Z],...Y}}function n6(Z){switch(Z){case"sqlite":return{database:S.DB_DATABASE||"database/stacks.sqlite",prefix:S.DB_PREFIX||""};case"mysql":return{name:S.DB_DATABASE||"stacks",host:S.DB_HOST||"127.0.0.1",port:S.DB_PORT??3306,username:S.DB_USERNAME||"root",password:S.DB_PASSWORD||"",prefix:S.DB_PREFIX||""};case"singlestore":return{name:S.DB_DATABASE||"stacks",host:S.DB_HOST||"127.0.0.1",port:S.DB_PORT??3306,username:S.DB_USERNAME||"root",password:S.DB_PASSWORD||"",prefix:S.DB_PREFIX||"",ssl:S.DB_SSL==="true"||S.DB_SSL==="1"};case"postgres":return{name:S.DB_DATABASE||"stacks",host:S.DB_HOST||"127.0.0.1",port:S.DB_PORT??5432,username:S.DB_USERNAME||"postgres",password:S.DB_PASSWORD||"",prefix:S.DB_PREFIX||"",schema:S.DB_SCHEMA||"public"};default:throw Error(`Unsupported driver: ${Z}`)}}function i6(){if(S.DB_CONNECTION)return S.DB_CONNECTION;if(S.DATABASE_URL?.startsWith("postgres"))return"postgres";if(S.DATABASE_URL?.startsWith("mysql"))return"mysql";return"sqlite"}F();function TY(Z,...Y){let $=[],J=[];for(let X=0;X<Z.length;X++)if($.push(Z[X]),X<Y.length)if(Y[X]&&typeof Y[X]==="object"&&"raw"in Y[X])$.push(Y[X].raw);else $.push("?"),J.push(Y[X]);return{sql:$.join(""),parameters:J}}TY.raw=function(Y){return{raw:Y}};TY.ref=function(Y){return{raw:Y}};F();import{existsSync as EZ,mkdirSync as F7,readdirSync as iY,readFileSync as Q4,unlinkSync as D7,writeFileSync as _4}from"fs";import{dirname as q7,join as t}from"path";import{log as d}from"@stacksjs/logging";import{err as aY,handleError as oY,ok as _Y}from"@stacksjs/error-handling";import{path as yY}from"@stacksjs/path";import{createQueryBuilder as O4,executeMigration as x7,generateMigration as IZ,resetConnection as nY,resetDatabase as T7,setConfig as V4}from"@stacksjs/query-builder";import{Buffer as H7}from"buffer";import{createHash as G7}from"crypto";import{closeSync as z7,openSync as U7,statSync as Q7,unlinkSync as H4,writeFileSync as _7}from"fs";import O7 from"process";import{userDatabasePath as V7}from"@stacksjs/path";var A7=30000,AZ=100,BZ=2000,B7=60000,VZ="stacks_migrations";async function G4(Z,Y,$={}){let J=$.timeoutMs??A7;if(Z!=="sqlite"&&Z!=="postgres"&&Z!=="mysql")throw Error(`[migration-lock] unknown dialect: ${String(Z)}`);if(Z==="sqlite")return j7($.sqliteLockPath,J);if(!Y)throw Error(`[migration-lock] ${Z} requires a database connection to acquire the lock`);if(Z==="postgres")return E7(Y,J);return I7(Y,J)}function L7(){let Z=G7("sha256").update(VZ).digest(),Y=Z.readInt32BE(0),$=Z.readInt32BE(4);return{key1:Y,key2:$}}async function E7(Z,Y){let{key1:$,key2:J}=L7(),X=Date.now(),W=AZ;while(!0){let H=await Z.unsafe(`SELECT pg_try_advisory_lock(${$}, ${J}) AS acquired`);if(S7(H,"acquired"))return{release:async()=>{try{await Z.unsafe(`SELECT pg_advisory_unlock(${$}, ${J})`)}catch{}}};if(Date.now()-X>=Y)throw Error("[migration-lock] another migration is in progress \u2014 could not acquire postgres advisory lock within timeout");await LZ(W),W=Math.min(W*2,BZ)}}async function I7(Z,Y){let $=Date.now(),J=AZ;while(!0){let X=await Z.unsafe(`SELECT GET_LOCK('${VZ}', 0) AS acquired`);if(M7(X,"acquired")===1)return{release:async()=>{try{await Z.unsafe(`SELECT RELEASE_LOCK('${VZ}')`)}catch{}}};if(Date.now()-$>=Y)throw Error("[migration-lock] another migration is in progress \u2014 could not acquire MySQL named lock within timeout");await LZ(J),J=Math.min(J*2,BZ)}}function K7(){return V7(".migration.lock")}async function j7(Z,Y){let $=Z??K7(),J=Date.now(),X=AZ;while(!0){if(R7($)){let W=!1;return{release:async()=>{if(W)return;W=!0;try{H4($)}catch{}}}}if(w7($),Date.now()-J>=Y)throw Error(`[migration-lock] another migration is in progress \u2014 lock file ${$} held within timeout`);await LZ(X),X=Math.min(X*2,BZ)}}function R7(Z){try{let Y=U7(Z,"wx");try{let $=JSON.stringify({pid:O7.pid,startedAt:new Date().toISOString()});_7(Y,H7.from($,"utf8"))}finally{z7(Y)}return!0}catch(Y){if(Y.code==="EEXIST")return!1;throw Y}}function w7(Z){try{let Y=Q7(Z);if(Date.now()-Y.mtimeMs>B7)try{H4(Z)}catch{}}catch{}}function LZ(Z){let Y=Z*(1+Math.random()*0.25);return new Promise(($)=>setTimeout($,Y))}function S7(Z,Y){let $=z4(Z);if(!$)return!1;let J=$[Y];return J===!0||J===1||J==="1"||J==="t"}function M7(Z,Y){let $=z4(Z);if(!$)return null;let J=$[Y];if(typeof J==="number")return J;if(typeof J==="string"&&/^-?\d+$/.test(J))return Number.parseInt(J,10);return null}function z4(Z){if(!Z)return null;if(Array.isArray(Z))return Z[0];if(typeof Z==="object"&&"rows"in Z&&Array.isArray(Z.rows))return Z.rows[0];return null}rY();import{env as tY}from"@stacksjs/env";var K={info:(...Z)=>typeof d?.info==="function"?d.info(...Z):console.log(...Z),success:(Z)=>typeof d?.success==="function"?d.success(Z):console.log(Z),warn:(Z)=>typeof d?.warn==="function"?d.warn(Z):console.warn(Z),error:(...Z)=>typeof d?.error==="function"?d.error(...Z):console.error(...Z),debug:(...Z)=>typeof d?.debug==="function"?d.debug(...Z):console.debug(...Z)},P7=tY.DB_CONNECTION||"sqlite",k7=o("sqlite",tY),PY=o("mysql",tY),kY=o("postgres",tY),NY={default:P7,connections:{sqlite:{database:k7.database,prefix:""},mysql:{name:PY.database,host:PY.host,username:PY.username,password:PY.password,port:PY.port,prefix:""},postgres:{name:kY.database,host:kY.host,username:kY.username,password:kY.password,port:kY.port,prefix:""}}};function A4(){return NY.default||"sqlite"}function e(){let Z=A4();if(Z==="sqlite"||Z==="mysql"||Z==="postgres")return Z;if(Z==="singlestore")return"mysql";if(Z==="dynamodb")throw Error("[database] DB_CONNECTION=dynamodb is not compatible with the SQL migration runner. "+"DynamoDB has no schema-migration concept \u2014 use the entity-style `dynamo.entity(...)` "+"API from @stacksjs/database directly. To run SQL migrations, set DB_CONNECTION to one of: sqlite, mysql, postgres.");throw Error(`[database] Unknown DB_CONNECTION "${Z}". Allowed values: sqlite, mysql, postgres, dynamodb.`)}function KZ(){return A4()==="singlestore"?"singlestore":e()}function hY(){let Z=e(),Y=NY.connections[Z];V4({dialect:Z,verbose:!1,database:{database:Y?.name||Y?.database||"stacks",host:Y?.host||"localhost",port:Y?.port||(Z==="postgres"?5432:Z==="mysql"?3306:0),username:Y?.username||"",password:Y?.password||""}}),nY()}function jZ(){let Z=yY.userModelsPath();return{modelsDir:Z,skip:!EZ(Z)}}function N7(){let Z=t(process.cwd(),"database","migrations"),Y;try{Y=iY(Z).filter((L)=>L.endsWith(".sql"))}catch{return}let $=[],J=(L,A)=>{K.info(`Skipping migration on SQLite (${A}): ${L}`),$.push(L)},X=(L,A,E)=>{K.info(`Dropping no-op migration (${E}): ${L}`);try{D7(A)}catch{}$.push(L)},W=[],H=/^\s*ALTER\s+TABLE\s+.+\s+ADD\s+CONSTRAINT\s+/i,G=/^\s*CREATE\s+TYPE\s+/i,z=/^\s*CREATE\s+UNIQUE\s+INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["'`]?(\w+)["'`]?/i,Q=/^\s*ALTER\s+TABLE\s+["']?(\w+)["']?\s+DROP\s+COLUMN\s+["']?(\w+)["']?\s*$/i,_=/^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i,U=new Map;for(let L of Y){let A=L.match(/^\d+-create-(\w+)-table\.sql$/);if(!A||!A[1])continue;let E=A[1],B=U.get(E);if(!B||L<B)U.set(E,L)}let I=t(process.cwd(),NY.connections.sqlite.database||"stacks.db"),O=null;if(EZ(I))try{let{Database:L}=p("bun:sqlite");O=new L(I,{readonly:!0})}catch{}for(let L of Y){K.debug(`[migration] Running: ${L}`);let A=t(Z,L),B=Q4(A,"utf-8").split(";").map((w)=>w.trim()).filter((w)=>w.length>0&&!w.startsWith("--"));if(B.length===0)continue;let j=B[0],R=j?j.match(_):null;if(R&&R[1]){let w=R[1],g=U.get(w);if(g&&g!==L){X(L,A,`duplicate create-table for "${w}" (kept ${g})`);continue}}if(B.every((w)=>H.test(w))){J(L,"SQLite does not support ALTER TABLE ADD CONSTRAINT");continue}if(B.every((w)=>G.test(w))){J(L,"SQLite does not support CREATE TYPE (enum types)");continue}let D=B.map((w)=>w.match(z)?.[1]).filter((w)=>Boolean(w));if(O&&D.length===B.length){let w=O.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?");if(D.filter((GY)=>!w.get(GY)).length>0)K.info(`Re-queueing unique-index migration (index missing from database): ${L}`),W.push(L);continue}if(B.some((w)=>Q.test(w))){let w=!1,g=[];for(let GY of B){let MY=GY.match(Q);if(MY&&MY[1]&&MY[2]){let lY=MY[1],FY=MY[2];if(!O){K.info(`Skipping DROP COLUMN "${FY}" \u2014 no database exists yet: ${L}`),w=!0;continue}try{let y6=lY.replace(/[^a-zA-Z0-9_]/g,""),mZ=O.prepare(`PRAGMA table_info("${y6}")`).all();if(mZ.length===0){K.info(`Skipping DROP COLUMN "${FY}" \u2014 table "${lY}" does not exist yet: ${L}`),w=!0;continue}if(!mZ.some((h6)=>h6.name===FY)){K.info(`Skipping DROP COLUMN "${FY}" from "${lY}" \u2014 column does not exist: ${L}`),w=!0;continue}}catch{K.info(`Skipping DROP COLUMN "${FY}" \u2014 table "${lY}" not found: ${L}`),w=!0;continue}}g.push(GY)}if(w){if(g.length===0)X(L,A,"columns already absent from table");else _4(A,`${g.join(`;
|
|
128
3
|
`)};
|
|
129
|
-
`);continue}}}if(
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
${
|
|
4
|
+
`);continue}}}if(O)try{O.close()}catch{}if($.length>0||W.length>0)try{let L=t(process.cwd(),NY.connections.sqlite.database||"stacks.db");F7(q7(L),{recursive:!0});let{Database:A}=p("bun:sqlite"),E=new A(L);try{E.exec(`CREATE TABLE IF NOT EXISTS migrations (
|
|
5
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
6
|
+
migration TEXT NOT NULL UNIQUE,
|
|
7
|
+
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
8
|
+
)`);let B=E.prepare("INSERT OR IGNORE INTO migrations (migration) VALUES (?)");for(let R of $)B.run(R);let j=E.prepare("DELETE FROM migrations WHERE migration = ?");for(let R of W)j.run(R)}finally{E.close()}}catch(L){K.debug(`[migration] Could not record dropped migrations as executed: ${L}`)}}async function y7(){let Z=e();if(Z==="sqlite")return;let Y=NY.connections[Z],$=(Y?.name||"stacks").replace(/['"]/g,""),J=Y?.host||"localhost",X=Y?.port||(Z==="postgres"?5432:3306),W=Y?.username||(Z==="postgres"?process.env.USER||"postgres":"root"),H=Y?.password||"",G=Z==="postgres"?"postgres":"mysql";try{V4({dialect:Z,database:{database:G,host:J,port:X,username:W,password:H}}),nY();let z=O4();if(Z==="postgres")try{await z.unsafe(`CREATE DATABASE "${$}"`),K.info(`Created database "${$}"`)}catch(Q){if(Q?.message?.includes("already exists")||Q?.errno==="42P04")K.info(`Database "${$}" already exists`);else throw Q}else if(Z==="mysql")try{await z.unsafe(`CREATE DATABASE IF NOT EXISTS \`${$}\``),K.info(`Ensured database "${$}" exists`)}catch(Q){if(Q?.message?.includes("database exists"))K.info(`Database "${$}" already exists`);else throw Q}nY()}catch(z){K.warn(`Could not auto-create database "${$}": ${z?.message||z}`),K.info("If the database already exists, this warning can be ignored."),nY()}}async function h7(){let Z=[];try{let{FEATURE_NAMES:Y,migrationFeature:$}=await import("@stacksjs/buddy"),{feature:J}=await import("@stacksjs/config"),X=await import("fs/promises"),W=yY.projectPath("database/migrations");if(!EZ(W))return Z;let H=new Set(Y.filter((z)=>!J(z)));if(H.size===0)return Z;let G=iY(W).filter((z)=>z.endsWith(".sql"));for(let z of G){let Q=$(z);if(!Q||!H.has(Q))continue;let _=t(W,z),U=`${_}.disabled`;await X.rename(_,U),Z.push({original:_,hidden:U,feature:Q})}if(Z.length>0){let z=Object.entries(Z.reduce((Q,_)=>{return Q[_.feature]=(Q[_.feature]??0)+1,Q},{})).map(([Q,_])=>`${Q}: ${_}`).join(", ");K.info(`[migration] Skipping ${Z.length} migration(s) for disabled features (${z}). Run \`./buddy <feature>:install\` to enable.`)}}catch{}return Z}async function v7(Z){let Y=await import("fs/promises");for(let{original:$,hidden:J}of Z)try{await Y.rename(J,$)}catch{}}async function U4(){try{let Z=await V.selectFrom("migrations").select(($)=>$.fn.count("id").as("n")).executeTakeFirst();if(!Z)return 0;let Y=Number(Z.n??Z.N??0);return Number.isFinite(Y)?Y:0}catch{return 0}}async function f7(Z){try{let Y=await import("fs/promises"),$=yY.projectPath(".stacks");await Y.mkdir($,{recursive:!0});let J=`${$}/last-migrate-result.json`,X=JSON.stringify({appliedCount:Z,completedAt:new Date().toISOString()});await Y.writeFile(J,X,"utf8")}catch{}}async function X5(){let Z=Date.now(),Y=await h7(),$=null;try{K.debug("Migrating database..."),await y7(),hY();let J=e(),X=J==="sqlite"?null:O4();if($=await G4(J,X),J==="sqlite")N7();let W=yY.userModelsPath(),H=await U4();K.debug(`[migration] Running migrations from: ${W}`),await x7(W);let G=await U4(),z=Math.max(0,G-H);return await f7(z),K.debug(`Database migration completed in ${Date.now()-Z}ms (applied ${z}).`),_Y(z===0?"Nothing to migrate.":`Applied ${z} migration${z===1?"":"s"}.`)}catch(J){let X=J instanceof Error?J.message:String(J);return K.error(`[migration] Failed after ${Date.now()-Z}ms: ${X}`),K.info("[migration] Run `./buddy migrate:fresh` to drop and recreate the schema if state is partial."),aY(oY("Migration failed",J))}finally{if($)try{await $.release()}catch{}await v7(Y)}}var b7=["oauth_refresh_tokens","oauth_access_tokens","oauth_clients","passkeys","failed_jobs","jobs","notifications","password_reset_tokens"];async function W5(){try{hY();let Z=yY.userModelsPath(),Y=e();return await p7(Y),await T7(Z,{dialect:Y}),_Y("All tables dropped successfully!")}catch(Z){return aY(oY("Database reset failed",Z))}}async function p7(Z){if(Z==="mysql")try{await V.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute()}catch(Y){K.warn(`Could not disable foreign key checks: ${Y instanceof Error?Y.message:String(Y)}`)}if(Z==="sqlite")try{await V.unsafe("PRAGMA foreign_keys = OFF").execute()}catch(Y){K.warn(`Could not disable foreign key checks: ${Y instanceof Error?Y.message:String(Y)}`)}for(let Y of b7)try{let $;if(Z==="postgres")$=`DROP TABLE IF EXISTS "${Y}" CASCADE`;else if(Z==="mysql")$=`DROP TABLE IF EXISTS \`${Y}\``;else $=`DROP TABLE IF EXISTS "${Y}"`;K.info(`Dropping framework table: ${Y}`),await V.unsafe($).execute(),K.info(`Dropped framework table: ${Y}`)}catch($){K.warn(`Could not drop table ${Y}: ${$ instanceof Error?$.message:String($)}`)}if(Z==="mysql")try{await V.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}catch(Y){K.warn(`Could not re-enable foreign key checks: ${Y instanceof Error?Y.message:String(Y)}`)}if(Z==="sqlite")try{await V.unsafe("PRAGMA foreign_keys = ON").execute()}catch(Y){K.warn(`Could not re-enable foreign key checks: ${Y instanceof Error?Y.message:String(Y)}`)}}function B4(Z){let Y=Z.applyRenames??(process.env.STACKS_MIGRATE_NO_RENAME==="1"?!1:void 0),$=Z.fromDb??(process.env.STACKS_MIGRATE_FROM_DB==="1"?!0:void 0);return{applyRenames:Y,fromDb:$}}async function H5(Z={}){try{hY();let Y=e(),{modelsDir:$,skip:J}=jZ();if(J)return[];let{applyRenames:X,fromDb:W}=B4(Z);return(await IZ($,{dialect:KZ(),dryRun:!0,applyRenames:X,fromDb:W})).operations??[]}catch(Y){return K.debug(`[migration] preview failed: ${Y instanceof Error?Y.message:String(Y)}`),[]}}async function G5(Z={}){try{K.debug("Generating migrations..."),hY();let Y=e(),{modelsDir:$,skip:J}=jZ();if(J)return K.debug("No app/Models directory found; using committed framework migrations"),_Y("Migrations generated");let{applyRenames:X,fromDb:W}=B4(Z);K.debug(`[migration] Generating migrations for dialect: ${Y}, models: ${$}`);let H=await IZ($,{dialect:KZ(),dryRun:!0,applyRenames:X,fromDb:W});if(H.hasChanges){let G=C7(H.sqlStatements??[]);if(G>0)K.success(`Generated ${G} migration file${G===1?"":"s"}`);else K.debug("Migration generation produced no new files (already up to date)")}else K.debug("No changes detected");return _Y("Migrations generated")}catch(Y){return aY(oY("Migration generation failed",Y))}}function C7(Z){if(!Z?.length)return 0;let Y=t(process.cwd(),"database","migrations");try{p("fs").mkdirSync(Y,{recursive:!0})}catch{}let $="";try{for(let z of iY(Y).filter((Q)=>Q.endsWith(".sql")))$+=`
|
|
9
|
+
${Q4(t(Y,z),"utf8")}`}catch{}let J=(z)=>z.replace(/\s+/g," ").trim(),X=J($),W=c7(Z),H=0,G=u7(Y);for(let z of W){let Q=z.statements.filter((O)=>!X.includes(J(O)));if(Q.length===0)continue;let _=`${String(G).padStart(10,"0")}-${z.label}.sql`,U=t(Y,_),I=`${Q.map((O)=>O.trim().replace(/;\s*$/,"")).join(`;
|
|
135
10
|
`)};
|
|
136
|
-
`;
|
|
137
|
-
`).slice(1).find((
|
|
138
|
-
UPDATE ${
|
|
139
|
-
WHERE ${
|
|
140
|
-
AND ${
|
|
141
|
-
SELECT ${
|
|
142
|
-
WHERE ${
|
|
143
|
-
LIMIT ${
|
|
11
|
+
`;_4(U,I),K.debug(`[migration] Wrote ${_} (${Q.length} stmt${Q.length===1?"":"s"})`),H+=1,G+=1}return H}function c7(Z){let Y=new Map,$=(J,X)=>{let W=Y.get(J)??[];W.push(X),Y.set(J,W)};for(let J of Z){let X=J.trim();if(!X)continue;let W=X.match(/^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?(\w+)["`]?/i);if(W){$(`create-${W[1]}-table`,X);continue}let H=X.match(/^\s*ALTER\s+TABLE\s+["`]?(\w+)["`]?\s+(?:ADD\s+COLUMN\s+["`]?(\w+)["`]?|DROP\s+COLUMN\s+["`]?(\w+)["`]?|ADD\s+CONSTRAINT)/i);if(H){$(`alter-${H[1]}-${H[2]||H[3]||"constraint"}`,X);continue}let G=X.match(/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?(\w+)["`]?\s+ON\s+["`]?(\w+)["`]?/i);if(G){$(`create-${G[1]}-index-in-${G[2]}`,X);continue}let z=X.match(/^\s*DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?["`]?(\w+)["`]?/i);if(z){$(`drop-${z[1]}-table`,X);continue}$("auto-misc",X)}return[...Y.entries()].map(([J,X])=>({label:J,statements:X}))}function u7(Z){let Y=0;try{for(let $ of iY(Z)){let J=$.match(/^(\d+)-/);if(J?.[1])Y=Math.max(Y,Number.parseInt(J[1],10))}}catch{}return Y+1}async function z5(){try{K.info("Generating fresh migrations..."),hY();let Z=e(),{modelsDir:Y,skip:$}=jZ();if($)return K.info("No app/Models directory found; using committed framework migrations"),_Y("Migrations generated");return await IZ(Y,{dialect:KZ(),full:!0,dryRun:!0}),K.success("Migrations generated"),_Y("Migrations generated")}catch(Z){return aY(oY("Fresh migration generation failed",Z))}}import{memoryUsage as m7}from"process";import{config as YY}from"@stacksjs/config";import{log as bY}from"@stacksjs/logging";function RZ(Z){let Y={normalized:"",type:"OTHER",tables:[]};if(!Z)return Y;try{let $=Z.trim().toUpperCase();if($.startsWith("SELECT"))Y.type="SELECT";else if($.startsWith("INSERT"))Y.type="INSERT";else if($.startsWith("UPDATE"))Y.type="UPDATE";else if($.startsWith("DELETE"))Y.type="DELETE";return Y.tables=g7(Z,Y.type),Y.normalized=d7(Z),Y}catch{return{normalized:Z,type:"OTHER",tables:[]}}}function vY(Z,Y="i"){return new RegExp(`${Z}\\s+(?:"([^"]+)"|\`([^\`]+)\`|\\[([^\\]]+)\\]|([\\w.]+))`,Y)}function fY(Z){if(!Z)return null;let Y=Z[1]??Z[2]??Z[3]??Z[4];if(!Y)return null;return Y.split(".").pop()??null}function g7(Z,Y){let $=[];try{switch(Y){case"SELECT":{let J=Z.match(vY("from")),X=fY(J);if(X)$.push(X);let W=vY("join","gi");for(let H of Z.matchAll(W)){let G=fY(H);if(G)$.push(G)}break}case"INSERT":{let J=Z.match(vY("into")),X=fY(J);if(X)$.push(X);break}case"UPDATE":{let J=Z.match(vY("update")),X=fY(J);if(X)$.push(X);break}case"DELETE":{let J=Z.match(vY("from")),X=fY(J);if(X)$.push(X);break}}}catch{}return[...new Set($)].filter(Boolean)}function d7(Z){try{let Y=Z;return Y=Y.replace(/(?<![a-zA-Z_])\b\d+\b(?![a-zA-Z_])/g,"?"),Y=Y.replace(/'([^']|'')*'/g,"?"),Y=Y.replace(/"([^"]|"")*"/g,"?"),Y=Y.replace(/\btrue\b/gi,"?"),Y=Y.replace(/\bfalse\b/gi,"?"),Y=Y.replace(/\bnull\b/gi,"?"),Y=Y.replace(/\s+/g," ").trim(),Y}catch{return Z}}F();var L4=()=>{};function s7(Z){L4=Z}var wZ=!1;async function l7(Z){if(wZ)return;try{let{query:Y,durationMs:$,error:J,bindings:X}=r7(Z);try{L4(Y,$,YY.database?.default||"unknown")}catch{}if(!YY.database?.queryLogging?.enabled)return;let W=n7($,J),H=await i7(Y,$,W,J,X);if(YY.database?.queryLogging?.analysis?.enabled&&(W==="slow"||YY.database.queryLogging.analysis.analyzeAll))await e7(H);wZ=!0;try{await J8(H)}finally{wZ=!1}if(W!=="completed")bY[W==="failed"?"error":"warn"](`Query ${W}:`,{query:H.query,duration:H.duration,connection:H.connection,...J&&{error:J}})}catch(Y){bY.error("Failed to log query:",Y)}}function r7(Z){let Y=Z.query?.sql||"",$=Z.queryDurationMillis||0,J=Z.error,X;if(Z.query?.parameters)try{X=JSON.stringify(Z.query.parameters)}catch{X="[]"}return{query:Y,durationMs:$,error:J,bindings:X}}function n7(Z,Y){let $=YY.database?.queryLogging?.slowThreshold||100;if(Y)return"failed";if(Z>$)return"slow";return"completed"}async function i7(Z,Y,$,J,X){let W=YY.database.default||"unknown",H=RZ(Z).normalized||Z,{trace:G,caller:z}=t7();return{query:Z,normalized_query:H,duration:Y,connection:W,status:$,error:J?String(J):void 0,executed_at:new Date().toISOString(),bindings:X,trace:G,...z,memory_usage:m7().heapUsed/1024/1024}}var a7=[/\b(?:sk|pk|rk|api|secret|token|bearer|password|pwd|key)[_-]?[A-Za-z0-9]{12,}/gi,/\bsk_(?:live|test)_[A-Za-z0-9]{20,}/g,/\bAKIA[0-9A-Z]{16}/g,/\b[A-Za-z0-9_-]{40,}\b(?=\s|$|['"])/g];function o7(Z){let Y=Z;for(let $ of a7)Y=Y.replace($,"<redacted>");return Y}function t7(){try{let Z=Error("Stack trace capture").stack||"",$=Z.split(`
|
|
12
|
+
`).slice(1).find((X)=>!X.includes("query-logger.ts")),J={};if($){let X=$.match(/at (.+?) \(/),W=$.match(/\((.+?):(\d+):(\d+)\)/);if(X&&X[1]){let H=X[1].split(".");J={model:H.length>1?H[0]:void 0,method:H.length>1?H[1]:H[0]}}if(W&&W[1]&&W[2])J={...J,file:W[1],line:Number.parseInt(W[2],10)}}return{trace:o7(Z),caller:J}}catch{return{trace:"",caller:{}}}}async function e7(Z){try{let{tables:Y,type:$}=RZ(Z.query);if(Z.affected_tables=JSON.stringify(Y||[]),$==="SELECT"&&YY.database?.queryLogging?.analysis?.explainPlan){let X=await Z8(Z.query);if(X){if(Z.explain_plan=X.plan,Z.indexes_used=JSON.stringify(X.indexesUsed||[]),Z.missing_indexes=JSON.stringify(X.missingIndexes||[]),YY.database?.queryLogging?.analysis?.suggestions)Z.optimization_suggestions=JSON.stringify($8(X,Z))}}let J=[$];if(Y&&Y.length>0)J.push(...Y.map((X)=>`table:${X}`));Z.tags=JSON.stringify(J)}catch(Y){bY.debug("Error during query analysis:",Y)}}var Y8=new Set(["sqlite","mysql","postgres"]);async function Z8(Z){try{let Y=(await import("@stacksjs/config")).config?.database?.default,$=typeof Y==="string"?Y:"sqlite";if(!Y8.has($))return null;let J;if($==="mysql")J=`EXPLAIN FORMAT=JSON ${Z}`;else if($==="postgres")J=`EXPLAIN (FORMAT JSON) ${Z}`;else J=`EXPLAIN QUERY PLAN ${Z}`;let X=await V.unsafe?.(J);if(!X)return null;let W=Array.isArray(X)?X:X.rows??[],H=JSON.stringify(W),G=[],z=[];if($==="sqlite")for(let Q of W){let _=Q?.detail||"",U=_.match(/USING (?:COVERING )?INDEX (\w+)/i);if(U&&U[1])G.push(U[1]);else{let I=_.match(/^SCAN\s+(\w+)/i);if(I&&I[1])z.push(I[1])}}else if($==="mysql"){let Q=H;for(let _ of Q.matchAll(/"key"\s*:\s*"([^"]+)"/g))if(_[1])G.push(_[1]);for(let _ of Q.matchAll(/"table_name"\s*:\s*"([^"]+)"[^}]*"access_type"\s*:\s*"ALL"/g))if(_[1])z.push(_[1])}else if($==="postgres"){let Q=H;for(let _ of Q.matchAll(/"Index Name"\s*:\s*"([^"]+)"/g))if(_[1])G.push(_[1]);for(let _ of Q.matchAll(/"Node Type"\s*:\s*"Seq Scan"[^}]*"Relation Name"\s*:\s*"([^"]+)"/g))if(_[1])z.push(_[1])}return{plan:H.length>4000?`${H.slice(0,4000)}\u2026`:H,indexesUsed:Array.from(new Set(G)),missingIndexes:Array.from(new Set(z))}}catch(Y){return bY.debug("[query-logger] EXPLAIN failed (non-fatal):",Y),null}}function $8(Z,Y){let $=[];if(Z.missingIndexes&&Z.missingIndexes.length>0)$.push(`Consider adding index on ${Z.missingIndexes.join(", ")}`);if(Y.status==="slow"){if($.push("Consider optimizing this query to reduce execution time"),Y.query.toLowerCase().includes("select *"))$.push("Specify only needed columns instead of using SELECT *");if(!Y.query.toLowerCase().includes("limit"))$.push("Consider adding LIMIT clause to reduce result set size")}return $}async function J8(Z){try{await V.insertInto("query_logs").values(Z).execute()}catch(Y){bY.error("Failed to store query log:",Y)}}import{log as ZY}from"@stacksjs/logging";import{path as X8}from"@stacksjs/path";import{fs as E4}from"@stacksjs/storage";class I4{dependencies;async call(Z){await new Z().run()}}function W8(Z){let Y=new Set(Z.map((G)=>G.name)),$=new Map;for(let G of Z){let z=new Set;for(let Q of G.dependencies??[]){if(Q===G.name)continue;if(!Y.has(Q)){ZY.warn(`[seeder] ${G.name} depends on '${Q}' but no seeder by that name was discovered \u2014 ignoring`);continue}z.add(Q)}$.set(G.name,z)}let J=new Map,X=new Map;for(let G of Z)J.set(G.name,$.get(G.name).size),X.set(G.name,new Set);for(let G of Z)for(let z of $.get(G.name))X.get(z).add(G.name);let W=Z.filter((G)=>J.get(G.name)===0).map((G)=>G.name).sort(),H=[];while(W.length>0){let G=W.shift();H.push(G);let z=[];for(let Q of X.get(G)){let _=(J.get(Q)??0)-1;if(J.set(Q,_),_===0)z.push(Q)}if(z.length>0)W.push(...z),W.sort()}if(H.length!==Z.length){let G=Z.map((z)=>z.name).filter((z)=>!H.includes(z));throw Error(`[seeder] Cycle in seeder \`dependencies\` among: ${G.join(", ")}`)}return H}async function H8(Z={}){try{let{injectGlobalAutoImports:Q}=await import("@stacksjs/server");await Q()}catch{}let Y=Z.dir??X8.projectPath("database/seeders"),$=[],J=[];if(!E4.existsSync(Y))return ZY.info(`[seeder] No class seeders directory at ${Y}`),{ran:$,skipped:J};let X=E4.readdirSync(Y).filter((Q)=>Q.endsWith(".ts")&&!Q.startsWith("_")).sort(),W=[];for(let Q of X){let _=Q.replace(/\.ts$/,"");try{let U=await import(`${Y}/${Q}`),I=U.default??U[_];if(!I){ZY.warn(`[seeder] ${Q} has no default export`),J.push(_);continue}let O=new I;if(typeof O.run!=="function"){ZY.warn(`[seeder] ${_} does not implement run()`),J.push(_);continue}W.push({className:_,inst:O})}catch(U){ZY.error(`[seeder] ${_} failed to load:`,U),J.push(_)}}let H=W.some((Q)=>(Q.inst.dependencies?.length??0)>0),G;if(H)try{G=W8(W.map((Q)=>({name:Q.className,dependencies:Q.inst.dependencies})))}catch(Q){return ZY.error(Q instanceof Error?Q.message:String(Q)),{ran:$,skipped:[...J,...W.map((_)=>_.className)]}}else G=W.map((Q)=>Q.className);let z=new Map(W.map((Q)=>[Q.className,Q.inst]));for(let Q of G){if(Z.class&&Q!==Z.class){J.push(Q);continue}let _=z.get(Q);try{ZY.info(`[seeder] Running ${Q}\u2026`),await _.run(),$.push(Q)}catch(U){ZY.error(`[seeder] ${Q} failed:`,U),J.push(Q)}}return{ran:$,skipped:J}}async function G8(Z,Y,$,J){let{type:X,defaultValue:W,notNull:H=!1,batchSize:G=1000}=J,z=Z,Q=W===void 0?"":` DEFAULT ${R4(W)}`;if(await OY(z,`ALTER TABLE ${T(Y)} ADD COLUMN ${T($)} ${X}${Q}`),W!==void 0)await j4(Z,Y,$,W,G);if(H)await OY(z,`ALTER TABLE ${T(Y)} ALTER COLUMN ${T($)} SET NOT NULL`)}async function OY(Z,Y){if(typeof Z.unsafe==="function")return await Z.unsafe(Y)??{};return await TY`${TY.raw(Y)}`.execute(Z),{}}async function j4(Z,Y,$,J,X=1000){let W=Z,H=0,G=0;do{let z=`
|
|
13
|
+
UPDATE ${T(Y)} SET ${T($)} = ${R4(J)}
|
|
14
|
+
WHERE ${T($)} IS NULL
|
|
15
|
+
AND ${K4(W)} IN (
|
|
16
|
+
SELECT ${K4(W)} FROM ${T(Y)}
|
|
17
|
+
WHERE ${T($)} IS NULL
|
|
18
|
+
LIMIT ${X}
|
|
144
19
|
)
|
|
145
|
-
`,Q=await u8(L,U);z=Q.numAffectedRows!=null?Number(Q.numAffectedRows):0,j+=z}while(z>0)}async function VO($,Z,X,_,Y){let L=$;if(Y.atomic){await u8(L,`ALTER TABLE ${c0(Z)} RENAME COLUMN ${c0(X)} TO ${c0(_)}`);return}await u8(L,`ALTER TABLE ${c0(Z)} ADD COLUMN ${c0(_)} ${Y.type}`),await u8(L,`UPDATE ${c0(Z)} SET ${c0(_)} = ${c0(X)}`)}function c0($){if(!/^[a-z_][a-z0-9_]*$/i.test($))throw Error(`Refusing to quote unsafe identifier: ${JSON.stringify($)}`);return`"${$}"`}function l4($){if($===null)return"NULL";if(typeof $==="number")return String($);if(typeof $==="boolean")return $?"TRUE":"FALSE";return`'${String($).replace(/'/g,"''")}'`}function m4($){return"id"}await p0();import{log as w0}from"@stacksjs/logging";import{faker as g6}from"@stacksjs/faker";import{path as o1}from"@stacksjs/path";import{hashMake as WO}from"@stacksjs/security";import{fs as n4}from"@stacksjs/storage";function p6($){return o1.frameworkPath(`defaults/app/Models/${$||""}`)}function i4($){return $.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Za-z])/g,"$1_$2").toLowerCase()}async function r1($,Z=!1){let X=[];if(!n4.existsSync($))return X;let _=n4.readdirSync($,{withFileTypes:!0});for(let Y of _){let L=o1.join($,Y.name);if(Y.isDirectory()&&Z){let z=await r1(L,!0);X.push(...z);continue}if(!Y.name.endsWith(".ts")||Y.name.startsWith("index")||Y.name.startsWith("_"))continue;try{let z=await import(L),j=z.default||z;if(!j)continue;let U=j.traits?.useSeeder??j.traits?.seedable;if(!U)continue;let Q=10;if(typeof U==="object"&&"count"in U)Q=U.count;let E=j.name||Y.name.replace(".ts",""),G=j.table||i4(E)+"s";X.push({name:E,table:G,count:Q,attributes:j.attributes||{},model:j,filePath:L})}catch(z){w0.error(`Failed to load model ${Y.name}:`,z)}}return X}async function r4($,Z=!1,X=!1){let _=p6(),Y=await r1($,!1);if(Y.length>0&&!X)return Y;let L=await r1(_,!0),z=new Map;for(let j of L)z.set(j.name,j);for(let j of Y){if(z.has(j.name)&&Z)w0.info(` User model "${j.name}" overrides default`);z.set(j.name,j)}return Array.from(z.values())}function KO($,Z){let X=$.toLowerCase();if(X==="password"||X.endsWith("_password")||X.endsWith("password"))return!0;if(Z.hidden===!0&&X.includes("pass"))return!0;return!1}async function IO($,Z,X=!1){let _={};for(let[Y,L]of Object.entries($)){let z=i4(Y),j;if(L.factory&&typeof L.factory==="function")try{j=L.factory(g6)}catch(U){let Q=U instanceof Error?U.message:String(U);if(X)w0.warn(` Factory failed for ${Z}.${Y}: ${Q}`);if(L.default!==void 0)j=L.default;else j=JO(Y)}else if(L.default!==void 0)j=L.default;else continue;if(KO(Y,L)&&typeof j==="string")try{j=await WO(j,{algorithm:"bcrypt"})}catch(U){let Q=U instanceof Error?U.message:String(U);if(X)w0.warn(` Failed to hash password for ${Z}.${Y}: ${Q}`)}_[z]=j}return _}function JO($){let Z=$.toLowerCase();if(Z.startsWith("is")||Z.startsWith("has")||Z.endsWith("able"))return!1;if(Z.includes("count")||Z.includes("amount")||Z.includes("quantity"))return 0;if(Z.includes("url")||Z.includes("link"))return"https://example.com";if(Z.includes("email"))return g6.internet.email();if(Z.includes("name"))return g6.person.fullName();return null}async function DO($,Z=!1){let X=[];for(let _=0;_<$.count;_++){let Y=await IO($.attributes,$.name,Z&&_===0);X.push(Y)}return X}async function o4($,Z){let X=Date.now();try{try{await v.selectFrom($.table).limit(0).execute()}catch(z){let j=z?.message||"";if(j.includes("does not exist")||j.includes("no such table")||j.includes("doesn't exist"))return w0.info(` Skipping ${$.name}: table "${$.table}" does not exist`),{model:$.name,table:$.table,count:0,success:!0,duration:Date.now()-X};throw z}let _=await DO($,Z.verbose);if(_.length===0)return{model:$.name,table:$.table,count:0,success:!0,duration:Date.now()-X};if(Z.fresh)try{if(await v.deleteFrom($.table).execute(),Z.verbose)w0.info(` Truncated table: ${$.table}`)}catch{}let Y=100,L=0;for(let z=0;z<_.length;z+=Y){let j=_.slice(z,z+Y);await v.insertInto($.table).values(j).execute(),L+=j.length}if(Z.verbose)w0.success(` Seeded ${$.name}: ${L} records`);return{model:$.name,table:$.table,count:L,success:!0,duration:Date.now()-X}}catch(_){let Y=_ instanceof Error?_.message:String(_);if(Z.verbose)w0.error(` Failed to seed ${$.name}: ${Y}`);return{model:$.name,table:$.table,count:0,success:!1,error:Y,duration:Date.now()-X}}}function RO($){let Z={User:0,Team:1,Project:2};return $.sort((X,_)=>{let Y=Z[X.name]??10,L=Z[_.name]??10;return Y-L})}async function SO($={}){let Z=Date.now();await A6();let X=$.modelsDir||o1.userModelsPath(),_=$.verbose??!0;if(_)w0.info("Seeding database using model factories..."),w0.info(`User models directory: ${X}`),w0.info(`Default models directory: ${p6()}`);let Y=await r4(X,_,$.includeDefaults??!1);if(Y.length===0)return w0.warn("No seedable models found in defaults or user directories"),{total:0,successful:0,failed:0,results:[],duration:Date.now()-Z};if($.only&&$.only.length>0)Y=Y.filter((Q)=>$.only.includes(Q.name));if($.except&&$.except.length>0)Y=Y.filter((Q)=>!$.except.includes(Q.name));if(Y=RO(Y),_)w0.info(`Found ${Y.length} seedable model(s)`);let L=[];for(let Q of Y){if(_)w0.info(`Seeding ${Q.name} (${Q.count} records)...`);try{let E=await o4(Q,$);L.push(E)}catch(E){let G=E instanceof Error?E.message:String(E);if(_)w0.error(` Unexpected error seeding ${Q.name}: ${G}`);L.push({model:Q.name,table:Q.table,count:0,success:!1,error:G,duration:0})}}let z=L.filter((Q)=>Q.success).length,j=L.filter((Q)=>!Q.success).length,U=L.reduce((Q,E)=>Q+E.count,0);if(_)if(w0.info(""),j===0)w0.success("Database seeded successfully!"),w0.info(` Total records: ${U}`),w0.info(` Models seeded: ${z}`);else w0.warn(`Seeding completed with ${j} failure(s)`),w0.info(` Successful: ${z}`),w0.info(` Failed: ${j}`);return{total:L.length,successful:z,failed:j,results:L,duration:Date.now()-Z}}async function RW($,Z={}){let X=o1.userModelsPath(),Y=(await r4(X,Z.verbose)).find((L)=>L.name===$);if(!Y)throw Error(`Model not found: ${$}`);if(Z.count)Y.count=Z.count;return o4(Y,{fresh:Z.fresh,verbose:Z.verbose??!0})}async function SW($={}){return SO({...$,fresh:!0})}async function MW(){let $=o1.userModelsPath(),Z=p6(),X=await r1(Z,!0),_=await r1($,!1),Y=[],L=new Set;for(let z of _)Y.push({name:z.name,table:z.table,count:z.count,source:"user"}),L.add(z.name);for(let z of X)if(!L.has(z.name))Y.push({name:z.name,table:z.table,count:z.count,source:"default"});return Y}await p0();import{log as z_}from"@stacksjs/logging";import{getTableName as MO}from"@stacksjs/orm";import{path as u9}from"@stacksjs/path";import{fs as m8,globSync as U_}from"@stacksjs/storage";import{plural as wO,snakeCase as HO}from"@stacksjs/strings";function a4($){return $.name==="string"}function t4($){return $.name==="number"}function e4($){return $.name==="enum"}function $_($){return $.name==="boolean"}function Z_($){return $.name==="date"}function X_($){return $.name==="unix"}function __($){return $.name==="float"}function Y_($){return $.name==="datetime"}function L_($){return $.name==="timestamp"}async function s8(){let $=await m8.promises.readdir(u9.userMigrationsPath());if($.length){for(let Z of $)if(Z.endsWith(".ts")){let X=u9.userMigrationsPath(`${Z}`);if(m8.existsSync(X))await Bun.$`rm ${X}`}}}async function l8(){let $=u9.frameworkPath("cache/models");if(!m8.existsSync($))return;let Z=await m8.promises.readdir($);if(Z.length){for(let X of Z)if(X.endsWith(".ts")){let _=u9.frameworkPath(`cache/models/${X}`);if(m8.existsSync(_))await Bun.$`rm ${_}`}}}async function P9($){let X=(await import(u9.frameworkPath(`cache/models/${$}`))).default,_={};if(typeof X.attributes==="object")_=X.attributes;else try{_=JSON.parse(X.attributes||"{}")}catch{_={}}return _}async function BW($){if(typeof $==="string")$=(await import($)).default;return $.table??HO(wO($?.name||""))}async function X8($){return z_.debug(`hasTableBeenMigrated for table: ${$}`),(await qO()).some((X)=>X.name.includes($))}async function q0($){return z_.debug(`hasTableBeenMigrated for table: ${$}`),U_([u9.userMigrationsPath("*.ts")],{absolute:!0}).some((X)=>X.includes(`create-${$}`))}async function qO(){try{return await v.selectFrom("migrations").select("name").execute()}catch($){if($?.message.includes("no such table: migrations"))return console.warn("Migrations table does not exist, returning empty list."),[];return[]}}function c6($){if("getRules"in $){let Z=$.getRules().find((X)=>X.name==="max");return Z?.params?.length||Z?.params?.max||255}return 255}function TO($,Z="mysql"){if(Z==="sqlite")return"'text'";return`'varchar(${c6($)})'`}function AW($,Z="mysql"){if(Z==="sqlite")return"'text'";let X=$.name;if(X==="unix")return"'bigint'";return X||"date"}function yW($,Z){return $.min===Z.min&&$.max===Z.max}async function n8($){return(await m8.readdir(u9.userMigrationsPath())).some((X)=>{let _=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(-${_}-)`).test(X)})}function i8($,Z){let X=$.filter((Y)=>!Z.includes(Y)),_=Z.filter((Y)=>!$.includes(Y));if(X.length===0&&_.length===0)return null;return{added:_,removed:X}}function _8($){if(!$)return[];let Z=Object.entries($);return Z.sort(([X,_],[Y,L])=>{let z=_.order??Number.POSITIVE_INFINITY,j=L.order??Number.POSITIVE_INFINITY;return z-j}),Z}function r8($,Z){if(!$||!Z)return!1;if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if($[X]!==Z[X])return!1;return!0}function o8($,Z){let X=[];for(let _ in $)if(Object.prototype.hasOwnProperty.call($,_)&&Object.prototype.hasOwnProperty.call(Z,_)){let Y=c6($[_].validation.rule),L=c6(Z[_].validation.rule);if(Y!==void 0&&L!==void 0){if(Y!==L)X.push({key:_,max:L,min:L})}}return X}async function d5(){let $=U_([u9.userModelsPath("*.ts"),u9.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Z=[];for(let X of $){let _=(await import(X)).default,Y=MO(_,X),L=G8(_,Y);if(L)Z.push(L);Z.push(Y)}return Z}function G8($,Z){let X=`${Z}_likes`,_=$.traits;return typeof _?.likeable==="object"?_.likeable.table||X:void 0}function PO($,Z="mysql"){if(Z==="sqlite")return"'integer'";if("getRules"in $){let X=$.getRules().find((z)=>z.name==="min"),_=$.getRules().find((z)=>z.name==="max"),Y=X?.params?.min??-2147483648,L=_?.params?.max??2147483647;return Y>=-2147483648&&L<=2147483647?"'integer'":"'bigint'"}return"'integer'"}function NO($,Z="mysql"){let X=$.getAllowedValues();if(!X)throw Error("Enum rule found but no allowedValues defined");let _=X.map((Y)=>`'${Y}'`).join(", ");if(Z==="postgres")return"'varchar(255)'";if(Z==="sqlite")return"'text'";return`sql\`enum(${_})\``}function Y8($,Z="mysql"){if(e4($))return NO($,Z);if(a4($))return TO($,Z);if(t4($))return PO($,Z);if($_($))return"'boolean'";if(Z_($))return"'date'";if(Y_($))return Z==="postgres"?"'timestamp'":"'datetime'";if(X_($))return"'bigint'";if(L_($))return"'timestamp'";if(__($))return"'float4'";if(["array","object"].includes($.name))return Z==="sqlite"?"'text'":"'json'";if(Z==="sqlite")return"'text'";return Z==="mysql"?"'varchar(255)'":"'text'"}function hW($){return $.includes(".required()")}await p0();import{log as R9}from"@stacksjs/logging";import{log as j_}from"@stacksjs/logging";import{path as O_}from"@stacksjs/path";function E_($){return`\x1B[3m${$}\x1B[23m`}async function u5(){if(await q0("password_resets"))return;let Z=`import type { Database } from '@stacksjs/database'
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
`,Z
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
`,
|
|
160
|
-
`,
|
|
161
|
-
|
|
162
|
-
`,
|
|
163
|
-
`,
|
|
164
|
-
`,
|
|
165
|
-
`,
|
|
166
|
-
|
|
167
|
-
`,
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
`,
|
|
172
|
-
|
|
173
|
-
`,
|
|
174
|
-
`,
|
|
175
|
-
`,
|
|
176
|
-
`,
|
|
177
|
-
`,
|
|
178
|
-
|
|
179
|
-
`,
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
`,
|
|
183
|
-
`,
|
|
184
|
-
|
|
185
|
-
`,
|
|
186
|
-
`,
|
|
187
|
-
`,
|
|
188
|
-
`,
|
|
189
|
-
|
|
190
|
-
`,
|
|
191
|
-
|
|
20
|
+
`,Q=await OY(W,z);H=Q.numAffectedRows!=null?Number(Q.numAffectedRows):0,G+=H}while(H>0)}async function z8(Z,Y,$,J,X){let W=Z;if(X.atomic){await OY(W,`ALTER TABLE ${T(Y)} RENAME COLUMN ${T($)} TO ${T(J)}`);return}await OY(W,`ALTER TABLE ${T(Y)} ADD COLUMN ${T(J)} ${X.type}`),await OY(W,`UPDATE ${T(Y)} SET ${T(J)} = ${T($)}`)}function T(Z){if(!/^[a-z_][a-z0-9_]*$/i.test(Z))throw Error(`Refusing to quote unsafe identifier: ${JSON.stringify(Z)}`);return`"${Z}"`}function R4(Z){if(Z===null)return"NULL";if(typeof Z==="number")return String(Z);if(typeof Z==="boolean")return Z?"TRUE":"FALSE";return`'${String(Z).replace(/'/g,"''")}'`}function K4(Z){return"id"}F();import{log as M}from"@stacksjs/logging";import{faker as SZ}from"@stacksjs/faker";import{path as CY}from"@stacksjs/path";import{hashMake as U8}from"@stacksjs/security";import{fs as w4}from"@stacksjs/storage";function MZ(Z){return CY.frameworkPath(`defaults/app/Models/${Z||""}`)}var Q8=Object.freeze(["OauthClient","OauthAccessToken","OauthRefreshToken","PersonalAccessToken"]);function _8(Z){return Q8.includes(Z)}function FZ(Z){return Z.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Za-z])/g,"$1_$2").toLowerCase()}async function pY(Z,Y=!1){let $=[];if(!w4.existsSync(Z))return $;let J=w4.readdirSync(Z,{withFileTypes:!0});for(let X of J){let W=CY.join(Z,X.name);if(X.isDirectory()&&Y){let H=await pY(W,!0);$.push(...H);continue}if(!X.name.endsWith(".ts")||X.name.startsWith("index")||X.name.startsWith("_"))continue;try{let H=await import(W),G=H.default||H;if(!G)continue;let z=G.traits?.useSeeder??G.traits?.seedable;if(!z)continue;let Q=10,_=[];if(typeof z==="object"&&"count"in z){let O=z;Q=O.count,_=O.fixtures??[]}let U=G.name||X.name.replace(".ts",""),I=G.table||FZ(U)+"s";$.push({name:U,table:I,count:Math.max(Q,_.length),fixtures:_,attributes:G.attributes||{},model:G,filePath:W})}catch(H){M.error(`Failed to load model ${X.name}:`,H)}}return $}async function S4(Z,Y=!1,$=!1){let J=MZ(),X=await pY(Z,!1);if(X.length>0&&!$)return X;let W=await pY(J,!0),H=new Map;for(let G of W)H.set(G.name,G);for(let G of X){if(H.has(G.name)&&Y)M.info(` User model "${G.name}" overrides default`);H.set(G.name,G)}return Array.from(H.values())}function O8(Z,Y){let $=Z.toLowerCase();if($==="password"||$.endsWith("_password")||$.endsWith("password"))return!0;if(Y.hidden===!0&&$.includes("pass"))return!0;return!1}async function V8(Z,Y,$=!1){let J={};for(let[X,W]of Object.entries(Z)){let H=FZ(X),G;if(W.factory&&typeof W.factory==="function")try{G=W.factory(SZ)}catch(z){let Q=z instanceof Error?z.message:String(z);if($)M.warn(` Factory failed for ${Y}.${X}: ${Q}`);if(W.default!==void 0)G=W.default;else G=A8(X)}else if(W.default!==void 0)G=W.default;else continue;if(O8(X,W)&&typeof G==="string")try{G=await U8(G,{algorithm:"bcrypt"})}catch(z){let Q=z instanceof Error?z.message:String(z);if($)M.warn(` Failed to hash password for ${Y}.${X}: ${Q}`)}J[H]=G}return J}function A8(Z){let Y=Z.toLowerCase();if(Y.startsWith("is")||Y.startsWith("has")||Y.endsWith("able"))return!1;if(Y.includes("count")||Y.includes("amount")||Y.includes("quantity"))return 0;if(Y.includes("url")||Y.includes("link"))return"https://example.com";if(Y.includes("email"))return SZ.internet.email();if(Y.includes("name"))return SZ.person.fullName();return null}function B8(Z){let Y={};for(let[$,J]of Object.entries(Z))Y[FZ($)]=J;return Y}async function L8(Z,Y=!1){let $=[];for(let J=0;J<Z.count;J++){let X=await V8(Z.attributes,Z.name,Y&&J===0),W=Z.fixtures[J];$.push(W?{...X,...B8(W)}:X)}return $}function M4(Z,Y){return DZ(Z,Y)}async function DZ(Z,Y){let $=Date.now();try{try{await V.selectFrom(Z.table).limit(0).execute()}catch(H){let G=H?.message||"";if(G.includes("does not exist")||G.includes("no such table")||G.includes("doesn't exist"))return M.info(` Skipping ${Z.name}: table "${Z.table}" does not exist`),{model:Z.name,table:Z.table,count:0,success:!0,duration:Date.now()-$};throw H}if(!Y.fresh){if(await V.selectFrom(Z.table).selectAll().limit(1).executeTakeFirst()){if(Y.verbose)M.info(` ${Z.name}: table already has rows \u2014 skipping (use --fresh to replace)`);return{model:Z.name,table:Z.table,count:0,success:!0,duration:Date.now()-$}}}let J=await L8(Z,Y.verbose);if(J.length===0)return{model:Z.name,table:Z.table,count:0,success:!0,duration:Date.now()-$};if(Y.fresh)try{if(await V.deleteFrom(Z.table).execute(),Y.verbose)M.info(` Truncated table: ${Z.table}`)}catch{}let X=100,W=0;for(let H=0;H<J.length;H+=X){let G=J.slice(H,H+X);await V.insertInto(Z.table).values(G).execute(),W+=G.length}if(Y.verbose)M.success(` Seeded ${Z.name}: ${W} records`);return{model:Z.name,table:Z.table,count:W,success:!0,duration:Date.now()-$}}catch(J){let X=J instanceof Error?J.message:String(J);if(Y.verbose)M.error(` Failed to seed ${Z.name}: ${X}`);return{model:Z.name,table:Z.table,count:0,success:!1,error:X,duration:Date.now()-$}}}function E8(Z){let Y={User:0,Team:1,Project:2};return Z.sort(($,J)=>{let X=Y[$.name]??10,W=Y[J.name]??10;return X-W})}async function I8(Z={}){let Y=Date.now();await _Z();let $=Z.modelsDir||CY.userModelsPath(),J=Z.verbose??!0;if(J)M.info("Seeding database using model factories..."),M.info(`User models directory: ${$}`),M.info(`Default models directory: ${MZ()}`);let X=await S4($,J,Z.includeDefaults??!1);if(X.length===0)return M.warn("No seedable models found in defaults or user directories"),{total:0,successful:0,failed:0,results:[],duration:Date.now()-Y};if(M.warn(`[seed] The \`useSeeder\` trait + auto-walker is deprecated (stacksjs/stacks#1919, #1929). Run \`./buddy seed:scaffold\` to generate a class seeder per \`useSeeder\` model AND strip the trait from the model in one pass. The walker + trait are scheduled for removal in the next major. Affected: ${X.map((Q)=>Q.name).join(", ")}`),Z.only&&Z.only.length>0)X=X.filter((Q)=>Z.only.includes(Q.name));if(Z.except&&Z.except.length>0)X=X.filter((Q)=>!Z.except.includes(Q.name));if(!Z.fresh&&!Z.allowProtected){let Q=[];if(X=X.filter((_)=>{if(_8(_.name))return Q.push(_),!1;return!0}),Q.length>0)M.info(`Skipped ${Q.length} protected auth model(s) to avoid invalidating live sessions: ${Q.map((_)=>_.name).join(", ")}`),M.info(" Re-run with --fresh (truncates tables first) or --allow-protected to include them.")}if(X=E8(X),J)M.info(`Found ${X.length} seedable model(s)`);let W=[];for(let Q of X){if(J)M.info(`Seeding ${Q.name} (${Q.count} records)...`);try{let _=await DZ(Q,Z);W.push(_)}catch(_){let U=_ instanceof Error?_.message:String(_);if(J)M.error(` Unexpected error seeding ${Q.name}: ${U}`);W.push({model:Q.name,table:Q.table,count:0,success:!1,error:U,duration:0})}}let H=W.filter((Q)=>Q.success).length,G=W.filter((Q)=>!Q.success).length,z=W.reduce((Q,_)=>Q+_.count,0);if(J)if(M.info(""),G===0)M.success("Database seeded successfully!"),M.info(` Total records: ${z}`),M.info(` Models seeded: ${H}`);else M.warn(`Seeding completed with ${G} failure(s)`),M.info(` Successful: ${H}`),M.info(` Failed: ${G}`);return{total:W.length,successful:H,failed:G,results:W,duration:Date.now()-Y}}async function T5(Z,Y={}){let $=CY.userModelsPath(),X=(await S4($,Y.verbose)).find((W)=>W.name===Z);if(!X)throw Error(`Model not found: ${Z}`);if(Y.count)X.count=Y.count;return DZ(X,{fresh:Y.fresh,verbose:Y.verbose??!0})}async function P5(Z={}){return I8({...Z,fresh:!0})}async function k5(){let Z=CY.userModelsPath(),Y=MZ(),$=await pY(Y,!0),J=await pY(Z,!1),X=[],W=new Set;for(let H of J)X.push({name:H.name,table:H.table,count:H.count,source:"user"}),W.add(H.name);for(let H of $)if(!W.has(H.name))X.push({name:H.name,table:H.table,count:H.count,source:"default"});return X}import{log as K8}from"@stacksjs/logging";function j8(Z){if(Z&&typeof Z==="object"){let Y=Z;if(Y._definition&&typeof Y._definition==="object"&&"name"in Y._definition)return Y._definition;if("name"in Y&&(("attributes"in Y)||("table"in Y)||("traits"in Y)))return Y}throw Error("factory.generate: expected a Stacks model (the default export of app/Models/*.ts, or a defineModel() return value). Got something without a `.name` field.")}function D4(Z){return Z.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Za-z])/g,"$1_$2").toLowerCase()}function F4(Z){let Y={};for(let[$,J]of Object.entries(Z))Y[D4($)]=J;return Y}function R8(Z,Y={}){let $=j8(Z),J=$.name,X=$.attributes??{},W=$.traits?.useSeeder,H=W&&typeof W==="object"?W:void 0,G=Y.count??H?.count??10,z=Y.with?F4(Y.with):void 0,Q=Y.rows??H?.fixtures??[],_=Math.max(G,Q.length),U=[];for(let O=0;O<_;O++){let L=Q[O];if(!z&&!L)continue;U[O]={...z??{},...L?F4(L):{}}}let I=$.table??`${D4(J)}s`;return{name:J,table:I,count:_,fixtures:U,attributes:X,model:$}}async function q4(Z,Y={}){let $=R8(Z,Y);try{return await M4({...$,filePath:""},{fresh:Y.fresh,verbose:Y.verbose??!1})}catch(J){let X=J instanceof Error?J.message:String(J);throw K8.error(`[factory] generate(${$.name}) failed: ${X}`),J}}var w8={generate:q4};import{log as qZ}from"@stacksjs/logging";import{path as cY}from"@stacksjs/path";import{fs as r}from"@stacksjs/storage";function S8(Z){let Y=Z,$=!1,J=!1;for(let X of["useSeeder","seedable"]){let H=new RegExp(`\\b${X}\\s*:`).exec(Y);if(!H)continue;let G=H.index,z=G+H[0].length;while(z<Y.length&&/\s/.test(Y[z]))z++;if(Y[z]==="{"){let I=0,O=null;for(;z<Y.length;z++){let L=Y[z];if(O){if(L==="\\"){z++;continue}if(L===O)O=null;continue}if(L==='"'||L==="'"||L==="`"){O=L;continue}if(L==="{")I++;else if(L==="}"){if(I--,I===0){z++;break}}}}else if(Y.startsWith("true",z)||Y.startsWith("false",z))z+=Y.startsWith("true",z)?4:5;else{J=!0;continue}let _=z;while(_<Y.length&&(Y[_]===" "||Y[_]==="\t"))_++;if(Y[_]===",")_++;while(_<Y.length&&(Y[_]===" "||Y[_]==="\t"))_++;if(Y[_]==="/"&&Y[_+1]==="/")while(_<Y.length&&Y[_]!==`
|
|
21
|
+
`)_++;let U=G;while(U>0&&(Y[U-1]===" "||Y[U-1]==="\t"))U--;if(U>0&&Y[U-1]===`
|
|
22
|
+
`&&Y[_]===`
|
|
23
|
+
`)_++;Y=Y.slice(0,U)+Y.slice(_),$=!0}return{source:Y,changed:$,skipped:J&&!$}}var x4=(Z,Y,$)=>`import { factory, Seeder } from '@stacksjs/database'
|
|
24
|
+
import ${Z} from '${Y}'
|
|
25
|
+
|
|
26
|
+
export default class ${Z}Seeder extends Seeder {
|
|
27
|
+
async run(): Promise<void> {
|
|
28
|
+
await factory.generate(${Z}, { count: ${$} })
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
`;function M8(Z,Y){let J=cY.relative(Z,Y).replace(/\\/g,"/").replace(/\.ts$/,"");return J.startsWith(".")?J:`./${J}`}async function F8(Z={}){let Y=Z.modelsDir??cY.userModelsPath(),$=Z.seedersDir??cY.projectPath("database/seeders"),J={generated:[],skipped:[],errors:[],strippedTrait:[],traitStripSkipped:[]};if(!r.existsSync(Y))return qZ.warn(`[seed:scaffold] No models directory at ${Y}`),J;if(!Z.dryRun&&!r.existsSync($))r.mkdirSync($,{recursive:!0});let X=r.readdirSync(Y,{withFileTypes:!0});for(let W of X){if(!W.isFile()||!W.name.endsWith(".ts"))continue;if(W.name.startsWith("_")||W.name.startsWith("index"))continue;let H=cY.join(Y,W.name),G;try{let O=await import(H);G=O.default||O}catch(O){J.errors.push({model:W.name,error:O.message});continue}if(!G||!G.name){J.errors.push({model:W.name,error:"missing default export with `name` field"});continue}let z=G.traits?.useSeeder??G.traits?.seedable;if(!z){J.skipped.push({model:G.name,file:"",reason:"no-useseeder"});continue}let Q=typeof z==="object"&&"count"in z?z.count:10,_=`${G.name}Seeder.ts`,U=cY.join($,_);if(r.existsSync(U)&&!Z.force)J.skipped.push({model:G.name,file:U,reason:"already-exists"});else{let O=M8($,H),L=x4(G.name,O,Q);if(Z.dryRun)qZ.info(`[seed:scaffold] would write ${U}`);else r.writeFileSync(U,L,"utf-8");J.generated.push({model:G.name,file:U})}try{let O=r.readFileSync(H,"utf-8"),{source:L,changed:A,skipped:E}=S8(O);if(A){if(Z.dryRun)qZ.info(`[seed:scaffold] would strip useSeeder trait from ${H}`);else r.writeFileSync(H,L,"utf-8");J.strippedTrait.push({model:G.name,file:H})}else if(E)J.traitStripSkipped.push({model:G.name,file:H})}catch(O){J.errors.push({model:G.name,error:`trait strip failed: ${O.message}`})}}return J}function D8(Z,Y,$){return x4(Z,Y,$)}F();import{log as p4}from"@stacksjs/logging";import{getTableName as q8}from"@stacksjs/orm";import{path as n}from"@stacksjs/path";import{fs as VY,globSync as C4}from"@stacksjs/storage";import{plural as x8,snakeCase as T8}from"@stacksjs/strings";function T4(Z){return Z.name==="string"}function P4(Z){return Z.name==="number"}function k4(Z){return Z.name==="enum"}function N4(Z){return Z.name==="boolean"}function y4(Z){return Z.name==="date"}function h4(Z){return Z.name==="unix"}function v4(Z){return Z.name==="float"}function f4(Z){return Z.name==="datetime"}function b4(Z){return Z.name==="timestamp"}async function AY(){let Z=await VY.promises.readdir(n.userMigrationsPath());if(Z.length){for(let Y of Z)if(Y.endsWith(".ts")){let $=n.userMigrationsPath(`${Y}`);if(VY.existsSync($))await Bun.$`rm ${$}`}}}async function BY(){let Z=n.frameworkPath("cache/models");if(!VY.existsSync(Z))return;let Y=await VY.promises.readdir(Z);if(Y.length){for(let $ of Y)if($.endsWith(".ts")){let J=n.frameworkPath(`cache/models/${$}`);if(VY.existsSync(J))await Bun.$`rm ${J}`}}}async function m(Z){let $=(await import(n.frameworkPath(`cache/models/${Z}`))).default,J={};if(typeof $.attributes==="object")J=$.attributes;else try{J=JSON.parse($.attributes||"{}")}catch{J={}}return J}async function n5(Z){if(typeof Z==="string")Z=(await import(Z)).default;return Z.table??T8(x8(Z?.name||""))}async function $Y(Z){return p4.debug(`hasTableBeenMigrated for table: ${Z}`),(await P8()).some(($)=>$.name.includes(Z))}async function q(Z){return p4.debug(`hasTableBeenMigrated for table: ${Z}`),C4([n.userMigrationsPath("*.ts")],{absolute:!0}).some(($)=>$.includes(`create-${Z}`))}async function P8(){try{return await V.selectFrom("migrations").select("name").execute()}catch(Z){if(Z?.message.includes("no such table: migrations"))return console.warn("Migrations table does not exist, returning empty list."),[];return[]}}function xZ(Z){if("getRules"in Z){let Y=Z.getRules().find(($)=>$.name==="max");return Y?.params?.length||Y?.params?.max||255}return 255}function k8(Z,Y="mysql"){if(Y==="sqlite")return"'text'";return`'varchar(${xZ(Z)})'`}function i5(Z,Y="mysql"){if(Y==="sqlite")return"'text'";let $=Z.name;if($==="unix")return"'bigint'";return $||"date"}function a5(Z,Y){return Z.min===Y.min&&Z.max===Y.max}async function LY(Z){return(await VY.promises.readdir(n.userMigrationsPath())).some(($)=>{let J=Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(-${J}-)`).test($)})}function EY(Z,Y){let $=Z.filter((X)=>!Y.includes(X)),J=Y.filter((X)=>!Z.includes(X));if($.length===0&&J.length===0)return null;return{added:J,removed:$}}function JY(Z){if(!Z)return[];let Y=Object.entries(Z);return Y.sort(([$,J],[X,W])=>{let H=J.order??Number.POSITIVE_INFINITY,G=W.order??Number.POSITIVE_INFINITY;return H-G}),Y}function IY(Z,Y){if(!Z||!Y)return!1;if(Z.length!==Y.length)return!1;for(let $=0;$<Z.length;$++)if(Z[$]!==Y[$])return!1;return!0}function KY(Z,Y){let $=[];for(let J in Z)if(Object.prototype.hasOwnProperty.call(Z,J)&&Object.prototype.hasOwnProperty.call(Y,J)){let X=xZ(Z[J].validation.rule),W=xZ(Y[J].validation.rule);if(X!==void 0&&W!==void 0){if(X!==W)$.push({key:J,max:W,min:W})}}return $}async function eY(){let Z=C4([n.userModelsPath("*.ts"),n.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Y=[];for(let $ of Z){let J=(await import($)).default,X=q8(J,$),W=zY(J,X);if(W)Y.push(W);Y.push(X)}return Y}function zY(Z,Y){let $=`${Y}_likes`,J=Z.traits;if(!J?.likeable)return;return typeof J.likeable==="object"?J.likeable.table||$:$}function jY(Z,Y){let $=Z.traits?.likeable;if($&&typeof $==="object"&&!Array.isArray($)&&$.foreignKey)return $.foreignKey;return`${Y.replace(/s$/,"")}_id`}function N8(Z,Y="mysql"){if(Y==="sqlite")return"'integer'";if("getRules"in Z){let $=Z.getRules().find((H)=>H.name==="min"),J=Z.getRules().find((H)=>H.name==="max"),X=$?.params?.min??-2147483648,W=J?.params?.max??2147483647;return X>=-2147483648&&W<=2147483647?"'integer'":"'bigint'"}return"'integer'"}function y8(Z,Y="mysql"){let $=Z.getAllowedValues();if(!$)throw Error("Enum rule found but no allowedValues defined");let J=$.map((X)=>`'${X}'`).join(", ");if(Y==="postgres")return"'varchar(255)'";if(Y==="sqlite")return"'text'";return`sql\`enum(${J})\``}function XY(Z,Y="mysql"){if(k4(Z))return y8(Z,Y);if(T4(Z))return k8(Z,Y);if(P4(Z))return N8(Z,Y);if(N4(Z))return"'boolean'";if(y4(Z))return"'date'";if(f4(Z))return Y==="postgres"?"'timestamp'":"'datetime'";if(h4(Z))return"'bigint'";if(b4(Z))return"'timestamp'";if(v4(Z))return"'float4'";if(["array","object"].includes(Z.name))return Y==="sqlite"?"'text'":"'json'";if(Y==="sqlite")return"'text'";return Y==="mysql"?"'varchar(255)'":"'text'"}function o5(Z){return Z.includes(".required()")}F();import{log as s}from"@stacksjs/logging";import{log as c4}from"@stacksjs/logging";import{path as g4}from"@stacksjs/path";function u4(Z){return`\x1B[3m${Z}\x1B[23m`}async function YZ(){if(await q("password_resets"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
32
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
33
|
+
|
|
34
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
35
|
+
`,Y+=` await db.schema
|
|
36
|
+
`,Y+=` .createTable('password_resets')
|
|
37
|
+
`,Y+=` .addColumn('email', 'varchar(255)', col => col.notNull())
|
|
38
|
+
`,Y+=` .addColumn('token', 'varchar(255)', col => col.notNull())
|
|
39
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
40
|
+
`,Y+=` .execute()
|
|
41
|
+
|
|
42
|
+
`,Y+=` await db.schema
|
|
43
|
+
`,Y+=` .createIndex('password_resets_email_index')
|
|
44
|
+
`,Y+=` .on('password_resets')
|
|
45
|
+
`,Y+=` .column('email')
|
|
46
|
+
`,Y+=` .execute()
|
|
47
|
+
|
|
48
|
+
`,Y+=` await db.schema
|
|
49
|
+
`,Y+=` .createIndex('password_resets_token_index')
|
|
50
|
+
`,Y+=` .on('password_resets')
|
|
51
|
+
`,Y+=` .column('token')
|
|
52
|
+
`,Y+=` .execute()
|
|
53
|
+
`,Y+=`}
|
|
54
|
+
`;let J=`${new Date().getTime().toString()}-create-password-resets-table.ts`,X=g4.userMigrationsPath(J);await Bun.write(X,Y),c4.success(`Created migration: ${u4(J)}`)}async function $1(){if(await q("password_resets"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
55
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
56
|
+
|
|
57
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
58
|
+
`,Y+=` await db.schema
|
|
59
|
+
`,Y+=` .createTable('password_resets')
|
|
60
|
+
`,Y+=` .addColumn('email', 'varchar(255)', col => col.notNull())
|
|
61
|
+
`,Y+=` .addColumn('token', 'varchar(255)', col => col.notNull())
|
|
62
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
63
|
+
`,Y+=` .execute()
|
|
64
|
+
|
|
65
|
+
`,Y+=` await db.schema
|
|
66
|
+
`,Y+=` .createIndex('password_resets_email_index')
|
|
67
|
+
`,Y+=` .on('password_resets')
|
|
68
|
+
`,Y+=` .column('email')
|
|
69
|
+
`,Y+=` .execute()
|
|
70
|
+
|
|
71
|
+
`,Y+=` await db.schema
|
|
72
|
+
`,Y+=` .createIndex('password_resets_token_index')
|
|
73
|
+
`,Y+=` .on('password_resets')
|
|
74
|
+
`,Y+=` .column('token')
|
|
75
|
+
`,Y+=` .execute()
|
|
76
|
+
`,Y+=`}
|
|
77
|
+
`;let J=`${new Date().getTime().toString()}-create-password-resets-table.ts`,X=g4.userMigrationsPath(J);await Bun.write(X,Y),c4.success(`Created migration: ${u4(J)}`)}import{ok as h8}from"@stacksjs/error-handling";import{getModelName as v8,getPivotTables as X6,getTableName as kZ}from"@stacksjs/orm";import{path as i}from"@stacksjs/path";import{fs as f8,globSync as b8}from"@stacksjs/storage";import{snakeCase as $Z}from"@stacksjs/strings";F();import{log as P}from"@stacksjs/logging";import{path as N}from"@stacksjs/path";function k(Z){return`\x1B[3m${Z}\x1B[23m`}function z1(){return["tags","taggables","categorizables","comments","commentables","commentable_upvotes","passkeys","password_resets","query_logs","migrations"]}async function d4(){if(await q("users"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
192
78
|
import { sql } from '@stacksjs/database'
|
|
193
79
|
|
|
194
|
-
`;
|
|
195
|
-
`,
|
|
196
|
-
`,
|
|
197
|
-
`,
|
|
198
|
-
`,
|
|
199
|
-
`,
|
|
200
|
-
`,
|
|
201
|
-
`,
|
|
202
|
-
`,
|
|
203
|
-
`,
|
|
204
|
-
`,
|
|
205
|
-
`,
|
|
206
|
-
`,
|
|
207
|
-
`,
|
|
208
|
-
`,
|
|
209
|
-
`,
|
|
210
|
-
`;let
|
|
80
|
+
`;Y+=`export async function up(db: Database<any>) {
|
|
81
|
+
`,Y+=` await db.schema
|
|
82
|
+
`,Y+=` .createTable('passkeys')
|
|
83
|
+
`,Y+=` .addColumn('id', 'text')
|
|
84
|
+
`,Y+=` .addColumn('cred_public_key', 'text')
|
|
85
|
+
`,Y+=` .addColumn('webauthn_user_id', 'varchar(255)')
|
|
86
|
+
`,Y+=` .addColumn('counter', 'integer', col => col.defaultTo(0))
|
|
87
|
+
`,Y+=` .addColumn('device_type', 'varchar(255)')
|
|
88
|
+
`,Y+=` .addColumn('credential_type', 'varchar(255)')
|
|
89
|
+
`,Y+=` .addColumn('backup_eligible', 'boolean', col => col.defaultTo(false))
|
|
90
|
+
`,Y+=` .addColumn('backup_status', 'boolean', col => col.defaultTo(false))
|
|
91
|
+
`,Y+=` .addColumn('transports', 'varchar(255)')
|
|
92
|
+
`,Y+=` .addColumn('last_used_at', 'text')
|
|
93
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
94
|
+
`,Y+=` .execute()
|
|
95
|
+
`,Y+=` }
|
|
96
|
+
`;let J=`${new Date().getTime().toString()}-create-passkeys-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function m4(){if(await q("users"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
211
97
|
import { sql } from '@stacksjs/database'
|
|
212
98
|
|
|
213
|
-
`;
|
|
214
|
-
`,
|
|
215
|
-
`,
|
|
216
|
-
`,
|
|
217
|
-
`,
|
|
218
|
-
`,
|
|
219
|
-
`,
|
|
220
|
-
`,
|
|
221
|
-
`,
|
|
222
|
-
`,
|
|
223
|
-
`,
|
|
224
|
-
`,
|
|
225
|
-
`,
|
|
226
|
-
`,
|
|
227
|
-
`,
|
|
228
|
-
|
|
229
|
-
`,
|
|
230
|
-
`;let
|
|
231
|
-
`;
|
|
232
|
-
|
|
233
|
-
`,
|
|
234
|
-
`,
|
|
235
|
-
`,
|
|
236
|
-
`,
|
|
237
|
-
`,
|
|
238
|
-
`,
|
|
239
|
-
`,
|
|
240
|
-
`,
|
|
241
|
-
`,
|
|
242
|
-
`,
|
|
243
|
-
`,
|
|
244
|
-
`,
|
|
245
|
-
`,
|
|
246
|
-
|
|
247
|
-
`,
|
|
248
|
-
`,
|
|
249
|
-
`,
|
|
250
|
-
`,
|
|
251
|
-
`,
|
|
252
|
-
|
|
253
|
-
`,
|
|
254
|
-
`,
|
|
255
|
-
`,
|
|
256
|
-
`,
|
|
257
|
-
`,
|
|
258
|
-
|
|
259
|
-
`,
|
|
260
|
-
`,
|
|
261
|
-
`,
|
|
262
|
-
`,
|
|
263
|
-
`,
|
|
264
|
-
|
|
265
|
-
`,
|
|
266
|
-
`;let
|
|
267
|
-
`;
|
|
268
|
-
|
|
269
|
-
`,
|
|
270
|
-
`,
|
|
271
|
-
`,
|
|
272
|
-
`,
|
|
273
|
-
`,
|
|
274
|
-
`,
|
|
275
|
-
`,
|
|
276
|
-
`,
|
|
277
|
-
`,
|
|
278
|
-
`,
|
|
279
|
-
`,
|
|
280
|
-
`,
|
|
281
|
-
`,
|
|
282
|
-
|
|
283
|
-
`,
|
|
284
|
-
`,
|
|
285
|
-
`,
|
|
286
|
-
`,
|
|
287
|
-
`,
|
|
288
|
-
|
|
289
|
-
`,
|
|
290
|
-
`,
|
|
291
|
-
`,
|
|
292
|
-
`,
|
|
293
|
-
`,
|
|
294
|
-
|
|
295
|
-
`,
|
|
296
|
-
`,
|
|
297
|
-
`,
|
|
298
|
-
`,
|
|
299
|
-
`,
|
|
300
|
-
|
|
301
|
-
`,
|
|
302
|
-
`;let
|
|
303
|
-
`;
|
|
304
|
-
|
|
305
|
-
`,
|
|
306
|
-
`,
|
|
307
|
-
`,
|
|
308
|
-
`,
|
|
309
|
-
`,
|
|
310
|
-
`,
|
|
311
|
-
`,
|
|
312
|
-
`,
|
|
313
|
-
`,
|
|
314
|
-
`,
|
|
315
|
-
`,
|
|
316
|
-
`,
|
|
317
|
-
|
|
318
|
-
`,
|
|
319
|
-
`,
|
|
320
|
-
`,
|
|
321
|
-
`,
|
|
322
|
-
`,
|
|
323
|
-
|
|
324
|
-
`,
|
|
325
|
-
`,
|
|
326
|
-
`,
|
|
327
|
-
`,
|
|
328
|
-
`,
|
|
329
|
-
|
|
330
|
-
`,
|
|
331
|
-
`,
|
|
332
|
-
`,
|
|
333
|
-
`,
|
|
334
|
-
`,
|
|
335
|
-
|
|
336
|
-
`,
|
|
337
|
-
`,
|
|
338
|
-
`,
|
|
339
|
-
`,
|
|
340
|
-
`,
|
|
341
|
-
`,
|
|
342
|
-
`;let
|
|
343
|
-
`;
|
|
344
|
-
|
|
345
|
-
`,
|
|
346
|
-
`,
|
|
347
|
-
`,
|
|
348
|
-
`,
|
|
349
|
-
`,
|
|
350
|
-
`,
|
|
351
|
-
`,
|
|
352
|
-
`,
|
|
353
|
-
`,
|
|
354
|
-
`,
|
|
355
|
-
`,
|
|
356
|
-
`,
|
|
357
|
-
`,
|
|
358
|
-
|
|
359
|
-
`,
|
|
360
|
-
`,
|
|
361
|
-
`,
|
|
362
|
-
`,
|
|
363
|
-
`,
|
|
364
|
-
|
|
365
|
-
`,
|
|
366
|
-
`,
|
|
367
|
-
`,
|
|
368
|
-
`,
|
|
369
|
-
`,
|
|
370
|
-
|
|
371
|
-
`,
|
|
372
|
-
`,
|
|
373
|
-
`,
|
|
374
|
-
`,
|
|
375
|
-
`,
|
|
376
|
-
|
|
377
|
-
`,
|
|
378
|
-
`,
|
|
379
|
-
`,
|
|
380
|
-
`,
|
|
381
|
-
`,
|
|
382
|
-
`,
|
|
383
|
-
`;let
|
|
384
|
-
`;if(
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
`;if(
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
`;let
|
|
415
|
-
`;
|
|
416
|
-
|
|
417
|
-
`,
|
|
418
|
-
`,
|
|
419
|
-
`,
|
|
420
|
-
`,
|
|
421
|
-
`,
|
|
422
|
-
`,
|
|
423
|
-
`,
|
|
424
|
-
`,
|
|
425
|
-
`,
|
|
426
|
-
`,
|
|
427
|
-
`,
|
|
428
|
-
`,
|
|
429
|
-
`,
|
|
430
|
-
`,
|
|
431
|
-
`,
|
|
432
|
-
`,
|
|
433
|
-
`,
|
|
434
|
-
`,
|
|
435
|
-
`,
|
|
436
|
-
`,
|
|
437
|
-
`,
|
|
438
|
-
|
|
439
|
-
`,
|
|
440
|
-
`,
|
|
441
|
-
`,
|
|
442
|
-
`;let
|
|
99
|
+
`;Y+=`export async function up(db: Database<any>) {
|
|
100
|
+
`,Y+=` await db.schema
|
|
101
|
+
`,Y+=` .createTable('passkeys')
|
|
102
|
+
`,Y+=` .addColumn('id', 'uuid', col => col.primaryKey())
|
|
103
|
+
`,Y+=` .addColumn('cred_public_key', 'text')
|
|
104
|
+
`,Y+=` .addColumn('webauthn_user_id', 'varchar(255)')
|
|
105
|
+
`,Y+=` .addColumn('counter', 'integer', col => col.defaultTo(0))
|
|
106
|
+
`,Y+=` .addColumn('device_type', 'varchar(255)')
|
|
107
|
+
`,Y+=` .addColumn('credential_type', 'varchar(255)')
|
|
108
|
+
`,Y+=` .addColumn('backup_eligible', 'boolean', col => col.defaultTo(false))
|
|
109
|
+
`,Y+=` .addColumn('backup_status', 'boolean', col => col.defaultTo(false))
|
|
110
|
+
`,Y+=` .addColumn('transports', 'varchar(255)')
|
|
111
|
+
`,Y+=` .addColumn('last_used_at', 'timestamp')
|
|
112
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
113
|
+
`,Y+=` .execute()
|
|
114
|
+
|
|
115
|
+
`,Y+=`}
|
|
116
|
+
`;let J=`${new Date().getTime().toString()}-create-passkeys-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function s4(){if(await q("tags"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
117
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
118
|
+
|
|
119
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
120
|
+
`,Y+=` await db.schema
|
|
121
|
+
`,Y+=` .createTable('tags')
|
|
122
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
123
|
+
`,Y+=` .addColumn('name', 'varchar(255)', col => col.notNull())
|
|
124
|
+
`,Y+=` .addColumn('slug', 'varchar(255)', col => col.notNull().unique())
|
|
125
|
+
`,Y+=` .addColumn('type', 'varchar(255)')
|
|
126
|
+
`,Y+=` .addColumn('color', 'varchar(255)')
|
|
127
|
+
`,Y+=` .addColumn('description', 'text')
|
|
128
|
+
`,Y+=` .addColumn('is_active', 'boolean', col => col.defaultTo(true))
|
|
129
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
130
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
131
|
+
`,Y+=` .execute()
|
|
132
|
+
|
|
133
|
+
`,Y+=` await db.schema
|
|
134
|
+
`,Y+=` .createIndex('idx_tags_slug')
|
|
135
|
+
`,Y+=` .on('tags')
|
|
136
|
+
`,Y+=` .column('slug')
|
|
137
|
+
`,Y+=` .execute()
|
|
138
|
+
|
|
139
|
+
`,Y+=` await db.schema
|
|
140
|
+
`,Y+=` .createIndex('idx_tags_type')
|
|
141
|
+
`,Y+=` .on('tags')
|
|
142
|
+
`,Y+=` .column('type')
|
|
143
|
+
`,Y+=` .execute()
|
|
144
|
+
|
|
145
|
+
`,Y+=` await db.schema
|
|
146
|
+
`,Y+=` .createIndex('idx_tags_name')
|
|
147
|
+
`,Y+=` .on('tags')
|
|
148
|
+
`,Y+=` .column('name')
|
|
149
|
+
`,Y+=` .execute()
|
|
150
|
+
|
|
151
|
+
`,Y+=`}
|
|
152
|
+
`;let J=`${new Date().getTime().toString()}-create-tags-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`),await new Promise((W)=>setTimeout(W,2)),await TZ()}async function l4(){if(await q("tags"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
153
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
154
|
+
|
|
155
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
156
|
+
`,Y+=` await db.schema
|
|
157
|
+
`,Y+=` .createTable('tags')
|
|
158
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
159
|
+
`,Y+=` .addColumn('name', 'varchar(255)', col => col.notNull())
|
|
160
|
+
`,Y+=` .addColumn('slug', 'varchar(255)', col => col.notNull().unique())
|
|
161
|
+
`,Y+=` .addColumn('type', 'varchar(255)')
|
|
162
|
+
`,Y+=` .addColumn('color', 'varchar(255)')
|
|
163
|
+
`,Y+=` .addColumn('description', 'text')
|
|
164
|
+
`,Y+=` .addColumn('is_active', 'boolean', col => col.defaultTo(true))
|
|
165
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
166
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
167
|
+
`,Y+=` .execute()
|
|
168
|
+
|
|
169
|
+
`,Y+=` await db.schema
|
|
170
|
+
`,Y+=` .createIndex('idx_tags_slug')
|
|
171
|
+
`,Y+=` .on('tags')
|
|
172
|
+
`,Y+=` .column('slug')
|
|
173
|
+
`,Y+=` .execute()
|
|
174
|
+
|
|
175
|
+
`,Y+=` await db.schema
|
|
176
|
+
`,Y+=` .createIndex('idx_tags_type')
|
|
177
|
+
`,Y+=` .on('tags')
|
|
178
|
+
`,Y+=` .column('type')
|
|
179
|
+
`,Y+=` .execute()
|
|
180
|
+
|
|
181
|
+
`,Y+=` await db.schema
|
|
182
|
+
`,Y+=` .createIndex('idx_tags_name')
|
|
183
|
+
`,Y+=` .on('tags')
|
|
184
|
+
`,Y+=` .column('name')
|
|
185
|
+
`,Y+=` .execute()
|
|
186
|
+
|
|
187
|
+
`,Y+=`}
|
|
188
|
+
`;let J=`${new Date().getTime().toString()}-create-tags-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`),await new Promise((W)=>setTimeout(W,2)),await PZ()}async function r4(){if(await q("categorizable"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
189
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
190
|
+
|
|
191
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
192
|
+
`,Y+=` await db.schema
|
|
193
|
+
`,Y+=` .createTable('categorizables')
|
|
194
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
195
|
+
`,Y+=` .addColumn('name', 'varchar(255)', col => col.notNull())
|
|
196
|
+
`,Y+=` .addColumn('slug', 'varchar(255)', col => col.notNull().unique())
|
|
197
|
+
`,Y+=` .addColumn('description', 'text')
|
|
198
|
+
`,Y+=` .addColumn('is_active', 'boolean', col => col.defaultTo(true))
|
|
199
|
+
`,Y+=` .addColumn('categorizable_type', 'varchar(255)', col => col.notNull())
|
|
200
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
201
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
202
|
+
`,Y+=` .execute()
|
|
203
|
+
|
|
204
|
+
`,Y+=` await db.schema
|
|
205
|
+
`,Y+=` .createIndex('categorizables_id_index')
|
|
206
|
+
`,Y+=` .on('categorizables')
|
|
207
|
+
`,Y+=` .column('id')
|
|
208
|
+
`,Y+=` .execute()
|
|
209
|
+
|
|
210
|
+
`,Y+=` await db.schema
|
|
211
|
+
`,Y+=` .createIndex('categorizables_slug_index')
|
|
212
|
+
`,Y+=` .on('categorizables')
|
|
213
|
+
`,Y+=` .column('slug')
|
|
214
|
+
`,Y+=` .execute()
|
|
215
|
+
|
|
216
|
+
`,Y+=` await db.schema
|
|
217
|
+
`,Y+=` .createIndex('categorizables_polymorphic_index')
|
|
218
|
+
`,Y+=` .on('categorizables')
|
|
219
|
+
`,Y+=` .columns(['categorizable_type'])
|
|
220
|
+
`,Y+=` .execute()
|
|
221
|
+
|
|
222
|
+
`,Y+=` await db.schema
|
|
223
|
+
`,Y+=` .createIndex('categorizables_is_active_index')
|
|
224
|
+
`,Y+=` .on('categorizables')
|
|
225
|
+
`,Y+=` .column('is_active')
|
|
226
|
+
`,Y+=` .execute()
|
|
227
|
+
`,Y+=`}
|
|
228
|
+
`;let J=`${new Date().getTime().toString()}-create-categorizables-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function n4(){if(await q("categorizable"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
229
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
230
|
+
|
|
231
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
232
|
+
`,Y+=` await db.schema
|
|
233
|
+
`,Y+=` .createTable('categorizables')
|
|
234
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
235
|
+
`,Y+=` .addColumn('name', 'varchar(255)', col => col.notNull())
|
|
236
|
+
`,Y+=` .addColumn('slug', 'varchar(255)', col => col.notNull().unique())
|
|
237
|
+
`,Y+=` .addColumn('description', 'text')
|
|
238
|
+
`,Y+=` .addColumn('order', 'integer', col => col.defaultTo(0))
|
|
239
|
+
`,Y+=` .addColumn('is_active', 'boolean', col => col.defaultTo(true))
|
|
240
|
+
`,Y+=` .addColumn('categorizable_type', 'varchar(255)', col => col.notNull())
|
|
241
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
242
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
243
|
+
`,Y+=` .execute()
|
|
244
|
+
|
|
245
|
+
`,Y+=` await db.schema
|
|
246
|
+
`,Y+=` .createIndex('idx_categorizables_slug')
|
|
247
|
+
`,Y+=` .on('categorizables')
|
|
248
|
+
`,Y+=` .column('slug')
|
|
249
|
+
`,Y+=` .execute()
|
|
250
|
+
|
|
251
|
+
`,Y+=` await db.schema
|
|
252
|
+
`,Y+=` .createIndex('idx_categorizables_polymorphic')
|
|
253
|
+
`,Y+=` .on('categorizables')
|
|
254
|
+
`,Y+=` .columns(['categorizable_type'])
|
|
255
|
+
`,Y+=` .execute()
|
|
256
|
+
|
|
257
|
+
`,Y+=` await db.schema
|
|
258
|
+
`,Y+=` .createIndex('idx_categorizables_order')
|
|
259
|
+
`,Y+=` .on('categorizables')
|
|
260
|
+
`,Y+=` .column('order')
|
|
261
|
+
`,Y+=` .execute()
|
|
262
|
+
|
|
263
|
+
`,Y+=` await db.schema
|
|
264
|
+
`,Y+=` .createIndex('idx_categorizables_is_active')
|
|
265
|
+
`,Y+=` .on('categorizables')
|
|
266
|
+
`,Y+=` .column('is_active')
|
|
267
|
+
`,Y+=` .execute()
|
|
268
|
+
`,Y+=`}
|
|
269
|
+
`;let J=`${new Date().getTime().toString()}-create-categorizables-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function i4(Z={}){if(await q("comments"))return;let $=`import type { Database } from '@stacksjs/database'
|
|
270
|
+
`;if($+=`import { sql } from '@stacksjs/database'
|
|
271
|
+
|
|
272
|
+
`,$+=`export async function up(db: Database<any>) {
|
|
273
|
+
`,$+=` await db.schema
|
|
274
|
+
`,$+=` .createTable('comments')
|
|
275
|
+
`,$+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
276
|
+
`,$+=` .addColumn('title', 'varchar(255)', col => col.notNull())
|
|
277
|
+
`,$+=` .addColumn('body', 'text', col => col.notNull())
|
|
278
|
+
`,$+=` .addColumn('content', 'text')
|
|
279
|
+
`,$+=` .addColumn('status', 'varchar(50)', col => col.notNull().defaultTo('${Z.requiresApproval?"pending":"approved"}'))
|
|
280
|
+
`,$+=` .addColumn('author_name', 'varchar(100)')
|
|
281
|
+
`,$+=` .addColumn('author_email', 'varchar(255)')
|
|
282
|
+
`,$+=` .addColumn('post_title', 'varchar(255)')
|
|
283
|
+
`,$+=` .addColumn('commentables_id', 'integer', col => col.notNull())
|
|
284
|
+
`,$+=` .addColumn('commentables_type', 'varchar(255)', col => col.notNull())
|
|
285
|
+
`,$+=` .addColumn('ip_address', 'varchar(45)')
|
|
286
|
+
`,$+=` .addColumn('user_agent', 'varchar(500)')
|
|
287
|
+
`,$+=` .addColumn('is_approved', 'integer', col => col.defaultTo(0))
|
|
288
|
+
`,$+=` .addColumn('approved_at', 'integer')
|
|
289
|
+
`,$+=` .addColumn('rejected_at', 'integer')
|
|
290
|
+
`,Z.reportable)$+=` .addColumn('reports_count', 'integer', col => col.defaultTo(0))
|
|
291
|
+
`,$+=` .addColumn('reported_at', 'integer')
|
|
292
|
+
`;if(Z.requiresAuth)$+=` .addColumn('user_id', 'integer', col => col.notNull())
|
|
293
|
+
`;$+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
294
|
+
`,$+=` .addColumn('updated_at', 'timestamp')
|
|
295
|
+
`,$+=` .execute()
|
|
296
|
+
|
|
297
|
+
`,$+=` await db.schema.createIndex('idx_comments_status').on('comments').column('status').execute()
|
|
298
|
+
`,$+=` await db.schema.createIndex('idx_comments_created_at').on('comments').column('created_at').execute()
|
|
299
|
+
`,$+=`}
|
|
300
|
+
`;let X=`${new Date().getTime().toString()}-create-comments-table.ts`,W=N.userMigrationsPath(X);await Bun.write(W,$),P.success(`Created migration: ${k(X)}`)}async function a4(){if(await q("comments"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
301
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
302
|
+
|
|
303
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
304
|
+
`,Y+=` await db.schema
|
|
305
|
+
`,Y+=` .createTable('comments')
|
|
306
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
307
|
+
`,Y+=` .addColumn('title', 'varchar(255)', col => col.notNull())
|
|
308
|
+
`,Y+=` .addColumn('body', 'text', col => col.notNull())
|
|
309
|
+
`,Y+=` .addColumn('content', 'text')
|
|
310
|
+
`,Y+=` .addColumn('commentables_id', 'integer', col => col.notNull())
|
|
311
|
+
`,Y+=` .addColumn('commentables_type', 'varchar(255)', col => col.notNull())
|
|
312
|
+
`,Y+=` .addColumn('status', 'varchar(50)', col => col.notNull().defaultTo('pending'))
|
|
313
|
+
`,Y+=` .addColumn('author_name', 'varchar(100)')
|
|
314
|
+
`,Y+=` .addColumn('author_email', 'varchar(255)')
|
|
315
|
+
`,Y+=` .addColumn('post_title', 'varchar(255)')
|
|
316
|
+
`,Y+=` .addColumn('ip_address', 'varchar(45)')
|
|
317
|
+
`,Y+=` .addColumn('user_agent', 'varchar(500)')
|
|
318
|
+
`,Y+=` .addColumn('is_approved', 'integer', col => col.defaultTo(0))
|
|
319
|
+
`,Y+=` .addColumn('approved_at', 'integer')
|
|
320
|
+
`,Y+=` .addColumn('rejected_at', 'integer')
|
|
321
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
322
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
323
|
+
`,Y+=` .execute()
|
|
324
|
+
|
|
325
|
+
`,Y+=` await db.schema.createIndex('idx_comments_status').on('comments').column('status').execute()
|
|
326
|
+
`,Y+=` await db.schema.createIndex('idx_comments_created_at').on('comments').column('created_at').execute()
|
|
327
|
+
`,Y+=`}
|
|
328
|
+
`;let J=`${new Date().getTime().toString()}-create-comments-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function ZZ(){await V.unsafe("DROP TABLE IF EXISTS passkeys").execute(),await V.unsafe("DROP TABLE IF EXISTS password_resets").execute(),await V.unsafe("DROP TABLE IF EXISTS query_logs").execute(),await V.unsafe("DROP TABLE IF EXISTS categorizables").execute(),await V.unsafe("DROP TABLE IF EXISTS commentable_upvotes").execute(),await V.unsafe("DROP TABLE IF EXISTS tags").execute(),await V.unsafe("DROP TABLE IF EXISTS taggables").execute(),await V.unsafe("DROP TABLE IF EXISTS categorizable_models").execute(),await V.unsafe("DROP TABLE IF EXISTS commentables").execute(),await V.unsafe("DROP TABLE IF EXISTS comments").execute(),await V.unsafe("DROP TABLE IF EXISTS categories_models").execute(),await V.unsafe("DROP TABLE IF EXISTS activities").execute()}async function U1(){await V.unsafe("DELETE FROM migrations").execute(),await V.unsafe("DELETE FROM migration_locks").execute()}async function o4(){await V.unsafe("DROP TABLE IF EXISTS migrations").execute(),await V.unsafe("DROP TABLE IF EXISTS migration_locks").execute()}async function t4(){if(await q("commentable_upvotes"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
443
329
|
import { sql } from '@stacksjs/database'
|
|
444
330
|
|
|
445
|
-
`;
|
|
446
|
-
`,
|
|
447
|
-
`,
|
|
448
|
-
`,
|
|
449
|
-
`,
|
|
450
|
-
`,
|
|
451
|
-
`,
|
|
452
|
-
`,
|
|
453
|
-
|
|
454
|
-
`,
|
|
455
|
-
`,
|
|
456
|
-
`;let
|
|
331
|
+
`;Y+=`export async function up(db: Database<any>) {
|
|
332
|
+
`,Y+=` await db.schema
|
|
333
|
+
`,Y+=` .createTable('commentable_upvotes')
|
|
334
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
335
|
+
`,Y+=` .addColumn('upvoteable_id', 'integer', col => col.notNull())
|
|
336
|
+
`,Y+=` .addColumn('upvoteable_type', 'varchar(255)', col => col.notNull())
|
|
337
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
338
|
+
`,Y+=` .execute()
|
|
339
|
+
|
|
340
|
+
`,Y+=` await db.schema.createIndex('idx_commentable_upvotes_upvoteable').on('commentable_upvotes').columns(['upvoteable_id', 'upvoteable_type']).execute()
|
|
341
|
+
`,Y+=`}
|
|
342
|
+
`;let J=`${new Date().getTime().toString()}-create-commentable_upvotes-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function e4(){if(await q("commentable_upvotes"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
457
343
|
import { sql } from '@stacksjs/database'
|
|
458
344
|
|
|
459
|
-
`;
|
|
460
|
-
`,
|
|
461
|
-
`,
|
|
462
|
-
`,
|
|
463
|
-
`,
|
|
464
|
-
`,
|
|
465
|
-
`,
|
|
466
|
-
`,
|
|
467
|
-
|
|
468
|
-
`,
|
|
469
|
-
`,
|
|
470
|
-
`;let
|
|
471
|
-
`;
|
|
472
|
-
|
|
473
|
-
`,
|
|
474
|
-
`,
|
|
475
|
-
`,
|
|
476
|
-
`,
|
|
477
|
-
`,
|
|
478
|
-
`,
|
|
479
|
-
`,
|
|
480
|
-
`,
|
|
481
|
-
`,
|
|
482
|
-
`,
|
|
483
|
-
|
|
484
|
-
`,
|
|
485
|
-
`,
|
|
486
|
-
`,
|
|
487
|
-
`,
|
|
488
|
-
`,
|
|
489
|
-
|
|
490
|
-
`,
|
|
491
|
-
`,
|
|
492
|
-
`,
|
|
493
|
-
`,
|
|
494
|
-
`,
|
|
495
|
-
|
|
496
|
-
`,
|
|
497
|
-
`,
|
|
498
|
-
`,
|
|
499
|
-
`,
|
|
500
|
-
`,
|
|
501
|
-
`,
|
|
502
|
-
|
|
503
|
-
`,
|
|
504
|
-
`;let
|
|
505
|
-
`;
|
|
506
|
-
|
|
507
|
-
`,
|
|
508
|
-
`,
|
|
509
|
-
`,
|
|
510
|
-
`,
|
|
511
|
-
`,
|
|
512
|
-
`,
|
|
513
|
-
`,
|
|
514
|
-
`,
|
|
515
|
-
`,
|
|
516
|
-
`,
|
|
517
|
-
|
|
518
|
-
`,
|
|
519
|
-
`,
|
|
520
|
-
`,
|
|
521
|
-
`,
|
|
522
|
-
|
|
523
|
-
`,
|
|
524
|
-
`,
|
|
525
|
-
`,
|
|
526
|
-
`,
|
|
527
|
-
`,
|
|
528
|
-
|
|
529
|
-
`,
|
|
530
|
-
`,
|
|
531
|
-
`,
|
|
532
|
-
`,
|
|
533
|
-
`,
|
|
534
|
-
|
|
535
|
-
`,
|
|
536
|
-
`,
|
|
537
|
-
`,
|
|
538
|
-
`,
|
|
539
|
-
`,
|
|
540
|
-
`,
|
|
541
|
-
|
|
542
|
-
`,
|
|
543
|
-
`;let
|
|
544
|
-
`;
|
|
545
|
-
|
|
546
|
-
`,
|
|
547
|
-
`,
|
|
548
|
-
`,
|
|
549
|
-
`,
|
|
550
|
-
`,
|
|
551
|
-
`,
|
|
552
|
-
`,
|
|
553
|
-
`,
|
|
554
|
-
`,
|
|
555
|
-
`,
|
|
556
|
-
|
|
557
|
-
`,
|
|
558
|
-
`,
|
|
559
|
-
`,
|
|
560
|
-
`,
|
|
561
|
-
`,
|
|
562
|
-
|
|
563
|
-
`,
|
|
564
|
-
`,
|
|
565
|
-
`,
|
|
566
|
-
`,
|
|
567
|
-
`,
|
|
568
|
-
|
|
569
|
-
`,
|
|
570
|
-
`,
|
|
571
|
-
`,
|
|
572
|
-
`,
|
|
573
|
-
`,
|
|
574
|
-
`,
|
|
575
|
-
|
|
576
|
-
`,
|
|
577
|
-
`;let
|
|
578
|
-
`;
|
|
579
|
-
|
|
580
|
-
`,
|
|
581
|
-
`,
|
|
582
|
-
`,
|
|
583
|
-
`,
|
|
584
|
-
`,
|
|
585
|
-
`,
|
|
586
|
-
`,
|
|
587
|
-
`,
|
|
588
|
-
`,
|
|
589
|
-
`,
|
|
590
|
-
|
|
591
|
-
`,
|
|
592
|
-
`,
|
|
593
|
-
`,
|
|
594
|
-
`,
|
|
595
|
-
|
|
596
|
-
`,
|
|
597
|
-
`,
|
|
598
|
-
`,
|
|
599
|
-
`,
|
|
600
|
-
`,
|
|
601
|
-
|
|
602
|
-
`,
|
|
603
|
-
`,
|
|
604
|
-
`,
|
|
605
|
-
`,
|
|
606
|
-
`,
|
|
607
|
-
|
|
608
|
-
`,
|
|
609
|
-
`,
|
|
610
|
-
`,
|
|
611
|
-
`,
|
|
612
|
-
`,
|
|
613
|
-
`,
|
|
614
|
-
|
|
615
|
-
`,
|
|
616
|
-
`;let
|
|
617
|
-
`;
|
|
618
|
-
|
|
619
|
-
`,
|
|
620
|
-
`,
|
|
621
|
-
`,
|
|
622
|
-
`,
|
|
623
|
-
`,
|
|
624
|
-
`,
|
|
625
|
-
`,
|
|
626
|
-
`,
|
|
627
|
-
`,
|
|
628
|
-
`,
|
|
629
|
-
`,
|
|
630
|
-
`,
|
|
631
|
-
`,
|
|
632
|
-
`,
|
|
633
|
-
`,
|
|
634
|
-
`,
|
|
635
|
-
`,
|
|
636
|
-
`,
|
|
637
|
-
`,
|
|
638
|
-
`,
|
|
639
|
-
`,
|
|
640
|
-
`,
|
|
641
|
-
|
|
642
|
-
`,
|
|
643
|
-
`,
|
|
644
|
-
`,
|
|
645
|
-
`,
|
|
646
|
-
`,
|
|
647
|
-
|
|
648
|
-
`,
|
|
649
|
-
`,
|
|
650
|
-
`,
|
|
651
|
-
`,
|
|
652
|
-
`,
|
|
653
|
-
|
|
654
|
-
`,
|
|
655
|
-
`,
|
|
656
|
-
`,
|
|
657
|
-
`,
|
|
658
|
-
`,
|
|
659
|
-
|
|
660
|
-
`,
|
|
661
|
-
`;let
|
|
662
|
-
`;
|
|
663
|
-
|
|
664
|
-
`,
|
|
665
|
-
`,
|
|
666
|
-
`,
|
|
667
|
-
`,
|
|
668
|
-
`,
|
|
669
|
-
`,
|
|
670
|
-
`,
|
|
671
|
-
`,
|
|
672
|
-
`,
|
|
673
|
-
`,
|
|
674
|
-
`,
|
|
675
|
-
`,
|
|
676
|
-
`,
|
|
677
|
-
`,
|
|
678
|
-
`,
|
|
679
|
-
`,
|
|
680
|
-
`,
|
|
681
|
-
`,
|
|
682
|
-
`,
|
|
683
|
-
`,
|
|
684
|
-
`,
|
|
685
|
-
`,
|
|
686
|
-
|
|
687
|
-
`,
|
|
688
|
-
`,
|
|
689
|
-
`,
|
|
690
|
-
`,
|
|
691
|
-
`,
|
|
692
|
-
|
|
693
|
-
`,
|
|
694
|
-
`,
|
|
695
|
-
`,
|
|
696
|
-
`,
|
|
697
|
-
`,
|
|
698
|
-
|
|
699
|
-
`,
|
|
700
|
-
`,
|
|
701
|
-
`,
|
|
702
|
-
`,
|
|
703
|
-
`,
|
|
704
|
-
|
|
705
|
-
`,
|
|
706
|
-
`;let
|
|
707
|
-
`;
|
|
708
|
-
|
|
709
|
-
`,
|
|
710
|
-
`,
|
|
711
|
-
`,
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
)
|
|
715
|
-
`;
|
|
716
|
-
|
|
717
|
-
`;
|
|
718
|
-
`;
|
|
719
|
-
`;if(
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
`,
|
|
725
|
-
|
|
726
|
-
`;if(
|
|
727
|
-
|
|
728
|
-
`;if(W.includes("twitter"))G+=` .addColumn('twitter_id', 'varchar(255)')
|
|
729
|
-
`;if(W.includes("facebook"))G+=` .addColumn('facebook_id', 'varchar(255)')
|
|
730
|
-
`}for(let[W,w]of _8(Z.attributes)){let J=w,R=a1(W),M=Y8(J.validation?.rule);G+=` .addColumn('${R}', ${M}`;let q="isRequired"in(J.validation?.rule??{})?(J.validation?.rule).isRequired:!1;if(q||J.unique||J.default!==void 0){if(G+=", col => col",q)G+=".notNull()";if(J.unique)G+=".unique()";if(J.default!==void 0)if(typeof J.default==="string")G+=`.defaultTo('${J.default.replace(/'/g,"\\'")}')`;else if(J.default===null)G+=".defaultTo(null)";else G+=`.defaultTo(${J.default})`;G+=""}G+=`)
|
|
731
|
-
`}if(_!==!1&&_)G+=` .addColumn('two_factor_secret', 'varchar(255)')
|
|
732
|
-
`;if(Q)G+=` .addColumn('stripe_id', 'varchar(255)')
|
|
733
|
-
`;if(U)G+=` .addColumn('public_passkey', 'varchar(255)')
|
|
734
|
-
`;if(Y)G+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
735
|
-
`,G+=` .addColumn('updated_at', 'timestamp')
|
|
736
|
-
`;if(j)G+=` .addColumn('deleted_at', 'timestamp')
|
|
737
|
-
`;if(G+=` .execute()
|
|
738
|
-
`,G+=bO(X),z){let W=G8(Z,X);if(W)G+=`
|
|
345
|
+
`;Y+=`export async function up(db: Database<any>) {
|
|
346
|
+
`,Y+=` await db.schema
|
|
347
|
+
`,Y+=` .createTable('commentable_upvotes')
|
|
348
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
349
|
+
`,Y+=` .addColumn('upvoteable_id', 'integer', col => col.notNull())
|
|
350
|
+
`,Y+=` .addColumn('upvoteable_type', 'varchar(255)', col => col.notNull())
|
|
351
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
352
|
+
`,Y+=` .execute()
|
|
353
|
+
|
|
354
|
+
`,Y+=` await db.schema.createIndex('idx_commentable_upvotes_upvoteable').on('commentable_upvotes').columns(['upvoteable_id', 'upvoteable_type']).execute()
|
|
355
|
+
`,Y+=`}
|
|
356
|
+
`;let J=`${new Date().getTime().toString()}-create-commentable_upvotes-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function Q1(){if(await q("commentables"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
357
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
358
|
+
|
|
359
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
360
|
+
`,Y+=` await db.schema
|
|
361
|
+
`,Y+=` .createTable('commentables')
|
|
362
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
363
|
+
`,Y+=` .addColumn('comment_id', 'integer', col => col.notNull())
|
|
364
|
+
`,Y+=` .addColumn('commentable_id', 'integer', col => col.notNull())
|
|
365
|
+
`,Y+=` .addColumn('commentable_type', 'varchar(255)', col => col.notNull())
|
|
366
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
367
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
368
|
+
`,Y+=` .execute()
|
|
369
|
+
|
|
370
|
+
`,Y+=` await db.schema
|
|
371
|
+
`,Y+=` .createIndex('idx_commentables_comment')
|
|
372
|
+
`,Y+=` .on('commentables')
|
|
373
|
+
`,Y+=` .column('comment_id')
|
|
374
|
+
`,Y+=` .execute()
|
|
375
|
+
|
|
376
|
+
`,Y+=` await db.schema
|
|
377
|
+
`,Y+=` .createIndex('idx_commentables_polymorphic')
|
|
378
|
+
`,Y+=` .on('commentables')
|
|
379
|
+
`,Y+=` .columns(['commentable_id', 'commentable_type'])
|
|
380
|
+
`,Y+=` .execute()
|
|
381
|
+
|
|
382
|
+
`,Y+=` await db.schema
|
|
383
|
+
`,Y+=` .createIndex('idx_commentables_unique')
|
|
384
|
+
`,Y+=` .on('commentables')
|
|
385
|
+
`,Y+=` .columns(['comment_id', 'commentable_id', 'commentable_type'])
|
|
386
|
+
`,Y+=` .unique()
|
|
387
|
+
`,Y+=` .execute()
|
|
388
|
+
|
|
389
|
+
`,Y+=`}
|
|
390
|
+
`;let J=`${new Date().getTime().toString()}-create-commentables-pivot-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function Y6(){if(await q("commentables_pivot"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
391
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
392
|
+
|
|
393
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
394
|
+
`,Y+=` await db.schema
|
|
395
|
+
`,Y+=` .createTable('commentables')
|
|
396
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
397
|
+
`,Y+=` .addColumn('comment_id', 'integer', col => col.notNull())
|
|
398
|
+
`,Y+=` .addColumn('commentable_id', 'integer', col => col.notNull())
|
|
399
|
+
`,Y+=` .addColumn('commentable_type', 'varchar(255)', col => col.notNull())
|
|
400
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
401
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
402
|
+
`,Y+=` .execute()
|
|
403
|
+
|
|
404
|
+
`,Y+=` await db.schema
|
|
405
|
+
`,Y+=` .alterTable('commentables')
|
|
406
|
+
`,Y+=` .addForeignKeyConstraint('commentables_comment_id_foreign', ['comment_id'], 'comments', ['id'], (cb) => cb.onDelete('cascade'))
|
|
407
|
+
`,Y+=` .execute()
|
|
408
|
+
|
|
409
|
+
`,Y+=` await db.schema
|
|
410
|
+
`,Y+=` .createIndex('idx_commentables_comment')
|
|
411
|
+
`,Y+=` .on('commentables')
|
|
412
|
+
`,Y+=` .column('comment_id')
|
|
413
|
+
`,Y+=` .execute()
|
|
414
|
+
|
|
415
|
+
`,Y+=` await db.schema
|
|
416
|
+
`,Y+=` .createIndex('idx_commentables_polymorphic')
|
|
417
|
+
`,Y+=` .on('commentables')
|
|
418
|
+
`,Y+=` .columns(['commentable_id', 'commentable_type'])
|
|
419
|
+
`,Y+=` .execute()
|
|
420
|
+
|
|
421
|
+
`,Y+=` await db.schema
|
|
422
|
+
`,Y+=` .createIndex('idx_commentables_unique')
|
|
423
|
+
`,Y+=` .on('commentables')
|
|
424
|
+
`,Y+=` .columns(['comment_id', 'commentable_id', 'commentable_type'])
|
|
425
|
+
`,Y+=` .unique()
|
|
426
|
+
`,Y+=` .execute()
|
|
427
|
+
|
|
428
|
+
`,Y+=`}
|
|
429
|
+
`;let J=`${new Date().getTime().toString()}-create-commentables-pivot-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function TZ(){if(await q("taggables"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
430
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
431
|
+
|
|
432
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
433
|
+
`,Y+=` await db.schema
|
|
434
|
+
`,Y+=` .createTable('taggables')
|
|
435
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
436
|
+
`,Y+=` .addColumn('tag_id', 'integer', col => col.notNull())
|
|
437
|
+
`,Y+=` .addColumn('taggable_id', 'integer', col => col.notNull())
|
|
438
|
+
`,Y+=` .addColumn('taggable_type', 'varchar(255)', col => col.notNull())
|
|
439
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
440
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
441
|
+
`,Y+=` .execute()
|
|
442
|
+
|
|
443
|
+
`,Y+=` await db.schema
|
|
444
|
+
`,Y+=` .createIndex('idx_taggables_tag')
|
|
445
|
+
`,Y+=` .on('taggables')
|
|
446
|
+
`,Y+=` .column('tag_id')
|
|
447
|
+
`,Y+=` .execute()
|
|
448
|
+
|
|
449
|
+
`,Y+=` await db.schema
|
|
450
|
+
`,Y+=` .createIndex('idx_taggables_polymorphic')
|
|
451
|
+
`,Y+=` .on('taggables')
|
|
452
|
+
`,Y+=` .columns(['taggable_id', 'taggable_type'])
|
|
453
|
+
`,Y+=` .execute()
|
|
454
|
+
|
|
455
|
+
`,Y+=` await db.schema
|
|
456
|
+
`,Y+=` .createIndex('idx_taggables_unique')
|
|
457
|
+
`,Y+=` .on('taggables')
|
|
458
|
+
`,Y+=` .columns(['tag_id', 'taggable_id', 'taggable_type'])
|
|
459
|
+
`,Y+=` .unique()
|
|
460
|
+
`,Y+=` .execute()
|
|
461
|
+
|
|
462
|
+
`,Y+=`}
|
|
463
|
+
`;let J=`${new Date().getTime().toString()}-create-taggables-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function PZ(){if(await q("taggables"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
464
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
465
|
+
|
|
466
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
467
|
+
`,Y+=` await db.schema
|
|
468
|
+
`,Y+=` .createTable('taggables')
|
|
469
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
470
|
+
`,Y+=` .addColumn('tag_id', 'integer', col => col.notNull())
|
|
471
|
+
`,Y+=` .addColumn('taggable_id', 'integer', col => col.notNull())
|
|
472
|
+
`,Y+=` .addColumn('taggable_type', 'varchar(255)', col => col.notNull())
|
|
473
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
474
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
475
|
+
`,Y+=` .execute()
|
|
476
|
+
|
|
477
|
+
`,Y+=` await db.schema
|
|
478
|
+
`,Y+=` .alterTable('taggables')
|
|
479
|
+
`,Y+=` .addForeignKeyConstraint('taggables_tag_id_foreign', ['tag_id'], 'tags', ['id'], (cb) => cb.onDelete('cascade'))
|
|
480
|
+
`,Y+=` .execute()
|
|
481
|
+
|
|
482
|
+
`,Y+=` await db.schema
|
|
483
|
+
`,Y+=` .createIndex('idx_taggables_tag')
|
|
484
|
+
`,Y+=` .on('taggables')
|
|
485
|
+
`,Y+=` .column('tag_id')
|
|
486
|
+
`,Y+=` .execute()
|
|
487
|
+
|
|
488
|
+
`,Y+=` await db.schema
|
|
489
|
+
`,Y+=` .createIndex('idx_taggables_polymorphic')
|
|
490
|
+
`,Y+=` .on('taggables')
|
|
491
|
+
`,Y+=` .columns(['taggable_id', 'taggable_type'])
|
|
492
|
+
`,Y+=` .execute()
|
|
493
|
+
|
|
494
|
+
`,Y+=` await db.schema
|
|
495
|
+
`,Y+=` .createIndex('idx_taggables_unique')
|
|
496
|
+
`,Y+=` .on('taggables')
|
|
497
|
+
`,Y+=` .columns(['tag_id', 'taggable_id', 'taggable_type'])
|
|
498
|
+
`,Y+=` .unique()
|
|
499
|
+
`,Y+=` .execute()
|
|
500
|
+
|
|
501
|
+
`,Y+=`}
|
|
502
|
+
`;let J=`${new Date().getTime().toString()}-create-taggables-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function Z6(){if(await q("query_logs"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
503
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
504
|
+
|
|
505
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
506
|
+
`,Y+=` await db.schema
|
|
507
|
+
`,Y+=` .createTable('query_logs')
|
|
508
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
509
|
+
`,Y+=` .addColumn('query', 'text', col => col.notNull())
|
|
510
|
+
`,Y+=` .addColumn('normalized_query', 'text')
|
|
511
|
+
`,Y+=` .addColumn('duration', 'integer')
|
|
512
|
+
`,Y+=` .addColumn('connection', 'varchar(255)')
|
|
513
|
+
`,Y+=` .addColumn('status', 'varchar(50)')
|
|
514
|
+
`,Y+=` .addColumn('executed_at', 'timestamp', col => col.notNull())
|
|
515
|
+
`,Y+=` .addColumn('model', 'varchar(255)')
|
|
516
|
+
`,Y+=` .addColumn('method', 'varchar(255)')
|
|
517
|
+
`,Y+=` .addColumn('rows_affected', 'integer')
|
|
518
|
+
`,Y+=` .addColumn('optimization_suggestions', 'json')
|
|
519
|
+
`,Y+=` .addColumn('affected_tables', 'json')
|
|
520
|
+
`,Y+=` .addColumn('indexes_used', 'json')
|
|
521
|
+
`,Y+=` .addColumn('missing_indexes', 'json')
|
|
522
|
+
`,Y+=` .addColumn('tags', 'json')
|
|
523
|
+
`,Y+=` .addColumn('bindings', 'json')
|
|
524
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
525
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
526
|
+
`,Y+=` .execute()
|
|
527
|
+
|
|
528
|
+
`,Y+=` await db.schema
|
|
529
|
+
`,Y+=` .createIndex('idx_query_logs_executed_at')
|
|
530
|
+
`,Y+=` .on('query_logs')
|
|
531
|
+
`,Y+=` .column('executed_at')
|
|
532
|
+
`,Y+=` .execute()
|
|
533
|
+
|
|
534
|
+
`,Y+=` await db.schema
|
|
535
|
+
`,Y+=` .createIndex('idx_query_logs_status')
|
|
536
|
+
`,Y+=` .on('query_logs')
|
|
537
|
+
`,Y+=` .column('status')
|
|
538
|
+
`,Y+=` .execute()
|
|
539
|
+
|
|
540
|
+
`,Y+=` await db.schema
|
|
541
|
+
`,Y+=` .createIndex('idx_query_logs_duration')
|
|
542
|
+
`,Y+=` .on('query_logs')
|
|
543
|
+
`,Y+=` .column('duration')
|
|
544
|
+
`,Y+=` .execute()
|
|
545
|
+
|
|
546
|
+
`,Y+=`}
|
|
547
|
+
`;let J=`${new Date().getTime().toString()}-create-query-logs-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}async function $6(){if(await q("query_logs"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
548
|
+
`;Y+=`import { sql } from '@stacksjs/database'
|
|
549
|
+
|
|
550
|
+
`,Y+=`export async function up(db: Database<any>) {
|
|
551
|
+
`,Y+=` await db.schema
|
|
552
|
+
`,Y+=` .createTable('query_logs')
|
|
553
|
+
`,Y+=` .addColumn('id', 'serial', col => col.primaryKey())
|
|
554
|
+
`,Y+=` .addColumn('query', 'text', col => col.notNull())
|
|
555
|
+
`,Y+=` .addColumn('normalized_query', 'text')
|
|
556
|
+
`,Y+=` .addColumn('duration', 'integer')
|
|
557
|
+
`,Y+=` .addColumn('connection', 'varchar(255)')
|
|
558
|
+
`,Y+=` .addColumn('status', 'varchar(50)')
|
|
559
|
+
`,Y+=` .addColumn('executed_at', 'timestamp', col => col.notNull())
|
|
560
|
+
`,Y+=` .addColumn('model', 'varchar(255)')
|
|
561
|
+
`,Y+=` .addColumn('method', 'varchar(255)')
|
|
562
|
+
`,Y+=` .addColumn('rows_affected', 'integer')
|
|
563
|
+
`,Y+=` .addColumn('optimization_suggestions', 'jsonb')
|
|
564
|
+
`,Y+=` .addColumn('affected_tables', 'jsonb')
|
|
565
|
+
`,Y+=` .addColumn('indexes_used', 'jsonb')
|
|
566
|
+
`,Y+=` .addColumn('missing_indexes', 'jsonb')
|
|
567
|
+
`,Y+=` .addColumn('tags', 'jsonb')
|
|
568
|
+
`,Y+=` .addColumn('bindings', 'jsonb')
|
|
569
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
570
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
571
|
+
`,Y+=` .execute()
|
|
572
|
+
|
|
573
|
+
`,Y+=` await db.schema
|
|
574
|
+
`,Y+=` .createIndex('idx_query_logs_executed_at')
|
|
575
|
+
`,Y+=` .on('query_logs')
|
|
576
|
+
`,Y+=` .column('executed_at')
|
|
577
|
+
`,Y+=` .execute()
|
|
578
|
+
|
|
579
|
+
`,Y+=` await db.schema
|
|
580
|
+
`,Y+=` .createIndex('idx_query_logs_status')
|
|
581
|
+
`,Y+=` .on('query_logs')
|
|
582
|
+
`,Y+=` .column('status')
|
|
583
|
+
`,Y+=` .execute()
|
|
584
|
+
|
|
585
|
+
`,Y+=` await db.schema
|
|
586
|
+
`,Y+=` .createIndex('idx_query_logs_duration')
|
|
587
|
+
`,Y+=` .on('query_logs')
|
|
588
|
+
`,Y+=` .column('duration')
|
|
589
|
+
`,Y+=` .execute()
|
|
590
|
+
|
|
591
|
+
`,Y+=`}
|
|
592
|
+
`;let J=`${new Date().getTime().toString()}-create-query-logs-table.ts`,X=N.userMigrationsPath(J);await Bun.write(X,Y),P.success(`Created migration: ${k(J)}`)}function J6(Z){return`\x1B[3m${Z}\x1B[23m`}async function S1(){return await p8(),await BY(),await AY(),h8("All tables dropped successfully!")}async function p8(){let Z=b8([i.userModelsPath("*.ts"),i.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Y=await eY();for(let $ of Y){if(!/^[a-z_][\w]*$/i.test($))throw Error(`[mysql] Refusing to drop table with unsafe name: ${$}`);await V.unsafe(`DROP TABLE IF EXISTS \`${$}\``).execute()}await ZZ();for(let $ of Z){let J=(await import($)).default,X=await X6(J,$);for(let W of X){if(!/^[a-z_][\w]*$/i.test(W.table))throw Error(`[mysql] Refusing to drop pivot table with unsafe name: ${W.table}`);await V.unsafe(`DROP TABLE IF EXISTS \`${W.table}\``).execute()}}}async function M1(Z){let Y=(await import(Z)).default,$=i.basename(Z),J=kZ(Y,Z),X=JSON.stringify(Y.attributes,null,2),W=i.frameworkPath(`cache/models/${$}`),H=!1;if(f8.existsSync(W)){s.info(`Fields have already been generated for ${J}`);let z=await m($);if(JSON.stringify(z,null,2)===X){s.debug(`Fields have not changed for ${J}`);return}H=!0,s.debug(`Fields have changed for ${J}`)}else s.debug(`Fields have not been generated for ${J}`);await Bun.$`mkdir -p ${i.frameworkPath("cache/models")} && cp ${Z} ${W}`;let G=await $Y(J);if(s.debug(`Has ${J} been migrated? ${G}`),H)await c8(Z);else await W6(Z)}async function F1(){await Promise.all([r4(),i4(),s4(),TZ(),YZ(),d4(),Z6(),t4()])}async function W6(Z){s.debug("createTableMigration modelPath:",Z);let Y=(await import(Z)).default,$=kZ(Y,Z),J=Y.traits?.useAuth&&typeof Y.traits.useAuth!=="boolean"?Y.traits.useAuth.useTwoFactor:!1;await C8(Y,Z);let X=Y?.traits?.useTimestamps??Y?.traits?.timestampable??!0,W=Y?.traits?.useSocials&&Array.isArray(Y.traits.useSocials)&&Y.traits.useSocials.length>0,H=Array.isArray(Y?.traits?.likeable)?Y.traits.likeable.length>0:Boolean(Y?.traits?.likeable),G=Y?.traits?.useSoftDeletes??Y?.traits?.softDeletable??!1,z=(typeof Y.traits?.useAuth==="object"&&Y.traits.useAuth.usePasskey)??!1,Q=Y.traits?.billable||!1,_=Y.traits?.useUuid||!1;if(Q&&$==="users")await W6(i.frameworkPath("defaults/app/Models/Subscription.ts"));let U=`import type { Database } from '@stacksjs/database'
|
|
593
|
+
`;if(U+=`import { sql } from '@stacksjs/database'
|
|
594
|
+
|
|
595
|
+
`,U+=`export async function up(db: Database<any>) {
|
|
596
|
+
`,U+=` await (db as any).schema
|
|
597
|
+
`,U+=` .createTable('${$}')
|
|
598
|
+
`,U+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
599
|
+
`,_)U+=` .addColumn('uuid', 'varchar(255)')
|
|
600
|
+
`;if(W){let A=Y.traits?.useSocials||[];if(A.includes("google"))U+=` .addColumn('google_id', 'varchar(255)')
|
|
601
|
+
`;if(A.includes("github"))U+=` .addColumn('github_id', 'varchar(255)')
|
|
602
|
+
`;if(A.includes("apple"))U+=` .addColumn('apple_id', 'varchar(255)')
|
|
603
|
+
`;if(A.includes("twitter"))U+=` .addColumn('twitter_id', 'varchar(255)')
|
|
604
|
+
`;if(A.includes("facebook"))U+=` .addColumn('facebook_id', 'varchar(255)')
|
|
605
|
+
`}for(let[A,E]of JY(Y.attributes)){let B=E,j=$Z(A),R=XY(B.validation?.rule);U+=` .addColumn('${j}', ${R}`;let f="isRequired"in(B.validation?.rule??{})?(B.validation?.rule).isRequired:!1;if(f||B.unique||B.default!==void 0){if(U+=", col => col",f)U+=".notNull()";if(B.unique)U+=".unique()";if(B.default!==void 0)if(typeof B.default==="string")U+=`.defaultTo('${B.default.replace(/'/g,"\\'")}')`;else if(B.default===null)U+=".defaultTo(null)";else U+=`.defaultTo(${B.default})`;U+=""}U+=`)
|
|
606
|
+
`}if(J!==!1&&J)U+=` .addColumn('two_factor_secret', 'varchar(255)')
|
|
607
|
+
`;if(Q)U+=` .addColumn('stripe_id', 'varchar(255)')
|
|
608
|
+
`;if(z)U+=` .addColumn('public_passkey', 'varchar(255)')
|
|
609
|
+
`;if(X)U+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
610
|
+
`,U+=` .addColumn('updated_at', 'timestamp')
|
|
611
|
+
`;if(G)U+=` .addColumn('deleted_at', 'timestamp')
|
|
612
|
+
`;if(U+=` .execute()
|
|
613
|
+
`,U+=u8($),H){let A=zY(Y,$);if(A){let E=jY(Y,$);U+=`
|
|
739
614
|
// Create upvote table
|
|
740
|
-
`,
|
|
741
|
-
`,
|
|
742
|
-
`,
|
|
743
|
-
`,
|
|
744
|
-
`,
|
|
745
|
-
`,
|
|
746
|
-
`,
|
|
747
|
-
`,
|
|
748
|
-
|
|
749
|
-
`,
|
|
750
|
-
`,
|
|
751
|
-
`,
|
|
752
|
-
`,
|
|
753
|
-
`}
|
|
754
|
-
`;let O=`${new Date().getTime().toString()}-create-${
|
|
755
|
-
`;
|
|
756
|
-
|
|
757
|
-
`,
|
|
758
|
-
`,
|
|
759
|
-
`,
|
|
760
|
-
`,
|
|
761
|
-
`,
|
|
762
|
-
`,
|
|
763
|
-
`,
|
|
764
|
-
`,
|
|
765
|
-
`,
|
|
766
|
-
`;let
|
|
767
|
-
`;if(
|
|
768
|
-
|
|
769
|
-
`,
|
|
770
|
-
`,Q.length||
|
|
771
|
-
`;let
|
|
772
|
-
`}let O=Object.values(
|
|
773
|
-
`,
|
|
774
|
-
`;let
|
|
775
|
-
`}function
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
`}function gO($,Z){let X=_8($),_="",Y="";for(let[L]of X){let z=a1(L);if(Y)_+=`await sql\`
|
|
779
|
-
ALTER TABLE ${Z}
|
|
780
|
-
MODIFY COLUMN ${z} VARCHAR(255) NOT NULL AFTER ${a1(Y)};
|
|
615
|
+
`,U+=` await (db as any).schema
|
|
616
|
+
`,U+=` .createTable('${A}')
|
|
617
|
+
`,U+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
618
|
+
`,U+=` .addColumn('${E}', 'integer', col => col.notNull())
|
|
619
|
+
`,U+=` .addColumn('user_id', 'integer', col => col.notNull())
|
|
620
|
+
`,U+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
621
|
+
`,U+=` .addColumn('updated_at', 'timestamp')
|
|
622
|
+
`,U+=` .execute()
|
|
623
|
+
|
|
624
|
+
`,U+=` // Add indexes for upvote table
|
|
625
|
+
`,U+=` await (db as any).schema.createIndex('${A}_${E}_index').on('${A}').column('${E}').execute()
|
|
626
|
+
`,U+=` await (db as any).schema.createIndex('${A}_user_${E}_unique').on('${A}').columns(['user_id', '${E}']).unique().execute()
|
|
627
|
+
`,U+=` await (db as any).schema.createIndex('${A}_id_index').on('${A}').column('id').execute()
|
|
628
|
+
`}}U+=`}
|
|
629
|
+
`;let O=`${new Date().getTime().toString()}-create-${$}-table.ts`,L=i.userMigrationsPath(O);s.debug(L),await Bun.write(L,U),s.success(`Created migration: ${J6(O)}`)}async function C8(Z,Y){let $=await X6(Z,Y),J=new Set;if(!$.length)return;for(let X of $){if(J.has(X.table))continue;if(await LY(X.table)){J.add(X.table);continue}let H=`import type { Database } from '@stacksjs/database'
|
|
630
|
+
`;H+=`import { sql } from '@stacksjs/database'
|
|
631
|
+
|
|
632
|
+
`,H+=`export async function up(db: Database<any>) {
|
|
633
|
+
`,H+=` await (db as any).schema
|
|
634
|
+
`,H+=` .createTable('${X.table}')
|
|
635
|
+
`,H+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
636
|
+
`,H+=` .addColumn('${X.firstForeignKey}', 'integer')
|
|
637
|
+
`,H+=` .addColumn('${X.secondForeignKey}', 'integer')
|
|
638
|
+
`,H+=` .addColumn('created_at', 'timestamp', col => col.defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
639
|
+
`,H+=` .execute()
|
|
640
|
+
`,H+=` }
|
|
641
|
+
`;let z=`${new Date().getTime().toString()}-create-${X.table}-table.ts`,Q=i.userMigrationsPath(z);await Bun.write(Q,H),J.add(X.table),s.success(`Created pivot migration: ${z}`)}}async function c8(Z){let Y=(await import(Z)).default,$=v8(Y,Z),J=kZ(Y,Z),X=!1,H=await m($)??{},G=Y.attributes,z=EY(Object.keys(H),Object.keys(G)),Q=z?.added||[],_=z?.removed||[],U=`import type { Database } from '@stacksjs/database'
|
|
642
|
+
`;if(U+=`import { sql } from '@stacksjs/database'
|
|
643
|
+
|
|
644
|
+
`,U+=`export async function up(db: Database<any>) {
|
|
645
|
+
`,Q.length||_.length)X=!0,U+=` await (db as any).schema.alterTable('${J}')
|
|
646
|
+
`;let I=KY(H,G);for(let A of I){X=!0;let E=$Z(A.key);U+=` .modifyColumn('${E}', 'varchar(${A.max})')
|
|
647
|
+
`}let O=Object.values(H).map((A)=>A.order),L=Object.values(G).map((A)=>A.order);if(!IY(O,L))X=!0,U+=g8(Y.attributes,J);if(X){U+=` .execute()
|
|
648
|
+
`,U+=`}
|
|
649
|
+
`;let E=`${new Date().getTime().toString()}-alter-${J}-table.ts`,B=i.userMigrationsPath(E);await Bun.write(B,U),s.success(`Created alter migration: ${J6(E)}`)}}function u8(Z){return` await (db as any).schema.createIndex('${Z}_id_index').on('${Z}').column('id').execute()
|
|
650
|
+
`}function g8(Z,Y){let $=JY(Z),J="",X="";for(let[W]of $){let H=$Z(W);if(X)J+=`await sql\`
|
|
651
|
+
ALTER TABLE ${Y}
|
|
652
|
+
MODIFY COLUMN ${H} VARCHAR(255) NOT NULL AFTER ${$Z(X)};
|
|
781
653
|
\`.execute(db)
|
|
782
654
|
|
|
783
|
-
`;
|
|
784
|
-
`;if(
|
|
785
|
-
|
|
786
|
-
`,
|
|
787
|
-
`,
|
|
788
|
-
`,
|
|
789
|
-
`,
|
|
790
|
-
`,
|
|
791
|
-
`;for(let[
|
|
792
|
-
`}if(
|
|
793
|
-
`;if(
|
|
794
|
-
`;if(
|
|
795
|
-
`;if(
|
|
796
|
-
|
|
797
|
-
`}if(
|
|
798
|
-
|
|
799
|
-
`;if(U
|
|
800
|
-
`;if(
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
`;if(G+=` .
|
|
804
|
-
|
|
655
|
+
`;X=H}return J}F();import{log as l}from"@stacksjs/logging";import{ok as d8}from"@stacksjs/error-handling";import{getModelName as m8,getPivotTables as H6,getTableName as JZ}from"@stacksjs/orm";import{path as y}from"@stacksjs/path";import{fs as RY,globSync as G6}from"@stacksjs/storage";import{plural as s8,snakeCase as NZ}from"@stacksjs/strings";function hZ(Z){return`\x1B[3m${Z}\x1B[23m`}async function l8(){let Z=await o8(),Y=G6([y.userModelsPath("*.ts"),y.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0});await o4();for(let $ of Z)await V.unsafe(`DROP TABLE IF EXISTS "${$}" CASCADE`).execute();await r8();for(let $ of Y){let J=(await import($)).default,X=await H6(J,$);for(let W of X)await V.unsafe(`DROP TABLE IF EXISTS "${W.table}" CASCADE`).execute()}}async function r8(){await V.unsafe('DROP TABLE IF EXISTS "passkeys" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "password_resets" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "query_logs" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "categorizables" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "commentables" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "comments" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "tags" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "taggables" CASCADE').execute(),await V.unsafe('DROP TABLE IF EXISTS "commentable_upvotes" CASCADE').execute()}async function p1(){await n4(),await a4(),await l4(),await e4(),await m4(),await $6(),await YZ(),await Y6(),await PZ()}async function C1(){return await l8(),await BY(),await AY(),await V.unsafe('CREATE TABLE IF NOT EXISTS "migrations" (id SERIAL PRIMARY KEY)').execute(),await V.unsafe('CREATE TABLE IF NOT EXISTS "migration_locks" (id SERIAL PRIMARY KEY)').execute(),await V.unsafe('CREATE TABLE IF NOT EXISTS "activities" (id SERIAL PRIMARY KEY)').execute(),d8("All tables dropped successfully!")}async function c1(Z){if((await RY.promises.readdir(y.userMigrationsPath(""))).length===0){l.debug("No migrations found in the database folder, clearing the model snapshot cache...");let _=y.frameworkPath("cache/models");if(RY.existsSync(_)){let U=await RY.promises.readdir(_);if(U.length){for(let I of U)if(I.endsWith(".ts"))await RY.promises.unlink(y.frameworkPath(`cache/models/${I}`))}}}let $=(await import(Z)).default,J=y.basename(Z),X=JZ($,Z),W=JSON.stringify($.attributes,null,2),H=y.frameworkPath(`cache/models/${J}`),G=!1;if(RY.existsSync(H)){l.info(`Fields have already been generated for ${X}`);let _=await m(J);if(JSON.stringify(_,null,2)===W){l.debug(`Fields have not changed for ${X}`);return}G=!0,l.debug(`Fields have changed for ${X}`)}else l.debug(`Fields have not been generated for ${X}`);await Bun.$`mkdir -p ${y.frameworkPath("cache/models")} && cp ${Z} ${H}`;let z=await $Y(X);if(l.debug(`Has ${X} been migrated? ${z}`),($.traits?.billable||!1)&&X==="users")await yZ(y.frameworkPath("defaults/app/Models/Subscription.ts"));if(G)await i8(Z);else await yZ(Z)}async function yZ(Z){l.debug("createTableMigration modelPath:",Z);let Y=(await import(Z)).default,$=JZ(Y,Z),J=Y.traits?.useAuth&&typeof Y.traits.useAuth!=="boolean"?Y.traits.useAuth.useTwoFactor:!1;await n8(Y,Z);let X=Y.traits?.useTimestamps??Y.traits?.timestampable??!0,W=Y?.traits?.useSocials&&Array.isArray(Y.traits.useSocials)&&Y.traits.useSocials.length>0,H=Array.isArray(Y?.traits?.likeable)?Y.traits.likeable.length>0:Boolean(Y?.traits?.likeable),G=Y.traits?.useSoftDeletes??Y.traits?.softDeletable??!1,z=(typeof Y.traits?.useAuth==="object"&&Y.traits.useAuth.usePasskey)??!1,Q=Y.traits?.billable||!1,_=Y.traits?.useUuid||!1;if(Q&&$==="users")await yZ(y.frameworkPath("defaults/app/Models/Subscription.ts"));let U=`import type { Database } from '@stacksjs/database'
|
|
656
|
+
`;if(U+=`import { sql } from '@stacksjs/database'
|
|
657
|
+
|
|
658
|
+
`,U+=`export async function up(db: Database<any>) {
|
|
659
|
+
`,U+=` await (db as any).schema
|
|
660
|
+
`,U+=` .createTable('${$}')
|
|
661
|
+
`,U+=` .addColumn('id', 'serial', (col) => col.primaryKey())
|
|
662
|
+
`,_)U+=` .addColumn('uuid', 'uuid', (col) => col.defaultTo(sql.raw('gen_random_uuid()')))
|
|
663
|
+
`;for(let[A,E]of JY(Y.attributes)){let B=E,j=NZ(A),R=XY(B.validation?.rule,"postgres"),f="isRequired"in(B.validation?.rule??{})?(B.validation?.rule).isRequired:!1;if(U+=` .addColumn('${j}', ${R}`,f||B.unique||B.default!==void 0){if(U+=", col => col",f)U+=".notNull()";if(B.unique)U+=".unique()";if(B.default!==void 0)if(typeof B.default==="string")U+=`.defaultTo('${B.default.replace(/'/g,"\\'")}')`;else if(B.default===null)U+=".defaultTo(null)";else U+=`.defaultTo(${B.default})`;U+=""}U+=`)
|
|
664
|
+
`}if(W){let A=Y.traits?.useSocials||[];if(A.includes("google"))U+=` .addColumn('google_id', 'text')
|
|
665
|
+
`;if(A.includes("github"))U+=` .addColumn('github_id', 'text')
|
|
666
|
+
`;if(A.includes("apple"))U+=` .addColumn('apple_id', 'text')
|
|
667
|
+
`;if(A.includes("twitter"))U+=` .addColumn('twitter_id', 'text')
|
|
668
|
+
`;if(A.includes("facebook"))U+=` .addColumn('facebook_id', 'text')
|
|
669
|
+
`}if(H){let A=Array.isArray(Y.traits?.likeable)?Y.traits.likeable:[];for(let E of A)U+=` .addColumn('${E}_count', 'integer', (col) => col.defaultTo(0))
|
|
670
|
+
`}if(J!==!1&&J)U+=` .addColumn('two_factor_secret', 'text')
|
|
671
|
+
`;if(Q)U+=` .addColumn('stripe_id', 'text')
|
|
672
|
+
`;if(z)U+=` .addColumn('public_passkey', 'text')
|
|
673
|
+
`;if(X)U+=` .addColumn('created_at', 'timestamptz', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
674
|
+
`,U+=` .addColumn('updated_at', 'timestamptz')
|
|
675
|
+
`;if(G)U+=` .addColumn('deleted_at', 'timestamptz')
|
|
676
|
+
`;if(U+=` .execute()
|
|
677
|
+
`,U+=a8($),H){let A=zY(Y,$);if(A){let E=jY(Y,$);U+=`
|
|
805
678
|
// Create upvote table
|
|
806
|
-
`,
|
|
807
|
-
`,
|
|
808
|
-
`,
|
|
809
|
-
`,
|
|
810
|
-
`,
|
|
811
|
-
`,
|
|
812
|
-
`,
|
|
813
|
-
`,
|
|
814
|
-
|
|
815
|
-
`,
|
|
816
|
-
`,
|
|
817
|
-
`,
|
|
818
|
-
`,
|
|
819
|
-
`}
|
|
820
|
-
`;let O=`${new Date().getTime().toString()}-create-${
|
|
821
|
-
`;
|
|
822
|
-
|
|
823
|
-
`,
|
|
824
|
-
`,
|
|
825
|
-
`,
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
)
|
|
829
|
-
|
|
830
|
-
`,
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
`,
|
|
836
|
-
|
|
837
|
-
`,
|
|
838
|
-
`,
|
|
839
|
-
`,
|
|
840
|
-
`,
|
|
841
|
-
|
|
842
|
-
`,
|
|
843
|
-
|
|
844
|
-
`,
|
|
845
|
-
`,
|
|
846
|
-
`,
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
`,
|
|
850
|
-
`,
|
|
851
|
-
`,
|
|
852
|
-
`,
|
|
853
|
-
|
|
854
|
-
`,z
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
`,
|
|
858
|
-
`,
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
`,
|
|
864
|
-
`,
|
|
865
|
-
|
|
866
|
-
`;let U=`${new Date().getTime().toString()}-create-${Y.table}-table.ts`,Q=d0.userMigrationsPath(U);await Bun.write(Q,z),_.add(Y.table),S9.success(`Created migration: ${l5(U)}`)}}async function lO($){let Z=(await import($)).default,X=n6(Z,$),_=t8(Z,$),Y=!1,z=await P9(X)??{},j=Z.attributes,U=i8(Object.keys(z),Object.keys(j)),Q=U?.added||[],E=U?.removed||[],G=`import type { Database } from '@stacksjs/database'
|
|
867
|
-
`;if(G+=`import { sql } from '@stacksjs/database'
|
|
868
|
-
|
|
869
|
-
`,G+=`export async function up(_db: Database<any>) {
|
|
870
|
-
`,Q.length||E.length)Y=!0,G+=` await (_db as any).schema.alterTable('${_}')
|
|
871
|
-
`;for(let W of Q){let w=j[W],J=Y8(w.validation?.rule,"postgres"),R=s5(W),M="isRequired"in(w.validation?.rule??{})?(w.validation?.rule).isRequired:!1;if(G+=` .addColumn('${R}', '${J}'`,M||w.unique||w.default!==void 0){if(G+=", col => col",M)G+=".notNull()";if(w.unique)G+=".unique()";if(w.default!==void 0)if(typeof w.default==="string")G+=`.defaultTo('${w.default}')`;else if(w.default===null)G+=".defaultTo(null)";else G+=`.defaultTo(${w.default})`;G+=""}G+=`)
|
|
872
|
-
`}for(let W of E)G+=` .dropColumn('${W}')
|
|
873
|
-
`;let F=o8(z,j);for(let W of F){Y=!0;let w=s5(W.key);G+=` .alterColumn('${w}', (col) => col.setDataType('text'))
|
|
874
|
-
`}let O=Object.values(z).map((W)=>W.order),K=Object.values(j).map((W)=>W.order);if(!r8(O,K))Y=!0;if(Y){G+=` .execute()
|
|
875
|
-
`,G+=`}
|
|
876
|
-
`;let w=`${new Date().getTime().toString()}-alter-${_}-table.ts`,J=d0.userMigrationsPath(w);await Bun.write(J,G),S9.success(`Created alter migration: ${l5(w)}`)}}function nO($,Z,X){let _=X.map((Y)=>`'${s5(Y)}'`).join(", ");return` await (_db as any).schema.createIndex('${Z}').on('${$}').columns([${_}]).execute()
|
|
877
|
-
`}function iO($){return` await (_db as any).schema.createIndex('${$}_id_index').on('${$}').column('id').execute()
|
|
878
|
-
`}function rO($,Z){return` await (_db as any).schema.createIndex('${$}_${Z}_index').on('${$}').column('${Z}').execute()
|
|
879
|
-
|
|
880
|
-
`}async function oO(){let $=C_([d0.userModelsPath("*.ts"),d0.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Z=[];for(let X of $){let _=(await import(X)).default,Y=t8(_,X);Z.push(Y)}return Z}await p0();import{log as W9}from"@stacksjs/logging";import{app as aO}from"@stacksjs/config";import{ok as tO}from"@stacksjs/error-handling";import{fetchOtherModelRelations as eO,getModelName as B_,getPivotTables as A_,getTableName as n5}from"@stacksjs/orm";import{path as Z9}from"@stacksjs/path";import{fs as y_,globSync as $Q}from"@stacksjs/storage";import{snakeCase as e8}from"@stacksjs/strings";function x_($){return`\x1B[3m${$}\x1B[23m`}async function vK(){return await l8(),await s8(),await ZQ(),tO("All tables dropped successfully!")}async function bK(){try{await v.unsafe("PRAGMA journal_mode = WAL").execute(),await v.unsafe("PRAGMA foreign_keys = ON").execute(),await v.unsafe("PRAGMA busy_timeout = 5000").execute()}catch($){W9.debug(`[sqlite] Failed to apply pragmas: ${$.message}`)}}async function ZQ(){let $=$Q([Z9.userModelsPath("*.ts"),Z9.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Z=await d5(),X=/^[a-z_][\w]*$/i;await v.unsafe("PRAGMA foreign_keys = OFF").execute();try{for(let _ of Z){if(!X.test(_))throw Error(`[sqlite] Refusing to drop table with unsafe name: ${_}`);await v.unsafe(`DROP TABLE IF EXISTS "${_}"`).execute()}await v.unsafe('DROP TABLE IF EXISTS "migrations"').execute(),await m5();for(let _ of $){let Y=(await import(_)).default,L=await A_(Y,_);for(let z of L){if(!X.test(z.table))throw Error(`[sqlite] Refusing to drop pivot table with unsafe name: ${z.table}`);await v.unsafe(`DROP TABLE IF EXISTS "${z.table}"`).execute()}}}finally{await v.unsafe("PRAGMA foreign_keys = ON").execute()}}function fK(){if(aO.env==="testing")return XQ();return Z9.userDatabasePath("stacks.sqlite")}function XQ(){return Z9.userDatabasePath("stacks_testing.sqlite")}async function gK($){let Z=(await import($)).default,X=Z9.basename($),_=await n5(Z,$),Y=JSON.stringify(Z.attributes,null,2),L=Z9.frameworkPath(`cache/models/${X}`),z=!1;if(y_.existsSync(L)){W9.debug(`Fields have already been generated for ${_}`);let U=await P9(X);if(JSON.stringify(U,null,2)===Y){W9.debug(`Fields have not changed for ${_}`);return}z=!0,W9.debug(`Fields have changed for ${_}`)}else W9.debug(`Fields have not been generated for ${_}`);await Bun.$`mkdir -p ${Z9.frameworkPath("cache/models")} && cp ${$} ${L}`;let j=!1;if(W9.debug(`Has ${_} been migrated? ${j}`),z)await LQ($);else await _Q($)}async function pK($){return}async function cK($){let Z=(await import($)).default,X=Z9.basename($),_=await n5(Z,$),Y=JSON.stringify(Z.attributes,null,2),L=Z9.frameworkPath(`cache/models/${X}`);if(y_.existsSync(L)){W9.debug(`Fields have already been generated for ${_}`);let z=await P9(X);if(JSON.stringify(z,null,2)===Y){W9.debug(`Fields have not changed for ${_}`);return}}await Bun.$`mkdir -p ${Z9.frameworkPath("cache/models")} && cp ${$} ${L}`}async function _Q($){W9.debug("createTableMigration modelPath:",$);let Z=(await import($)).default,X=n5(Z,$),_=B_(Z,$),Y=Z.traits?.useAuth&&typeof Z.traits.useAuth!=="boolean"?Z.traits.useAuth.useTwoFactor:!1;await YQ(Z,$);let L=await eO(_),z=Z?.traits?.useTimestamps??Z?.traits?.timestampable??!0,j=Z?.traits?.useSocials&&Array.isArray(Z.traits.useSocials)&&Z.traits.useSocials.length>0,U=Z?.traits?.likeable&&Array.isArray(Z.traits.likeable)&&Z.traits.likeable.length>0,Q=Z?.traits?.useSoftDeletes??Z?.traits?.softDeletable??!1,E=(typeof Z.traits?.useAuth==="object"&&Z.traits.useAuth.usePasskey)??!1,G=Z.traits?.billable||!1,F=Z.traits?.useUuid||!1,O=`import type { Database } from '@stacksjs/database'
|
|
679
|
+
`,U+=` await (db as any).schema
|
|
680
|
+
`,U+=` .createTable('${A}')
|
|
681
|
+
`,U+=` .addColumn('id', 'serial', (col) => col.primaryKey())
|
|
682
|
+
`,U+=` .addColumn('${E}', 'integer', (col) => col.notNull())
|
|
683
|
+
`,U+=` .addColumn('user_id', 'integer', (col) => col.notNull())
|
|
684
|
+
`,U+=` .addColumn('created_at', 'timestamptz', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
685
|
+
`,U+=` .addColumn('updated_at', 'timestamptz')
|
|
686
|
+
`,U+=` .execute()
|
|
687
|
+
|
|
688
|
+
`,U+=` // Add indexes for upvote table
|
|
689
|
+
`,U+=` await (db as any).schema.createIndex('${A}_${E}_index').on('${A}').column('${E}').execute()
|
|
690
|
+
`,U+=` await (db as any).schema.createIndex('${A}_user_${E}_unique').on('${A}').columns(['user_id', '${E}']).unique().execute()
|
|
691
|
+
`,U+=` await (db as any).schema.createIndex('${A}_id_index').on('${A}').column('id').execute()
|
|
692
|
+
`}}U+=`}
|
|
693
|
+
`;let O=`${new Date().getTime().toString()}-create-${$}-table.ts`,L=y.userMigrationsPath(O);await Bun.write(L,U),l.success(`Created migration: ${hZ(O)}`)}async function n8(Z,Y){let $=await H6(Z,Y),J=new Set;if(!$.length)return;for(let X of $){if(J.has(X.table))continue;if(await LY(X.table)){J.add(X.table);continue}let H=`import type { Database } from '@stacksjs/database'
|
|
694
|
+
`;H+=`import { sql } from '@stacksjs/database'
|
|
695
|
+
|
|
696
|
+
`,H+=`export async function up(db: Database<any>) {
|
|
697
|
+
`,H+=` await (db as any).schema
|
|
698
|
+
`,H+=` .createTable('${X.table}')
|
|
699
|
+
`,H+=` .addColumn('id', 'serial', (col) => col.primaryKey())
|
|
700
|
+
`,H+=` .addColumn('${X.firstForeignKey}', 'integer', (col) => col.notNull())
|
|
701
|
+
`,H+=` .addColumn('${X.secondForeignKey}', 'integer', (col) => col.notNull())
|
|
702
|
+
`,H+=` .addColumn('created_at', 'timestamptz', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
703
|
+
`,H+=` .execute()
|
|
704
|
+
|
|
705
|
+
`,H+=` await (db as any).schema
|
|
706
|
+
`,H+=` .alterTable('${X.table}')
|
|
707
|
+
`,H+=` .addForeignKeyConstraint('${X.table}_${X.firstForeignKey}_fkey', ['${X.firstForeignKey}'], '${s8(X.firstForeignKey?.replace(/_id$/,"")||"")}', ['id'], (cb) => cb.onDelete('cascade'))
|
|
708
|
+
`,H+=` .execute()
|
|
709
|
+
|
|
710
|
+
`,H+=` await (db as any).schema
|
|
711
|
+
`,H+=` .alterTable('${X.table}')
|
|
712
|
+
`,H+=` .addUniqueConstraint('${X.table}_unique', ['${X.firstForeignKey}', '${X.secondForeignKey}'])
|
|
713
|
+
`,H+=` .execute()
|
|
714
|
+
|
|
715
|
+
`,H+=` await (db as any).schema
|
|
716
|
+
`,H+=` .createIndex('${X.table}_${X.firstForeignKey}_idx')
|
|
717
|
+
`,H+=` .on('${X.table}')
|
|
718
|
+
`,H+=` .column('${X.firstForeignKey}')
|
|
719
|
+
`,H+=` .execute()
|
|
720
|
+
|
|
721
|
+
`,H+=` await (db as any).schema
|
|
722
|
+
`,H+=` .createIndex('${X.table}_${X.secondForeignKey}_idx')
|
|
723
|
+
`,H+=` .on('${X.table}')
|
|
724
|
+
`,H+=` .column('${X.secondForeignKey}')
|
|
725
|
+
`,H+=` .execute()
|
|
726
|
+
`,H+=`}
|
|
727
|
+
`;let z=`${new Date().getTime().toString()}-create-${X.table}-table.ts`,Q=y.userMigrationsPath(z);await Bun.write(Q,H),J.add(X.table),l.success(`Created migration: ${hZ(z)}`)}}async function i8(Z){let Y=(await import(Z)).default,$=m8(Y,Z),J=JZ(Y,Z),X=!1,H=await m($)??{},G=Y.attributes,z=EY(Object.keys(H),Object.keys(G)),Q=z?.added||[],_=z?.removed||[],U=`import type { Database } from '@stacksjs/database'
|
|
728
|
+
`;if(U+=`import { sql } from '@stacksjs/database'
|
|
729
|
+
|
|
730
|
+
`,U+=`export async function up(db: Database<any>) {
|
|
731
|
+
`,Q.length||_.length)X=!0,U+=` await (db as any).schema.alterTable('${J}')
|
|
732
|
+
`;for(let A of Q){let E=G[A],B=XY(E.validation?.rule,"postgres"),j=NZ(A),R="isRequired"in(E.validation?.rule??{})?(E.validation?.rule).isRequired:!1;if(U+=` .addColumn('${j}', '${B}'`,R||E.unique||E.default!==void 0){if(U+=", col => col",R)U+=".notNull()";if(E.unique)U+=".unique()";if(E.default!==void 0)if(typeof E.default==="string")U+=`.defaultTo('${E.default}')`;else if(E.default===null)U+=".defaultTo(null)";else U+=`.defaultTo(${E.default})`;U+=""}U+=`)
|
|
733
|
+
`}for(let A of _)U+=` .dropColumn('${A}')
|
|
734
|
+
`;let I=KY(H,G);for(let A of I){X=!0;let E=NZ(A.key);U+=` .alterColumn('${E}', (col) => col.setDataType('text'))
|
|
735
|
+
`}let O=Object.values(H).map((A)=>A.order),L=Object.values(G).map((A)=>A.order);if(!IY(O,L))X=!0;if(X){U+=` .execute()
|
|
736
|
+
`,U+=`}
|
|
737
|
+
`;let E=`${new Date().getTime().toString()}-alter-${J}-table.ts`,B=y.userMigrationsPath(E);await Bun.write(B,U),l.success(`Created alter migration: ${hZ(E)}`)}}function a8(Z){return` await (db as any).schema.createIndex('${Z}_id_index').on('${Z}').column('id').execute()
|
|
738
|
+
`}async function o8(){let Z=G6([y.userModelsPath("*.ts"),y.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Y=[];for(let $ of Z){let J=(await import($)).default,X=JZ(J,$);Y.push(X)}return Y}F();import{log as c}from"@stacksjs/logging";import{app as t8}from"@stacksjs/config";import{ok as e8}from"@stacksjs/error-handling";import{fetchOtherModelRelations as Y$,getModelName as U6,getPivotTables as Q6,getTableName as XZ}from"@stacksjs/orm";import{path as b}from"@stacksjs/path";import{fs as _6,globSync as Z$}from"@stacksjs/storage";import{snakeCase as UY}from"@stacksjs/strings";function z6(Z){return`\x1B[3m${Z}\x1B[23m`}async function t1(){return await BY(),await AY(),await $$(),e8("All tables dropped successfully!")}async function e1(){try{for(let Z of OZ)await V.unsafe(Z).execute()}catch(Z){c.debug(`[sqlite] Failed to apply pragmas: ${Z.message}`)}}async function $$(){let Z=Z$([b.userModelsPath("*.ts"),b.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),Y=await eY(),$=/^[a-z_][\w]*$/i;await V.unsafe("PRAGMA foreign_keys = OFF").execute();try{for(let J of Y){if(!$.test(J))throw Error(`[sqlite] Refusing to drop table with unsafe name: ${J}`);await V.unsafe(`DROP TABLE IF EXISTS "${J}"`).execute()}await V.unsafe('DROP TABLE IF EXISTS "migrations"').execute(),await ZZ();for(let J of Z){let X=(await import(J)).default,W=await Q6(X,J);for(let H of W){if(!$.test(H.table))throw Error(`[sqlite] Refusing to drop pivot table with unsafe name: ${H.table}`);await V.unsafe(`DROP TABLE IF EXISTS "${H.table}"`).execute()}}}finally{await V.unsafe("PRAGMA foreign_keys = ON").execute()}}function Y9(){if(t8.env==="testing")return J$();return b.userDatabasePath("stacks.sqlite")}function J$(){return b.userDatabasePath("stacks_testing.sqlite")}async function Z9(Z){let Y=(await import(Z)).default,$=b.basename(Z),J=await XZ(Y,Z),X=JSON.stringify(Y.attributes,null,2),W=b.frameworkPath(`cache/models/${$}`),H=!1;if(_6.existsSync(W)){c.debug(`Fields have already been generated for ${J}`);let z=await m($);if(JSON.stringify(z,null,2)===X){c.debug(`Fields have not changed for ${J}`);return}H=!0,c.debug(`Fields have changed for ${J}`)}else c.debug(`Fields have not been generated for ${J}`);await Bun.$`mkdir -p ${b.frameworkPath("cache/models")} && cp ${Z} ${W}`;let G=!1;if(c.debug(`Has ${J} been migrated? ${G}`),H)await H$(Z);else await X$(Z)}async function $9(Z){let Y=(await import(Z)).default,$=b.basename(Z),J=await XZ(Y,Z),X=JSON.stringify(Y.attributes,null,2),W=b.frameworkPath(`cache/models/${$}`);if(_6.existsSync(W)){c.debug(`Fields have already been generated for ${J}`);let H=await m($);if(JSON.stringify(H,null,2)===X){c.debug(`Fields have not changed for ${J}`);return}}await Bun.$`mkdir -p ${b.frameworkPath("cache/models")} && cp ${Z} ${W}`}async function X$(Z){c.debug("createTableMigration modelPath:",Z);let Y=(await import(Z)).default,$=XZ(Y,Z),J=U6(Y,Z),X=Y.traits?.useAuth&&typeof Y.traits.useAuth!=="boolean"?Y.traits.useAuth.useTwoFactor:!1;await W$(Y,Z);let W=await Y$(J),H=Y?.traits?.useTimestamps??Y?.traits?.timestampable??!0,G=Y?.traits?.useSocials&&Array.isArray(Y.traits.useSocials)&&Y.traits.useSocials.length>0,z=Array.isArray(Y?.traits?.likeable)?Y.traits.likeable.length>0:Boolean(Y?.traits?.likeable),Q=Y?.traits?.useSoftDeletes??Y?.traits?.softDeletable??!1,_=(typeof Y.traits?.useAuth==="object"&&Y.traits.useAuth.usePasskey)??!1,U=Y.traits?.billable||!1,I=Y.traits?.useUuid||!1,O=`import type { Database } from '@stacksjs/database'
|
|
881
739
|
`;if(O+=`import { sql } from '@stacksjs/database'
|
|
882
740
|
|
|
883
741
|
`,O+=`export async function up(db: Database<any>) {
|
|
884
742
|
`,O+=` await (db as any).schema
|
|
885
|
-
`,O+=` .createTable('${
|
|
743
|
+
`,O+=` .createTable('${$}')
|
|
886
744
|
`,O+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
887
|
-
`,
|
|
888
|
-
`;if(
|
|
889
|
-
`;if(
|
|
890
|
-
`;if(
|
|
891
|
-
`;if(
|
|
892
|
-
|
|
893
|
-
`}
|
|
894
|
-
|
|
745
|
+
`,I)O+=` .addColumn('uuid', 'text')
|
|
746
|
+
`;if(G){let B=Y.traits?.useSocials||[];if(B.includes("google"))O+=` .addColumn('google_id', 'text')
|
|
747
|
+
`;if(B.includes("github"))O+=` .addColumn('github_id', 'text')
|
|
748
|
+
`;if(B.includes("apple"))O+=` .addColumn('apple_id', 'text')
|
|
749
|
+
`;if(B.includes("twitter"))O+=` .addColumn('twitter_id', 'text')
|
|
750
|
+
`;if(B.includes("facebook"))O+=` .addColumn('facebook_id', 'text')
|
|
751
|
+
`}for(let[B,j]of JY(Y.attributes)){let R=j,f=UY(B),sY=XY(R.validation?.rule,"sqlite");O+=` .addColumn('${f}', ${sY}`;let D=R.validation?.rule.isRequired;if(D||R.unique||R.default!==void 0){if(O+=", col => col",D)O+=".notNull()";if(R.unique)O+=".unique()";if(R.default!==void 0)if(typeof R.default==="string")O+=`.defaultTo('${R.default}')`;else if(R.default===null)O+=".defaultTo(null)";else O+=`.defaultTo(${R.default})`;O+=""}O+=`)
|
|
752
|
+
`}if(X!==!1&&X)O+=` .addColumn('two_factor_secret', 'text')
|
|
753
|
+
`;if(U)O+=` .addColumn('stripe_id', 'text')
|
|
895
754
|
`;if(Q)O+=` .addColumn('deleted_at', 'timestamp')
|
|
896
|
-
`;if(
|
|
897
|
-
`;if(
|
|
898
|
-
col.references('${
|
|
755
|
+
`;if(_)O+=` .addColumn('public_passkey', 'text')
|
|
756
|
+
`;if(W?.length)for(let B of W){if(!B.foreignKey)continue;O+=` .addColumn('${B.foreignKey}', 'integer', (col) =>
|
|
757
|
+
col.references('${B.relationTable}.id').onDelete('cascade')
|
|
899
758
|
)
|
|
900
|
-
`}if(
|
|
759
|
+
`}if(H)O+=" .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`))\n",O+=` .addColumn('updated_at', 'timestamp')
|
|
901
760
|
`;if(O+=` .execute()
|
|
902
761
|
|
|
903
|
-
`,
|
|
904
|
-
`;for(let
|
|
762
|
+
`,W?.length)for(let B of W){if(!B.foreignKey)continue;O+=U$($,B.foreignKey)}if(Y.indexes?.length){O+=`
|
|
763
|
+
`;for(let B of Y.indexes)O+=O6($,B)}if(O+=z$($),z){let B=zY(Y,$);if(B){let j=jY(Y,$);O+=`
|
|
905
764
|
// Create upvote table
|
|
906
765
|
`,O+=` await (db as any).schema
|
|
907
|
-
`,O+=` .createTable('${
|
|
766
|
+
`,O+=` .createTable('${B}')
|
|
908
767
|
`,O+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
909
|
-
`,O+=` .addColumn('${
|
|
768
|
+
`,O+=` .addColumn('${j}', 'integer', col => col.notNull())
|
|
910
769
|
`,O+=` .addColumn('user_id', 'integer', col => col.notNull())
|
|
911
770
|
`,O+=" .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`))\n",O+=` .addColumn('updated_at', 'timestamp')
|
|
912
771
|
`,O+=` .execute()
|
|
913
772
|
|
|
914
773
|
`,O+=` // Add indexes for upvote table
|
|
915
|
-
`,O+=` await (db as any).schema.createIndex('${
|
|
916
|
-
`,O+=` await (db as any).schema.createIndex('${
|
|
917
|
-
`,O+=` await (db as any).schema.createIndex('${
|
|
918
|
-
`}O+=`}
|
|
919
|
-
`;let
|
|
920
|
-
`;
|
|
921
|
-
|
|
922
|
-
`,
|
|
923
|
-
`,
|
|
924
|
-
`,
|
|
925
|
-
`,
|
|
926
|
-
`,
|
|
927
|
-
`,
|
|
928
|
-
`,
|
|
929
|
-
`,
|
|
930
|
-
`,
|
|
931
|
-
`;let
|
|
774
|
+
`,O+=` await (db as any).schema.createIndex('${B}_${j}_index').on('${B}').column('${j}').execute()
|
|
775
|
+
`,O+=` await (db as any).schema.createIndex('${B}_user_${j}_unique').on('${B}').columns(['user_id', '${j}']).unique().execute()
|
|
776
|
+
`,O+=` await (db as any).schema.createIndex('${B}_id_index').on('${B}').column('id').execute()
|
|
777
|
+
`}}O+=`}
|
|
778
|
+
`;let A=`${new Date().getTime().toString()}-create-${$}-table.ts`,E=b.userMigrationsPath(A);await Bun.write(E,O),c.success(`Created migration: ${z6(A)}`)}async function W$(Z,Y){let $=await Q6(Z,Y);if(!$.length)return;for(let J of $){if(await LY(J.table))return;let W=`import type { Database } from '@stacksjs/database'
|
|
779
|
+
`;W+=`import { sql } from '@stacksjs/database'
|
|
780
|
+
|
|
781
|
+
`,W+=`export async function up(db: Database<any>) {
|
|
782
|
+
`,W+=` await (db as any).schema
|
|
783
|
+
`,W+=` .createTable('${J.table}')
|
|
784
|
+
`,W+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
785
|
+
`,W+=` .addColumn('${J.firstForeignKey}', 'integer')
|
|
786
|
+
`,W+=` .addColumn('${J.secondForeignKey}', 'integer')
|
|
787
|
+
`,W+=` .addColumn('created_at', 'timestamp', col => col.defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
788
|
+
`,W+=` .execute()
|
|
789
|
+
`,W+=` }
|
|
790
|
+
`;let G=`${new Date().getTime().toString()}-create-${J.table}-table.ts`,z=b.userMigrationsPath(G);await Bun.write(z,W),c.success(`Created pivot migration: ${G}`)}}async function H$(Z){let Y=(await import(Z)).default,$=U6(Y,Z),J=XZ(Y,Z),X=!1,H=(await import(b.frameworkPath(`cache/models/${$}.ts`))).default,z=await m($)??{},Q=Y.attributes,_=EY(Object.keys(z),Object.keys(Q)),U=_?.added||[],I=_?.removed||[],O=`import type { Database } from '@stacksjs/database'
|
|
932
791
|
`;if(O+=`import { sql } from '@stacksjs/database'
|
|
933
792
|
|
|
934
793
|
`,O+=`export async function up(db: Database<any>) {
|
|
935
|
-
`,
|
|
936
|
-
`;let
|
|
937
|
-
ALTER TABLE ${
|
|
938
|
-
MODIFY COLUMN ${
|
|
794
|
+
`,U.length||I.length)X=!0,O+=` await (db as any).schema.alterTable('${J}')
|
|
795
|
+
`;let L=KY(z,Q);for(let D of L){X=!0;let x=UY(D.key);O+=`await sql\`
|
|
796
|
+
ALTER TABLE ${J}
|
|
797
|
+
MODIFY COLUMN ${x} TEXT
|
|
939
798
|
\`.execute(db)
|
|
940
799
|
|
|
941
|
-
`}for(let
|
|
800
|
+
`}for(let D of U){let x=Q[D],w=XY(x.validation?.rule,"sqlite"),g=UY(D),GY=x.validation?.rule.isRequired;if(O+=` .addColumn('${g}', ${w}`,GY||x.unique||x.default!==void 0){if(O+=", col => col",GY)O+=".notNull()";if(x.unique)O+=".unique()";if(x.default!==void 0)if(typeof x.default==="string")O+=`.defaultTo('${x.default}')`;else if(x.default===null)O+=".defaultTo(null)";else O+=`.defaultTo(${x.default})`;O+=""}O+=`)
|
|
942
801
|
|
|
943
|
-
`}for(let
|
|
944
|
-
`;if(
|
|
945
|
-
`;let
|
|
946
|
-
`;for(let
|
|
947
|
-
`;let
|
|
948
|
-
ALTER TABLE ${
|
|
949
|
-
MODIFY COLUMN ${
|
|
802
|
+
`}for(let D of I)O+=` .dropColumn('${D}')
|
|
803
|
+
`;if(U.length||I.length)O+=` .execute();
|
|
804
|
+
`;let A=Object.values(z).map((D)=>D.order),E=Object.values(Q).map((D)=>D.order);if(!IY(A,E))X=!0,O+=G$(Y.attributes,J);let B=H.indexes||[],j=Y.indexes||[];for(let D of B)if(!j.find((x)=>x.name===D.name))X=!0,O+=` await (db as any).schema.dropIndex('${D.name}').execute()
|
|
805
|
+
`;for(let D of j)if(!B.find((x)=>x.name===D.name))X=!0,O+=O6(J,D);O+=`}
|
|
806
|
+
`;let f=`${new Date().getTime().toString()}-update-${J}-table.ts`,sY=b.userMigrationsPath(f);if(X)await Bun.write(sY,O),c.success(`Created migration: ${z6(f)}`)}function G$(Z,Y){let $=JY(Z),J="",X="";for(let[W]of $){let H=UY(W);if(X)J+=`await sql\`
|
|
807
|
+
ALTER TABLE ${Y}
|
|
808
|
+
MODIFY COLUMN ${H} TEXT NOT NULL AFTER ${UY(X)};
|
|
950
809
|
\`.execute(db)
|
|
951
810
|
|
|
952
|
-
`;
|
|
953
|
-
`}
|
|
954
|
-
`}function
|
|
811
|
+
`;X=H}return J}function O6(Z,Y){if(Y.unique||Y.where){let J=Y.unique?"UNIQUE ":"",X=Y.columns.map((H)=>UY(H)).join(", "),W=Y.where?` WHERE ${Y.where}`:"";return` await db.unsafe(\`CREATE ${J}INDEX IF NOT EXISTS "${Y.name}" ON "${Z}" (${X})${W}\`).execute()
|
|
812
|
+
`}let $=Y.columns.map((J)=>`\`${UY(J)}\``).join(", ");return` await (db as any).schema.createIndex('${Y.name}').on('${Z}').columns([${$}]).execute()
|
|
813
|
+
`}function z$(Z){return` await (db as any).schema.createIndex('${Z}_id_index').on('${Z}').column('id').execute()
|
|
814
|
+
`}function U$(Z,Y){return` await (db as any).schema.createIndex('${Z}_${Y}_index').on('${Z}').column(\`${Y}\`).execute()
|
|
955
815
|
|
|
956
|
-
`}function i6($){if($===null||$===void 0)return{NULL:!0};if(typeof $==="string")return{S:$};if(typeof $==="number")return{N:String($)};if(typeof $==="boolean")return{BOOL:$};if(Array.isArray($))return{L:$.map((Z)=>i6(Z))};if(typeof $==="object"){let Z={};for(let[X,_]of Object.entries($))Z[X]=i6(_);return{M:Z}}return{S:String($)}}function r6($){if($.NULL)return null;if($.S!==void 0)return $.S;if($.N!==void 0)return Number($.N);if($.BOOL!==void 0)return $.BOOL;if($.L!==void 0)return $.L.map((Z)=>r6(Z));if($.M!==void 0){let Z={};for(let[X,_]of Object.entries($.M))Z[X]=r6(_);return Z}if($.SS!==void 0)return $.SS;if($.NS!==void 0)return $.NS.map((Z)=>Number(Z));if($.B!==void 0)return $.B;if($.BS!==void 0)return $.BS;return null}function i0($){let Z={};for(let[X,_]of Object.entries($))Z[X]=i6(_);return Z}function e1($){let Z={};for(let[X,_]of Object.entries($))Z[X]=r6(_);return Z}class o6{client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor($,Z,X){this.client=$,this.tableName=Z,this.pkAttribute=X.pkAttribute,this.skAttribute=X.skAttribute,this.entityTypeAttr=X.entityTypeAttribute,this.delimiter=X.keyDelimiter}entity($){return this._entityType=$,this}pk($){return this._pkValue=$,this}get sk(){let $=this;return{equals(Z){return $._skCondition={type:"eq",value:Z},$},beginsWith(Z){return $._skCondition={type:"begins_with",value:Z},$},between(Z,X){return $._skCondition={type:"between",value:Z,value2:X},$},lt(Z){return $._skCondition={type:"lt",value:Z},$},lte(Z){return $._skCondition={type:"lte",value:Z},$},gt(Z){return $._skCondition={type:"gt",value:Z},$},gte(Z){return $._skCondition={type:"gte",value:Z},$}}}index($){return this._indexName=$,this}project(...$){return this._projectionAttrs.push(...$),this}filter($,Z,X){return this._filterConditions.push({attribute:$,operator:Z,value:X}),this}where($,Z){return this.filter($,"=",Z)}whereIn($,Z){return this._filterConditions.push({attribute:$,operator:"IN",values:Z}),this}limit($){return this._limitValue=$,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom($){return this._startKey=$,this}toRequest(){let $={TableName:this.tableName};if(this._indexName)$.IndexName=this._indexName;let Z=[],X={},_={},Y=0;if(this._pkValue){let L=`#pk${Y}`,z=`:pk${Y}`;X[L]=this.pkAttribute,_[z]={S:this._pkValue},Z.push(`${L} = ${z}`),Y++}if(this._skCondition){let L=`#sk${Y}`;switch(X[L]=this.skAttribute,this._skCondition.type){case"eq":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} = ${z}`);break}case"begins_with":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`begins_with(${L}, ${z})`);break}case"between":{let z=`:sk${Y}a`,j=`:sk${Y}b`;_[z]={S:this._skCondition.value},_[j]={S:this._skCondition.value2},Z.push(`${L} BETWEEN ${z} AND ${j}`);break}case"lt":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} < ${z}`);break}case"lte":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} <= ${z}`);break}case"gt":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} > ${z}`);break}case"gte":{let z=`:sk${Y}`;_[z]={S:this._skCondition.value},Z.push(`${L} >= ${z}`);break}}Y++}if(Z.length>0)$.KeyConditionExpression=Z.join(" AND ");if(this._filterConditions.length>0){let L=[];for(let z of this._filterConditions){let j=`#flt${Y}`;if(X[j]=z.attribute,z.operator==="IN"&&z.values){let U=z.values.map((Q,E)=>`:flt${Y}_${E}`);z.values.forEach((Q,E)=>{_[`:flt${Y}_${E}`]=i0({v:Q}).v}),L.push(`${j} IN (${U.join(", ")})`)}else{let U=`:flt${Y}`;_[U]=i0({v:z.value}).v,L.push(`${j} ${z.operator} ${U}`)}Y++}$.FilterExpression=L.join(" AND ")}if(this._projectionAttrs.length>0){let L=[];for(let z of this._projectionAttrs){let j=`#proj${Y}`;X[j]=z,L.push(j),Y++}$.ProjectionExpression=L.join(", ")}if(Object.keys(X).length>0)$.ExpressionAttributeNames=X;if(Object.keys(_).length>0)$.ExpressionAttributeValues=_;if(this._limitValue!==void 0)$.Limit=this._limitValue;if($.ScanIndexForward=this._scanForward,this._consistentRead)$.ConsistentRead=!0;if(this._startKey)$.ExclusiveStartKey=i0(this._startKey);return $}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let $=this.toRequest();return((this._pkValue!==void 0?await this.client.query($):await this.client.scan($)).Items??[]).map((_)=>e1(_))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let $=[],Z;do{if(Z)this._startKey=Z;let X=this.toRequest(),Y=this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X),L=(Y.Items??[]).map((z)=>e1(z));$.push(...L),Z=Y.LastEvaluatedKey?e1(Y.LastEvaluatedKey):void 0}while(Z);return $}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let $=this.toRequest();return $.Select="COUNT",(this._pkValue!==void 0?await this.client.query($):await this.client.scan($)).Count??0}}class a6{client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;_configured=!1;connection($){return this.tableName=$.table,this.pkAttribute=$.pkAttribute??"pk",this.skAttribute=$.skAttribute??"sk",this.entityTypeAttr=$.entityTypeAttribute??"_et",this.delimiter=$.keyDelimiter??"#",this._configured=!0,this}isConfigured(){return this._configured}setClient($){return this.client=$,this}getClient(){return this.client}registerEntity($){return this.entityMappings.set($.entityType,$),this}registerModel($){let Z=$.name??"Unknown",X=Z.toUpperCase(),_={entityType:Z,pkPattern:`${X}#{id}`,skPattern:`${X}#{id}`};return this.entityMappings.set(Z,_),this}getEntityMapping($){return this.entityMappings.get($)}entity($){if(!this._configured)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new o6(this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity($)}async batchWrite($){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this._configured)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let Z=[];for(let X of $)if(X.put){let _={...X.put.item,[this.entityTypeAttr]:X.put.entity};Z.push({PutRequest:{Item:i0(_)}})}else if(X.delete)Z.push({DeleteRequest:{Key:i0({[this.pkAttribute]:X.delete.pk,[this.skAttribute]:X.delete.sk})}});if(Z.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:Z}})}async transactWrite($){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this._configured)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let Z=[];for(let X of $)if(X.put){let _={...X.put.item,[this.entityTypeAttr]:X.put.entity},Y={Put:{TableName:this.tableName,Item:i0(_)}};if(X.put.condition)Y.Put.ConditionExpression=X.put.condition;Z.push(Y)}else if(X.update){let _={[this.pkAttribute]:X.update.pk};if(X.update.sk)_[this.skAttribute]=X.update.sk;let Y=[],L={},z={},j=0;if(X.update.set){let U=[];for(let[Q,E]of Object.entries(X.update.set)){let G=`#set${j}`,F=`:set${j}`;L[G]=Q,z[F]=i0({v:E}).v,U.push(`${G} = ${F}`),j++}if(U.length>0)Y.push(`SET ${U.join(", ")}`)}if(X.update.add){let U=[];for(let[Q,E]of Object.entries(X.update.add)){let G=`#add${j}`,F=`:add${j}`;L[G]=Q,z[F]={N:String(E)},U.push(`${G} ${F}`),j++}if(U.length>0)Y.push(`ADD ${U.join(", ")}`)}if(X.update.remove&&X.update.remove.length>0){let U=[];for(let Q of X.update.remove){let E=`#rem${j}`;L[E]=Q,U.push(E),j++}Y.push(`REMOVE ${U.join(", ")}`)}Z.push({Update:{TableName:this.tableName,Key:i0(_),UpdateExpression:Y.join(" "),ExpressionAttributeNames:L,ExpressionAttributeValues:z}})}else if(X.delete){let _={Delete:{TableName:this.tableName,Key:i0({[this.pkAttribute]:X.delete.pk,[this.skAttribute]:X.delete.sk})}};if(X.delete.condition)_.Delete.ConditionExpression=X.delete.condition;Z.push(_)}else if(X.conditionCheck)Z.push({ConditionCheck:{TableName:this.tableName,Key:i0({[this.pkAttribute]:X.conditionCheck.pk,[this.skAttribute]:X.conditionCheck.sk}),ConditionExpression:X.conditionCheck.condition}});if(Z.length>0)await this.client.transactWriteItems({TransactItems:Z})}async put($,Z){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let X={...Z,[this.entityTypeAttr]:$};await this.client.putItem({TableName:this.tableName,Item:i0(X)})}async get($,Z){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let X={[this.pkAttribute]:$};if(Z)X[this.skAttribute]=Z;let _=await this.client.getItem({TableName:this.tableName,Key:i0(X)});if(!_.Item)return;return e1(_.Item)}async delete($,Z){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let X={[this.pkAttribute]:$};if(Z)X[this.skAttribute]=Z;await this.client.deleteItem({TableName:this.tableName,Key:i0(X)})}async update($,Z,X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let _={[this.pkAttribute]:$};if(Z)_[this.skAttribute]=Z;let Y=[],L={},z={},j=0,U=[];for(let[Q,E]of Object.entries(X)){let G=`#upd${j}`,F=`:upd${j}`;L[G]=Q,z[F]=i0({v:E}).v,U.push(`${G} = ${F}`),j++}if(U.length>0)Y.push(`SET ${U.join(", ")}`);await this.client.updateItem({TableName:this.tableName,Key:i0(_),UpdateExpression:Y.join(" "),ExpressionAttributeNames:L,ExpressionAttributeValues:z})}getTableName(){return this.tableName}getConfig(){return{tableName:this.tableName,pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}}}function EQ($,Z="id"){return`${$.toUpperCase()}#{${Z}}`}function OQ($,Z){let X={},_=$.split("#"),Y=Z.split("#");for(let L=0;L<_.length;L++){let z=_[L],j=Y[L];if(z?.startsWith("{")&&z.endsWith("}")){let U=z.slice(1,-1);X[U]=j??""}}return X}function QQ($,Z){let X=$;for(let[_,Y]of Object.entries(Z))X=X.replace(`{${_}}`,Y);return X}var GQ=new a6;function FQ(){return new a6}import{log as VQ}from"@stacksjs/logging";import{database as WQ}from"@stacksjs/config";import{path as KQ}from"@stacksjs/path";async function YI(){if(!["sqlite","mysql"].includes(IQ()))return;if(await X8("model_audits"))return;let Z=`import type { Database } from '@stacksjs/database'
|
|
816
|
+
`}function vZ(Z){if(Z===null||Z===void 0)return{NULL:!0};if(typeof Z==="string")return{S:Z};if(typeof Z==="number")return{N:String(Z)};if(typeof Z==="boolean")return{BOOL:Z};if(Array.isArray(Z))return{L:Z.map((Y)=>vZ(Y))};if(typeof Z==="object"){let Y={};for(let[$,J]of Object.entries(Z))Y[$]=vZ(J);return{M:Y}}return{S:String(Z)}}function fZ(Z){if("NULL"in Z&&Z.NULL)return null;if("S"in Z&&Z.S!==void 0)return Z.S;if("N"in Z&&Z.N!==void 0)return Number(Z.N);if("BOOL"in Z&&Z.BOOL!==void 0)return Z.BOOL;if("L"in Z&&Z.L!==void 0)return Z.L.map((Y)=>fZ(Y));if("M"in Z&&Z.M!==void 0){let Y={};for(let[$,J]of Object.entries(Z.M))Y[$]=fZ(J);return Y}if("SS"in Z&&Z.SS!==void 0)return Z.SS;if("NS"in Z&&Z.NS!==void 0)return Z.NS.map((Y)=>Number(Y));if("B"in Z&&Z.B!==void 0)return Z.B;if("BS"in Z&&Z.BS!==void 0)return Z.BS;return null}function h(Z){let Y={};for(let[$,J]of Object.entries(Z))Y[$]=vZ(J);return Y}function uY(Z){let Y={};for(let[$,J]of Object.entries(Z))Y[$]=fZ(J);return Y}class bZ{client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(Z,Y,$){this.client=Z,this.tableName=Y,this.pkAttribute=$.pkAttribute,this.skAttribute=$.skAttribute,this.entityTypeAttr=$.entityTypeAttribute,this.delimiter=$.keyDelimiter}entity(Z){return this._entityType=Z,this}pk(Z){return this._pkValue=Z,this}get sk(){let Z=this;return{equals(Y){return Z._skCondition={type:"eq",value:Y},Z},beginsWith(Y){return Z._skCondition={type:"begins_with",value:Y},Z},between(Y,$){return Z._skCondition={type:"between",value:Y,value2:$},Z},lt(Y){return Z._skCondition={type:"lt",value:Y},Z},lte(Y){return Z._skCondition={type:"lte",value:Y},Z},gt(Y){return Z._skCondition={type:"gt",value:Y},Z},gte(Y){return Z._skCondition={type:"gte",value:Y},Z}}}index(Z){return this._indexName=Z,this}project(...Z){return this._projectionAttrs.push(...Z),this}filter(Z,Y,$){return this._filterConditions.push({attribute:Z,operator:Y,value:$}),this}where(Z,Y){return this.filter(Z,"=",Y)}whereIn(Z,Y){return this._filterConditions.push({attribute:Z,operator:"IN",values:Y}),this}limit(Z){return this._limitValue=Z,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(Z){return this._startKey=Z,this}toRequest(){let Z={TableName:this.tableName};if(this._indexName)Z.IndexName=this._indexName;let Y=[],$={},J={},X=0;if(this._pkValue){let W=`#pk${X}`,H=`:pk${X}`;$[W]=this.pkAttribute,J[H]={S:this._pkValue},Y.push(`${W} = ${H}`),X++}if(this._skCondition){let W=`#sk${X}`;switch($[W]=this.skAttribute,this._skCondition.type){case"eq":{let H=`:sk${X}`;J[H]={S:this._skCondition.value},Y.push(`${W} = ${H}`);break}case"begins_with":{let H=`:sk${X}`;J[H]={S:this._skCondition.value},Y.push(`begins_with(${W}, ${H})`);break}case"between":{let H=`:sk${X}a`,G=`:sk${X}b`;J[H]={S:this._skCondition.value},J[G]={S:this._skCondition.value2},Y.push(`${W} BETWEEN ${H} AND ${G}`);break}case"lt":{let H=`:sk${X}`;J[H]={S:this._skCondition.value},Y.push(`${W} < ${H}`);break}case"lte":{let H=`:sk${X}`;J[H]={S:this._skCondition.value},Y.push(`${W} <= ${H}`);break}case"gt":{let H=`:sk${X}`;J[H]={S:this._skCondition.value},Y.push(`${W} > ${H}`);break}case"gte":{let H=`:sk${X}`;J[H]={S:this._skCondition.value},Y.push(`${W} >= ${H}`);break}}X++}if(Y.length>0)Z.KeyConditionExpression=Y.join(" AND ");if(this._filterConditions.length>0){let W=[];for(let H of this._filterConditions){let G=`#flt${X}`;if($[G]=H.attribute,H.operator==="IN"&&H.values){let z=H.values.map((Q,_)=>`:flt${X}_${_}`);H.values.forEach((Q,_)=>{J[`:flt${X}_${_}`]=h({v:Q}).v}),W.push(`${G} IN (${z.join(", ")})`)}else{let z=`:flt${X}`;J[z]=h({v:H.value}).v,W.push(`${G} ${H.operator} ${z}`)}X++}Z.FilterExpression=W.join(" AND ")}if(this._projectionAttrs.length>0){let W=[];for(let H of this._projectionAttrs){let G=`#proj${X}`;$[G]=H,W.push(G),X++}Z.ProjectionExpression=W.join(", ")}if(Object.keys($).length>0)Z.ExpressionAttributeNames=$;if(Object.keys(J).length>0)Z.ExpressionAttributeValues=J;if(this._limitValue!==void 0)Z.Limit=this._limitValue;if(Z.ScanIndexForward=this._scanForward,this._consistentRead)Z.ConsistentRead=!0;if(this._startKey)Z.ExclusiveStartKey=h(this._startKey);return Z}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let Z=this.toRequest();return((this._pkValue!==void 0?await this.client.query(Z):await this.client.scan(Z)).Items??[]).map((J)=>uY(J))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let Z=[],Y;do{if(Y)this._startKey=Y;let $=this.toRequest(),X=this._pkValue!==void 0?await this.client.query($):await this.client.scan($),W=(X.Items??[]).map((H)=>uY(H));Z.push(...W),Y=X.LastEvaluatedKey?uY(X.LastEvaluatedKey):void 0}while(Y);return Z}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let Z=this.toRequest();return Z.Select="COUNT",(this._pkValue!==void 0?await this.client.query(Z):await this.client.scan(Z)).Count??0}}class pZ{client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;_configured=!1;connection(Z){return this.tableName=Z.table,this.pkAttribute=Z.pkAttribute??"pk",this.skAttribute=Z.skAttribute??"sk",this.entityTypeAttr=Z.entityTypeAttribute??"_et",this.delimiter=Z.keyDelimiter??"#",this._configured=!0,this}isConfigured(){return this._configured}setClient(Z){return this.client=Z,this}getClient(){return this.client}registerEntity(Z){return this.entityMappings.set(Z.entityType,Z),this}registerModel(Z){let Y=Z.name??"Unknown",$=Y.toUpperCase(),J={entityType:Y,pkPattern:`${$}#{id}`,skPattern:`${$}#{id}`};return this.entityMappings.set(Y,J),this}getEntityMapping(Z){return this.entityMappings.get(Z)}entity(Z){if(!this._configured)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new bZ(this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(Z)}async batchWrite(Z){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this._configured)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let Y=[];for(let $ of Z)if($.put){let J={...$.put.item,[this.entityTypeAttr]:$.put.entity};Y.push({PutRequest:{Item:h(J)}})}else if($.delete)Y.push({DeleteRequest:{Key:h({[this.pkAttribute]:$.delete.pk,[this.skAttribute]:$.delete.sk})}});if(Y.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:Y}})}async transactWrite(Z){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this._configured)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let Y=[];for(let $ of Z)if($.put){let J={...$.put.item,[this.entityTypeAttr]:$.put.entity},X={TableName:this.tableName,Item:h(J)};if($.put.condition)X.ConditionExpression=$.put.condition;Y.push({Put:X})}else if($.update){let J={[this.pkAttribute]:$.update.pk};if($.update.sk)J[this.skAttribute]=$.update.sk;let X=[],W={},H={},G=0;if($.update.set){let z=[];for(let[Q,_]of Object.entries($.update.set)){let U=`#set${G}`,I=`:set${G}`;W[U]=Q,H[I]=h({v:_}).v,z.push(`${U} = ${I}`),G++}if(z.length>0)X.push(`SET ${z.join(", ")}`)}if($.update.add){let z=[];for(let[Q,_]of Object.entries($.update.add)){let U=`#add${G}`,I=`:add${G}`;W[U]=Q,H[I]={N:String(_)},z.push(`${U} ${I}`),G++}if(z.length>0)X.push(`ADD ${z.join(", ")}`)}if($.update.remove&&$.update.remove.length>0){let z=[];for(let Q of $.update.remove){let _=`#rem${G}`;W[_]=Q,z.push(_),G++}X.push(`REMOVE ${z.join(", ")}`)}Y.push({Update:{TableName:this.tableName,Key:h(J),UpdateExpression:X.join(" "),ExpressionAttributeNames:W,ExpressionAttributeValues:H}})}else if($.delete){let J={TableName:this.tableName,Key:h({[this.pkAttribute]:$.delete.pk,[this.skAttribute]:$.delete.sk})};if($.delete.condition)J.ConditionExpression=$.delete.condition;Y.push({Delete:J})}else if($.conditionCheck)Y.push({ConditionCheck:{TableName:this.tableName,Key:h({[this.pkAttribute]:$.conditionCheck.pk,[this.skAttribute]:$.conditionCheck.sk}),ConditionExpression:$.conditionCheck.condition}});if(Y.length>0)await this.client.transactWriteItems({TransactItems:Y})}async put(Z,Y){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let $={...Y,[this.entityTypeAttr]:Z};await this.client.putItem({TableName:this.tableName,Item:h($)})}async get(Z,Y){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let $={[this.pkAttribute]:Z};if(Y)$[this.skAttribute]=Y;let J=await this.client.getItem({TableName:this.tableName,Key:h($)});if(!J.Item)return;return uY(J.Item)}async delete(Z,Y){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let $={[this.pkAttribute]:Z};if(Y)$[this.skAttribute]=Y;await this.client.deleteItem({TableName:this.tableName,Key:h($)})}async update(Z,Y,$){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");let J={[this.pkAttribute]:Z};if(Y)J[this.skAttribute]=Y;let X=[],W={},H={},G=0,z=[];for(let[Q,_]of Object.entries($)){let U=`#upd${G}`,I=`:upd${G}`;W[U]=Q,H[I]=h({v:_}).v,z.push(`${U} = ${I}`),G++}if(z.length>0)X.push(`SET ${z.join(", ")}`);await this.client.updateItem({TableName:this.tableName,Key:h(J),UpdateExpression:X.join(" "),ExpressionAttributeNames:W,ExpressionAttributeValues:H})}getTableName(){return this.tableName}getConfig(){return{tableName:this.tableName,pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}}}function Q$(Z,Y="id"){return`${Z.toUpperCase()}#{${Y}}`}function _$(Z,Y){let $={},J=Z.split("#"),X=Y.split("#");for(let W=0;W<J.length;W++){let H=J[W],G=X[W];if(H?.startsWith("{")&&H.endsWith("}")){let z=H.slice(1,-1);$[z]=G??""}}return $}function O$(Z,Y){let $=Z;for(let[J,X]of Object.entries(Y))$=$.replace(`{${J}}`,X);return $}var V$=new pZ;function A$(){return new pZ}import{log as B$}from"@stacksjs/logging";import{database as L$}from"@stacksjs/config";import{path as E$}from"@stacksjs/path";async function K9(){if(!["sqlite","mysql"].includes(I$()))return;if(await $Y("model_audits"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
957
817
|
import { sql } from '@stacksjs/database'
|
|
958
818
|
|
|
959
|
-
`;
|
|
960
|
-
`,
|
|
961
|
-
`,
|
|
962
|
-
`,
|
|
963
|
-
`,
|
|
964
|
-
`,
|
|
965
|
-
`,
|
|
966
|
-
`,
|
|
967
|
-
`,
|
|
968
|
-
`,
|
|
969
|
-
`,
|
|
970
|
-
`,
|
|
971
|
-
|
|
972
|
-
`,
|
|
973
|
-
`,
|
|
974
|
-
`,
|
|
975
|
-
`,
|
|
976
|
-
`,
|
|
977
|
-
`,
|
|
978
|
-
`;let
|
|
819
|
+
`;Y+=`export async function up(db: Database<any>) {
|
|
820
|
+
`,Y+=` await db.schema
|
|
821
|
+
`,Y+=` .createTable('model_audits')
|
|
822
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
823
|
+
`,Y+=` .addColumn('auditable_type', 'varchar(255)', col => col.notNull())
|
|
824
|
+
`,Y+=` .addColumn('auditable_id', 'varchar(255)', col => col.notNull())
|
|
825
|
+
`,Y+=` .addColumn('event', 'varchar(32)', col => col.notNull())
|
|
826
|
+
`,Y+=` .addColumn('old_values', 'text')
|
|
827
|
+
`,Y+=` .addColumn('new_values', 'text')
|
|
828
|
+
`,Y+=` .addColumn('user_id', 'integer')
|
|
829
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
830
|
+
`,Y+=` .execute()
|
|
831
|
+
|
|
832
|
+
`,Y+=` await db.schema
|
|
833
|
+
`,Y+=` .createIndex('idx_model_audits_lookup')
|
|
834
|
+
`,Y+=` .on('model_audits')
|
|
835
|
+
`,Y+=` .columns(['auditable_type', 'auditable_id', 'created_at'])
|
|
836
|
+
`,Y+=` .execute()
|
|
837
|
+
`,Y+=`}
|
|
838
|
+
`;let J=`${new Date().getTime().toString()}-create-model-audits-table.ts`,X=E$.userMigrationsPath(J);await Bun.write(X,Y),B$.success("Created model_audits table migration")}function I$(){return L$.default||""}import{log as K$}from"@stacksjs/logging";import{database as j$}from"@stacksjs/config";import{path as R$}from"@stacksjs/path";async function F9(){if(["sqlite","mysql"].includes(w$())){if(await $Y("errors"))return;let Y=`import type { Database } from '@stacksjs/database'
|
|
979
839
|
import { sql } from '@stacksjs/database'
|
|
980
840
|
|
|
981
|
-
`;
|
|
982
|
-
`,
|
|
983
|
-
`,
|
|
984
|
-
`,
|
|
985
|
-
`,
|
|
986
|
-
`,
|
|
987
|
-
`,
|
|
988
|
-
`,
|
|
989
|
-
`,
|
|
990
|
-
`,
|
|
991
|
-
`,
|
|
992
|
-
`,
|
|
993
|
-
`,
|
|
994
|
-
`,
|
|
995
|
-
`;let
|
|
841
|
+
`;Y+=`export async function up(db: Database<any>) {
|
|
842
|
+
`,Y+=` await db.schema
|
|
843
|
+
`,Y+=` .createTable('errors')
|
|
844
|
+
`,Y+=` .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
|
|
845
|
+
`,Y+=` .addColumn('type', 'varchar(255)', col => col.notNull())
|
|
846
|
+
`,Y+=` .addColumn('message', 'text', col => col.notNull())
|
|
847
|
+
`,Y+=` .addColumn('stack', 'text')
|
|
848
|
+
`,Y+=` .addColumn('status', 'integer', col => col.notNull().defaultTo(0))
|
|
849
|
+
`,Y+=` .addColumn('user_id', 'integer')
|
|
850
|
+
`,Y+=` .addColumn('additional_info', 'text')
|
|
851
|
+
`,Y+=` .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
|
|
852
|
+
`,Y+=` .addColumn('updated_at', 'timestamp')
|
|
853
|
+
`,Y+=` .execute()
|
|
854
|
+
`,Y+=`}
|
|
855
|
+
`;let J=`${new Date().getTime().toString()}-create-errors-table.ts`,X=R$.userMigrationsPath(J);await Bun.write(X,Y),K$.success("Created errors table")}}function w$(){return j$.default||""}import{err as S$,ok as M$}from"@stacksjs/error-handling";import{existsSync as wY,readdirSync as F$,writeFileSync as D$,mkdirSync as q$}from"fs";import{join as CZ}from"path";import V6 from"process";import WZ from"bun:sqlite";import{env as A6}from"@stacksjs/env";function cZ(){return A6.DB_CONNECTION||"sqlite"}function B6(){return CZ(V6.cwd(),"database","migrations")}function x$(){try{let Z=B6();if(!wY(Z))return!1;return F$(Z).some(($)=>$.includes("create-jobs-table"))}catch{return!1}}async function T$(){let Z=HZ();if(wY(Z))try{let $=new WZ(Z),J=$.query("SELECT name FROM sqlite_master WHERE type='table' AND name='job_batches'").get();return $.close(),J!==null}catch{}if(cZ()!=="sqlite")try{let{db:$}=await Promise.resolve().then(() => (F(),u));return await $.selectFrom("job_batches").select("id").limit(1).execute(),!0}catch{return!1}return!1}function HZ(){let Z=A6.APP_ROOT||V6.cwd();return CZ(Z,"database","stacks.sqlite")}async function P$(){let Z=cZ(),Y=HZ();if(wY(Y))try{let $=new WZ(Y),J=$.query("SELECT name FROM sqlite_master WHERE type='table' AND name='jobs'").get();return $.close(),J!==null}catch{}if(Z!=="sqlite")try{let{db:$}=await Promise.resolve().then(() => (F(),u));return await $.selectFrom("jobs").select("id").limit(1).execute(),!0}catch{return!1}return!1}async function y9(){try{let Z=cZ();if(["sqlite","mysql","postgres"].includes(Z)){if(!x$()){let X="";if(Z==="sqlite")X=`-- Create jobs table
|
|
996
856
|
CREATE TABLE IF NOT EXISTS jobs (
|
|
997
857
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
998
858
|
queue TEXT NOT NULL DEFAULT 'default',
|
|
@@ -1016,6 +876,11 @@ CREATE TABLE IF NOT EXISTS failed_jobs (
|
|
|
1016
876
|
);
|
|
1017
877
|
|
|
1018
878
|
-- Create job_batches table
|
|
879
|
+
-- then_handler / catch_handler / finally_handler columns persist
|
|
880
|
+
-- the terminal handlers across worker restarts
|
|
881
|
+
-- (stacksjs/stacks#1883). Each holds JSON for one
|
|
882
|
+
-- PersistentBatchHandler. Nullable so callers that only use the
|
|
883
|
+
-- in-memory `.then(fn)` API don't need to populate them.
|
|
1019
884
|
CREATE TABLE IF NOT EXISTS job_batches (
|
|
1020
885
|
id TEXT PRIMARY KEY,
|
|
1021
886
|
name TEXT NOT NULL DEFAULT '',
|
|
@@ -1026,9 +891,58 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1026
891
|
options TEXT,
|
|
1027
892
|
cancelled_at DATETIME,
|
|
1028
893
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
1029
|
-
finished_at DATETIME
|
|
894
|
+
finished_at DATETIME,
|
|
895
|
+
then_handler TEXT,
|
|
896
|
+
catch_handler TEXT,
|
|
897
|
+
finally_handler TEXT
|
|
898
|
+
);
|
|
899
|
+
|
|
900
|
+
-- Dead-letter queue (stacksjs/stacks#1885). Jobs that have already
|
|
901
|
+
-- been retried and failed again land here instead of cycling back
|
|
902
|
+
-- through the queue. \`reason\` distinguishes "repeat-failure" from
|
|
903
|
+
-- "poison-detected" / "circuit-broken" for operator triage.
|
|
904
|
+
CREATE TABLE IF NOT EXISTS dead_letter_jobs (
|
|
905
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
906
|
+
uuid TEXT NOT NULL,
|
|
907
|
+
connection TEXT NOT NULL,
|
|
908
|
+
queue TEXT NOT NULL,
|
|
909
|
+
payload TEXT NOT NULL,
|
|
910
|
+
exception TEXT NOT NULL,
|
|
911
|
+
reason TEXT NOT NULL,
|
|
912
|
+
total_failures INTEGER NOT NULL DEFAULT 1,
|
|
913
|
+
first_failed_at DATETIME,
|
|
914
|
+
last_failed_at DATETIME,
|
|
915
|
+
dead_lettered_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
916
|
+
);
|
|
917
|
+
|
|
918
|
+
-- Poison-message quarantine (stacksjs/stacks#1885). Tracks
|
|
919
|
+
-- failure counts per (jobName + payload-hash) over a rolling
|
|
920
|
+
-- window. When the count breaches the configured threshold, new
|
|
921
|
+
-- dispatches of that exact job+payload combination go directly to
|
|
922
|
+
-- the DLQ instead of the queue.
|
|
923
|
+
CREATE TABLE IF NOT EXISTS job_quarantine (
|
|
924
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
925
|
+
job_name TEXT NOT NULL,
|
|
926
|
+
payload_hash TEXT NOT NULL,
|
|
927
|
+
failure_count INTEGER NOT NULL DEFAULT 0,
|
|
928
|
+
window_start DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
929
|
+
quarantined_at DATETIME,
|
|
930
|
+
UNIQUE(job_name, payload_hash)
|
|
931
|
+
);
|
|
932
|
+
|
|
933
|
+
-- Per-queue circuit-breaker state (stacksjs/stacks#1885). Tracks
|
|
934
|
+
-- success/failure counts in a rolling window so the worker can
|
|
935
|
+
-- pause a queue with a sustained high failure rate. Reads + writes
|
|
936
|
+
-- are best-effort; a missing row means "not tripped".
|
|
937
|
+
CREATE TABLE IF NOT EXISTS queue_circuit_state (
|
|
938
|
+
queue_name TEXT PRIMARY KEY,
|
|
939
|
+
success_count INTEGER NOT NULL DEFAULT 0,
|
|
940
|
+
failure_count INTEGER NOT NULL DEFAULT 0,
|
|
941
|
+
window_start DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
942
|
+
paused_at DATETIME,
|
|
943
|
+
resume_at DATETIME
|
|
1030
944
|
);
|
|
1031
|
-
`;else if(
|
|
945
|
+
`;else if(Z==="mysql")X=`-- Create jobs table
|
|
1032
946
|
CREATE TABLE IF NOT EXISTS jobs (
|
|
1033
947
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
1034
948
|
queue VARCHAR(255) NOT NULL DEFAULT 'default',
|
|
@@ -1052,6 +966,8 @@ CREATE TABLE IF NOT EXISTS failed_jobs (
|
|
|
1052
966
|
);
|
|
1053
967
|
|
|
1054
968
|
-- Create job_batches table
|
|
969
|
+
-- then_handler / catch_handler / finally_handler persist
|
|
970
|
+
-- terminal handlers across worker restarts (stacksjs/stacks#1883).
|
|
1055
971
|
CREATE TABLE IF NOT EXISTS job_batches (
|
|
1056
972
|
id VARCHAR(255) PRIMARY KEY,
|
|
1057
973
|
name VARCHAR(255) NOT NULL DEFAULT '',
|
|
@@ -1062,9 +978,46 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1062
978
|
options LONGTEXT,
|
|
1063
979
|
cancelled_at TIMESTAMP NULL,
|
|
1064
980
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1065
|
-
finished_at TIMESTAMP NULL
|
|
981
|
+
finished_at TIMESTAMP NULL,
|
|
982
|
+
then_handler LONGTEXT,
|
|
983
|
+
catch_handler LONGTEXT,
|
|
984
|
+
finally_handler LONGTEXT
|
|
1066
985
|
);
|
|
1067
|
-
|
|
986
|
+
|
|
987
|
+
-- DLQ + poison-quarantine + circuit-breaker (stacksjs/stacks#1885)
|
|
988
|
+
CREATE TABLE IF NOT EXISTS dead_letter_jobs (
|
|
989
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
990
|
+
uuid VARCHAR(255) NOT NULL,
|
|
991
|
+
connection VARCHAR(255) NOT NULL,
|
|
992
|
+
queue VARCHAR(255) NOT NULL,
|
|
993
|
+
payload LONGTEXT NOT NULL,
|
|
994
|
+
exception LONGTEXT NOT NULL,
|
|
995
|
+
reason VARCHAR(64) NOT NULL,
|
|
996
|
+
total_failures INT NOT NULL DEFAULT 1,
|
|
997
|
+
first_failed_at TIMESTAMP NULL,
|
|
998
|
+
last_failed_at TIMESTAMP NULL,
|
|
999
|
+
dead_lettered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1000
|
+
);
|
|
1001
|
+
|
|
1002
|
+
CREATE TABLE IF NOT EXISTS job_quarantine (
|
|
1003
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
1004
|
+
job_name VARCHAR(255) NOT NULL,
|
|
1005
|
+
payload_hash VARCHAR(64) NOT NULL,
|
|
1006
|
+
failure_count INT NOT NULL DEFAULT 0,
|
|
1007
|
+
window_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1008
|
+
quarantined_at TIMESTAMP NULL,
|
|
1009
|
+
UNIQUE KEY job_quarantine_unique (job_name, payload_hash)
|
|
1010
|
+
);
|
|
1011
|
+
|
|
1012
|
+
CREATE TABLE IF NOT EXISTS queue_circuit_state (
|
|
1013
|
+
queue_name VARCHAR(255) PRIMARY KEY,
|
|
1014
|
+
success_count INT NOT NULL DEFAULT 0,
|
|
1015
|
+
failure_count INT NOT NULL DEFAULT 0,
|
|
1016
|
+
window_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1017
|
+
paused_at TIMESTAMP NULL,
|
|
1018
|
+
resume_at TIMESTAMP NULL
|
|
1019
|
+
);
|
|
1020
|
+
`;else if(Z==="postgres")X=`-- Create jobs table
|
|
1068
1021
|
CREATE TABLE IF NOT EXISTS jobs (
|
|
1069
1022
|
id SERIAL PRIMARY KEY,
|
|
1070
1023
|
queue VARCHAR(255) NOT NULL DEFAULT 'default',
|
|
@@ -1088,6 +1041,8 @@ CREATE TABLE IF NOT EXISTS failed_jobs (
|
|
|
1088
1041
|
);
|
|
1089
1042
|
|
|
1090
1043
|
-- Create job_batches table
|
|
1044
|
+
-- then_handler / catch_handler / finally_handler persist
|
|
1045
|
+
-- terminal handlers across worker restarts (stacksjs/stacks#1883).
|
|
1091
1046
|
CREATE TABLE IF NOT EXISTS job_batches (
|
|
1092
1047
|
id VARCHAR(255) PRIMARY KEY,
|
|
1093
1048
|
name VARCHAR(255) NOT NULL DEFAULT '',
|
|
@@ -1098,9 +1053,46 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1098
1053
|
options TEXT,
|
|
1099
1054
|
cancelled_at TIMESTAMP,
|
|
1100
1055
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1101
|
-
finished_at TIMESTAMP
|
|
1056
|
+
finished_at TIMESTAMP,
|
|
1057
|
+
then_handler TEXT,
|
|
1058
|
+
catch_handler TEXT,
|
|
1059
|
+
finally_handler TEXT
|
|
1102
1060
|
);
|
|
1103
|
-
|
|
1061
|
+
|
|
1062
|
+
-- DLQ + poison-quarantine + circuit-breaker (stacksjs/stacks#1885)
|
|
1063
|
+
CREATE TABLE IF NOT EXISTS dead_letter_jobs (
|
|
1064
|
+
id SERIAL PRIMARY KEY,
|
|
1065
|
+
uuid VARCHAR(255) NOT NULL,
|
|
1066
|
+
connection VARCHAR(255) NOT NULL,
|
|
1067
|
+
queue VARCHAR(255) NOT NULL,
|
|
1068
|
+
payload TEXT NOT NULL,
|
|
1069
|
+
exception TEXT NOT NULL,
|
|
1070
|
+
reason VARCHAR(64) NOT NULL,
|
|
1071
|
+
total_failures INTEGER NOT NULL DEFAULT 1,
|
|
1072
|
+
first_failed_at TIMESTAMP,
|
|
1073
|
+
last_failed_at TIMESTAMP,
|
|
1074
|
+
dead_lettered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1075
|
+
);
|
|
1076
|
+
|
|
1077
|
+
CREATE TABLE IF NOT EXISTS job_quarantine (
|
|
1078
|
+
id SERIAL PRIMARY KEY,
|
|
1079
|
+
job_name VARCHAR(255) NOT NULL,
|
|
1080
|
+
payload_hash VARCHAR(64) NOT NULL,
|
|
1081
|
+
failure_count INTEGER NOT NULL DEFAULT 0,
|
|
1082
|
+
window_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1083
|
+
quarantined_at TIMESTAMP,
|
|
1084
|
+
UNIQUE (job_name, payload_hash)
|
|
1085
|
+
);
|
|
1086
|
+
|
|
1087
|
+
CREATE TABLE IF NOT EXISTS queue_circuit_state (
|
|
1088
|
+
queue_name VARCHAR(255) PRIMARY KEY,
|
|
1089
|
+
success_count INTEGER NOT NULL DEFAULT 0,
|
|
1090
|
+
failure_count INTEGER NOT NULL DEFAULT 0,
|
|
1091
|
+
window_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1092
|
+
paused_at TIMESTAMP,
|
|
1093
|
+
resume_at TIMESTAMP
|
|
1094
|
+
);
|
|
1095
|
+
`;let H=`${new Date().getTime().toString()}-create-jobs-table.sql`,G=B6();if(!wY(G))q$(G,{recursive:!0});let z=CZ(G,H);D$(z,X),console.log("\u2713 Created jobs migration file")}else console.log("\u2713 Jobs migration file already exists");if(!await P$()){console.log(" Running migration...");let X=HZ();if(Z==="sqlite"||wY(X)){let W=new WZ(X);W.run(`CREATE TABLE IF NOT EXISTS jobs (
|
|
1104
1096
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1105
1097
|
queue TEXT NOT NULL DEFAULT 'default',
|
|
1106
1098
|
payload TEXT NOT NULL,
|
|
@@ -1109,7 +1101,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1109
1101
|
available_at INTEGER,
|
|
1110
1102
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
1111
1103
|
updated_at DATETIME
|
|
1112
|
-
)`),
|
|
1104
|
+
)`),W.run(`CREATE TABLE IF NOT EXISTS failed_jobs (
|
|
1113
1105
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1114
1106
|
uuid TEXT NOT NULL,
|
|
1115
1107
|
connection TEXT NOT NULL,
|
|
@@ -1117,7 +1109,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1117
1109
|
payload TEXT NOT NULL,
|
|
1118
1110
|
exception TEXT NOT NULL,
|
|
1119
1111
|
failed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
1120
|
-
)`),
|
|
1112
|
+
)`),W.close()}else if(Z==="mysql"){let{db:W}=await Promise.resolve().then(() => (F(),u));await W.unsafe(`CREATE TABLE IF NOT EXISTS jobs (
|
|
1121
1113
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
1122
1114
|
queue VARCHAR(255) NOT NULL DEFAULT 'default',
|
|
1123
1115
|
payload LONGTEXT NOT NULL,
|
|
@@ -1126,7 +1118,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1126
1118
|
available_at INT UNSIGNED NULL,
|
|
1127
1119
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1128
1120
|
updated_at TIMESTAMP NULL
|
|
1129
|
-
)`).execute(),await
|
|
1121
|
+
)`).execute(),await W.unsafe(`CREATE TABLE IF NOT EXISTS failed_jobs (
|
|
1130
1122
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
1131
1123
|
uuid VARCHAR(255) NOT NULL,
|
|
1132
1124
|
connection VARCHAR(255) NOT NULL,
|
|
@@ -1134,7 +1126,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1134
1126
|
payload LONGTEXT NOT NULL,
|
|
1135
1127
|
exception LONGTEXT NOT NULL,
|
|
1136
1128
|
failed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1137
|
-
)`).execute()}else if(
|
|
1129
|
+
)`).execute()}else if(Z==="postgres"){let{db:W}=await Promise.resolve().then(() => (F(),u));await W.unsafe(`CREATE TABLE IF NOT EXISTS jobs (
|
|
1138
1130
|
id SERIAL PRIMARY KEY,
|
|
1139
1131
|
queue VARCHAR(255) NOT NULL DEFAULT 'default',
|
|
1140
1132
|
payload TEXT NOT NULL,
|
|
@@ -1143,7 +1135,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1143
1135
|
available_at INTEGER,
|
|
1144
1136
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1145
1137
|
updated_at TIMESTAMP
|
|
1146
|
-
)`).execute(),await
|
|
1138
|
+
)`).execute(),await W.unsafe(`CREATE TABLE IF NOT EXISTS failed_jobs (
|
|
1147
1139
|
id SERIAL PRIMARY KEY,
|
|
1148
1140
|
uuid VARCHAR(255) NOT NULL,
|
|
1149
1141
|
connection VARCHAR(255) NOT NULL,
|
|
@@ -1151,7 +1143,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1151
1143
|
payload TEXT NOT NULL,
|
|
1152
1144
|
exception TEXT NOT NULL,
|
|
1153
1145
|
failed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1154
|
-
)`).execute()}console.log("\u2713 Jobs and failed_jobs tables created")}else console.log("\u2713 Jobs tables already exist");if(!await
|
|
1146
|
+
)`).execute()}console.log("\u2713 Jobs and failed_jobs tables created")}else console.log("\u2713 Jobs tables already exist");if(!await T$()){console.log(" Creating job_batches table...");let X=HZ();if(Z==="sqlite"||wY(X)){let W=new WZ(X);W.run(`CREATE TABLE IF NOT EXISTS job_batches (
|
|
1155
1147
|
id TEXT PRIMARY KEY,
|
|
1156
1148
|
name TEXT NOT NULL DEFAULT '',
|
|
1157
1149
|
total_jobs INTEGER NOT NULL DEFAULT 0,
|
|
@@ -1162,7 +1154,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1162
1154
|
cancelled_at DATETIME,
|
|
1163
1155
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
1164
1156
|
finished_at DATETIME
|
|
1165
|
-
)`),
|
|
1157
|
+
)`),W.close()}else if(Z==="mysql"){let{db:W}=await Promise.resolve().then(() => (F(),u));await W.unsafe(`CREATE TABLE IF NOT EXISTS job_batches (
|
|
1166
1158
|
id VARCHAR(255) PRIMARY KEY,
|
|
1167
1159
|
name VARCHAR(255) NOT NULL DEFAULT '',
|
|
1168
1160
|
total_jobs INT NOT NULL DEFAULT 0,
|
|
@@ -1173,7 +1165,7 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1173
1165
|
cancelled_at TIMESTAMP NULL,
|
|
1174
1166
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1175
1167
|
finished_at TIMESTAMP NULL
|
|
1176
|
-
)`).execute()}else if(
|
|
1168
|
+
)`).execute()}else if(Z==="postgres"){let{db:W}=await Promise.resolve().then(() => (F(),u));await W.unsafe(`CREATE TABLE IF NOT EXISTS job_batches (
|
|
1177
1169
|
id VARCHAR(255) PRIMARY KEY,
|
|
1178
1170
|
name VARCHAR(255) NOT NULL DEFAULT '',
|
|
1179
1171
|
total_jobs INTEGER NOT NULL DEFAULT 0,
|
|
@@ -1184,148 +1176,192 @@ CREATE TABLE IF NOT EXISTS job_batches (
|
|
|
1184
1176
|
cancelled_at TIMESTAMP,
|
|
1185
1177
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1186
1178
|
finished_at TIMESTAMP
|
|
1187
|
-
)`).execute()}console.log("\u2713 job_batches table created")}else console.log("\u2713 job_batches table already exists")}return
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
)
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
oauth_client_id INTEGER NOT NULL,
|
|
1231
|
-
token TEXT NOT NULL,
|
|
1232
|
-
name VARCHAR(255),
|
|
1233
|
-
scopes TEXT,
|
|
1234
|
-
revoked BOOLEAN NOT NULL DEFAULT false,
|
|
1235
|
-
expires_at TIMESTAMP,
|
|
1236
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1237
|
-
updated_at TIMESTAMP
|
|
1238
|
-
)
|
|
1239
|
-
`).execute();else if(Y)await v.unsafe(`
|
|
1240
|
-
CREATE TABLE IF NOT EXISTS oauth_access_tokens (
|
|
1241
|
-
id INTEGER AUTO_INCREMENT PRIMARY KEY,
|
|
1242
|
-
user_id INTEGER NOT NULL,
|
|
1243
|
-
oauth_client_id INTEGER NOT NULL,
|
|
1244
|
-
token TEXT NOT NULL,
|
|
1245
|
-
name VARCHAR(255),
|
|
1246
|
-
scopes TEXT,
|
|
1247
|
-
revoked BOOLEAN NOT NULL DEFAULT 0,
|
|
1248
|
-
expires_at TIMESTAMP NULL,
|
|
1249
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1250
|
-
updated_at TIMESTAMP NULL
|
|
1251
|
-
)
|
|
1252
|
-
`).execute();else await v.unsafe(`
|
|
1253
|
-
CREATE TABLE IF NOT EXISTS oauth_access_tokens (
|
|
1254
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1255
|
-
user_id INTEGER NOT NULL,
|
|
1256
|
-
oauth_client_id INTEGER NOT NULL,
|
|
1257
|
-
token TEXT NOT NULL,
|
|
1258
|
-
name VARCHAR(255),
|
|
1259
|
-
scopes TEXT,
|
|
1260
|
-
revoked BOOLEAN NOT NULL DEFAULT 0,
|
|
1261
|
-
expires_at TIMESTAMP,
|
|
1262
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1263
|
-
updated_at TIMESTAMP
|
|
1264
|
-
)
|
|
1265
|
-
`).execute();try{await v.unsafe(`
|
|
1266
|
-
CREATE INDEX IF NOT EXISTS idx_oauth_access_tokens_token ON oauth_access_tokens(token(255))
|
|
1267
|
-
`).execute()}catch{try{await v.unsafe(`
|
|
1268
|
-
CREATE INDEX IF NOT EXISTS idx_oauth_access_tokens_token ON oauth_access_tokens(token)
|
|
1269
|
-
`).execute()}catch{}}if($.verbose)m9.info("Creating oauth_refresh_tokens table...");if(_)await v.unsafe(`
|
|
1270
|
-
CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (
|
|
1271
|
-
id SERIAL PRIMARY KEY,
|
|
1272
|
-
access_token_id INTEGER NOT NULL,
|
|
1273
|
-
token TEXT NOT NULL,
|
|
1274
|
-
revoked BOOLEAN NOT NULL DEFAULT false,
|
|
1275
|
-
expires_at TIMESTAMP,
|
|
1276
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1277
|
-
)
|
|
1278
|
-
`).execute();else if(Y)await v.unsafe(`
|
|
1279
|
-
CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (
|
|
1280
|
-
id INTEGER AUTO_INCREMENT PRIMARY KEY,
|
|
1281
|
-
access_token_id INTEGER NOT NULL,
|
|
1282
|
-
token TEXT NOT NULL,
|
|
1283
|
-
revoked BOOLEAN NOT NULL DEFAULT 0,
|
|
1284
|
-
expires_at TIMESTAMP NULL,
|
|
1285
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1286
|
-
)
|
|
1287
|
-
`).execute();else await v.unsafe(`
|
|
1288
|
-
CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (
|
|
1289
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1290
|
-
access_token_id INTEGER NOT NULL,
|
|
1291
|
-
token TEXT NOT NULL,
|
|
1292
|
-
revoked BOOLEAN NOT NULL DEFAULT 0,
|
|
1293
|
-
expires_at TIMESTAMP,
|
|
1294
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1295
|
-
)
|
|
1296
|
-
`).execute();try{await v.unsafe(`
|
|
1297
|
-
CREATE INDEX IF NOT EXISTS idx_oauth_refresh_tokens_token ON oauth_refresh_tokens(token(255))
|
|
1298
|
-
`).execute()}catch{try{await v.unsafe(`
|
|
1299
|
-
CREATE INDEX IF NOT EXISTS idx_oauth_refresh_tokens_token ON oauth_refresh_tokens(token)
|
|
1300
|
-
`).execute()}catch{}}if($.verbose)m9.info("Creating password_resets table...");if(_)await v.unsafe(`
|
|
1301
|
-
CREATE TABLE IF NOT EXISTS password_resets (
|
|
1302
|
-
id SERIAL PRIMARY KEY,
|
|
1303
|
-
email VARCHAR(255) NOT NULL,
|
|
1304
|
-
token VARCHAR(255) NOT NULL,
|
|
1305
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1306
|
-
)
|
|
1307
|
-
`).execute();else if(Y)await v.unsafe(`
|
|
1308
|
-
CREATE TABLE IF NOT EXISTS password_resets (
|
|
1309
|
-
id INTEGER AUTO_INCREMENT PRIMARY KEY,
|
|
1310
|
-
email VARCHAR(255) NOT NULL,
|
|
1311
|
-
token VARCHAR(255) NOT NULL,
|
|
1312
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1313
|
-
)
|
|
1314
|
-
`).execute();else await v.unsafe(`
|
|
1315
|
-
CREATE TABLE IF NOT EXISTS password_resets (
|
|
1316
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1317
|
-
email VARCHAR(255) NOT NULL,
|
|
1318
|
-
token VARCHAR(255) NOT NULL,
|
|
1319
|
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1320
|
-
)
|
|
1321
|
-
`).execute();try{await v.unsafe(`
|
|
1179
|
+
)`).execute()}console.log("\u2713 job_batches table created")}else console.log("\u2713 job_batches table already exists")}return M$("Migration created and executed.")}catch(Z){return S$(Z instanceof Error?Z:Error(String(Z)))}}F();import{randomBytes as k$}from"crypto";import{log as v}from"@stacksjs/logging";import{env as N$}from"@stacksjs/env";function WY(Z){let Y=Z==="postgres",$=Z==="mysql"||Z==="singlestore";return{driver:Z,isPostgres:Y,isMysql:$,isSqlite:!Y&&!$,now:Y||$?"NOW()":"datetime('now')",boolTrue:Y?"true":"1",boolFalse:Y?"false":"0",autoIncrement:Y?"SERIAL":"INTEGER",primaryKey:Y?"PRIMARY KEY":$?"PRIMARY KEY AUTO_INCREMENT":"PRIMARY KEY AUTOINCREMENT",pkColumn:Y?"id SERIAL PRIMARY KEY":$?"id INTEGER PRIMARY KEY AUTO_INCREMENT":"id INTEGER PRIMARY KEY AUTOINCREMENT",nullableTimestamp:$?"TIMESTAMP NULL":"TIMESTAMP",param(X){return Y?`$${X}`:"?"},params(...X){if(Y)return{sql:X.map((G,z)=>`$${z+1}`).join(", "),values:X};return{sql:X.map(()=>"?").join(", "),values:X}}}}function y$(){return N$.DB_CONNECTION||"sqlite"}function h$(Z){return`ALTER TABLE users ADD COLUMN email_verified_at ${Z.nullableTimestamp}`}function v$(Z){return`ALTER TABLE users ADD COLUMN password_changed_at ${Z.nullableTimestamp}`}function f$(Z){return["ALTER TABLE users ADD COLUMN two_factor_secret VARCHAR(255)",`ALTER TABLE users ADD COLUMN two_factor_enabled BOOLEAN NOT NULL DEFAULT ${Z.boolFalse}`]}function b$(){return"ALTER TABLE users ADD COLUMN stripe_id VARCHAR(255)"}async function p$(Z,Y={}){let $=[h$(Z),v$(Z),...f$(Z),b$()];for(let J of $)try{await V.unsafe(J).execute()}catch{if(Y.verbose)v.debug(`[auth-tables] Skipped (already applied or users missing): ${J}`)}try{await V.unsafe("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_stripe_id ON users(stripe_id)").execute()}catch{if(Y.verbose)v.debug("[auth-tables] Skipped users.stripe_id unique index (already applied or users missing)")}}async function s9(Z={}){let Y=y$(),$=WY(Y),{isPostgres:J,boolTrue:X,now:W,pkColumn:H,nullableTimestamp:G}=$;if(Z.verbose)v.info(`Creating auth tables for ${Y}...`);try{if(Z.verbose)v.info("Creating oauth_clients table...");if(await V.unsafe(`
|
|
1180
|
+
CREATE TABLE IF NOT EXISTS oauth_clients (
|
|
1181
|
+
${H},
|
|
1182
|
+
name VARCHAR(255) NOT NULL,
|
|
1183
|
+
secret VARCHAR(100),
|
|
1184
|
+
provider VARCHAR(255),
|
|
1185
|
+
redirect VARCHAR(2000) NOT NULL,
|
|
1186
|
+
personal_access_client BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1187
|
+
password_client BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1188
|
+
revoked BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1189
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1190
|
+
updated_at ${G}
|
|
1191
|
+
)
|
|
1192
|
+
`).execute(),Z.verbose)v.info("Creating oauth_access_tokens table...");if(await V.unsafe(`
|
|
1193
|
+
CREATE TABLE IF NOT EXISTS oauth_access_tokens (
|
|
1194
|
+
${H},
|
|
1195
|
+
user_id INTEGER NOT NULL,
|
|
1196
|
+
oauth_client_id INTEGER NOT NULL,
|
|
1197
|
+
token TEXT NOT NULL,
|
|
1198
|
+
name VARCHAR(255),
|
|
1199
|
+
scopes TEXT,
|
|
1200
|
+
revoked BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1201
|
+
expires_at ${G},
|
|
1202
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1203
|
+
updated_at ${G}
|
|
1204
|
+
)
|
|
1205
|
+
`).execute(),await L6("idx_oauth_access_tokens_token","oauth_access_tokens","token"),Z.verbose)v.info("Creating oauth_refresh_tokens table...");if(await V.unsafe(`
|
|
1206
|
+
CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (
|
|
1207
|
+
${H},
|
|
1208
|
+
access_token_id INTEGER NOT NULL,
|
|
1209
|
+
token TEXT NOT NULL,
|
|
1210
|
+
revoked BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1211
|
+
expires_at ${G},
|
|
1212
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1213
|
+
)
|
|
1214
|
+
`).execute(),await L6("idx_oauth_refresh_tokens_token","oauth_refresh_tokens","token"),Z.verbose)v.info("Creating password_resets table...");await V.unsafe(`
|
|
1215
|
+
CREATE TABLE IF NOT EXISTS password_resets (
|
|
1216
|
+
${H},
|
|
1217
|
+
email VARCHAR(255) NOT NULL,
|
|
1218
|
+
token VARCHAR(255) NOT NULL,
|
|
1219
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1220
|
+
)
|
|
1221
|
+
`).execute();try{await V.unsafe(`
|
|
1322
1222
|
CREATE INDEX IF NOT EXISTS idx_password_resets_email ON password_resets(email)
|
|
1323
|
-
`).execute()}catch{}if(
|
|
1324
|
-
|
|
1325
|
-
|
|
1223
|
+
`).execute()}catch{}if(Z.verbose)v.info("Creating passkeys table...");await V.unsafe(`
|
|
1224
|
+
CREATE TABLE IF NOT EXISTS passkeys (
|
|
1225
|
+
id VARCHAR(255) PRIMARY KEY,
|
|
1226
|
+
cred_public_key TEXT NOT NULL,
|
|
1227
|
+
user_id INTEGER NOT NULL,
|
|
1228
|
+
webauthn_user_id VARCHAR(255) NOT NULL,
|
|
1229
|
+
counter INTEGER NOT NULL DEFAULT 0,
|
|
1230
|
+
credential_type VARCHAR(50),
|
|
1231
|
+
device_type VARCHAR(50),
|
|
1232
|
+
backup_eligible BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1233
|
+
backup_status BOOLEAN NOT NULL DEFAULT ${$.boolFalse},
|
|
1234
|
+
transports TEXT,
|
|
1235
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1236
|
+
last_used_at ${G}
|
|
1237
|
+
)
|
|
1238
|
+
`).execute();try{await V.unsafe(`
|
|
1239
|
+
CREATE INDEX IF NOT EXISTS idx_passkeys_user_id ON passkeys(user_id)
|
|
1240
|
+
`).execute()}catch{}if(Z.verbose)v.info("Creating webauthn_challenges table...");await V.unsafe(`
|
|
1241
|
+
CREATE TABLE IF NOT EXISTS webauthn_challenges (
|
|
1242
|
+
${H},
|
|
1243
|
+
user_id INTEGER NOT NULL,
|
|
1244
|
+
challenge TEXT NOT NULL,
|
|
1245
|
+
purpose VARCHAR(20) NOT NULL,
|
|
1246
|
+
expires_at TIMESTAMP NOT NULL,
|
|
1247
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1248
|
+
)
|
|
1249
|
+
`).execute();try{await V.unsafe(`
|
|
1250
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_webauthn_challenges_user_purpose ON webauthn_challenges(user_id, purpose)
|
|
1251
|
+
`).execute()}catch{}if(Z.verbose)v.info("Creating two_factor_challenges table...");await V.unsafe(`
|
|
1252
|
+
CREATE TABLE IF NOT EXISTS two_factor_challenges (
|
|
1253
|
+
id VARCHAR(255) PRIMARY KEY,
|
|
1254
|
+
user_id INTEGER NOT NULL,
|
|
1255
|
+
expires_at TIMESTAMP NOT NULL,
|
|
1256
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1257
|
+
)
|
|
1258
|
+
`).execute();try{await V.unsafe(`
|
|
1259
|
+
CREATE INDEX IF NOT EXISTS idx_two_factor_challenges_user_id ON two_factor_challenges(user_id)
|
|
1260
|
+
`).execute()}catch{}if(Z.verbose)v.info("Creating two_factor_pending_secrets table...");if(await V.unsafe(`
|
|
1261
|
+
CREATE TABLE IF NOT EXISTS two_factor_pending_secrets (
|
|
1262
|
+
user_id INTEGER PRIMARY KEY,
|
|
1263
|
+
secret VARCHAR(255) NOT NULL,
|
|
1264
|
+
expires_at TIMESTAMP NOT NULL,
|
|
1265
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
1266
|
+
)
|
|
1267
|
+
`).execute(),Z.verbose)v.info("Ensuring users auth columns exist (users may not exist yet on a fresh install \u2014 see ensureUsersAuthColumns)...");if(await p$($,Z),Z.verbose)v.info("Ensuring personal access client exists...");if((await V.unsafe(`
|
|
1268
|
+
SELECT id FROM oauth_clients WHERE personal_access_client = ${X} LIMIT 1
|
|
1269
|
+
`).execute())?.length===0){let Q=k$(40).toString("hex");if(J)await V.unsafe(`
|
|
1326
1270
|
INSERT INTO oauth_clients (name, secret, provider, redirect, personal_access_client, password_client, revoked, created_at)
|
|
1327
1271
|
VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
|
|
1328
|
-
`,["Personal Access Client",
|
|
1272
|
+
`,["Personal Access Client",Q,"local","http://localhost",!0,!1,!1]).execute();else await V.unsafe(`
|
|
1329
1273
|
INSERT INTO oauth_clients (name, secret, provider, redirect, personal_access_client, password_client, revoked, created_at)
|
|
1330
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ${
|
|
1331
|
-
`,["Personal Access Client",
|
|
1274
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ${W})
|
|
1275
|
+
`,["Personal Access Client",Q,"local","http://localhost",1,0,0]).execute();if(Z.verbose)v.success("Personal access client created")}return v.debug("Auth tables migrated successfully"),{success:!0}}catch(z){let Q=z instanceof Error?z.message:String(z);return v.error("Failed to migrate auth tables:",Q),{success:!1,error:Q}}}async function L6(Z,Y,$){try{await V.unsafe(`
|
|
1276
|
+
CREATE INDEX IF NOT EXISTS ${Z} ON ${Y}(${$}(255))
|
|
1277
|
+
`).execute()}catch{try{await V.unsafe(`
|
|
1278
|
+
CREATE INDEX IF NOT EXISTS ${Z} ON ${Y}(${$})
|
|
1279
|
+
`).execute()}catch{}}}F();import C$ from"process";import{log as E6}from"@stacksjs/logging";import{path as uZ}from"@stacksjs/path";import{getTableName as c$}from"@stacksjs/orm";import{fs as I6}from"@stacksjs/storage";function u$(){return C$.env.DB_CONNECTION||"sqlite"}function g$(Z){if(Z.isPostgres)return"UUID";if(Z.isMysql)return"VARCHAR(255)";return"TEXT"}function d$(Z,Y){return`ALTER TABLE ${Z} ADD COLUMN uuid ${g$(Y)}`}async function K6(Z){let Y=[];if(!I6.existsSync(Z))return Y;let $=I6.readdirSync(Z,{withFileTypes:!0});for(let J of $){let X=uZ.join(Z,J.name);if(J.isDirectory()){Y.push(...await K6(X));continue}if(!J.name.endsWith(".ts"))continue;if(J.name.startsWith("_")||J.name.startsWith("index"))continue;try{let W=(await import(X)).default;if(W?.name||W?.table)Y.push({filePath:X,model:W})}catch{}}return Y}async function m$(){let Z=[uZ.userModelsPath(),uZ.frameworkPath("defaults/app/Models")],Y=new Set;for(let $ of Z)for(let{filePath:J,model:X}of await K6($)){if(!X.traits?.useUuid)continue;Y.add(c$(X,J))}return[...Y]}async function s$(Z,Y={}){let $=await m$();for(let J of $)try{if(await V.unsafe(d$(J,Z)).execute(),Y.verbose)E6.debug(`[uuid-columns] Added uuid column to ${J}`)}catch{if(Y.verbose)E6.debug(`[uuid-columns] Skipped (already applied or ${J} missing): uuid column`)}}async function ZJ(Z={}){await s$(WY(u$()),Z)}F();import{log as gY}from"@stacksjs/logging";import{env as l$}from"@stacksjs/env";function r$(){return l$.DB_CONNECTION||"sqlite"}function n$(Z){let{pkColumn:Y,nullableTimestamp:$}=Z;return`CREATE TABLE IF NOT EXISTS notifications (
|
|
1280
|
+
${Y},
|
|
1281
|
+
user_id INTEGER NOT NULL,
|
|
1282
|
+
type VARCHAR(255) NOT NULL,
|
|
1283
|
+
data TEXT NOT NULL,
|
|
1284
|
+
read_at ${$},
|
|
1285
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1286
|
+
updated_at ${$}
|
|
1287
|
+
)`}function i$(Z){let{pkColumn:Y,boolTrue:$,nullableTimestamp:J}=Z;return`CREATE TABLE IF NOT EXISTS notification_preferences (
|
|
1288
|
+
${Y},
|
|
1289
|
+
user_id INTEGER NOT NULL,
|
|
1290
|
+
channel VARCHAR(50) NOT NULL,
|
|
1291
|
+
enabled BOOLEAN NOT NULL DEFAULT ${$},
|
|
1292
|
+
category VARCHAR(255),
|
|
1293
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1294
|
+
updated_at ${J},
|
|
1295
|
+
UNIQUE (user_id, channel, category)
|
|
1296
|
+
)`}async function a$(Z={}){let Y=r$(),$=WY(Y);if(Z.verbose)gY.info(`Creating notification tables for ${Y}...`);try{if(Z.verbose)gY.info("Creating notifications table...");if(await V.unsafe(n$($)).execute(),await V.unsafe("CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications (user_id)").execute(),Z.verbose)gY.info("Creating notification_preferences table...");if(await V.unsafe(i$($)).execute(),await V.unsafe("CREATE INDEX IF NOT EXISTS idx_notification_preferences_user ON notification_preferences (user_id)").execute(),Z.verbose)gY.success("Notification tables created");return{success:!0}}catch(J){let X=J instanceof Error?J.message:String(J);return gY.error(`Failed to create notification tables: ${X}`),{success:!1,error:X}}}F();import{log as HY}from"@stacksjs/logging";import{env as o$}from"@stacksjs/env";function t$(){return o$.DB_CONNECTION||"sqlite"}function e$(Z){let{pkColumn:Y,nullableTimestamp:$}=Z;return`CREATE TABLE IF NOT EXISTS roles (
|
|
1297
|
+
${Y},
|
|
1298
|
+
name VARCHAR(255) NOT NULL,
|
|
1299
|
+
guard_name VARCHAR(255) NOT NULL DEFAULT 'web',
|
|
1300
|
+
description TEXT,
|
|
1301
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1302
|
+
updated_at ${$},
|
|
1303
|
+
UNIQUE (name, guard_name)
|
|
1304
|
+
)`}function Y0(Z){let{pkColumn:Y,nullableTimestamp:$}=Z;return`CREATE TABLE IF NOT EXISTS permissions (
|
|
1305
|
+
${Y},
|
|
1306
|
+
name VARCHAR(255) NOT NULL,
|
|
1307
|
+
guard_name VARCHAR(255) NOT NULL DEFAULT 'web',
|
|
1308
|
+
description TEXT,
|
|
1309
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1310
|
+
updated_at ${$},
|
|
1311
|
+
UNIQUE (name, guard_name)
|
|
1312
|
+
)`}function Z0(){return`CREATE TABLE IF NOT EXISTS user_roles (
|
|
1313
|
+
user_id INTEGER NOT NULL,
|
|
1314
|
+
role_id INTEGER NOT NULL,
|
|
1315
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1316
|
+
PRIMARY KEY (user_id, role_id)
|
|
1317
|
+
)`}function $0(){return`CREATE TABLE IF NOT EXISTS user_permissions (
|
|
1318
|
+
user_id INTEGER NOT NULL,
|
|
1319
|
+
permission_id INTEGER NOT NULL,
|
|
1320
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1321
|
+
PRIMARY KEY (user_id, permission_id)
|
|
1322
|
+
)`}function J0(){return`CREATE TABLE IF NOT EXISTS role_permissions (
|
|
1323
|
+
role_id INTEGER NOT NULL,
|
|
1324
|
+
permission_id INTEGER NOT NULL,
|
|
1325
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
1326
|
+
PRIMARY KEY (role_id, permission_id)
|
|
1327
|
+
)`}async function X0(Z={}){let Y=t$(),$=WY(Y);if(Z.verbose)HY.info(`Creating RBAC tables for ${Y}...`);try{if(Z.verbose)HY.info("Creating roles table...");if(await V.unsafe(e$($)).execute(),Z.verbose)HY.info("Creating permissions table...");if(await V.unsafe(Y0($)).execute(),Z.verbose)HY.info("Creating user_roles pivot...");if(await V.unsafe(Z0()).execute(),Z.verbose)HY.info("Creating user_permissions pivot...");if(await V.unsafe($0()).execute(),Z.verbose)HY.info("Creating role_permissions pivot...");if(await V.unsafe(J0()).execute(),Z.verbose)HY.success("RBAC tables created");return{success:!0}}catch(J){let X=J instanceof Error?J.message:String(J);return HY.error(`Failed to create RBAC tables: ${X}`),{success:!1,error:X}}}rY();import{existsSync as W0}from"fs";import{dirname as j6}from"path";import{plural as gZ,singular as R6,snakeCase as dY}from"@stacksjs/strings";import{path as w6}from"@stacksjs/path";import{globSync as H0}from"@stacksjs/storage";function mY(Z){let Y=Z.search(/[*?[]/),$=Y===-1?j6(Z):j6(Z.slice(0,Y));if(!W0($))return[];try{return H0(Z,{absolute:!0})}catch{return[]}}async function S6(){let Z=[...mY(w6.userModelsPath("*.ts")),...mY(w6.storagePath("framework/defaults/app/Models/**/*.ts"))],Y=[];for(let $ of Z){let J;try{J=(await import($)).default}catch{continue}if(!J||typeof J!=="object")continue;let X=J.table||gZ(dY(J.name||"")),W=J.belongsTo;if(Array.isArray(W))for(let H of W){let G=typeof H==="string"?H:H?.model??"";if(!G)continue;let z=`${dY(R6(G))}_id`,Q=gZ(dY(G));Y.push({fromTable:X,fromColumn:z,toTable:Q,toColumn:"id",model:J.name||""})}else if(W&&typeof W==="object")for(let H of Object.keys(W)){let G=`${dY(R6(H))}_id`,z=gZ(dY(H));Y.push({fromTable:X,fromColumn:G,toTable:z,toColumn:"id",model:J.name||""})}}return Y}async function M6(){let{db:Z}=await Promise.resolve().then(() => (F(),u)),Y=await F6();if(Y==="sqlite")return U0(Z);if(Y==="mysql")return Q0(Z);if(Y==="postgres")return _0(Z);return[]}async function G0(){let Z=await S6(),Y=await M6(),$=new Set(Y.map((X)=>`${X.fromTable.toLowerCase()}.${X.fromColumn.toLowerCase()}\u2192${X.toTable.toLowerCase()}.${X.toColumn.toLowerCase()}`)),J=Z.filter((X)=>{let W=`${X.fromTable.toLowerCase()}.${X.fromColumn.toLowerCase()}\u2192${X.toTable.toLowerCase()}.${X.toColumn.toLowerCase()}`;return!$.has(W)});return{declared:Z,live:Y,missing:J}}async function z0(Z){if((Z??await F6())!=="sqlite")return{supported:!1,total:0,orphans:[]};let{db:$}=await Promise.resolve().then(() => (F(),u)),J=await $.unsafe("PRAGMA foreign_key_check").execute(),X=Array.isArray(J)?J:[],W=new Map;async function H(_){if(W.has(_))return W.get(_);if(!/^[a-z_]\w*$/i.test(_))return W.set(_,[]),[];let U=await $.unsafe(`PRAGMA foreign_key_list("${_}")`).execute(),I=Array.isArray(U)?U:[];return W.set(_,I),I}let G=new Map;for(let _ of X){let U=_,I=String(U.table??""),O=String(U.parent??"");if(!I||!O)continue;let L=Number(U.fkid??0),A="",E=await H(I);for(let R of E){let f=R;if(Number(f.id)===L&&f.from){A=String(f.from);break}}let B=`${I}\x00${O}\x00${L}`,j=G.get(B);if(!j)j={table:I,column:A,parent:O,count:0,sampleRowids:[]},G.set(B,j);if(j.count++,j.sampleRowids.length<5&&typeof U.rowid==="number")j.sampleRowids.push(U.rowid)}let z=[...G.values()];return{supported:!0,total:z.reduce((_,U)=>_+U.count,0),orphans:z}}async function F6(){let Y=((await import("@stacksjs/env")).env?.DB_CONNECTION??"sqlite").toLowerCase();if(Y==="sqlite"||Y==="mysql"||Y==="postgres")return Y;return"other"}async function U0(Z){let Y=await Z.unsafe("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"),$=Array.isArray(Y)?Y:[],J=[];for(let X of $){let W=X.name;if(!W)continue;if(!/^[a-z_][\w]*$/i.test(W))continue;let H=await Z.unsafe(`PRAGMA foreign_key_list("${W}")`);for(let G of Array.isArray(H)?H:[]){let z=G;if((z.seq??0)!==0)continue;if(!z.from||!z.to||!z.table)continue;J.push({fromTable:W,fromColumn:z.from,toTable:z.table,toColumn:z.to})}}return J}async function Q0(Z){let Y=await Z.unsafe(`
|
|
1328
|
+
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
|
|
1329
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
1330
|
+
WHERE TABLE_SCHEMA = DATABASE()
|
|
1331
|
+
AND REFERENCED_TABLE_NAME IS NOT NULL
|
|
1332
|
+
`);return(Array.isArray(Y)?Y:[]).map(($)=>({fromTable:String($.TABLE_NAME??$.table_name??""),fromColumn:String($.COLUMN_NAME??$.column_name??""),toTable:String($.REFERENCED_TABLE_NAME??$.referenced_table_name??""),toColumn:String($.REFERENCED_COLUMN_NAME??$.referenced_column_name??"")})).filter(($)=>$.fromTable&&$.fromColumn&&$.toTable&&$.toColumn)}async function _0(Z){let Y=await Z.unsafe(`
|
|
1333
|
+
SELECT
|
|
1334
|
+
kcu.table_name AS from_table,
|
|
1335
|
+
kcu.column_name AS from_column,
|
|
1336
|
+
ccu.table_name AS to_table,
|
|
1337
|
+
ccu.column_name AS to_column
|
|
1338
|
+
FROM information_schema.referential_constraints rc
|
|
1339
|
+
JOIN information_schema.key_column_usage kcu
|
|
1340
|
+
ON kcu.constraint_name = rc.constraint_name
|
|
1341
|
+
AND kcu.constraint_schema = rc.constraint_schema
|
|
1342
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
1343
|
+
ON ccu.constraint_name = rc.constraint_name
|
|
1344
|
+
AND ccu.constraint_schema = rc.constraint_schema
|
|
1345
|
+
WHERE rc.constraint_schema = 'public'
|
|
1346
|
+
`);return(Array.isArray(Y)?Y:[]).map(($)=>({fromTable:String($.from_table??""),fromColumn:String($.from_column??""),toTable:String($.to_table??""),toColumn:String($.to_column??"")})).filter(($)=>$.fromTable&&$.fromColumn&&$.toTable&&$.toColumn)}import{path as D6}from"@stacksjs/path";import{plural as O0,snakeCase as dZ}from"@stacksjs/strings";async function x6(){let Z=[...mY(D6.userModelsPath("*.ts")),...mY(D6.storagePath("framework/defaults/app/Models/**/*.ts"))],Y=[];for(let $ of Z){let J;try{J=(await import($)).default}catch{continue}if(!J||typeof J!=="object")continue;let X=J.table||O0(dZ(J.name||"")),W=J.name||"",H=J.attributes;if(H&&typeof H==="object"){for(let[z,Q]of Object.entries(H))if(Q&&typeof Q==="object"&&Q.unique===!0)Y.push({table:X,columns:[dZ(z)],model:W,source:"attribute"})}let G=J.indexes;if(Array.isArray(G)){for(let z of G)if(z&&z.unique===!0&&Array.isArray(z.columns)&&z.columns.length>0)Y.push({table:X,columns:z.columns.map((Q)=>dZ(Q)),model:W,source:"index",indexName:z.name})}}return Y}async function T6(Z){let{db:Y}=await Promise.resolve().then(() => (F(),u)),$=Z??await P6();if($==="sqlite")return B0(Y);if($==="mysql")return L0(Y);if($==="postgres")return E0(Y);return[]}async function V0(Z){let Y=Z??await P6();if(Y!=="sqlite"&&Y!=="mysql"&&Y!=="postgres")return{supported:!1,declared:[],live:[],missing:[],skippedTables:[]};let $=await x6(),J=await T6(Y),X=await A0(Y),W=new Map;for(let z of J){let Q=z.table.toLowerCase(),_=q6(z.columns);if(!W.has(Q))W.set(Q,new Set);W.get(Q).add(_)}let H=[],G=new Set;for(let z of $){let Q=z.table.toLowerCase();if(!X.has(Q)){G.add(z.table);continue}let _=q6(z.columns);if(!(W.get(Q)?.has(_)??!1))H.push(z)}return{supported:!0,declared:$,live:J,missing:H,skippedTables:[...G]}}async function A0(Z){let{db:Y}=await Promise.resolve().then(() => (F(),u)),$=[];if(Z==="sqlite"){let J=await Y.unsafe("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").execute();$=(Array.isArray(J)?J:[]).map((X)=>X.name)}else if(Z==="mysql"){let J=await Y.unsafe("SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()").execute();$=(Array.isArray(J)?J:[]).map((X)=>X.name??X.TABLE_NAME)}else if(Z==="postgres"){let J=await Y.unsafe("SELECT tablename AS name FROM pg_tables WHERE schemaname = 'public'").execute();$=(Array.isArray(J)?J:[]).map((X)=>X.name??X.tablename)}return new Set($.filter((J)=>typeof J==="string"&&J.length>0).map((J)=>J.toLowerCase()))}function q6(Z){return[...Z].map((Y)=>Y.toLowerCase()).sort().join(",")}async function P6(){let Y=((await import("@stacksjs/env")).env?.DB_CONNECTION??"sqlite").toLowerCase();if(Y==="sqlite"||Y==="mysql"||Y==="postgres")return Y;return"other"}async function B0(Z){let Y=await Z.unsafe("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").execute(),$=Array.isArray(Y)?Y:[],J=[];for(let X of $){let W=X.name;if(!W)continue;if(!/^[a-z_]\w*$/i.test(W))continue;let H=await Z.unsafe(`PRAGMA index_list("${W}")`).execute();for(let G of Array.isArray(H)?H:[]){let z=G;if(Number(z.unique)!==1||!z.name)continue;if(!/^[a-z_]\w*$/i.test(z.name))continue;let Q=await Z.unsafe(`PRAGMA index_info("${z.name}")`).execute(),_=(Array.isArray(Q)?Q:[]).map((U)=>String(U.name??"")).filter((U)=>U.length>0);if(_.length>0)J.push({table:W,name:z.name,columns:_})}}return J}async function L0(Z){let Y=await Z.unsafe(`
|
|
1347
|
+
SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX
|
|
1348
|
+
FROM information_schema.STATISTICS
|
|
1349
|
+
WHERE TABLE_SCHEMA = DATABASE()
|
|
1350
|
+
AND NON_UNIQUE = 0
|
|
1351
|
+
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
|
|
1352
|
+
`).execute();return k6(Array.isArray(Y)?Y:[],($)=>({table:String($.TABLE_NAME??$.table_name??""),name:String($.INDEX_NAME??$.index_name??""),column:String($.COLUMN_NAME??$.column_name??"")}))}async function E0(Z){let Y=await Z.unsafe(`
|
|
1353
|
+
SELECT
|
|
1354
|
+
t.relname AS table_name,
|
|
1355
|
+
ix.relname AS index_name,
|
|
1356
|
+
a.attname AS column_name,
|
|
1357
|
+
k.ord AS seq_in_index
|
|
1358
|
+
FROM pg_index i
|
|
1359
|
+
JOIN pg_class t ON t.oid = i.indrelid
|
|
1360
|
+
JOIN pg_class ix ON ix.oid = i.indexrelid
|
|
1361
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
1362
|
+
JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) ON true
|
|
1363
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
1364
|
+
WHERE i.indisunique = true
|
|
1365
|
+
AND n.nspname = 'public'
|
|
1366
|
+
ORDER BY table_name, index_name, seq_in_index
|
|
1367
|
+
`).execute();return k6(Array.isArray(Y)?Y:[],($)=>({table:String($.table_name??""),name:String($.index_name??""),column:String($.column_name??"")}))}function k6(Z,Y){let $=new Map;for(let J of Z){let{table:X,name:W,column:H}=Y(J);if(!X||!W||!H)continue;let G=`${X} ${W}`,z=$.get(G);if(z)z.columns.push(H);else $.set(G,{table:X,name:W,columns:[H]})}return[...$.values()]}import{AsyncLocalStorage as I0}from"async_hooks";var SY=new I0;function K0(){return SY.getStore()!==void 0}function j0(Z){let Y=SY.getStore();if(!Y)return!1;return Y.pending.push(Z),!0}async function R0(Z,Y={}){let $=SY.getStore();if($){$.depth+=1;try{return await Z()}finally{$.depth-=1}}let J={pending:[],depth:1,onError:Y.onError},X;try{X=await SY.run(J,Z)}catch(W){throw J.pending.length=0,W}return await N6(J),X}async function N6(Z){for(let Y=0;Y<Z.pending.length;Y++)try{await Z.pending[Y]()}catch($){if(Z.onError)try{Z.onError($,Y)}catch{}else console.error("[transaction-context] after-commit callback threw:",$)}Z.pending.length=0}async function w0(){let Z=SY.getStore();if(!Z)return 0;let Y=Z.pending.length;return await N6(Z),Y}function S0(){return SY.getStore()?.pending.length??0}import{createQueryBuilder as iJ,setConfig as aJ}from"@stacksjs/query-builder";export{l6 as validateDriverConfig,d$ as uuidColumnSql,f$ as usersTwoFactorColumnsSql,b$ as usersStripeIdSql,v$ as usersPasswordChangedAtSql,h$ as usersEmailVerifiedAtSql,uY as unmarshall,U1 as truncateMigrationTables,WY as sqlHelpers,TY as sql,s7 as setQueryTracker,aJ as setConfig,M4 as seedModelDirect,T5 as seedModel$,I8 as seed,F8 as scaffoldClassSeedersFromModels,I8 as runSeeders,R0 as runInTransactionScope,X5 as runDatabaseMigration,H8 as runClassSeeders,t1 as resetSqliteDatabase,C1 as resetPostgresDatabase,S1 as resetMysqlDatabase,W5 as resetDatabase,D8 as renderSeederFile,z8 as renameColumnSafely,H5 as previewPendingMigrations,N7 as preprocessSqliteMigrations,k8 as prepareTextColumnType,N8 as prepareNumberColumnType,y8 as prepareEnumColumnType,i5 as prepareDateTimeColumnType,EY as pluckChanges,_$ as parseKeyPattern,n5 as modelTableName,X0 as migrateRbacTables,a$ as migrateNotificationTables,s9 as migrateAuthTables,r6 as mergeWithDefaults,h as marshall,XY as mapFieldTypeToColumnType,l7 as logQuery,k5 as listSeedableModels,_8 as isProtectedModel,K0 as isInTransaction,IY as isArrayEqual,Z4 as initializeDbConfig,$Y as hasTableBeenMigrated,q as hasMigrationBeenCreated,zY as getUpvoteTableName,z1 as getTraitTables,T6 as getLiveUniqueIndexes,M6 as getLiveFKs,jY as getLikeableForeignKey,m as getLastMigrationFields,P8 as getExecutedMigrations,x6 as getDeclaredUniques,S6 as getDeclaredFKs,s6 as getConnectionString,o as getConnectionDefaults,n6 as getConfigFromEnv,Z9 as generateSqliteMigration,p1 as generatePostgresTraitMigrations,c1 as generatePostgresMigration,F1 as generateMysqlTraitMigrations,M1 as generateMysqlMigration,z5 as generateMigrations2,G5 as generateMigrations,Q$ as generateKeyPattern,P5 as freshWithSeed,P5 as freshSeed,m$ as findUuidTables,z0 as findFkOrphans,KY as findDifferingKeys,J$ as fetchTestSqliteFile,eY as fetchTables,Y9 as fetchSqliteFile,o8 as fetchPostgresTables,q4 as factoryGenerate,w8 as factory,ZJ as ensureUuidColumnsForCurrentDriver,s$ as ensureUuidColumns,p$ as ensureUsersAuthColumns,_Z as ensureDatabaseConfigLoaded,j0 as enqueueAfterCommit,V$ as dynamo,$$ as dropSqliteTables,l8 as dropPostgresTables,p8 as dropMysqlTables,o4 as dropMigrationTables,ZZ as dropCommonTables,lZ as driverDefaults,i6 as detectDriver,AY as deleteMigrationFiles,BY as deleteFrameworkModels,V as db,TZ as createTaggablesTable,s4 as createTaggableTable,g6 as createSqliteDatabase,Z6 as createQueryLogsTable,iJ as createQueryBuilder,l4 as createPostgresTagsTable,PZ as createPostgresTaggablesTable,$6 as createPostgresQueryLogsTable,$1 as createPostgresPasswordResetsTable,m4 as createPostgresPasskeyMigration,d6 as createPostgresDatabase,a4 as createPostgresCommentsTable,Y6 as createPostgresCommentablesPivotTable,e4 as createPostgresCommentUpvoteMigration,n4 as createPostgresCategorizableTable,YZ as createPasswordResetsTable,d4 as createPasskeyMigration,m6 as createMysqlDatabase,K9 as createModelAuditsTable,y9 as createJobsMigration,F9 as createErrorsTable,A$ as createDynamo,u6 as createDatabase,i4 as createCommentablesTable,Q1 as createCommentablesPivotTable,t4 as createCommentUpvoteMigration,r4 as createCategorizableTable,c8 as createAlterTableMigration,$9 as copyModelFiles,e1 as configureSqlitePragmas,a5 as compareRanges,LY as checkPivotMigration,o5 as checkIsRequired,O$ as buildKey,j4 as backfillInBatches,V0 as auditUniqueIndexes,G0 as auditForeignKeys,JY as arrangeColumns,W7 as applySqlitePragmas,G8 as addColumnSafely,e6 as acquireDbConfigLock,S0 as __pendingAfterCommitCount,w0 as __flushAfterCommitNow,I4 as Seeder,OZ as SQLITE_BOOTSTRAP_PRAGMAS,N0 as REDIS_DEFAULTS,Q8 as PROTECTED_MODELS,bZ as EntityQueryBuilder,a as Database,nZ as DB_USERS,rZ as DB_PORTS,GZ as DB_NAMES,k0 as DB_HOST_DEFAULT,y0 as AWS_DEFAULTS};
|