bun-query-builder 0.2.52 → 0.2.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/dist/bin/cli.js CHANGED
@@ -1,528 +1,44 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var{defineProperty:n5,getOwnPropertyNames:VZ,getOwnPropertyDescriptor:OZ}=Object,MZ=Object.prototype.hasOwnProperty;function KZ($){return this[$]}var BZ=($)=>{var J=($U??=new WeakMap).get($),G;if(J)return J;if(J=n5({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var H of VZ($))if(!MZ.call(J,H))n5(J,H,{get:KZ.bind($,H),enumerable:!(G=OZ($,H))||G.enumerable})}return $U.set($,J),J},$U;var CZ=($)=>$;function IZ($,J){this[$]=CZ.bind(null,J)}var r5=($,J)=>{for(var G in J)n5($,G,{get:J[G],enumerable:!0,configurable:!0,set:IZ.bind(J,G)})};var a=($,J)=>()=>($&&(J=$($=0)),J);var G0=import.meta.require;function v4($){j0={...j0,...$}}function g4(){return j0}function b4(){return typeof window<"u"&&typeof document<"u"}async function oG(){if(j0.getToken){let $=j0.getToken();return $ instanceof Promise?$:$}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function G$(){let $={"Content-Type":"application/json",Accept:"application/json",...j0.headers},J=await oG();if(J)$.Authorization=`Bearer ${J}`;return $}async function Q$($){if($.status===401)throw j0.onUnauthorized?.(),new m$("Unauthorized",401);if(!$.ok){let G=await $.json().catch(()=>({message:"Request failed"}));throw new m$(G.message||`HTTP ${$.status}`,$.status)}let J=await $.json();if(j0.transformResponse)return j0.transformResponse(J);return J}class JU{state;constructor($){this.state={table:$,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...$){return this.state.selectColumns=$,this}where($,J,G){if(G===void 0)this.state.wheres.push({column:$,operator:"=",value:J,boolean:"and"});else this.state.wheres.push({column:$,operator:J,value:G,boolean:"and"});return this}orWhere($,J,G){if(G===void 0)this.state.wheres.push({column:$,operator:"=",value:J,boolean:"or"});else this.state.wheres.push({column:$,operator:J,value:G,boolean:"or"});return this}andWhere($,J,G){return G===void 0?this.where($,J):this.where($,J,G)}whereNull($){return this.where($,"is",null)}whereNotNull($){return this.where($,"is not",null)}whereIn($,J){return this.where($,"in",J)}whereNotIn($,J){return this.where($,"not in",J)}orderBy($,J="asc"){return this.state.orderBy.push({column:$,direction:J}),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 J of this.state.wheres)if(J.operator==="=")$.append(J.column,String(J.value));else if(J.operator==="in"&&Array.isArray(J.value))$.append(`${J.column}[]`,J.value.join(","));else if(J.operator==="is"&&J.value===null)$.append(`filter[${J.column}][is]`,"null");else if(J.operator==="is not"&&J.value===null)$.append(`filter[${J.column}][is_not]`,"null");else $.append(`filter[${J.column}][${J.operator}]`,String(J.value));if(this.state.orderBy.length>0){let J=this.state.orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");$.append("sort",J)}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 J=`${j0.baseUrl}/${this.state.table}`;if($!==void 0)return`${J}/${$}`;let H=this.buildQueryParams().toString();return H?`${J}?${H}`:J}async get(){let $=this.buildUrl(),J=await fetch($,{method:"GET",headers:await G$()}),G=await Q$(J);return Array.isArray(G)?G:G.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new m$(`No ${this.state.table} found`,404);return $}async find($){let J=this.buildUrl($);try{let G=await fetch(J,{method:"GET",headers:await G$()});if(G.status===404)return null;let H=await Q$(G);return"data"in H&&!Array.isArray(H.data)?H.data:H}catch{return null}}async findOrFail($){let J=await this.find($);if(!J)throw new m$(`${this.state.table} with id ${$} not found`,404);return J}async count(){let $=this.buildQueryParams();$.append("count","true");let J=`${j0.baseUrl}/${this.state.table}?${$.toString()}`,G=await fetch(J,{method:"GET",headers:await G$()});return(await Q$(G)).count}async exists(){return await this.count()>0}async create($){let J=`${j0.baseUrl}/${this.state.table}`,G=j0.transformRequest?j0.transformRequest($):$,H=await fetch(J,{method:"POST",headers:await G$(),body:JSON.stringify(G)}),A=await Q$(H);return"data"in A&&!Array.isArray(A.data)?A.data:A}async insert($){return this.create($)}async update($,J){let G=`${j0.baseUrl}/${this.state.table}/${$}`,H=j0.transformRequest?j0.transformRequest(J):J,A=await fetch(G,{method:"PATCH",headers:await G$(),body:JSON.stringify(H)}),z=await Q$(A);return"data"in z&&!Array.isArray(z.data)?z.data:z}async delete($){let J=`${j0.baseUrl}/${this.state.table}/${$}`;return(await fetch(J,{method:"DELETE",headers:await G$()})).ok}async destroy($){return this.delete($)}async paginate($=1,J=15){this.limit(J).offset(($-1)*J);let G=this.buildQueryParams();G.append("paginate","true");let H=`${j0.baseUrl}/${this.state.table}?${G.toString()}`,A=await fetch(H,{method:"GET",headers:await G$()});return Q$(A)}toState(){return{...this.state}}}function GU($){return new JU($)}function m4(){return new Proxy({},{get:($,J)=>{return()=>GU(J)}})}class p1{_attributes;_definition;constructor($,J={}){this._definition=$,this._attributes={...J}}get($){return this._attributes[$]}set($,J){this._attributes[$]=J}get attributes(){return{...this._attributes}}get id(){let $=this._definition.primaryKey||"id";return this._attributes[$]}toJSON(){let $=new Set;for(let[G,H]of Object.entries(this._definition.attributes))if(H.hidden)$.add(G);let J={};for(let[G,H]of Object.entries(this._attributes))if(!$.has(G))J[G]=H;return J}}class C0{_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($,J,G){if(G===void 0)this._wheres.push({column:$,operator:"=",value:J,boolean:"and"});else this._wheres.push({column:$,operator:J,value:G,boolean:"and"});return this}orWhere($,J,G){if(G===void 0)this._wheres.push({column:$,operator:"=",value:J,boolean:"or"});else this._wheres.push({column:$,operator:J,value:G,boolean:"or"});return this}whereIn($,J){return this._wheres.push({column:$,operator:"in",value:J,boolean:"and"}),this}whereNotIn($,J){return this._wheres.push({column:$,operator:"not in",value:J,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($,J){return this._wheres.push({column:$,operator:"like",value:J,boolean:"and"}),this}orderBy($,J="asc"){return this._orderBy.push({column:$,direction:J}),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 J of this._wheres)if(J.operator==="=")$.append(J.column,String(J.value));else if(J.operator==="in"&&Array.isArray(J.value))$.append(`${J.column}[]`,J.value.join(","));else if(J.operator==="is"&&J.value===null)$.append(`filter[${J.column}][is]`,"null");else if(J.operator==="is not"&&J.value===null)$.append(`filter[${J.column}][is_not]`,"null");else $.append(`filter[${J.column}][${J.operator}]`,String(J.value));if(this._orderBy.length>0){let J=this._orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");$.append("sort",J)}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 J=`${j0.baseUrl}/${this.getTablePath()}`;if($!==void 0)return`${J}/${$}`;let H=this.buildQueryParams().toString();return H?`${J}?${H}`:J}async get(){let $=this.buildUrl(),J=await fetch($,{method:"GET",headers:await G$()}),G=await Q$(J);return(Array.isArray(G)?G:G.data).map((A)=>new p1(this._definition,A))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new m$(`No ${this._definition.name} found`,404);return $}async find($){let J=this.buildUrl($);try{let G=await fetch(J,{method:"GET",headers:await G$()});if(G.status===404)return null;let H=await Q$(G),A="data"in H&&!Array.isArray(H.data)?H.data:H;return new p1(this._definition,A)}catch{return null}}async findOrFail($){let J=await this.find($);if(!J)throw new m$(`${this._definition.name} with id ${$} not found`,404);return J}async count(){let $=this.buildQueryParams();$.append("count","true");let J=`${j0.baseUrl}/${this.getTablePath()}?${$.toString()}`,G=await fetch(J,{method:"GET",headers:await G$()});return(await Q$(G)).count}async exists(){return await this.count()>0}async pluck($){return this._select=[$],(await this.get()).map((G)=>G.get($))}async paginate($=1,J=15){this._limit=J,this._offset=($-1)*J;let G=this.buildQueryParams();G.append("paginate","true");let H=`${j0.baseUrl}/${this.getTablePath()}?${G.toString()}`,A=await fetch(H,{method:"GET",headers:await G$()}),z=await Q$(A);return{...z,data:z.data.map((U)=>new p1(this._definition,U))}}}function HU($){return new Proxy({query:()=>new C0($),where(G,H,A){return new C0($).where(G,H,A)},orWhere(G,H,A){return new C0($).orWhere(G,H,A)},whereIn(G,H){return new C0($).whereIn(G,H)},whereNotIn(G,H){return new C0($).whereNotIn(G,H)},whereNull(G){return new C0($).whereNull(G)},whereNotNull(G){return new C0($).whereNotNull(G)},whereLike(G,H){return new C0($).whereLike(G,H)},orderBy(G,H="asc"){return new C0($).orderBy(G,H)},orderByDesc(G){return new C0($).orderByDesc(G)},select(...G){return new C0($).select(...G)},limit:(G)=>new C0($).limit(G),take:(G)=>new C0($).take(G),skip:(G)=>new C0($).skip(G),latest:(G="created_at")=>new C0($).latest(G),oldest:(G="created_at")=>new C0($).oldest(G),async find(G){return new C0($).find(G)},async findOrFail(G){return new C0($).findOrFail(G)},async all(){return new C0($).get()},async first(){return new C0($).first()},async firstOrFail(){return new C0($).firstOrFail()},async count(){return new C0($).count()},async exists(){return new C0($).exists()},async paginate(G,H){return new C0($).paginate(G,H)},async pluck(G){return new C0($).pluck(G)},async create(G){let H=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,A=`${j0.baseUrl}/${H}`,z=j0.transformRequest?j0.transformRequest(G):G,U=await fetch(A,{method:"POST",headers:await G$(),body:JSON.stringify(z)}),h=await Q$(U),Y="data"in h&&!Array.isArray(h.data)?h.data:h;return new p1($,Y)},async update(G,H){let A=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,z=`${j0.baseUrl}/${A}/${G}`,U=j0.transformRequest?j0.transformRequest(H):H,h=await fetch(z,{method:"PATCH",headers:await G$(),body:JSON.stringify(U)}),Y=await Q$(h),Z="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new p1($,Z)},async delete(G){let H=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,A=`${j0.baseUrl}/${H}/${G}`;return(await fetch(A,{method:"DELETE",headers:await G$()})).ok},async destroy(G){return this.delete(G)},getDefinition:()=>$,getTable:()=>$.table},{get(G,H){if(typeof H==="string"&&H.startsWith("where")&&H.length>5){let A=H.slice(5),z=A.charAt(0).toLowerCase()+A.slice(1);if(z in $.attributes||z==="id"||z===$.primaryKey)return(U)=>new C0($).where(z,U)}return Reflect.get(G,H)}})}var j0,m$,c4,u4;var l5=a(()=>{j0={baseUrl:""};m$=class m$ extends Error{status;constructor($,J){super($);this.name="BrowserQueryError",this.status=J}};c4={async login($){let J=await fetch(`${j0.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...j0.headers},body:JSON.stringify($)});if(!J.ok){let A=await J.json().catch(()=>({message:"Login failed"}));throw new m$(A.message||"Login failed",J.status)}let G=await J.json(),H=G.data||G;if(typeof localStorage<"u"&&H.token)localStorage.setItem("auth_token",H.token);return H},async register($){let J=await fetch(`${j0.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...j0.headers},body:JSON.stringify($)});if(!J.ok){let A=await J.json().catch(()=>({message:"Registration failed"}));throw new m$(A.message||"Registration failed",J.status)}let G=await J.json(),H=G.data||G;if(typeof localStorage<"u"&&H.token)localStorage.setItem("auth_token",H.token);return H},async logout(){if(await oG())try{await fetch(`${j0.baseUrl}/logout`,{method:"POST",headers:await G$()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await oG())return null;try{let J=await fetch(`${j0.baseUrl}/user`,{method:"GET",headers:await G$()});if(J.status===401)return j0.onUnauthorized?.(),null;if(!J.ok)return null;let G=await J.json();return G.user||G}catch{return null}},async check(){return await this.user()!==null},getToken:oG},u4=GU});class s5{config;entityMappings=new Map;constructor($){if(this.config=$,$.entityMappings)for(let J of $.entityMappings)this.registerEntity(J)}createTable($){return{...$,billingMode:$.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable($){return{tableName:$}}registerEntity($){this.entityMappings.set($.entityType,$)}getEntityMapping($){return this.entityMappings.get($)}buildPrimaryKey($,J){let G=this.entityMappings.get($);if(!G)throw Error(`No entity mapping found for type: ${$}`);let H=this.interpolatePattern(G.pkPattern,J),A=this.interpolatePattern(G.skPattern,J);return{pk:H,sk:A}}parseEntityFromItem($){let J=$.pk||$.PK;if(!J)return null;for(let[G,H]of this.entityMappings){let A=H.pkPattern.split("${")[0];if(J.startsWith(A))return{entityType:G,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 J={},G={},H=[],A=0;if($.set&&Object.keys($.set).length>0){let z=[];for(let[U,h]of Object.entries($.set)){let Y=`#attr${A}`,Z=`:val${A}`;J[Y]=U,G[Z]=this.marshallValue(h),z.push(`${Y} = ${Z}`),A++}H.push(`SET ${z.join(", ")}`)}if($.remove&&$.remove.length>0){let z=[];for(let U of $.remove){let h=`#attr${A}`;J[h]=U,z.push(h),A++}H.push(`REMOVE ${z.join(", ")}`)}if($.add&&Object.keys($.add).length>0){let z=[];for(let[U,h]of Object.entries($.add)){let Y=`#attr${A}`,Z=`:val${A}`;J[Y]=U,G[Z]=this.marshallValue(h),z.push(`${Y} ${Z}`),A++}H.push(`ADD ${z.join(", ")}`)}if($.delete&&Object.keys($.delete).length>0){let z=[];for(let[U,h]of Object.entries($.delete)){let Y=`#attr${A}`,Z=`:val${A}`;J[Y]=U,G[Z]=this.marshallValue(h),z.push(`${Y} ${Z}`),A++}H.push(`DELETE ${z.join(", ")}`)}return{expression:H.join(" "),expressionAttributeNames:J,expressionAttributeValues:G}}buildProjectionExpression($){let J={},G=[];return $.forEach((H,A)=>{let z=`#proj${A}`;J[z]=H,G.push(z)}),{expression:G.join(", "),expressionAttributeNames:J}}marshall($){let J={};for(let[G,H]of Object.entries($))J[G]=this.marshallValue(H);return J}unmarshall($){let J={};for(let[G,H]of Object.entries($))J[G]=this.unmarshallValue(H);return J}interpolatePattern($,J){return $.replace(/\$\{(\w+)\}/g,(G,H)=>{if(!(H in J))throw Error(`Missing value for pattern key: ${H}`);return String(J[H])})}buildExpression($,J){let G={},H={},A=[];return $.forEach((z,U)=>{let h=`#attr${U}`;G[h]=z.attribute;let Y;switch(z.operator){case"=":case"<":case"<=":case">":case">=":{let Z=`:val${U}`;H[Z]=this.marshallValue(z.value),Y=`${h} ${z.operator} ${Z}`;break}case"BETWEEN":{let Z=`:val${U}a`,E=`:val${U}b`;H[Z]=this.marshallValue(z.values?.[0]),H[E]=this.marshallValue(z.values?.[1]),Y=`${h} BETWEEN ${Z} AND ${E}`;break}case"begins_with":{let Z=`:val${U}`;H[Z]=this.marshallValue(z.value),Y=`begins_with(${h}, ${Z})`;break}case"contains":{let Z=`:val${U}`;H[Z]=this.marshallValue(z.value),Y=`contains(${h}, ${Z})`;break}case"attribute_exists":Y=`attribute_exists(${h})`;break;case"attribute_not_exists":Y=`attribute_not_exists(${h})`;break;case"attribute_type":{let Z=`:val${U}`;H[Z]={S:z.value},Y=`attribute_type(${h}, ${Z})`;break}case"IN":{let Z=(z.values??[]).map((E,X)=>`:val${U}_${X}`);z.values?.forEach((E,X)=>{H[`:val${U}_${X}`]=this.marshallValue(E)}),Y=`${h} IN (${Z.join(", ")})`;break}default:throw Error(`Unknown operator: ${z.operator}`)}A.push(Y)}),{expression:A.join(` ${J} `),expressionAttributeNames:G,expressionAttributeValues:H}}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 J=typeof $[0],G=$.every((A)=>typeof A==="string"),H=$.every((A)=>typeof A==="number");if(G)return{SS:$};if(H)return{NS:$.map(String)};return{L:$.map((A)=>this.marshallValue(A))}}if(typeof $==="object"){let J={};for(let[G,H]of Object.entries($))J[G]=this.marshallValue(H);return{M:J}}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((J)=>this.unmarshallValue(J));if("M"in $){let J={};for(let[G,H]of Object.entries($.M))J[G]=this.unmarshallValue(H);return J}return $}}function C$($){return new s5($)}async function pJ($,J){let G=$ instanceof ArrayBuffer?$:$.buffer.slice($.byteOffset,$.byteOffset+$.byteLength),H=await crypto.subtle.importKey("raw",G,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",H,new TextEncoder().encode(J))}async function AU($){let J=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return Array.from(new Uint8Array(J)).map((G)=>G.toString(16).padStart(2,"0")).join("")}async function SZ($,J,G,H){let A=await pJ(new TextEncoder().encode(`AWS4${$}`),J),z=await pJ(A,G),U=await pJ(z,H);return pJ(U,"aws4_request")}async function _Z($,J,G,H,A,z,U){let Y=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),Z=Y.slice(0,8),E=J.pathname,X=J.search.slice(1),F={...G,host:J.host,"x-amz-date":Y};if(A.sessionToken)F["x-amz-security-token"]=A.sessionToken;let R=Object.keys(F).sort(),C=R.map((N)=>`${N.toLowerCase()}:${F[N].trim()}`).join(`
4
- `)+`
5
- `,W=R.map((N)=>N.toLowerCase()).join(";"),Q=await AU(H),D=[$,E,X,C,W,Q].join(`
6
- `),w=await AU(D),K="AWS4-HMAC-SHA256",V=`${Z}/${z}/${U}/aws4_request`,q=[K,Y,V,w].join(`
7
- `),P=await SZ(A.secretAccessKey,Z,z,U),T=await pJ(P,q),I=Array.from(new Uint8Array(T)).map((N)=>N.toString(16).padStart(2,"0")).join(""),B=`${K} Credential=${A.accessKeyId}/${V}, SignedHeaders=${W}, Signature=${I}`;return{...F,authorization:B}}class tG{config;endpoint;credentials;constructor($){if(this.config=$,this.endpoint=$.endpoint??`https://dynamodb.${$.region}.amazonaws.com`,this.credentials=$.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute($,J){let G=new URL(this.endpoint),H=JSON.stringify(J),A={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${$}`},z=await _Z("POST",G,A,H,this.credentials,this.config.region,"dynamodb"),U=await fetch(G.toString(),{method:"POST",headers:z,body:H});if(!U.ok){let h=await U.text(),Y;try{let Z=JSON.parse(h);Y=Z.message??Z.Message??h}catch{Y=h}throw Error(`DynamoDB ${$} failed: ${U.status} - ${Y}`)}return U.json()}async query($){return this.execute("Query",$)}async scan($){return this.execute("Scan",$)}async getItem($){return this.execute("GetItem",$)}async putItem($){return this.execute("PutItem",$)}async updateItem($){return this.execute("UpdateItem",$)}async deleteItem($){return this.execute("DeleteItem",$)}async batchGetItem($){return this.execute("BatchGetItem",$)}async batchWriteItem($){return this.execute("BatchWriteItem",$)}async transactWriteItems($){return this.execute("TransactWriteItems",$)}async describeTable($){return this.execute("DescribeTable",{TableName:$})}async createTable($){return this.execute("CreateTable",$)}async deleteTable($){return this.execute("DeleteTable",{TableName:$})}async listTables($){return this.execute("ListTables",$??{})}async updateTable($){return this.execute("UpdateTable",$)}async updateTimeToLive($){return this.execute("UpdateTimeToLive",$)}async describeTimeToLive($){return this.execute("DescribeTimeToLive",{TableName:$})}}function i1($){return new tG($)}function PZ($){h1={...h1,...$},aG=null,eG=null}function I1(){if(!aG)aG=i1({region:h1.region??"us-east-1",endpoint:h1.endpoint,credentials:h1.credentials});return aG}function S1(){if(!eG)eG=C$({region:h1.region??"us-east-1",endpoint:h1.endpoint,credentials:h1.credentials});return eG}class zU{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor($={}){this._attributes={...$},this._original={...$};for(let[J,G]of Object.entries($))this[J]=G}static query(){return new UU(this)}static async find($){let J=this,G=I1(),H=S1(),A=`${J.pkPrefix}${J.keyDelimiter}${$}`,z=J.skPrefix;try{let U=await G.getItem({TableName:J.tableName,Key:H.marshall({[J.pkAttribute]:A,[J.skAttribute]:z})});if(!U.Item)return null;let h=H.unmarshall(U.Item),Y=new J(h);return Y._exists=!0,Y}catch(U){return console.error("Find error:",U),null}}static async findOrFail($){let J=await this.find($);if(!J)throw Error(`${this.name} not found with id: ${$}`);return J}static async all(){return this.query().get()}static async create($){let J=this,G=I1(),H=S1(),A=$[J.primaryKey];if(!A)throw Error(`${J.primaryKey} is required`);let z=`${J.pkPrefix}${J.keyDelimiter}${A}`,U=J.skPrefix,h=new Date().toISOString(),Y={...$,[J.pkAttribute]:z,[J.skAttribute]:U,[J.entityTypeAttribute]:J.name};if(J.timestamps)Y[J.createdAtField]=h,Y[J.updatedAtField]=h;await G.putItem({TableName:J.tableName,Item:H.marshall(Y),ConditionExpression:`attribute_not_exists(${J.pkAttribute})`});let Z=new J(Y);return Z._exists=!0,Z}static async updateOrCreate($,J){let G=this,H=$[G.primaryKey],A=await G.find(H);if(A)return await A.update(J),A;return G.create({...$,...J})}static where($,J,G){return this.query().where($,J,G)}static wherePk($){return this.query().wherePk($)}getKey(){let $=this.constructor;return this[$.primaryKey]}getAttribute($){return this._attributes[$]}setAttribute($,J){return this._attributes[$]=J,this[$]=J,this}getAttributes(){return{...this._attributes}}isDirty($){if($)return this._attributes[$]!==this._original[$];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let $={};for(let[J,G]of Object.entries(this._attributes))if(G!==this._original[J])$[J]=G;return $}async save(){if(this._exists){let $=this.getDirty();if(Object.keys($).length>0)await this.update($)}else{let J=await this.constructor.create(this._attributes);this._attributes=J._attributes,this._original={...this._attributes},this._exists=!0}return this}async update($){let J=this.constructor,G=I1(),H=S1(),A=this.getKey(),z=`${J.pkPrefix}${J.keyDelimiter}${A}`,U=J.skPrefix,h=new Date().toISOString(),Y={...$};if(J.timestamps)Y[J.updatedAtField]=h;let Z=[],E={},X={},F=0;for(let[R,C]of Object.entries(Y)){let W=`#attr${F}`,Q=`:val${F}`;E[W]=R,X[Q]=H.marshall({v:C}).v,Z.push(`${W} = ${Q}`),F++}await G.updateItem({TableName:J.tableName,Key:H.marshall({[J.pkAttribute]:z,[J.skAttribute]:U}),UpdateExpression:`SET ${Z.join(", ")}`,ExpressionAttributeNames:E,ExpressionAttributeValues:X});for(let[R,C]of Object.entries(Y))this._attributes[R]=C,this[R]=C;return this._original={...this._attributes},this}async delete(){let $=this.constructor,J=I1(),G=S1(),H=this.getKey(),A=`${$.pkPrefix}${$.keyDelimiter}${H}`,z=$.skPrefix;return await J.deleteItem({TableName:$.tableName,Key:G.marshall({[$.pkAttribute]:A,[$.skAttribute]:z})}),this._exists=!1,!0}async refresh(){let J=await this.constructor.find(this.getKey());if(J){this._attributes=J._attributes,this._original={...this._attributes};for(let[G,H]of Object.entries(this._attributes))this[G]=H}return this}toObject(){let $=this.constructor,J={...this._attributes};return delete J[$.pkAttribute],delete J[$.skAttribute],delete J[$.entityTypeAttribute],J}toJSON(){return this.toObject()}}class UU{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor($){this.ModelClass=$}wherePk($){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${$}`,this}where($,J,G){if(G===void 0)this._filterConditions.push({attribute:$,operator:"=",value:J});else this._filterConditions.push({attribute:$,operator:J,value:G});return this}whereIn($,J){return this._filterConditions.push({attribute:$,operator:"IN",values:J}),this}whereBetween($,J,G){return this._filterConditions.push({attribute:$,operator:"BETWEEN",value:J,values:[J,G]}),this}whereBeginsWith($,J){return this._filterConditions.push({attribute:$,operator:"begins_with",value:J}),this}whereExists($){return this._filterConditions.push({attribute:$,operator:"attribute_exists"}),this}whereNotExists($){return this._filterConditions.push({attribute:$,operator:"attribute_not_exists"}),this}orderBy($){return this._scanForward=$==="asc",this}limit($){return this._limitValue=$,this}select(...$){return this._projectionAttrs.push(...$),this}index($){return this._indexName=$,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom($){return this._startKey=$,this}buildRequest(){let $=S1(),J={TableName:this.ModelClass.tableName};if(this._indexName)J.IndexName=this._indexName;let G={},H={},A=0,z=[];if(this._pkValue){let U=`#pk${A}`,h=`:pk${A}`;G[U]=this.ModelClass.pkAttribute,H[h]={S:this._pkValue},z.push(`${U} = ${h}`),A++}if(this._skCondition){let U=`#sk${A}`;switch(G[U]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let h=`:sk${A}`;H[h]={S:this._skCondition.value},z.push(`${U} = ${h}`);break}case"begins_with":{let h=`:sk${A}`;H[h]={S:this._skCondition.value},z.push(`begins_with(${U}, ${h})`);break}}A++}if(z.length>0)J.KeyConditionExpression=z.join(" AND ");if(this._filterConditions.length>0){let U=[];for(let h of this._filterConditions){let Y=`#flt${A}`;if(G[Y]=h.attribute,h.operator==="attribute_exists")U.push(`attribute_exists(${Y})`);else if(h.operator==="attribute_not_exists")U.push(`attribute_not_exists(${Y})`);else if(h.operator==="IN"&&h.values){let Z=h.values.map((E,X)=>`:flt${A}_${X}`);h.values.forEach((E,X)=>{H[`:flt${A}_${X}`]=$.marshall({v:E}).v}),U.push(`${Y} IN (${Z.join(", ")})`)}else if(h.operator==="BETWEEN"&&h.values){let Z=`:flt${A}a`,E=`:flt${A}b`;H[Z]=$.marshall({v:h.values[0]}).v,H[E]=$.marshall({v:h.values[1]}).v,U.push(`${Y} BETWEEN ${Z} AND ${E}`)}else if(h.operator==="begins_with"){let Z=`:flt${A}`;H[Z]=$.marshall({v:h.value}).v,U.push(`begins_with(${Y}, ${Z})`)}else{let Z=`:flt${A}`;H[Z]=$.marshall({v:h.value}).v,U.push(`${Y} ${h.operator} ${Z}`)}A++}J.FilterExpression=U.join(" AND ")}if(this._projectionAttrs.length>0){let U=[];for(let h of this._projectionAttrs){let Y=`#proj${A}`;G[Y]=h,U.push(Y),A++}J.ProjectionExpression=U.join(", ")}if(Object.keys(G).length>0)J.ExpressionAttributeNames=G;if(Object.keys(H).length>0)J.ExpressionAttributeValues=H;if(this._limitValue!==void 0)J.Limit=this._limitValue;if(J.ScanIndexForward=this._scanForward,this._consistentReadValue)J.ConsistentRead=!0;if(this._startKey)J.ExclusiveStartKey=$.marshall(this._startKey);return J}async get(){let $=I1(),J=S1(),G=this.buildRequest();return((this._pkValue!==void 0?await $.query(G):await $.scan(G)).Items??[]).map((U)=>{let h=J.unmarshall(U),Y=new this.ModelClass(h);return Y._exists=!0,Y})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let $=I1(),J=this.buildRequest();return J.Select="COUNT",(this._pkValue!==void 0?await $.query(J):await $.scan(J)).Count??0}async paginate($,J){let G=S1();if(J)this._startKey=J;this._limitValue=$;let H=I1(),A=this.buildRequest(),U=this._pkValue!==void 0?await H.query(A):await H.scan(A);return{items:(U.Items??[]).map((Y)=>{let Z=G.unmarshall(Y),E=new this.ModelClass(Z);return E._exists=!0,E}),lastKey:U.LastEvaluatedKey?G.unmarshall(U.LastEvaluatedKey):void 0}}}var h1,aG=null,eG=null;var YU=a(()=>{h1={region:process.env.AWS_REGION??"us-east-1"}});function n1($){let J=JSON.stringify({tableName:$.tableName,keySchema:$.keySchema,attributeDefinitions:[...$.attributeDefinitions||[]].sort((H,A)=>H.name.localeCompare(A.name)),globalSecondaryIndexes:[...$.globalSecondaryIndexes||[]].sort((H,A)=>H.indexName.localeCompare(A.indexName)),localSecondaryIndexes:[...$.localSecondaryIndexes||[]].sort((H,A)=>H.indexName.localeCompare(A.indexName)),billingMode:$.billingMode,ttlAttribute:$.ttlAttribute,streamSpecification:$.streamSpecification}),G=0;for(let H=0;H<J.length;H++){let A=J.charCodeAt(H);G=(G<<5)-G+A,G=G&G}return Math.abs(G).toString(16).padStart(8,"0")}function o5($){let J=hU($);return ZU(J)}function hU($){return{tableName:$.tableName||"",pkAttribute:$.pkAttribute||"pk",skAttribute:$.skAttribute||"sk",pkPrefix:$.pkPrefix||"",skPrefix:$.skPrefix||"METADATA",entityTypeAttribute:$.entityTypeAttribute||"_et",timestamps:$.timestamps!==!1,ttlAttribute:$.ttlAttribute,gsis:$.gsis,lsis:$.lsis,billingMode:$.billingMode||"PAY_PER_REQUEST",provisionedThroughput:$.provisionedThroughput,streamEnabled:$.streamEnabled,streamViewType:$.streamViewType}}function ZU($){let J=[{name:$.pkAttribute,type:"S"},{name:$.skAttribute,type:"S"}],G=[];if($.gsis)for(let H of $.gsis){if(!J.some((A)=>A.name===H.pkAttribute))J.push({name:H.pkAttribute,type:"S"});if(H.skAttribute&&!J.some((A)=>A.name===H.skAttribute))J.push({name:H.skAttribute,type:"S"});G.push({indexName:H.indexName,keySchema:{partitionKey:H.pkAttribute,sortKey:H.skAttribute},projection:{type:Array.isArray(H.projection)?"INCLUDE":H.projection||"ALL",nonKeyAttributes:Array.isArray(H.projection)?H.projection:void 0},provisionedThroughput:H.provisionedThroughput})}return{tableName:$.tableName,keySchema:{partitionKey:$.pkAttribute,sortKey:$.skAttribute},attributeDefinitions:J,globalSecondaryIndexes:G.length>0?G:void 0,billingMode:$.billingMode,provisionedThroughput:$.provisionedThroughput,ttlAttribute:$.ttlAttribute,streamSpecification:$.streamEnabled?{enabled:!0,viewType:$.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function t5($,J){let G=[],H=J.tableName;if(!$)G.push({type:"CREATE_TABLE",tableName:H,details:{definition:J}});else{let A=$.keySchema.partitionKey!==J.keySchema.partitionKey,z=$.keySchema.sortKey!==J.keySchema.sortKey;if(A||z)console.warn(`[Migration] Table ${H}: Key schema changes require table recreation. Current: pk=${$.keySchema.partitionKey}, sk=${$.keySchema.sortKey}. Target: pk=${J.keySchema.partitionKey}, sk=${J.keySchema.sortKey}. This operation is not supported automatically.`);let U=$.globalSecondaryIndexes||[],h=J.globalSecondaryIndexes||[],Y=new Set(U.map((F)=>F.indexName)),Z=new Set(h.map((F)=>F.indexName));for(let F of h)if(!Y.has(F.indexName))G.push({type:"ADD_GSI",tableName:H,details:{gsi:F}});for(let F of U)if(!Z.has(F.indexName))G.push({type:"DELETE_GSI",tableName:H,details:{indexName:F.indexName}});if($.billingMode!==J.billingMode&&J.billingMode)G.push({type:"UPDATE_BILLING_MODE",tableName:H,details:{billingMode:J.billingMode,provisionedThroughput:J.provisionedThroughput}});if($.ttlAttribute!==J.ttlAttribute)G.push({type:"UPDATE_TTL",tableName:H,details:{ttlAttribute:J.ttlAttribute||null,enabled:!!J.ttlAttribute}});let E=$.streamSpecification?.enabled,X=J.streamSpecification?.enabled;if(E!==X)if(X)G.push({type:"ENABLE_STREAM",tableName:H,details:{viewType:J.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else G.push({type:"DISABLE_STREAM",tableName:H,details:{}})}return{tableName:H,operations:G,timestamp:new Date().toISOString(),hash:n1(J)}}function NZ($,J){return n1($)===n1(J)}class $H{client;initialized=!1;constructor($){this.client=$}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(x$),this.initialized=!0}catch($){if($.message?.includes("ResourceNotFoundException")||$.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${x$}`),await this.client.createTable({TableName:x$,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(x$),this.initialized=!0;else throw $}}async waitForTableActive($,J=30){for(let G=0;G<J;G++){try{if((await this.client.describeTable($)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((H)=>setTimeout(H,1000))}throw Error(`Table ${$} did not become active within ${J} seconds`)}async getLatestState($){await this.ensureMigrationsTable();let J=`${iJ}#${$}`,G=await this.client.query({TableName:x$,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:J}},ScanIndexForward:!1,Limit:1});if(!G.Items||G.Items.length===0)return null;return this.unmarshallState(G.Items[0])}async getHistory($){await this.ensureMigrationsTable();let J=`${iJ}#${$}`,G=await this.client.query({TableName:x$,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:J}},ScanIndexForward:!1});if(!G.Items)return[];return G.Items.map((H)=>this.unmarshallState(H))}async recordMigration($,J,G){await this.ensureMigrationsTable();let H=await this.getLatestState($),A=G??(H?H.version+1:1),z=`${iJ}#${$}`,U=`${EU}#${String(A).padStart(6,"0")}`,h={tableName:$,hash:n1(J),definition:J,appliedAt:new Date().toISOString(),version:A};return await this.client.putItem({TableName:x$,Item:this.marshallState(h,z,U)}),console.log(`[Migration] Recorded migration for ${$} (version ${A})`),h}async listTrackedTables(){await this.ensureMigrationsTable();let $=await this.client.scan({TableName:x$,ProjectionExpression:"pk"});if(!$.Items)return[];let J=new Set;for(let G of $.Items){let A=(G.pk?.S||"").replace(`${iJ}#`,"");if(A)J.add(A)}return Array.from(J)}async hasMigrations($){return await this.getLatestState($)!==null}async deleteMigrationHistory($){await this.ensureMigrationsTable();let J=await this.getHistory($),G=`${iJ}#${$}`;for(let H of J){let A=`${EU}#${String(H.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:x$,Key:{pk:{S:G},sk:{S:A}}})}console.log(`[Migration] Deleted migration history for ${$}`)}marshallState($,J,G){return{pk:{S:J},sk:{S:G},tableName:{S:$.tableName},hash:{S:$.hash},definition:{S:JSON.stringify($.definition)},appliedAt:{S:$.appliedAt},version:{N:String($.version)}}}unmarshallState($){return{tableName:$.tableName?.S||"",hash:$.hash?.S||"",definition:JSON.parse($.definition?.S||"{}"),appliedAt:$.appliedAt?.S||"",version:Number($.version?.N||0)}}}var x$="_qb_migrations",iJ="MIGRATION",EU="VERSION";var a5=()=>{};class e5{client;tracker;config;constructor($){this.config=$,this.client=i1({region:$.region,endpoint:$.endpoint,credentials:$.credentials}),this.tracker=new $H(this.client)}async execute($){let J={tableName:$.tableName,success:!0,operations:[]};if($.operations.length===0)return this.log(`[Migration] No changes needed for ${$.tableName}`),J;this.log(`[Migration] Executing ${$.operations.length} operations for ${$.tableName}`);try{for(let G of $.operations)await this.executeOperation(G),J.operations.push(G.type);this.log(`[Migration] Successfully applied ${J.operations.length} operations to ${$.tableName}`)}catch(G){J.success=!1,J.error=G.message,console.error(`[Migration] Failed to execute migration for ${$.tableName}:`,G)}return J}async executeOperation($){if(this.log(`[Migration] Executing ${$.type} on ${$.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${$.type}`,$.details);return}switch($.type){case"CREATE_TABLE":await this.createTable($.details.definition);break;case"DELETE_TABLE":await this.deleteTable($.tableName);break;case"ADD_GSI":await this.addGSI($.tableName,$.details.gsi);break;case"DELETE_GSI":await this.deleteGSI($.tableName,$.details.indexName);break;case"UPDATE_TTL":await this.updateTTL($.tableName,$.details.ttlAttribute,$.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode($.tableName,$.details.billingMode,$.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream($.tableName,$.details.viewType);break;case"DISABLE_STREAM":await this.disableStream($.tableName);break;default:throw Error(`Unknown migration operation type: ${$.type}`)}}async createTable($){let J={TableName:$.tableName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:$.attributeDefinitions.map((G)=>({AttributeName:G.name,AttributeType:G.type})),BillingMode:$.billingMode||"PAY_PER_REQUEST"};if($.keySchema.sortKey)J.KeySchema.push({AttributeName:$.keySchema.sortKey,KeyType:"RANGE"});if($.billingMode==="PROVISIONED"&&$.provisionedThroughput)J.ProvisionedThroughput={ReadCapacityUnits:$.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:$.provisionedThroughput.writeCapacityUnits};if($.globalSecondaryIndexes&&$.globalSecondaryIndexes.length>0)J.GlobalSecondaryIndexes=$.globalSecondaryIndexes.map((G)=>({IndexName:G.indexName,KeySchema:[{AttributeName:G.keySchema.partitionKey,KeyType:"HASH"},...G.keySchema.sortKey?[{AttributeName:G.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:G.projection.type,...G.projection.nonKeyAttributes?{NonKeyAttributes:G.projection.nonKeyAttributes}:{}},...G.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:G.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:G.provisionedThroughput.writeCapacityUnits}}:{}}));if($.localSecondaryIndexes&&$.localSecondaryIndexes.length>0)J.LocalSecondaryIndexes=$.localSecondaryIndexes.map((G)=>({IndexName:G.indexName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:G.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:G.projection.type,...G.projection.nonKeyAttributes?{NonKeyAttributes:G.projection.nonKeyAttributes}:{}}}));if($.streamSpecification?.enabled)J.StreamSpecification={StreamEnabled:!0,StreamViewType:$.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${$.tableName}`),await this.client.createTable(J),await this.waitForTableActive($.tableName),$.ttlAttribute)await this.updateTTL($.tableName,$.ttlAttribute,!0);this.log(`[Migration] Table created: ${$.tableName}`)}async deleteTable($){this.log(`[Migration] Deleting table: ${$}`),await this.client.deleteTable($),this.log(`[Migration] Table deleted: ${$}`)}async addGSI($,J){this.log(`[Migration] Adding GSI ${J.indexName} to ${$}`);let G=await this.client.describeTable($),H=new Set(G.Table?.AttributeDefinitions?.map((U)=>U.AttributeName)||[]),A=[];if(!H.has(J.keySchema.partitionKey))A.push({AttributeName:J.keySchema.partitionKey,AttributeType:"S"});if(J.keySchema.sortKey&&!H.has(J.keySchema.sortKey))A.push({AttributeName:J.keySchema.sortKey,AttributeType:"S"});let z={TableName:$,AttributeDefinitions:A.length>0?A:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:J.indexName,KeySchema:[{AttributeName:J.keySchema.partitionKey,KeyType:"HASH"},...J.keySchema.sortKey?[{AttributeName:J.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:J.projection.type,...J.projection.nonKeyAttributes?{NonKeyAttributes:J.projection.nonKeyAttributes}:{}},...J.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:J.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:J.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(z),await this.waitForGSIActive($,J.indexName),this.log(`[Migration] GSI ${J.indexName} added to ${$}`)}async deleteGSI($,J){this.log(`[Migration] Deleting GSI ${J} from ${$}`);let G={TableName:$,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:J}}]};await this.executeUpdateTable(G),this.log(`[Migration] GSI ${J} deleted from ${$}`)}async updateTTL($,J,G){this.log(`[Migration] Updating TTL on ${$}: ${G?J:"disabled"}`);let H={TableName:$,TimeToLiveSpecification:{Enabled:G,AttributeName:J||"ttl"}};await this.executeUpdateTimeToLive(H),this.log(`[Migration] TTL updated on ${$}`)}async updateBillingMode($,J,G){this.log(`[Migration] Updating billing mode on ${$} to ${J}`);let H={TableName:$,BillingMode:J};if(J==="PROVISIONED"&&G)H.ProvisionedThroughput={ReadCapacityUnits:G.readCapacityUnits,WriteCapacityUnits:G.writeCapacityUnits};await this.executeUpdateTable(H),await this.waitForTableActive($),this.log(`[Migration] Billing mode updated on ${$}`)}async enableStream($,J){this.log(`[Migration] Enabling stream on ${$} with view type ${J}`);let G={TableName:$,StreamSpecification:{StreamEnabled:!0,StreamViewType:J}};await this.executeUpdateTable(G),await this.waitForTableActive($),this.log(`[Migration] Stream enabled on ${$}`)}async disableStream($){this.log(`[Migration] Disabling stream on ${$}`);let J={TableName:$,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(J),await this.waitForTableActive($),this.log(`[Migration] Stream disabled on ${$}`)}async executeUpdateTable($){await this.client.updateTable($)}async executeUpdateTimeToLive($){await this.client.updateTimeToLive($)}async waitForTableActive($,J=60){this.log(`[Migration] Waiting for table ${$} to become active...`);for(let G=0;G<J;G++){try{let A=(await this.client.describeTable($)).Table?.TableStatus;if(A==="ACTIVE")return;this.log(`[Migration] Table status: ${A}, waiting...`)}catch{}await new Promise((H)=>setTimeout(H,2000))}throw Error(`Table ${$} did not become active within ${J*2} seconds`)}async waitForGSIActive($,J,G=120){this.log(`[Migration] Waiting for GSI ${J} to become active...`);for(let H=0;H<G;H++){try{let z=(await this.client.describeTable($)).Table?.GlobalSecondaryIndexes?.find((h)=>h.IndexName===J);if(z?.IndexStatus==="ACTIVE")return;let U=z?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${U}, waiting...`)}catch{}await new Promise((A)=>setTimeout(A,5000))}throw Error(`GSI ${J} did not become active within ${G*5} seconds`)}async migrateModel($){let J=o5($),G=null;try{let z=await this.client.describeTable(J.tableName);if(z.Table)G=this.tableInfoToDefinition(z.Table)}catch(z){if(!z.message?.includes("ResourceNotFoundException")&&!z.message?.includes("not found"))throw z}let H=t5(G,J),A=await this.execute(H);if(A.success&&!this.config.dryRun)A.state=await this.tracker.recordMigration(J.tableName,J);return A}async migrateModels($){let J=[];for(let G of $)try{let H=await this.migrateModel(G);J.push(H)}catch(H){J.push({tableName:G.tableName||"unknown",success:!1,operations:[],error:H.message})}return J}async getStatus(){let $=new Map,J=await this.tracker.listTrackedTables();for(let G of J){let H=await this.tracker.getLatestState(G);$.set(G,H)}return $}tableInfoToDefinition($){let J={partitionKey:"",sortKey:void 0};for(let A of $.KeySchema||[])if(A.KeyType==="HASH")J.partitionKey=A.AttributeName;else if(A.KeyType==="RANGE")J.sortKey=A.AttributeName;let G=($.AttributeDefinitions||[]).map((A)=>({name:A.AttributeName,type:A.AttributeType})),H=($.GlobalSecondaryIndexes||[]).map((A)=>{let z={partitionKey:"",sortKey:void 0};for(let U of A.KeySchema||[])if(U.KeyType==="HASH")z.partitionKey=U.AttributeName;else if(U.KeyType==="RANGE")z.sortKey=U.AttributeName;return{indexName:A.IndexName,keySchema:z,projection:{type:A.Projection?.ProjectionType||"ALL",nonKeyAttributes:A.Projection?.NonKeyAttributes},provisionedThroughput:A.ProvisionedThroughput?{readCapacityUnits:A.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:A.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:$.TableName,keySchema:J,attributeDefinitions:G,globalSecondaryIndexes:H.length>0?H:void 0,billingMode:$.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:$.ProvisionedThroughput?{readCapacityUnits:$.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:$.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:$.TimeToLiveDescription?.AttributeName,streamSpecification:$.StreamSpecification?{enabled:$.StreamSpecification.StreamEnabled,viewType:$.StreamSpecification.StreamViewType}:void 0}}log(...$){if(this.config.verbose||this.config.dryRun)console.log(...$)}}function XU($){return new e5($)}async function TZ($,J){return XU(J).migrateModels($)}var jU=a(()=>{a5()});class WU{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor($,J,G,H){this.driver=$,this.client=J,this.tableName=G,this.pkAttribute=H.pkAttribute,this.skAttribute=H.skAttribute,this.entityTypeAttr=H.entityTypeAttribute,this.delimiter=H.keyDelimiter}entity($){return this._entityType=$,this}pk($){return this._pkValue=$,this}get sk(){let $=this;return{equals(J){return $._skCondition={type:"eq",value:J},$},beginsWith(J){return $._skCondition={type:"begins_with",value:J},$},between(J,G){return $._skCondition={type:"between",value:J,value2:G},$},lt(J){return $._skCondition={type:"lt",value:J},$},lte(J){return $._skCondition={type:"lte",value:J},$},gt(J){return $._skCondition={type:"gt",value:J},$},gte(J){return $._skCondition={type:"gte",value:J},$}}}index($){return this._indexName=$,this}project(...$){return this._projectionAttrs.push(...$),this}filter($,J,G){return this._filterConditions.push({attribute:$,operator:J,value:G}),this}where($,J){return this.filter($,"=",J)}whereIn($,J){return this._filterConditions.push({attribute:$,operator:"IN",values:J}),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 J=[],G={},H={},A=0;if(this._pkValue){let z=`#pk${A}`,U=`:pk${A}`;G[z]=this.pkAttribute,H[U]={S:this._pkValue},J.push(`${z} = ${U}`),A++}if(this._skCondition){let z=`#sk${A}`;switch(G[z]=this.skAttribute,this._skCondition.type){case"eq":{let U=`:sk${A}`;H[U]={S:this._skCondition.value},J.push(`${z} = ${U}`);break}case"begins_with":{let U=`:sk${A}`;H[U]={S:this._skCondition.value},J.push(`begins_with(${z}, ${U})`);break}case"between":{let U=`:sk${A}a`,h=`:sk${A}b`;H[U]={S:this._skCondition.value},H[h]={S:this._skCondition.value2},J.push(`${z} BETWEEN ${U} AND ${h}`);break}case"lt":{let U=`:sk${A}`;H[U]={S:this._skCondition.value},J.push(`${z} < ${U}`);break}case"lte":{let U=`:sk${A}`;H[U]={S:this._skCondition.value},J.push(`${z} <= ${U}`);break}case"gt":{let U=`:sk${A}`;H[U]={S:this._skCondition.value},J.push(`${z} > ${U}`);break}case"gte":{let U=`:sk${A}`;H[U]={S:this._skCondition.value},J.push(`${z} >= ${U}`);break}}A++}if(J.length>0)$.KeyConditionExpression=J.join(" AND ");if(this._filterConditions.length>0){let z=[];for(let U of this._filterConditions){let h=`#flt${A}`;if(G[h]=U.attribute,U.operator==="IN"&&U.values){let Y=U.values.map((Z,E)=>`:flt${A}_${E}`);U.values.forEach((Z,E)=>{H[`:flt${A}_${E}`]=this.driver.marshall({v:Z}).v}),z.push(`${h} IN (${Y.join(", ")})`)}else{let Y=`:flt${A}`;H[Y]=this.driver.marshall({v:U.value}).v,z.push(`${h} ${U.operator} ${Y}`)}A++}$.FilterExpression=z.join(" AND ")}if(this._projectionAttrs.length>0){let z=[];for(let U of this._projectionAttrs){let h=`#proj${A}`;G[h]=U,z.push(h),A++}$.ProjectionExpression=z.join(", ")}if(Object.keys(G).length>0)$.ExpressionAttributeNames=G;if(Object.keys(H).length>0)$.ExpressionAttributeValues=H;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((H)=>this.driver.unmarshall(H))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let $=[],J;do{if(J)this._startKey=J;let G=this.toRequest(),A=this._pkValue!==void 0?await this.client.query(G):await this.client.scan(G),z=(A.Items??[]).map((U)=>this.driver.unmarshall(U));$.push(...z),J=A.LastEvaluatedKey?this.driver.unmarshall(A.LastEvaluatedKey):void 0}while(J);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 $A{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection($){let J={region:$.region,tableName:$.table,endpoint:$.endpoint,credentials:$.credentials};return this.driver=C$(J),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 WU(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 J=[];for(let G of $)if(G.put){let H={...G.put.item,[this.entityTypeAttr]:G.put.entity};J.push({PutRequest:{Item:this.driver.marshall(H)}})}else if(G.delete)J.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:G.delete.pk,[this.skAttribute]:G.delete.sk})}});if(J.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:J}})}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 J=[];for(let G of $)if(G.put){let H={...G.put.item,[this.entityTypeAttr]:G.put.entity},A={Put:{TableName:this.tableName,Item:this.driver.marshall(H)}};if(G.put.condition)A.Put.ConditionExpression=G.put.condition;J.push(A)}else if(G.update){let H={[this.pkAttribute]:G.update.pk};if(G.update.sk)H[this.skAttribute]=G.update.sk;let A=[],z={},U={},h=0;if(G.update.set){let Y=[];for(let[Z,E]of Object.entries(G.update.set)){let X=`#set${h}`,F=`:set${h}`;z[X]=Z,U[F]=this.driver.marshall({v:E}).v,Y.push(`${X} = ${F}`),h++}if(Y.length>0)A.push(`SET ${Y.join(", ")}`)}if(G.update.add){let Y=[];for(let[Z,E]of Object.entries(G.update.add)){let X=`#add${h}`,F=`:add${h}`;z[X]=Z,U[F]={N:String(E)},Y.push(`${X} ${F}`),h++}if(Y.length>0)A.push(`ADD ${Y.join(", ")}`)}if(G.update.remove&&G.update.remove.length>0){let Y=[];for(let Z of G.update.remove){let E=`#rem${h}`;z[E]=Z,Y.push(E),h++}A.push(`REMOVE ${Y.join(", ")}`)}J.push({Update:{TableName:this.tableName,Key:this.driver.marshall(H),UpdateExpression:A.join(" "),ExpressionAttributeNames:z,ExpressionAttributeValues:U}})}else if(G.delete){let H={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:G.delete.pk,[this.skAttribute]:G.delete.sk})}};if(G.delete.condition)H.Delete.ConditionExpression=G.delete.condition;J.push(H)}else if(G.conditionCheck)J.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:G.conditionCheck.pk,[this.skAttribute]:G.conditionCheck.sk}),ConditionExpression:G.conditionCheck.condition}});if(J.length>0)await this.client.transactWriteItems({TransactItems:J})}getDriver(){return this.driver}}function hF(){return new $A}var YF;var FU=a(()=>{YU();jU();a5();YF=new $A});import{existsSync as LU,statSync as wU}from"fs";import{resolve as rJ}from"path";import kZ from"process";import{existsSync as xZ,mkdirSync as QF,readdirSync as VF,readFileSync as fZ,writeFileSync as OF}from"fs";import{homedir as r1}from"os";import{dirname as BF,resolve as f$}from"path";import qH from"process";import{existsSync as RU,statSync as DU}from"fs";import{existsSync as VA,mkdirSync as vZ,readdirSync as gZ,writeFileSync as bZ}from"fs";import{homedir as l1}from"os";import{dirname as QU,resolve as U$}from"path";import P1 from"process";import{join as mZ,relative as cZ,resolve as VU}from"path";import VH from"process";import{existsSync as UY,mkdirSync as yF,readdirSync as xF,writeFileSync as fF}from"fs";import{homedir as JA}from"os";import{dirname as bF,resolve as z$}from"path";import sJ from"process";import{join as dZ,relative as uZ,resolve as OU}from"path";import OH from"process";import{existsSync as YY,mkdirSync as pF,readdirSync as iF,writeFileSync as nF}from"fs";import{dirname as lF,resolve as MH}from"path";import OA from"process";import{Buffer as Z1}from"buffer";import{createCipheriv as pZ,createDecipheriv as iZ,randomBytes as GA}from"crypto";import{closeSync as HA,createReadStream as MU,createWriteStream as nZ,existsSync as AA,fsyncSync as KU,openSync as BU,writeFileSync as rZ}from"fs";import{access as lZ,constants as CU,mkdir as sZ,readdir as JH,rename as IU,stat as s1,unlink as GH,writeFile as zA}from"fs/promises";import{join as o1}from"path";import a0 from"process";import{pipeline as oZ}from"stream/promises";import{createGzip as SU}from"zlib";import t1 from"process";import u$ from"process";import{Buffer as c$}from"buffer";import{createCipheriv as tZ,createDecipheriv as aZ,randomBytes as UA}from"crypto";import{closeSync as YA,createReadStream as _U,createWriteStream as eZ,existsSync as HH,fsyncSync as PU,openSync as NU,writeFileSync as $7}from"fs";import{access as J7,constants as TU,mkdir as G7,readdir as AH,rename as kU,stat as a1,unlink as zH,writeFile as hA}from"fs/promises";import{isAbsolute as H7,join as e1,resolve as A7}from"path";import w0 from"process";import{pipeline as z7}from"stream/promises";import{createGzip as qU}from"zlib";import $J from"process";import p$ from"process";import UH from"process";import{existsSync as YH}from"fs";import{resolve as ZA}from"path";import{existsSync as U7}from"fs";import{existsSync as Y7,readdirSync as h7}from"fs";import{extname as EA,resolve as yU}from"path";import Z7 from"process";import{join as E7,relative as X7,resolve as xU}from"path";import KH from"process";import{Buffer as d$}from"buffer";import{createCipheriv as j7,createDecipheriv as W7,randomBytes as XA}from"crypto";import{closeSync as jA,createReadStream as fU,createWriteStream as F7,existsSync as hH,fsyncSync as vU,openSync as gU,writeFileSync as L7}from"fs";import{access as w7,constants as bU,mkdir as R7,readdir as ZH,rename as mU,stat as JJ,unlink as EH,writeFile as WA}from"fs/promises";import{isAbsolute as D7,join as GJ,resolve as Q7}from"path";import R0 from"process";import{pipeline as V7}from"stream/promises";import{createGzip as cU}from"zlib";import HJ from"process";import i$ from"process";import jH from"process";import{existsSync as WH}from"fs";import{resolve as JY}from"path";import{existsSync as mE}from"fs";class GY{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let G=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${G}`}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(([,G],[,H])=>G.timestamp.getTime()-H.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let G=0;G<J;G++)this.cache.delete($[G][0])}set($,J,G,H){if(!this.options.enabled)return;let A=this.generateKey($,G),z=H??this.options.ttl,U=this.estimateSize(J);this.cache.set(A,{value:J,timestamp:new Date,ttl:z,hits:0,size:U}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let G=this.generateKey($,J),H=this.cache.get(G);if(!H){this.totalMisses++;return}if(this.isExpired(H)){this.cache.delete(G),this.totalMisses++;return}return H.hits++,this.totalHits++,H.value}isFileModified($,J){try{if(!LU($))return!0;return wU($).mtime>J}catch{return!0}}getWithFileCheck($,J){let G=this.get($,J);if(!G)return;if(this.isFileModified(J,G.fileTimestamp)){this.delete($,J);return}return G.value}setWithFileCheck($,J,G,H){try{let A=LU(G)?wU(G):null,z=A?A.mtime:new Date;this.set($,{value:J,fileTimestamp:z},G,H)}catch{this.set($,J,G,H)}}delete($,J){let G=this.generateKey($,J);return this.cache.delete(G)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,G]of this.cache.entries())if(this.isExpired(G))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((H,A)=>H+A.size,0),G=$.map((H)=>H.timestamp).sort();return{size:J,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:G[0],newestEntry:G[G.length-1]}}export(){let $={};for(let[J,G]of this.cache.entries())$[J]={value:G.value,timestamp:G.timestamp.toISOString(),ttl:G.ttl,hits:G.hits,size:G.size};return $}import($){this.cache.clear();for(let[J,G]of Object.entries($))if(typeof G==="object"&&G!==null){let H=G;this.cache.set(J,{value:H.value,timestamp:new Date(H.timestamp),ttl:H.ttl,hits:H.hits,size:H.size})}}}class HY{metrics=[];maxMetrics=1000;async track($,J,G={}){let H=performance.now(),A=new Date;try{let z=await J(),U=performance.now()-H;return this.recordMetric({operation:$,duration:U,timestamp:A,...G}),z}catch(z){let U=performance.now()-H;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:A,...G}),z}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((A)=>A.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let G=J.map((A)=>A.duration),H=G.reduce((A,z)=>A+z,0);return{count:J.length,averageDuration:H/J.length,minDuration:Math.min(...G),maxDuration:Math.max(...G),totalDuration:H,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function zY($={}){let{name:J="",alias:G}=$,H=["config",".config"];if(J)H.push(J,`.${J}.config`,`${J}.config`,`.${J}`);let A=G===void 0?[]:Array.isArray(G)?G:[G];for(let z of A){if(!z)continue;if(H.push(z,`.${z}.config`,`${z}.config`,`.${z}`),J)H.push(`${J}.${z}.config`,`.${J}.${z}.config`)}return Array.from(new Set(H.filter(Boolean)))}function qZ($){return zY($).flatMap((G)=>AY.map((H)=>rJ($.directory,`${G}${H}`)))}function yZ($={}){let J=rJ($.cwd||kZ.cwd());return Array.from(new Set([J,rJ(J,"config"),rJ(J,".config"),$.configDir?rJ(J,$.configDir):void 0].filter((G)=>Boolean(G))))}function K7($,J){this[$]=M7.bind(null,J)}class qA{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let G=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${G}`}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(([,G],[,H])=>G.timestamp.getTime()-H.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let G=0;G<J;G++)this.cache.delete($[G][0])}set($,J,G,H){if(!this.options.enabled)return;let A=this.generateKey($,G),z=H??this.options.ttl,U=this.estimateSize(J);this.cache.set(A,{value:J,timestamp:new Date,ttl:z,hits:0,size:U}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let G=this.generateKey($,J),H=this.cache.get(G);if(!H){this.totalMisses++;return}if(this.isExpired(H)){this.cache.delete(G),this.totalMisses++;return}return H.hits++,this.totalHits++,H.value}isFileModified($,J){try{if(!RU($))return!0;return DU($).mtime>J}catch{return!0}}getWithFileCheck($,J){let G=this.get($,J);if(!G)return;if(this.isFileModified(J,G.fileTimestamp)){this.delete($,J);return}return G.value}setWithFileCheck($,J,G,H){try{let A=RU(G)?DU(G):null,z=A?A.mtime:new Date;this.set($,{value:J,fileTimestamp:z},G,H)}catch{this.set($,J,G,H)}}delete($,J){let G=this.generateKey($,J);return this.cache.delete(G)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,G]of this.cache.entries())if(this.isExpired(G))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((H,A)=>H+A.size,0),G=$.map((H)=>H.timestamp).sort();return{size:J,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:G[0],newestEntry:G[G.length-1]}}export(){let $={};for(let[J,G]of this.cache.entries())$[J]={value:G.value,timestamp:G.timestamp.toISOString(),ttl:G.ttl,hits:G.hits,size:G.size};return $}import($){this.cache.clear();for(let[J,G]of Object.entries($))if(typeof G==="object"&&G!==null){let H=G;this.cache.set(J,{value:H.value,timestamp:new Date(H.timestamp),ttl:H.ttl,hits:H.hits,size:H.size})}}}class yA{metrics=[];maxMetrics=1000;async track($,J,G={}){let H=performance.now(),A=new Date;try{let z=await J(),U=performance.now()-H;return this.recordMetric({operation:$,duration:U,timestamp:A,...G}),z}catch(z){let U=performance.now()-H;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:A,...G}),z}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((A)=>A.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let G=J.map((A)=>A.duration),H=G.reduce((A,z)=>A+z,0);return{count:J.length,averageDuration:H/J.length,minDuration:Math.min(...G),maxDuration:Math.max(...G),totalDuration:H,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function I7($,J={}){let H=Object.keys(J).sort().map((A)=>`${A}:${J[A]}`).join("|");return H?`${$}:${H}`:$}function S7($,J){try{return JSON.stringify($)===JSON.stringify(J)}catch{return $===J}}function _7($){return $.getStats().size*2}function xA($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&k0(J[0])&&"id"in J[0]&&J[0].id===3&&k0(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(k0(J)&&k0($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(k0($)&&"arr"in $&&Array.isArray($.arr)&&k0(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&k0(J[0])&&k0($[0])){let H=[...J];for(let A of $)if(k0(A)&&"name"in A){if(!H.find((U)=>k0(U)&&("name"in U)&&U.name===A.name))H.push(A)}else if(k0(A)&&"path"in A){if(!H.find((U)=>k0(U)&&("path"in U)&&U.path===A.path))H.push(A)}else if(!H.some((z)=>BH(z,A)))H.push(A);return H}if(J.every((H)=>typeof H==="string")&&$.every((H)=>typeof H==="string")){let H=[...J];for(let A of $)if(!H.includes(A))H.push(A);return H}return J}if(!k0(J)||!k0($))return J;let G={...$};for(let H in J)if(Object.prototype.hasOwnProperty.call(J,H)){let A=J[H];if(A===null||A===void 0)continue;else if(k0(A)&&k0(G[H]))G[H]=xA(G[H],A);else if(Array.isArray(A)&&Array.isArray(G[H]))if(A.length>0&&G[H].length>0&&k0(A[0])&&k0(G[H][0])){let z=[...A];for(let U of G[H])if(k0(U)&&"name"in U){if(!z.find((Y)=>k0(Y)&&("name"in Y)&&Y.name===U.name))z.push(U)}else if(k0(U)&&"path"in U){if(!z.find((Y)=>k0(Y)&&("path"in Y)&&Y.path===U.path))z.push(U)}else if(!z.some((h)=>BH(h,U)))z.push(U);G[H]=z}else if(A.every((z)=>typeof z==="string")&&G[H].every((z)=>typeof z==="string")){let z=[...A];for(let U of G[H])if(!z.includes(U))z.push(U);G[H]=z}else G[H]=A;else G[H]=A}return G}function BH($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let G=0;G<$.length;G++)if(!BH($[G],J[G]))return!1;return!0}if(k0($)&&k0(J)){let G=Object.keys($),H=Object.keys(J);if(G.length!==H.length)return!1;for(let A of G){if(!Object.prototype.hasOwnProperty.call(J,A))return!1;if(!BH($[A],J[A]))return!1}return!0}return!1}function k0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function P7($,J){if(!YY($))return null;try{let G=await import($),H=G.default||G;if(typeof H!=="object"||H===null||Array.isArray(H))return null;try{return xA(J,H)}catch{return null}}catch{return null}}async function N7({name:$="",cwd:J,defaultConfig:G}){let H=J||OA.cwd(),A=[".ts",".js",".mjs",".cjs",".json"],z=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of z)for(let h of A){let Y=MH(H,`${U}${h}`),Z=await P7(Y,G);if(Z!==null)return Z}try{let U=MH(H,"package.json");if(YY(U)){let Y=(await import(U))[$];if(Y&&typeof Y==="object"&&!Array.isArray(Y))try{return xA(G,Y)}catch{}}}catch{}return G}function T7($,J={}){let G=OH.cwd();while(G.includes("storage"))G=OU(G,"..");let H=OU(G,$||"");if(J?.relative)return uZ(OH.cwd(),H);return H}async function k7(){try{let $=await N7({name:"clarity",defaultConfig:LH,cwd:OH.cwd(),endpoint:"",headers:{}});return{...LH,...$}}catch{return LH}}function f0(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q7(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u$<"u"){let $=u$.type;if($==="renderer"||$==="worker")return!1;return!!(u$.versions&&(u$.versions.node||u$.versions.bun))}return!1}class ZY{async format($){let J=await q7(),G=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:G})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:t1.pid,hostname:J(),environment:t1.env.NODE_ENV||"development",platform:t1.platform,version:t1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:t1.env.NODE_ENV||t1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class CH{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($,J={}){this.name=$,this.config={...KA},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new ZY,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??a0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let G={...J},H=J.timestamp!==void 0;if(H)delete G.timestamp;if(this.config={...this.config,...G,timestamp:H||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let A=this.generateKeyId(),z=this.generateKey();this.currentKeyId=A,this.keys.set(A,z),this.encryptionKeys.set(A,{key:z,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...wH,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...wH};return{...wH,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:KA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},G={...J,...Object.fromEntries(Object.entries($).filter(([,H])=>H!==void 0))};if(!G.level||!["debug","info","success","warning","error"].includes(G.level))G.level=J.level;return G}async writeToFile($){let G=(async()=>{let A,z=0,U=3,h=1000;while(z<U)try{try{try{await lZ(this.config.logDirectory,CU.F_OK|CU.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await sZ(this.config.logDirectory,{recursive:!0,mode:493});else if(Z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Z;else throw Z}}catch(Z){throw console.error("Debug: [writeToFile] Failed to create log directory:",Z),Z}let Y=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Z1.from($);try{if(!AA(this.currentLogFile))await zA(this.currentLogFile,"",{mode:420});if(A=BU(this.currentLogFile,"a",420),rZ(A,Y,{flag:"a"}),KU(A),A!==void 0)HA(A),A=void 0;if((await s1(this.currentLogFile)).size===0){if(await zA(this.currentLogFile,Y,{flag:"w",mode:420}),(await s1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(z<U-1){let X=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${z+1}/${U}:`,X);let F=h*2**z;await new Promise((R)=>setTimeout(R,F)),z++;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(A!==void 0)try{HA(A)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(Y){if(z===U-1){let E=Y,X=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",X),Y}z++;let Z=h*2**(z-1);await new Promise((E)=>setTimeout(E,Z))}})();this.pendingOperations.push(G);let H=this.pendingOperations.length-1;try{await G}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(H,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 o1(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 o1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return o1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let G=typeof J.interval==="number"?J.interval:60,H=Math.max(G,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},H)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,G=this.generateKeyId(),H=this.generateKey();this.currentKeyId=G,this.keys.set(G,H),this.encryptionKeys.set(G,{key:H,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,h],[,Y])=>Y.createdAt.getTime()-h.createdAt.getTime()),z=typeof J.maxKeys==="number"?J.maxKeys:1,U=Math.max(1,z);if(A.length>U)for(let[h]of A.slice(U))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return GA(16).toString("hex")}generateKey(){return GA(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:J}=this.getCurrentKey(),G=GA(16),H=pZ("aes-256-gcm",J,G),A=Z1.concat([H.update($,"utf8"),H.final()]),z=H.getAuthTag();return{encrypted:Z1.concat([G,A,z]),iv:G}}async compressData($){return new Promise((J,G)=>{let H=SU(),A=[];H.on("data",(z)=>A.push(z)),H.on("end",()=>J(Z1.from(Z1.concat(A)))),H.on("error",G),H.write($),H.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 J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(f0())return;let $=await s1(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let G=this.currentLogFile,H=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let A=await JH(this.config.logDirectory),z=A.filter((Y)=>Y.startsWith(this.name)&&/\.log\.\d+$/.test(Y)).sort((Y,Z)=>{let E=Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=z.length>0?Number.parseInt(z[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${G}.${U}`;if(await s1(G).catch(()=>null))try{if(await IU(G,h),J.compress)try{let Y=`${h}.gz`;await this.compressLogFile(h,Y),await GH(h)}catch(Y){console.error("Error compressing rotated file:",Y)}if(z.length===0&&!A.some((Y)=>Y.endsWith(".log.1")))try{let Y=`${G}.1`;await zA(Y,"")}catch(Y){console.error("Error creating backup file:",Y)}}catch(Y){console.error(`Error during rotation: ${Y instanceof Error?Y.message:String(Y)}`)}}else{let A=new Date().toISOString().replace(/[:.]/g,"-"),z=G.replace(/\.log$/,`-${A}.log`);if(await s1(G).catch(()=>null))await IU(G,z)}if(this.currentLogFile=H,J.maxFiles){let z=(await JH(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,h)=>h.localeCompare(U));for(let U of z.slice(J.maxFiles))await GH(o1(this.config.logDirectory,U))}}}async compressLogFile($,J){let G=MU($),H=nZ(J),A=SU();await oZ(G,A,H)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let G of this.logBuffer){let H=await this.formatter.format(G);await this.writeToFile(H),console.log(H)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(J),console.log(J);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let G={timestamp:new Date,level:$,message:J,name:this.name};this.logBuffer.push(G)}}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 J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),AA(this.currentLogFile))try{let $=BU(this.currentLogFile,"r+");KU($),HA($)}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(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await JH(this.config.logDirectory)).filter((G)=>(G.includes("temp")||G.includes(".tmp"))&&G.includes(this.name));for(let G of J)try{await GH(o1(this.config.logDirectory,G))}catch(H){console.error(`Failed to delete temp file ${G}:`,H)}}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?N0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:J,icon:G="",tag:H="",message:A,level:z,showTimestamp:U=!0}=$,h=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(U)R.push(J);if(z==="warning")R.push("WARN");else if(z==="error")R.push("ERROR");else if(G)R.push(G.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(H)R.push(H.replace(/[[\]]/g,""));return R.push(A),R.join(" ")}let Y=a0.stdout.columns||120,Z="";if(z==="warning"||z==="error")Z=`${G} ${A}`;else if(z==="info"||z==="success")Z=`${G} ${H} ${A}`;else Z=`${G} ${H} ${N0.cyan(A)}`;if(!U)return Z.trim();let E=h(Z).trim().length,X=h(J).length,F=Math.max(1,Y-2-E-X);return`${Z.trim()}${" ".repeat(F)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(z,U)=>{let h=Number.parseInt(U,10);return h<J[0].length?String(J[0][h]):z});let G=/%([sdijfo%])/g,H=0,A=$.replace(G,(z,U)=>{if(U==="%")return"%";if(H>=J.length)return z;let h=J[H++];switch(U){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return z}});if(H<J.length)A+=` ${J.slice(H).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`;return A}async log($,J,...G){let H=new Date,A=this.formatConsoleTimestamp(H),z=this.formatFileTimestamp(H),U,h;if(J instanceof Error)U=J.message,h=J.stack;else U=this.formatMessage(J,G);if(this.fancy&&!f0()){let Z=QY[$],E=this.options.showTags!==!1&&this.name?N0.gray(this.formatTag(this.name)):"",X;switch($){case"debug":X=this.formatConsoleMessage({timestamp:A,icon:Z,tag:E,message:N0.gray(U),level:$}),console.error(X);break;case"info":X=this.formatConsoleMessage({timestamp:A,icon:Z,tag:E,message:U,level:$}),console.error(X);break;case"success":X=this.formatConsoleMessage({timestamp:A,icon:Z,tag:E,message:N0.green(U),level:$}),console.error(X);break;case"warning":X=this.formatConsoleMessage({timestamp:A,icon:Z,tag:E,message:U,level:$}),console.warn(X);break;case"error":if(X=this.formatConsoleMessage({timestamp:A,icon:Z,tag:E,message:U,level:$}),console.error(X),h){let F=h.split(`
8
- `);for(let R of F)if(R.trim()&&!R.includes(U))console.error(this.formatConsoleMessage({timestamp:A,message:N0.gray(` ${R}`),level:$,showTimestamp:!1}))}break}}else if(!f0()){if(console.error(`${z} ${this.environment}.${$.toUpperCase()}: ${U}`),h)console.error(h)}if(!this.shouldLog($))return;let Y=`${z} ${this.environment}.${$.toUpperCase()}: ${U}
9
- `;if(h)Y+=`${h}
10
- `;Y=Y.replace(this.ANSI_PATTERN,""),await this.writeToFile(Y)}time($){let J=performance.now();if(this.fancy&&!f0()){let G=this.options.showTags!==!1&&this.name?N0.gray(this.formatTag(this.name)):"",H=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:H,icon:N0.blue("\u25D0"),tag:G,message:`${N0.cyan($)}...`}))}return async(G)=>{if(!this.enabled)return;let H=performance.now(),A=Math.round(H-J),z=`${$} completed in ${A}ms`,U=new Date,h=this.formatConsoleTimestamp(U),Z=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${z}`;if(G)Z+=` ${JSON.stringify(G)}`;if(Z+=`
11
- `,Z=Z.replace(this.ANSI_PATTERN,""),this.fancy&&!f0()){let E=this.options.showTags!==!1&&this.name?N0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:N0.green("\u2713"),tag:E,message:`${z}${G?` ${JSON.stringify(G)}`:""}`}))}else if(!f0())console.error(Z.trim());await this.writeToFile(Z)}}async debug($,...J){await this.log("debug",$,...J)}async info($,...J){await this.log("info",$,...J)}async success($,...J){await this.log("success",$,...J)}async warn($,...J){await this.log("warning",$,...J)}async error($,...J){await this.log("error",$,...J)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:J}=$;return!!J}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let J=`${this.name}:${$}`,G=new CH(J,{...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(G),G}createReadStream(){if(f0())throw Error("createReadStream is not supported in browser environments");if(!AA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return MU(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let J=this.config.rotation;if(!J.encrypt||typeof J.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let G=this.keys.get(this.currentKeyId);try{let H=Z1.isBuffer($)?$:Z1.from($,"base64"),A=H.slice(0,16),z=H.slice(-16),U=H.slice(16,-16),h=iZ("aes-256-gcm",G,A);return h.setAuthTag(z),Z1.concat([h.update(U),h.final()]).toString("utf8")}catch(H){throw Error(`Decryption failed: ${H instanceof Error?H.message:String(H)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return f0()}isServerMode(){return!f0()}setTestEncryptionKey($,J){this.currentKeyId=$,this.keys.set($,J)}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 J=new Date,G=this.formatConsoleTimestamp(J),H=this.formatFileTimestamp(J);if(this.fancy&&!f0()){let z=$.split(`
12
- `),U=Math.max(...z.map((E)=>E.length))+2,h=`\u250C${"\u2500".repeat(U)}\u2510`,Y=`\u2514${"\u2500".repeat(U)}\u2518`,Z=z.map((E)=>{let X=" ".repeat(U-E.length-2);return`\u2502 ${E}${X} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:G,message:N0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:G,message:N0.cyan(h)})),Z.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:G,message:N0.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:G,message:N0.cyan(Y),showTimestamp:!1}))}else if(!f0())console.error(`${H} ${this.environment}.INFO: [BOX] ${$}`);let A=`${H} ${this.environment}.INFO: [BOX] ${$}
13
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}async prompt($){if(f0())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${N0.cyan("?")} ${$} (y/n) `);let G=(H)=>{let A=H.toString().trim().toLowerCase();a0.stdin.removeListener("data",G);try{if(typeof a0.stdin.setRawMode==="function")a0.stdin.setRawMode(!1)}catch{}a0.stdin.pause(),console.error(""),J(A==="y"||A==="yes")};try{if(typeof a0.stdin.setRawMode==="function")a0.stdin.setRawMode(!0)}catch{}a0.stdin.resume(),a0.stdin.once("data",G)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let G=$;if(J&&J.length>0){let U=/%([sdijfo%])/g,h=0;if(G=$.replace(U,(Y,Z)=>{if(Z==="%")return"%";if(h>=J.length)return Y;let E=J[h++];switch(Z){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 Y}}),h<J.length)G+=` ${J.slice(h).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`}if(this.fancy&&!f0()){let U=this.options.showTags!==!1&&this.name?N0.gray(this.formatTag(this.name)):"",h=N0.blue("\u25D0");console.error(`${h} ${U} ${N0.cyan(G)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${G}
14
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(z)}progress($,J=""){if(!this.enabled||!this.fancy||f0()||$<=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 G=20;return this.activeProgressBar={total:$,current:0,message:J,barLength:G,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),h!==void 0)this.activeProgressBar.message=h;let Y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Y)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,h="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f0())return;a0.stdout.write(`${"\r".padEnd(a0.stdout.columns||80)}\r`),this.log(h,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,J=!1){if(!this.enabled||!this.fancy||f0()||!a0.stdout.isTTY)return;let G=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),H=Math.round($.barLength*G/100),A=$.barLength-H,z=N0.green("\u2501".repeat(H)),U=N0.gray("\u2501".repeat(A)),h=`[${z}${U}]`,Y=`${G}%`.padStart(4),Z=$.message?` ${$.message}`:"",E=J||G===100?N0.green("\u2713"):N0.blue("\u25B6"),X=this.options.showTags!==!1&&this.name?` ${N0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${X} ${h} ${Y}${Z}`,R=a0.stdout.columns||80,C=" ".repeat(Math.max(0,R-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${C}`,a0.stdout.write($.lastRenderedLine),J)a0.stdout.write(`
15
- `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||f0()||!a0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await JH(this.config.logDirectory),G=[];for(let H of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(H):H.startsWith(this.name))||!H.endsWith(".log"))continue;let z=o1(this.config.logDirectory,H);if($.before)try{if((await s1(z)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${z}:`,U);continue}G.push(z)}if(G.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${G.length} log file(s)...`);for(let H of G)try{await GH(H),console.warn(`Deleted log file: ${H}`)}catch(A){console.error(`Failed to delete log file ${H}:`,A)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}function FH($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&O0(J[0])&&"id"in J[0]&&J[0].id===3&&O0(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(O0(J)&&O0($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(O0($)&&"arr"in $&&Array.isArray($.arr)&&O0(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&O0(J[0])&&O0($[0])){let H=[...J];for(let A of $)if(O0(A)&&"name"in A){if(!H.find((U)=>O0(U)&&("name"in U)&&U.name===A.name))H.push(A)}else if(O0(A)&&"path"in A){if(!H.find((U)=>O0(U)&&("path"in U)&&U.path===A.path))H.push(A)}else if(!H.some((z)=>IH(z,A)))H.push(A);return H}if(J.every((H)=>typeof H==="string")&&$.every((H)=>typeof H==="string")){let H=[...J];for(let A of $)if(!H.includes(A))H.push(A);return H}return J}if(!O0(J)||!O0($))return J;let G={...$};for(let H in J)if(Object.prototype.hasOwnProperty.call(J,H)){let A=J[H];if(A===null||A===void 0)continue;else if(O0(A)&&O0(G[H]))G[H]=FH(G[H],A);else if(Array.isArray(A)&&Array.isArray(G[H]))if(A.length>0&&G[H].length>0&&O0(A[0])&&O0(G[H][0])){let z=[...A];for(let U of G[H])if(O0(U)&&"name"in U){if(!z.find((Y)=>O0(Y)&&("name"in Y)&&Y.name===U.name))z.push(U)}else if(O0(U)&&"path"in U){if(!z.find((Y)=>O0(Y)&&("path"in Y)&&Y.path===U.path))z.push(U)}else if(!z.some((h)=>IH(h,U)))z.push(U);G[H]=z}else if(A.every((z)=>typeof z==="string")&&G[H].every((z)=>typeof z==="string")){let z=[...A];for(let U of G[H])if(!z.includes(U))z.push(U);G[H]=z}else G[H]=A;else G[H]=A}return G}function fA($,J,G="replace"){if(J===null||J===void 0)return $;if(Array.isArray(J))return G==="replace"?J:FH($,J);if(Array.isArray($))return G==="replace"?J:FH($,J);if(!O0(J)||!O0($))return J;let H={...$};for(let A of Object.keys(J)){if(!Object.prototype.hasOwnProperty.call(J,A))continue;let z=J[A],U=H[A];if(z===null||z===void 0)continue;if(Array.isArray(z)||Array.isArray(U))if(G==="replace")H[A]=z;else H[A]=FH(U,z);else if(O0(z)&&O0(U))H[A]=fA(U,z,G);else H[A]=z}return H}function IH($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let G=0;G<$.length;G++)if(!IH($[G],J[G]))return!1;return!0}if(O0($)&&O0(J)){let G=Object.keys($),H=Object.keys(J);if(G.length!==H.length)return!1;for(let A of G){if(!Object.prototype.hasOwnProperty.call(J,A))return!1;if(!IH($[A],J[A]))return!1}return!0}return!1}function O0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function XH($,J,G="replace"){if(!UY($))return null;try{let H=await import($),A=H.default||H;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return fA(J,A,G)}catch{return null}}catch{return null}}function y7($,J,G=!1){if(!$)return J;let H=$.toUpperCase().replace(/-/g,"_"),A={...J};function z(U,h=[]){let Y={...U};for(let[Z,E]of Object.entries(U)){let X=[...h,Z],F=(W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase(),R=`${H}_${X.map(F).join("_")}`,C=`${H}_${X.map((W)=>W.toUpperCase()).join("_")}`;if(G)$$.info(`Checking environment variable ${R} for config ${$}.${X.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))Y[Z]=z(E,X);else{let W=sJ.env[R]||sJ.env[C];if(W!==void 0){if(G)$$.info(`Using environment variable ${W?R:C} for config ${$}.${X.join(".")}`);if(typeof E==="number")Y[Z]=Number(W);else if(typeof E==="boolean")Y[Z]=W.toLowerCase()==="true";else if(Array.isArray(E))try{let Q=JSON.parse(W);if(Array.isArray(Q))Y[Z]=Q;else Y[Z]=W.split(",").map((D)=>D.trim())}catch{Y[Z]=W.split(",").map((Q)=>Q.trim())}else Y[Z]=W}}}return Y}return z(A)}async function x7({name:$="",alias:J,cwd:G,configDir:H,defaultConfig:A,verbose:z=!1,checkEnv:U=!0,arrayStrategy:h="replace"}){let Y=U&&typeof A==="object"&&A!==null&&!Array.isArray(A)?y7($,A,z):A,Z=G||sJ.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(z)$$.info(`Loading configuration for "${$}"${J?` (alias: "${J}")`:""} from ${Z}`);let X=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),R=J?[J,`.${J}`]:[],C=J?[`${J}.config`,`.${J}.config`]:[],W=Array.from(new Set([Z,z$(Z,"config"),z$(Z,".config"),H?z$(Z,H):void 0].filter(Boolean)));for(let Q of W){if(z)$$.info(`Searching for configuration in: ${Q}`);let w=[z$(Z,"config"),z$(Z,".config")].concat(H?[z$(Z,H)]:[]).includes(Q)?[...X,...F,...R,...C]:[...F,...X,...C,...R];for(let K of w)for(let V of E){let q=z$(Q,`${K}${V}`),P=await XH(q,Y,h);if(P!==null){if(z)$$.success(`Configuration loaded from: ${q}`);return P}}}if($){let Q=z$(JA(),".config",$),D=["config",`${$}.config`];if(J)D.push(`${J}.config`);if(z)$$.info(`Checking user config directory: ${Q}`);for(let w of D)for(let K of E){let V=z$(Q,`${w}${K}`),q=await XH(V,Y,h);if(q!==null){if(z)$$.success(`Configuration loaded from user config directory: ${V}`);return q}}}if($){let Q=z$(JA(),".config"),D=[`.${$}.config`];if(J)D.push(`.${J}.config`);if(z)$$.info(`Checking user config directory for dotfile configs: ${Q}`);for(let w of D)for(let K of E){let V=z$(Q,`${w}${K}`),q=await XH(V,Y,h);if(q!==null){if(z)$$.success(`Configuration loaded from user config directory dotfile: ${V}`);return q}}}if($){let Q=JA(),D=[`.${$}.config`,`.${$}`];if(J)D.push(`.${J}.config`),D.push(`.${J}`);if(z)$$.info(`Checking user home directory for dotfile configs: ${Q}`);for(let w of D)for(let K of E){let V=z$(Q,`${w}${K}`),q=await XH(V,Y,h);if(q!==null){if(z)$$.success(`Configuration loaded from user home directory: ${V}`);return q}}}try{let Q=z$(Z,"package.json");if(UY(Q)){let D=await import(Q),w=D[$];if(!w&&J){if(w=D[J],w&&z)$$.success(`Using alias "${J}" configuration from package.json`)}if(w&&typeof w==="object"&&!Array.isArray(w))try{if(z)$$.success(`Configuration loaded from package.json: ${w===D[$]?$:J}`);return fA(Y,w,h)}catch(K){if(z)$$.warn("Failed to merge package.json config:",K)}}}catch(Q){if(z)$$.warn("Failed to load package.json:",Q)}if(z)$$.info(`No configuration found for "${$}"${J?` or alias "${J}"`:""}, using default configuration with environment variables`);return Y}function f7($,J={}){let G=VH.cwd();while(G.includes("storage"))G=VU(G,"..");let H=VU(G,$||"");if(J?.relative)return cZ(VH.cwd(),H);return H}async function v7(){try{let $=await x7({name:"clarity",alias:"logging",defaultConfig:RH,cwd:VH.cwd()});return{...RH,...$||{}}}catch{return RH}}function u0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function g7(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class EY{async format($){let J=await g7(),G=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:G})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:$J.pid,hostname:J(),environment:$J.env.NODE_ENV||"development",platform:$J.platform,version:$J.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$J.env.NODE_ENV||$J.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class SH{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($,J={}){this.name=$,this.config={...BA},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new EY,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??w0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let G={...J},H=J.timestamp!==void 0;if(H)delete G.timestamp;if(this.config={...this.config,...G,timestamp:H||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let A=this.generateKeyId(),z=this.generateKey();this.currentKeyId=A,this.keys.set(A,z),this.encryptionKeys.set(A,{key:z,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},G=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[G]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...DH,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...DH};return{...DH,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:BA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},G={...J,...Object.fromEntries(Object.entries($).filter(([,H])=>H!==void 0))};if(!G.level||!["debug","info","success","warning","error"].includes(G.level))G.level=J.level;return G}shouldWriteToFile(){return!u0()&&this.config.writeToFile===!0}async writeToFile($){let G=(async()=>{let A,z=0,U=3,h=1000;while(z<U)try{try{try{await J7(this.config.logDirectory,TU.F_OK|TU.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await G7(this.config.logDirectory,{recursive:!0,mode:493});else if(Z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Z;else throw Z}}catch(Z){throw console.error("Debug: [writeToFile] Failed to create log directory:",Z),Z}let Y=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:c$.from($);try{if(!HH(this.currentLogFile))await hA(this.currentLogFile,"",{mode:420});if(A=NU(this.currentLogFile,"a",420),$7(A,Y,{flag:"a"}),PU(A),A!==void 0)YA(A),A=void 0;if((await a1(this.currentLogFile)).size===0){if(await hA(this.currentLogFile,Y,{flag:"w",mode:420}),(await a1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(z<U-1){let X=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${z+1}/${U}:`,X);let F=h*2**z;await new Promise((R)=>setTimeout(R,F)),z++;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(A!==void 0)try{YA(A)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(Y){if(z===U-1){let E=Y,X=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",X),Y}z++;let Z=h*2**(z-1);await new Promise((E)=>setTimeout(E,Z))}})();this.pendingOperations.push(G);let H=this.pendingOperations.length-1;try{await G}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(H,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 e1(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 e1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return e1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(u0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let G=typeof J.interval==="number"?J.interval:60,H=Math.max(G,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},H)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,G=this.generateKeyId(),H=this.generateKey();this.currentKeyId=G,this.keys.set(G,H),this.encryptionKeys.set(G,{key:H,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,h],[,Y])=>Y.createdAt.getTime()-h.createdAt.getTime()),z=typeof J.maxKeys==="number"?J.maxKeys:1,U=Math.max(1,z);if(A.length>U)for(let[h]of A.slice(U))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return UA(16).toString("hex")}generateKey(){return UA(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:J}=this.getCurrentKey(),G=UA(16),H=tZ("aes-256-gcm",J,G),A=c$.isBuffer($)?$:c$.from($,"utf8"),z=H.update(A),U=H.final(),h=z.length+U.length,Y=H.getAuthTag(),Z=c$.allocUnsafe(16+h+16);return G.copy(Z,0),z.copy(Z,16),U.copy(Z,16+z.length),Y.copy(Z,16+h),{encrypted:Z,iv:G}}async compressData($){return new Promise((J,G)=>{let H=qU(),A=[];H.on("data",(z)=>A.push(z)),H.on("end",()=>J(c$.from(c$.concat(A)))),H.on("error",G),H.write($),H.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 J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(u0())return;if(!this.shouldWriteToFile())return;let $=await a1(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let G=this.currentLogFile,H=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let A=await AH(this.config.logDirectory),z=A.filter((Y)=>Y.startsWith(this.name)&&/\.log\.\d+$/.test(Y)).sort((Y,Z)=>{let E=Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=z.length>0?Number.parseInt(z[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${G}.${U}`;if(await a1(G).catch(()=>null))try{if(await kU(G,h),J.compress)try{let Y=`${h}.gz`;await this.compressLogFile(h,Y),await zH(h)}catch(Y){console.error("Error compressing rotated file:",Y)}if(z.length===0&&!A.some((Y)=>Y.endsWith(".log.1")))try{let Y=`${G}.1`;await hA(Y,"")}catch(Y){console.error("Error creating backup file:",Y)}}catch(Y){console.error(`Error during rotation: ${Y instanceof Error?Y.message:String(Y)}`)}}else{let A=new Date().toISOString().replace(/[:.]/g,"-"),z=G.replace(/\.log$/,`-${A}.log`);if(await a1(G).catch(()=>null))await kU(G,z)}if(this.currentLogFile=H,J.maxFiles){let z=(await AH(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,h)=>h.localeCompare(U));for(let U of z.slice(J.maxFiles))await zH(e1(this.config.logDirectory,U))}}}async compressLogFile($,J){let G=_U($),H=eZ(J),A=qU();await z7(G,A,H)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let G of this.logBuffer){let H=await this.formatter.format(G);if(this.shouldWriteToFile())await this.writeToFile(H);console.log(H)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),HH(this.currentLogFile))try{let $=NU(this.currentLogFile,"r+");PU($),YA($)}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(!u0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await AH(this.config.logDirectory)).filter((G)=>(G.includes("temp")||G.includes(".tmp"))&&G.includes(this.name));for(let G of J)try{await zH(e1(this.config.logDirectory,G))}catch(H){console.error(`Failed to delete temp file ${G}:`,H)}}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()?D0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||u0())return!1;let $=typeof w0.env.NO_COLOR<"u",J=w0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof w0.stderr<"u"&&w0.stderr.isTTY||typeof w0.stdout<"u"&&w0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:G="",tag:H="",message:A,level:z,showTimestamp:U=!0}=$,h=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(U)R.push(J);if(z==="warning")R.push("WARN");else if(z==="error")R.push("ERROR");else if(G)R.push(G.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(H)R.push(H.replace(/[[\]]/g,""));return R.push(A),R.join(" ")}let Y=w0.stdout.columns||120,Z="";if(z==="warning"||z==="error")Z=`${G} ${A}`;else if(z==="info"||z==="success")Z=`${G} ${H} ${A}`;else Z=`${G} ${H} ${D0.cyan(A)}`;if(!U)return Z.trim();let E=h(Z).trim().length,X=h(J).length,F=Math.max(1,Y-2-E-X);return`${Z.trim()}${" ".repeat(F)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(z,U)=>{let h=Number.parseInt(U,10);return h<J[0].length?String(J[0][h]):z});let G=/%([sdijfo%])/g,H=0,A=$.replace(G,(z,U)=>{if(U==="%")return"%";if(H>=J.length)return z;let h=J[H++];switch(U){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return z}});if(H<J.length)A+=` ${J.slice(H).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`;return A}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(G,H,A)=>{let z=D0.underline(D0.blue(H)),U=this.toAbsoluteFilePath(A);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(U)}`,Y="\x1B]8;;",Z="\x1B\\";return`\x1B]8;;${h}\x1B\\${z}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${A}\x1B\\${z}\x1B]8;;\x1B\\`;return z}),J=J.replace(/`([^`]+)`/g,(G,H)=>D0.bgGray(H)),J=J.replace(/\*\*([^*]+)\*\*/g,(G,H)=>D0.bold(H)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(G,H)=>D0.italic(H)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(G,H)=>D0.italic(H)),J=J.replace(/~([^~]+)~/g,(G,H)=>D0.strikethrough(H)),J}supportsHyperlinks(){if(u0())return!1;let $=w0.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 J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let G=w0.env.HOME||"";if(G)J=J.replace(/^~(?=$|\/)/,G)}if(H7(J)||J.startsWith("./")||J.startsWith("../"))J=A7(J);else return null;return HH(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,G=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:G}}async log($,J,...G){let H=new Date,A=this.formatConsoleTimestamp(H),z=this.formatFileTimestamp(H),U,h;if(J instanceof Error)U=J.message,h=J.stack;else U=this.formatMessage(J,G);let{consoleText:Y,fileText:Z}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let X=this.options.showIcons===!1?"":VY[$],F=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"",R;switch($){case"debug":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:D0.gray(Y),level:$}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.warn(R);break;case"success":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:D0.green(Y),level:$}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.error(R),h){let C=h.split(`
16
- `);for(let W of C)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:A,message:D0.gray(` ${W}`),level:$,showTimestamp:!1}))}break}}else if(!u0()){if(console.error(`${z} ${this.environment}.${$.toUpperCase()}: ${U}`),h)console.error(h)}if(!this.shouldLog($))return;let E=`${z} ${this.environment}.${$.toUpperCase()}: ${Z}
17
- `;if(h)E+=`${h}
18
- `;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,J=""){let G={update:(h,Y)=>{},finish:(h)=>{},interrupt:(h,Y)=>{}};if(!this.enabled)return G;let H=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:J||"",barLength:H,lastRenderedLine:""},this.shouldStyleConsole()&&!u0()&&w0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,Y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),Y!==void 0)this.activeProgressBar.message=Y;if(this.shouldStyleConsole()&&!u0()&&w0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,Y="info")=>{if(!u0()&&w0.stdout.isTTY)w0.stdout.write(`
19
- `);if(this[Y==="warning"?"warn":Y](h),this.activeProgressBar&&this.shouldStyleConsole()&&!u0()&&w0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let J=performance.now();if(this.shouldStyleConsole()){let G=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"",H=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":D0.blue("\u25D0"),tag:G,message:`${D0.cyan($)}...`}))}return async(G)=>{if(!this.enabled)return;let H=performance.now(),A=Math.round(H-J),z=`${$} completed in ${A}ms`,U=new Date,h=this.formatConsoleTimestamp(U),Z=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${z}`;if(G)Z+=` ${JSON.stringify(G)}`;if(Z+=`
20
- `,Z=Z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":D0.green("\u2713"),tag:E,message:`${z}${G?` ${JSON.stringify(G)}`:""}`}))}else if(!u0())console.error(Z.trim());if(this.shouldWriteToFile())await this.writeToFile(Z)}}async debug($,...J){await this.log("debug",$,...J)}async info($,...J){await this.log("info",$,...J)}async success($,...J){await this.log("success",$,...J)}async warn($,...J){await this.log("warning",$,...J)}async error($,...J){await this.log("error",$,...J)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:J}=$;return!!J}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let J=`${this.name}:${$}`,G=new SH(J,{...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(G),G}createReadStream(){if(u0())throw Error("createReadStream is not supported in browser environments");if(!HH(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return _U(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let J=this.config.rotation;if(!J.encrypt||typeof J.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let G=this.keys.get(this.currentKeyId);try{let H=c$.isBuffer($)?$:c$.from($,"base64"),A=H.subarray(0,16),z=H.subarray(H.length-16),U=H.subarray(16,H.length-16),h=aZ("aes-256-gcm",G,A);h.setAuthTag(z);let Y=h.update(U),Z=h.final(),E=Y.length+Z.length,X=c$.allocUnsafe(E);return Y.copy(X,0),Z.copy(X,Y.length),X.toString("utf8")}catch(H){throw Error(`Decryption failed: ${H instanceof Error?H.message:String(H)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return u0()}isServerMode(){return!u0()}setTestEncryptionKey($,J){this.currentKeyId=$,this.keys.set($,J)}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 J=new Date,G=this.formatConsoleTimestamp(J),H=this.formatFileTimestamp(J),{consoleText:A,fileText:z}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let h=A.split(`
21
- `),Y=Math.max(...h.map((F)=>F.length))+2,Z=`\u250C${"\u2500".repeat(Y)}\u2510`,E=`\u2514${"\u2500".repeat(Y)}\u2518`,X=h.map((F)=>{return this.formatConsoleMessage({timestamp:G,message:D0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:G,message:D0.cyan(Z),showTimestamp:!1})),X.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:G,message:D0.cyan(E),showTimestamp:!1}))}else if(!u0())console.error(`${H} ${this.environment}.INFO: [BOX] ${z}`);let U=`${H} ${this.environment}.INFO: [BOX] ${z}
22
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(u0())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${D0.cyan("?")} ${$} (y/n) `);let G=(H)=>{let A=H.toString().trim().toLowerCase();w0.stdin.removeListener("data",G);try{if(typeof w0.stdin.setRawMode==="function")w0.stdin.setRawMode(!1)}catch{}w0.stdin.pause(),console.error(""),J(A==="y"||A==="yes")};try{if(typeof w0.stdin.setRawMode==="function")w0.stdin.setRawMode(!0)}catch{}w0.stdin.resume(),w0.stdin.once("data",G)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let G=$;if(J&&J.length>0){let Y=/%([sdijfo%])/g,Z=0;if(G=$.replace(Y,(E,X)=>{if(X==="%")return"%";if(Z>=J.length)return E;let F=J[Z++];switch(X){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}}),Z<J.length)G+=` ${J.slice(Z).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:H,fileText:A}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?D0.gray(this.formatTag(this.name)):"",Z=this.options.showIcons===!1?"":`${D0.blue("\u25D0")} `;console.error(`${Z}${Y} ${D0.cyan(H)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
23
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar($,J=!1){if(!this.enabled||!this.shouldStyleConsole()||!w0.stdout.isTTY)return;let G=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),H=Math.round($.barLength*G/100),A=$.barLength-H,z=D0.green("\u2501".repeat(H)),U=D0.gray("\u2501".repeat(A)),h=`[${z}${U}]`,Y=`${G}%`.padStart(4),Z=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":J||G===100?D0.green("\u2713"):D0.blue("\u25B6"),X=this.options.showTags!==!1&&this.name?` ${D0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${X} ${h} ${Y}${Z}`,R=w0.stdout.columns||80,C=" ".repeat(Math.max(0,R-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${C}`,w0.stdout.write($.lastRenderedLine),J)w0.stdout.write(`
24
- `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||u0()||!w0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(u0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await AH(this.config.logDirectory),G=[];for(let H of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(H):H.startsWith(this.name))||!H.endsWith(".log"))continue;let z=e1(this.config.logDirectory,H);if($.before)try{if((await a1(z)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${z}:`,U);continue}G.push(z)}if(G.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${G.length} log file(s)...`);for(let H of G)try{await zH(H),console.warn(`Deleted log file: ${H}`)}catch(A){console.error(`Failed to delete log file ${H}:`,A)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}async function XY($,J={}){let{maxRetries:G=3,retryDelay:H=1000,isRetryable:A=()=>!0,fallback:z}=J,U=Error("Unknown error occurred");for(let h=0;h<=G;h++)try{return await $()}catch(Y){if(U=Y instanceof Error?Y:Error(String(Y)),h===G||!A(U))break;if(H>0)await new Promise((Z)=>setTimeout(Z,H))}if(z!==void 0)return z;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function jY($){return $ instanceof W$}function b7($){return $ instanceof _H}function m7($){if(jY($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((G)=>$.message.toLowerCase().includes(G.toLowerCase()))}class yH{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,J)=>J==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let J=$.toLowerCase();return["true","1","yes"].includes(J)}},{name:"number",canParse:($,J)=>J==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let J=Number($);if(Number.isNaN(J))throw TypeError(`Cannot parse "${$}" as number`);return J}},{name:"array",canParse:($,J)=>J==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let J=JSON.parse($);if(Array.isArray(J))return J}catch{}return $.split(",").map((J)=>J.trim())}},{name:"json",canParse:($,J)=>J==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(J){throw Error(`Cannot parse "${$}" as JSON: ${J}`)}}}]}async applyEnvironmentVariables($,J,G={}){let{prefix:H,useCamelCase:A=!0,useBackwardCompatibility:z=!0,customParsers:U={},verbose:h=!1,trackPerformance:Y=!0}=G,Z=async()=>{if(!$)return{config:J,source:{type:"environment",priority:50,timestamp:new Date}};let E=H||this.generateEnvPrefix($),X={...J};return this.processObject(X,[],E,{useCamelCase:A,useBackwardCompatibility:z,customParsers:U,verbose:h,configName:$}),{config:X,source:{type:"environment",priority:50,timestamp:new Date}}};if(Y)return aJ.track("applyEnvironmentVariables",Z,{configName:$});return Z()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,J){if(!J)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,J,G,H){for(let[A,z]of Object.entries($)){let U=[...J,A],h=U.map((E)=>this.formatEnvKey(E,H.useCamelCase)),Y=`${G}_${h.join("_")}`,Z=H.useBackwardCompatibility?`${G}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(H.verbose);if(typeof z==="object"&&z!==null&&!Array.isArray(z))this.processObject(z,U,G,H);else{let E=UH.env[Y]||(Z?UH.env[Z]:void 0);if(E!==void 0){if(H.verbose){let X=UH.env[Y]?Y:Z}try{$[A]=this.parseEnvironmentValue(E,typeof z,Y,H.customParsers,H.configName)}catch(X){if(X instanceof PH)throw X;throw E1.envVar(Y,E,typeof z,H.configName)}}}}}parseEnvironmentValue($,J,G,H,A){for(let[z,U]of Object.entries(H))try{return U($)}catch{continue}for(let z of this.defaultParsers)if(z.canParse($,J))try{return z.parse($)}catch{throw E1.envVar(G,$,`${J} (via ${z.name} parser)`,A)}return $}getEnvironmentVariables($){let J={},G=$.toUpperCase();for(let[H,A]of Object.entries(UH.env))if(H.startsWith(G)&&A!==void 0)J[H]=A;return J}validateEnvironmentVariable($,J,G){let H=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))H.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(G)try{this.parseEnvironmentValue($,J,G,{})}catch(A){H.push(`Cannot parse value "${J}" as ${G}: ${A}`)}return{isValid:H.length===0,errors:H}}generateEnvVarDocs($,J,G={}){let{prefix:H,format:A="text"}=G,z=H||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(J,[],z,U),A){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,J,G,H){for(let[A,z]of Object.entries($)){let U=[...J,A],h=`${G}_${U.map((Y)=>this.formatEnvKey(Y,!0)).join("_")}`;if(typeof z==="object"&&z!==null&&!Array.isArray(z))this.extractEnvVarInfo(z,U,G,H);else H.push({key:h,type:Array.isArray(z)?"array":typeof z,description:`Configuration for ${U.join(".")}`,example:this.generateExample(z)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,J){let G=`Environment Variables for ${J}:
25
-
26
- `;for(let H of $)G+=`${H.key}
27
- `,G+=` Type: ${H.type}
28
- `,G+=` Description: ${H.description}
29
- `,G+=` Example: ${H.example}
30
-
31
- `;return G}formatAsMarkdown($,J){let G=`# Environment Variables for ${J}
32
-
33
- `;G+=`| Variable | Type | Description | Example |
34
- `,G+=`|----------|------|-------------|----------|
35
- `;for(let H of $)G+=`| \`${H.key}\` | ${H.type} | ${H.description} | \`${H.example}\` |
36
- `;return G}}function c7($,J){let G=RY("process");if(typeof G>"u"||!G.env)return J;let H=G.env[$];return H!==void 0?H:J}function WY($,J,G={}){return FY($,J,G,new WeakMap)}function FY($,J,G,H){let{arrayMergeMode:A="replace",skipNullish:z=!1,customMerger:U}=G;if(J===null||J===void 0)return z?$:J;if(U){let h=U($,J);if(h!==void 0)return h}if(Array.isArray(J)||Array.isArray($))return LY($,J,A,H);if(!V$(J)||!V$($))return J;return i7($,J,G,H)}function LY($,J,G,H){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(G){case"replace":return J;case"concat":return d7($,J);case"smart":return u7($,J,H);default:return J}return J}function d7($,J){let G=[...J];for(let H of $)if(!G.some((A)=>MA(A,H)))G.push(H);return G}function u7($,J,G){if(J.length===0)return $;if($.length===0)return J;if(V$(J[0])&&V$($[0]))return p7($,J,G);if(J.every((H)=>typeof H==="string")&&$.every((H)=>typeof H==="string")){let H=[...J];for(let A of $)if(!H.includes(A))H.push(A);return H}return J}function p7($,J,G){let H=[...J];for(let A of $){if(!V$(A)){H.push(A);continue}let z=["id","name","key","path","type"],U=!1;for(let h of z)if(h in A){if(H.find((Z)=>V$(Z)&&(h in Z)&&Z[h]===A[h])){U=!0;break}}if(!U)H.push(A)}return H}function i7($,J,G,H){let A=J;if(V$(A)&&H.has(A))return H.get(A);let z={...$};if(V$(A))H.set(A,z);for(let U in A){if(!Object.prototype.hasOwnProperty.call(A,U))continue;let h=A[U],Y=z[U];if(G.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){z[U]=h;continue}if(V$(h)&&V$(Y))z[U]=FY(Y,h,G,H);else if(Array.isArray(h)||Array.isArray(Y))z[U]=LY(Y,h,G.arrayMergeMode||"smart",H);else z[U]=h}return z}function vA($,J,G="replace"){return WY($,J,{arrayMergeMode:G==="replace"?"replace":"smart",skipNullish:!0})}function MA($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let G=0;G<$.length;G++)if(!MA($[G],J[G]))return!1;return!0}if(V$($)&&V$(J)){let G=Object.keys($),H=Object.keys(J);if(G.length!==H.length)return!1;for(let A of G){if(!Object.prototype.hasOwnProperty.call(J,A))return!1;if(!MA($[A],J[A]))return!1}return!0}return!1}function V$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class xH{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,G={}){let{arrayStrategy:H="replace",useCache:A=!0,cacheTtl:z,trackPerformance:U=!0,verbose:h=!1}=G;if(A){let Z=AJ.getWithFileCheck("file",$);if(Z){if(h)console.log(`Configuration loaded from cache: ${$}`);return Z}}let Y=async()=>{if(!YH($))return null;try{let Z=`?t=${Date.now()}`,E=await import($+Z),X=E.default||E,F="default"in E,R=Object.keys(E).length>0;if(!F&&!R)throw new oJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof X!=="object"||X===null||Array.isArray(X))throw new oJ($,Error("Configuration must export a valid object"),"unknown");let Q={config:vA(J,X,H),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(A)AJ.setWithFileCheck("file",Q,$,z);return Q}catch(Z){throw Z instanceof Error?E1.configLoad($,Z):E1.configLoad($,Error(String(Z)))}};if(U)return aJ.track("loadFromPath",Y,{path:$});return Y()}async tryLoadFromPaths($,J,G={}){for(let H of $)try{let A=await this.loadFromPath(H,J,G);if(A)return A}catch(A){if(A instanceof Error&&A.name==="ConfigLoadError")throw A;if(G.verbose)console.warn(`Failed to load config from ${H}:`,A)}return null}generateConfigPaths($,J,G){let H=this.generateNamePatterns($,G),A=[];for(let z of H)for(let U of this.extensions)A.push(ZA(J,`${z}${U}`));return A}generateNamePatterns($,J){let G=[];if(G.push("config",".config"),$)G.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(J){if(G.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)G.push(`${$}.${J}.config`,`.${$}.${J}.config`)}return G.filter(Boolean)}checkFileAccess($){return XY(async()=>{return YH($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,G){let H=[];if(!YH($))return H;if(J||G){let A=this.generateNamePatterns(J||"",G);for(let z of A)for(let U of this.extensions){let h=ZA($,`${z}${U}`);if(await this.checkFileAccess(h))H.push(h)}}else try{let{readdirSync:A}=await import("fs"),z=A($);for(let U of z)if(this.looksLikeConfigFile(U)){let h=ZA($,U);if(await this.checkFileAccess(h))H.push(h)}}catch{return[]}return H}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((G)=>G.test($))}async validateConfigFile($){let J=[];try{if(!YH($))return J.push("Configuration file does not exist"),J;let G=await import($),H=G.default||G;if(H===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof H!=="object"||H===null)J.push("Configuration must be an object");else if(Array.isArray(H))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:A}=await import("fs"),z=A($,"utf8");JSON.parse(z)}catch(A){J.push(`Invalid JSON syntax: ${A}`)}}catch(G){J.push(`Failed to load configuration file: ${G}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let G=new Map;return await Promise.allSettled($.map(async(H)=>{try{let A=await this.loadFromPath(H,{},J);if(A)G.set(H,A.config)}catch(A){if(J.verbose)console.warn(`Failed to preload ${H}:`,A)}})),G}}class gA{async validateConfiguration($,J,G={}){let{stopOnFirstError:H=!1,validateRequired:A=!0,validateTypes:z=!0,customRules:U=[],trackPerformance:h=!0,verbose:Y=!1}=G,Z=async()=>{let E=[],X=[],F={stopOnFirstError:H,validateRequired:A,validateTypes:z,customRules:U,trackPerformance:h,verbose:Y};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,F);else if(Array.isArray(J))return this.validateWithRules($,[...J,...U],F);else return this.validateWithJSONSchema($,J,F)}catch(R){return E.push({path:"",message:`Validation failed: ${R}`,rule:"system"}),{isValid:!1,errors:E,warnings:X}}};if(h)return await aJ.track("validateConfiguration",Z);return Z()}async validateWithSchemaFile($,J,G){try{if(!U7(J))throw new tJ(J,[{path:"",message:"Schema file does not exist"}]);let H=await import(J),A=H.default||H;if(Array.isArray(A))return this.validateWithRules($,A,G);else return this.validateWithJSONSchema($,A,G)}catch(H){throw new tJ(J,[{path:"",message:`Failed to load schema: ${H}`}])}}validateWithJSONSchema($,J,G){let H=[],A=[];return this.validateObjectAgainstSchema($,J,"",H,A,G),{isValid:H.length===0,errors:H,warnings:A}}validateObjectAgainstSchema($,J,G,H,A,z){if(z.validateTypes&&J.type){let U=Array.isArray($)?"array":typeof $,h=Array.isArray(J.type)?J.type:[J.type];if(!h.includes(U)){if(H.push({path:G,message:`Expected type ${h.join(" or ")}, got ${U}`,expected:h.join(" or "),actual:U,rule:"type"}),z.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(H.push({path:G,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),z.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)H.push({path:G,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)H.push({path:G,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))H.push({path:G,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)H.push({path:G,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)H.push({path:G,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let U=0;U<$.length;U++){let h=G?`${G}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],J.items,h,H,A,z),z.stopOnFirstError&&H.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(z.validateRequired&&J.required){for(let h of J.required)if(!(h in U)){if(H.push({path:G?`${G}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),z.stopOnFirstError)return}}if(J.properties){for(let[h,Y]of Object.entries(J.properties))if(h in U){let Z=G?`${G}.${h}`:h;if(this.validateObjectAgainstSchema(U[h],Y,Z,H,A,z),z.stopOnFirstError&&H.length>0)return}}if(J.additionalProperties===!1){let h=new Set(Object.keys(J.properties||{}));for(let Y of Object.keys(U))if(!h.has(Y))A.push({path:G?`${G}.${Y}`:Y,message:`Additional property '${Y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,G){let H=[],A=[];for(let z of J)try{let U=this.getValueByPath($,z.path),h=this.validateWithRule(U,z,z.path);if(H.push(...h),G.stopOnFirstError&&H.length>0)break}catch(U){H.push({path:z.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:H.length===0,errors:H,warnings:A}}validateWithRule($,J,G){let H=[];if(J.required&&($===void 0||$===null))return H.push({path:G,message:J.message||`Property '${G}' is required`,expected:"required",rule:"required"}),H;if($===void 0||$===null)return H;if(J.type){let A=Array.isArray($)?"array":typeof $;if(A!==J.type)H.push({path:G,message:J.message||`Expected type ${J.type}, got ${A}`,expected:J.type,actual:A,rule:"type"})}if(J.min!==void 0){let A=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(A<J.min)H.push({path:G,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:A,rule:"min"})}if(J.max!==void 0){let A=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(A>J.max)H.push({path:G,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:A,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))H.push({path:G,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))H.push({path:G,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let A=J.validator($);if(A)H.push({path:G,message:J.message||A,rule:"custom"})}return H}getValueByPath($,J){if(!J)return $;let G=J.split("."),H=$;for(let A of G)if(H&&typeof H==="object"&&A in H)H=H[A];else return;return H}generateRulesFromInterface($){let J=[],G=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let H of G){let[,A,z,U]=H;J.push({path:A,required:!z,type:this.mapTypeScriptType(U)})}return J}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:MY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class bA{fileLoader=new xH;envProcessor=new yH;validator=new gA;async loadConfig($){let J=Date.now(),{cache:G,performance:H,schema:A,validate:z,...U}=$;try{if(G?.enabled){let Y=this.checkCache(U.name||"",U);if(Y)return Y}let h;try{h=await this.loadConfigurationStrategies(U,!0,G)}catch(Y){let Z=U.__strictErrorHandling;if(Y instanceof Error&&Y.name==="ConfigNotFoundError"){if(Z)throw Y;h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Y instanceof Error&&Y.name==="ConfigLoadError"){let E=Y.message.includes("EACCES")||Y.message.includes("EPERM")||Y.message.includes("permission denied"),X=!E&&(Y.message.includes("syntax")||Y.message.includes("Expected")||Y.message.includes("Unexpected")||Y.message.includes("BuildMessage")||Y.message.includes("errors building")),F=Y.message.includes("Configuration must export a valid object")||Y.message.includes("Configuration file is empty and exports nothing");if(Z&&(F||E))throw Y;if(X&&(!Z||!F))h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Z)h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Y.message}`]};else throw Y}else h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Y instanceof Error?Y.message:String(Y)}`]}}if(A||z)await this.validateConfiguration(h.config,A,z,U.name);if(G?.enabled&&h)this.cacheResult(U.name||"",h,G,U);if(H?.enabled){let Y={operation:"loadConfig",duration:Date.now()-J,configName:U.name,timestamp:new Date};if(H.onMetrics)H.onMetrics(Y);if(H.slowThreshold&&Y.duration>H.slowThreshold)S$.warn(`Slow configuration loading detected: ${Y.duration}ms for ${U.name}`);h.metrics=Y}return h}catch(h){let Y=Date.now()-J;throw S$.error(`Configuration loading failed after ${Y}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies($,J=!1,G){let{name:H="",alias:A,cwd:z,configDir:U,defaultConfig:h,checkEnv:Y=!0,arrayStrategy:Z="replace",verbose:E=!1}=$,X=z||P1.cwd(),F=[],R=await this.loadLocalConfiguration(H,A,X,U,h,Z,E,Y,G);if(R)return F.push(...this.getLocalSearchPaths(H,A,X,U)),this.finalizeResult(R,F,Y,H,E);let C=await this.loadHomeConfiguration(H,A,h,Z,E,Y);if(C)return F.push(...this.getHomeSearchPaths(H,A)),this.finalizeResult(C,F,Y,H,E);let W=await this.loadPackageJsonConfiguration(H,A,X,h,Z,E,Y);if(W)return F.push(U$(X,"package.json")),this.finalizeResult(W,F,Y,H,E);if(F.push(...this.getAllSearchPaths(H,A,X,U)),J)throw E1.configNotFound(H,F,A);return{...await this.applyEnvironmentVariables(H,h,Y,E),warnings:[`No configuration file found for "${H}"${A?` or alias "${A}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,G,H,A,z,U,h,Y){let Z=h?lJ($,A,U):A,E=this.getLocalDirectories(G,H);for(let X of E){if(U)S$.info(`Searching for configuration in: ${X}`);let F=this.fileLoader.generateConfigPaths($,X,J),R=await this.fileLoader.tryLoadFromPaths(F,Z,{arrayStrategy:z,verbose:U,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(R){if(U)S$.success(`Configuration loaded from: ${R.source.path}`);return R}}return null}async loadHomeConfiguration($,J,G,H,A,z){if(!$)return null;let U=z?lJ($,G,A):G,h=[U$(l1(),".config",$),U$(l1(),".config"),l1()];for(let Y of h){if(A)S$.info(`Checking home directory: ${Y}`);let Z=this.fileLoader.generateConfigPaths($,Y,J),E=await this.fileLoader.tryLoadFromPaths(Z,U,{arrayStrategy:H,verbose:A});if(E){if(A)S$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,J,G,H,A,z,U){let h=U?lJ($,H,z):H;try{let Y=U$(G,"package.json");if(!VA(Y))return null;let Z=await import(Y),E=Z[$],X=$;if(!E&&J)E=Z[J],X=J;if(E&&typeof E==="object"&&!Array.isArray(E)){if(z)S$.success(`Configuration loaded from package.json: ${X}`);return{config:vA(h,E,A),source:{type:"package.json",path:Y,priority:30,timestamp:new Date}}}}catch(Y){if(z)S$.warn("Failed to load package.json:",[Y instanceof Error?Y:Error(String(Y))])}return null}async applyEnvironmentVariables($,J,G,H){if(!G||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:lJ($,J,H),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,G,H,A){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,G,H){let A=[];if(G){let z=G($);if(z)A.push(...z)}if(J){let z=await this.validator.validateConfiguration($,J);if(!z.isValid)A.push(...z.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(A.length>0)throw E1.configValidation(H||"unknown",A,H)}checkCache($,J){let G=this.generateCacheKey($,J);return AJ.get(G)||null}cacheResult($,J,G,H){let A=this.generateCacheKey($,H);AJ.set(A,J,void 0,G.ttl)}generateCacheKey($,J){let G=[$];if(J.alias)G.push(`alias:${J.alias}`);if(J.cwd)G.push(`cwd:${J.cwd}`);if(J.configDir)G.push(`configDir:${J.configDir}`);if("checkEnv"in J)G.push(`checkEnv:${J.checkEnv}`);return G.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,U$($,"config"),U$($,".config"),J?U$($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,G,H){let A=[];return A.push(...this.getLocalSearchPaths($,J,G,H)),A.push(...this.getHomeSearchPaths($,J)),A.push(U$(G,"package.json")),A}getLocalSearchPaths($,J,G,H){let A=this.getLocalDirectories(G,H),z=[];for(let U of A)z.push(...this.fileLoader.generateConfigPaths($,U,J));return z}getHomeSearchPaths($,J){if(!$)return[];let G=[U$(l1(),".config",$),U$(l1(),".config"),l1()],H=[];for(let A of G)H.push(...this.fileLoader.generateConfigPaths($,A,J));return H}async loadConfigWithResult($){return this.loadConfig($)}}function dU($){let G=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),H=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return G||H}async function n7($){return n$.loadConfig({...$,__strictErrorHandling:!0})}async function wY($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},G="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let H;if(G)H=await n$.loadConfig($);else H=await n$.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return H?.config??J}catch(H){let A=H instanceof Error?H.name:"UnknownError",z=H instanceof Error?H.message:String(H);if(!(A==="ConfigNotFoundError"||A==="ConfigLoadError"||A==="ConfigValidationError"||z.includes("config"))&&$.verbose)S$.warn("Unexpected error loading config, using defaults:",[H instanceof Error?H:Error(String(H))]);let h=G?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await n$.applyEnvironmentVariables(h.name||"",J,!0,h.verbose||!1))?.config??J;return J}}async function r7($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:J}=await import("process");try{return(await n$.loadConfig({name:$,cwd:J(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(G){if(G instanceof Error&&(G.name==="ConfigNotFoundError"||G.name==="ConfigLoadError"&&dU(G)))return(await n$.applyEnvironmentVariables($,{},!0,!1)).config;throw G}}try{return(await n$.loadConfig({...$,cwd:$.cwd||P1.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(J){if(J instanceof Error&&(J.name==="ConfigNotFoundError"||J.name==="ConfigLoadError"&&dU(J)))return(await n$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw J}}async function l7($,J,G="replace"){let H=new xH;try{let A=await H.loadFromPath($,J,{arrayStrategy:G,useCache:!1,trackPerformance:!1});return A?A.config:null}catch{return null}}function lJ($,J,G=!1){let H=new yH,A=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function z(U,h=[]){let Y={...U};for(let[Z,E]of Object.entries(U)){let X=[...h,Z],F=[`${A}_${X.join("_").toUpperCase()}`,`${A}_${X.map((W)=>W.toUpperCase()).join("")}`,`${A}_${X.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],R,C;for(let W of F)if(R=P1.env[W],R!==void 0){C=W;break}if(R!==void 0&&C)if(typeof E==="boolean")Y[Z]=["true","1","yes"].includes(R.toLowerCase());else if(typeof E==="number"){let W=Number(R);if(!Number.isNaN(W))Y[Z]=W}else if(Array.isArray(E))try{Y[Z]=JSON.parse(R)}catch{Y[Z]=R.split(",").map((W)=>W.trim())}else Y[Z]=R;else if(E&&typeof E==="object"&&!Array.isArray(E))Y[Z]=z(E,X)}return Y}return z(J)}function s7($){let J=U$(P1.cwd(),$.configDir),G=U$(P1.cwd(),$.generatedDir),H=U$(G,"config-types.ts");if(!VA(QU(H)))vZ(QU(H),{recursive:!0,mode:511});let A=VA(J)?gZ(J).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],z=`// Generated by bunfig v${BE}
37
- export type ConfigNames = ${A.length?`'${A.join("' | '")}'`:"string"}
38
- `;bZ(H,z,{mode:438})}function o7($){let J=null,G=null,H=()=>{if(!G)G=wY($).then((z)=>{return J=z,z},(z)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(J=U,"verbose"in $&&$.verbose)S$.warn("Config loading failed, using defaults:",[z instanceof Error?z:Error(String(z))]);return U});return G},A="defaultConfig"in $?$.defaultConfig:{};return J=A,H(),new Proxy({},{get(z,U){if(J)return J[U];let h=A[U];return H(),h},has(z,U){return U in(J||A)},ownKeys(){return Object.keys(J||A)},getOwnPropertyDescriptor(z,U){return Object.getOwnPropertyDescriptor(J||A,U)},set(z,U,h){if(!J)J={...A};return J[U]=h,!0}})}function t7($){let J=yU(Z7.cwd(),$?.configDir||"./config");function G(){if(!Y7(J))return[];let A=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),z=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=h7(J).filter((Y)=>A.has(EA(Y))).map((Y)=>({base:Y.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Y})),h=new Map;for(let{base:Y,file:Z}of U){let E=EA(Z).toLowerCase(),X=h.get(Y);if(!X){h.set(Y,Z);continue}let F=EA(X).toLowerCase();if(z.indexOf(E)<z.indexOf(F))h.set(Y,Z)}return Array.from(h.entries()).map(([Y,Z])=>({base:Y,file:Z})).sort((Y,Z)=>Y.base.localeCompare(Z.base))}function H(){let A=G(),z=A.map((Z)=>Z.base),U=z.length?z.map((Z)=>`'${Z}'`).join(" | "):"string",h=A.length?`{
39
- ${A.map((Z)=>{let E=yU(J,Z.file).replace(/\\/g,"/");return` '${Z.base}': typeof import('${E}').default`}).join(`,
40
- `)}
41
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
42
- export type ConfigByName = ${h}
43
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
44
- export type ConfigOf = Config
45
- `}return{name:"bunfig-plugin",setup(A){A.onResolve({filter:/^virtual:bunfig-types$/},(z)=>{return{path:z.path,namespace:"bunfig-virtual"}}),A.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:H(),loader:"ts"}})}}}function IE($,J={}){let G=KH.cwd();while(G.includes("storage"))G=xU(G,"..");let H=xU(G,$||"");if(J?.relative)return X7(KH.cwd(),H);return H}function i0(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _E(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i$<"u"){let $=i$.type;if($==="renderer"||$==="worker")return!1;return!!(i$.versions&&(i$.versions.node||i$.versions.bun))}return!1}class IY{async format($){let J=await _E(),G=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:G})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:HJ.pid,hostname:J(),environment:HJ.env.NODE_ENV||"development",platform:HJ.platform,version:HJ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:HJ.env.NODE_ENV||HJ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class fH{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($,J={}){this.name=$,this.config={...NH},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new IY,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??R0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let G={...J},H=J.timestamp!==void 0;if(H)delete G.timestamp;if(this.config={...this.config,...G,timestamp:H||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let A=this.generateKeyId(),z=this.generateKey();this.currentKeyId=A,this.keys.set(A,z),this.encryptionKeys.set(A,{key:z,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},G=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[G]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...DA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...DA};return{...DA,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:NH.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},G={...J,...Object.fromEntries(Object.entries($).filter(([,H])=>H!==void 0))};if(!G.level||!["debug","info","success","warning","error"].includes(G.level))G.level=J.level;return G}shouldWriteToFile(){return!i0()&&this.config.writeToFile===!0}async writeToFile($){let G=(async()=>{let A,z=0,U=3,h=1000;while(z<U)try{try{try{await w7(this.config.logDirectory,bU.F_OK|bU.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await R7(this.config.logDirectory,{recursive:!0,mode:493});else if(Z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Z;else throw Z}}catch(Z){throw console.error("Debug: [writeToFile] Failed to create log directory:",Z),Z}let Y=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:d$.from($);try{if(!hH(this.currentLogFile))await WA(this.currentLogFile,"",{mode:420});if(A=gU(this.currentLogFile,"a",420),L7(A,Y,{flag:"a"}),vU(A),A!==void 0)jA(A),A=void 0;if((await JJ(this.currentLogFile)).size===0){if(await WA(this.currentLogFile,Y,{flag:"w",mode:420}),(await JJ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(z<U-1){let X=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${z+1}/${U}:`,X);let F=h*2**z;await new Promise((R)=>setTimeout(R,F)),z++;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(A!==void 0)try{jA(A)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(Y){if(z===U-1){let E=Y,X=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",X),Y}z++;let Z=h*2**(z-1);await new Promise((E)=>setTimeout(E,Z))}})();this.pendingOperations.push(G);let H=this.pendingOperations.length-1;try{await G}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(H,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 GJ(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 GJ(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return GJ(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(i0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let G=typeof J.interval==="number"?J.interval:60,H=Math.max(G,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},H)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,G=this.generateKeyId(),H=this.generateKey();this.currentKeyId=G,this.keys.set(G,H),this.encryptionKeys.set(G,{key:H,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,h],[,Y])=>Y.createdAt.getTime()-h.createdAt.getTime()),z=typeof J.maxKeys==="number"?J.maxKeys:1,U=Math.max(1,z);if(A.length>U)for(let[h]of A.slice(U))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return XA(16).toString("hex")}generateKey(){return XA(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:J}=this.getCurrentKey(),G=XA(16),H=j7("aes-256-gcm",J,G),A=d$.isBuffer($)?$:d$.from($,"utf8"),z=H.update(A),U=H.final(),h=z.length+U.length,Y=H.getAuthTag(),Z=d$.allocUnsafe(16+h+16);return G.copy(Z,0),z.copy(Z,16),U.copy(Z,16+z.length),Y.copy(Z,16+h),{encrypted:Z,iv:G}}async compressData($){return new Promise((J,G)=>{let H=cU(),A=[];H.on("data",(z)=>A.push(z)),H.on("end",()=>J(d$.from(d$.concat(A)))),H.on("error",G),H.write($),H.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 J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(i0())return;if(!this.shouldWriteToFile())return;let $=await JJ(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let G=this.currentLogFile,H=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let A=await ZH(this.config.logDirectory),z=A.filter((Y)=>Y.startsWith(this.name)&&/\.log\.\d+$/.test(Y)).sort((Y,Z)=>{let E=Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=z.length>0?Number.parseInt(z[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${G}.${U}`;if(await JJ(G).catch(()=>null))try{if(await mU(G,h),J.compress)try{let Y=`${h}.gz`;await this.compressLogFile(h,Y),await EH(h)}catch(Y){console.error("Error compressing rotated file:",Y)}if(z.length===0&&!A.some((Y)=>Y.endsWith(".log.1")))try{let Y=`${G}.1`;await WA(Y,"")}catch(Y){console.error("Error creating backup file:",Y)}}catch(Y){console.error(`Error during rotation: ${Y instanceof Error?Y.message:String(Y)}`)}}else{let A=new Date().toISOString().replace(/[:.]/g,"-"),z=G.replace(/\.log$/,`-${A}.log`);if(await JJ(G).catch(()=>null))await mU(G,z)}if(this.currentLogFile=H,J.maxFiles){let z=(await ZH(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,h)=>h.localeCompare(U));for(let U of z.slice(J.maxFiles))await EH(GJ(this.config.logDirectory,U))}}}async compressLogFile($,J){let G=fU($),H=F7(J),A=cU();await V7(G,A,H)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let G of this.logBuffer){let H=await this.formatter.format(G);if(this.shouldWriteToFile())await this.writeToFile(H);console.log(H)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),hH(this.currentLogFile))try{let $=gU(this.currentLogFile,"r+");vU($),jA($)}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(!i0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await ZH(this.config.logDirectory)).filter((G)=>(G.includes("temp")||G.includes(".tmp"))&&G.includes(this.name));for(let G of J)try{await EH(GJ(this.config.logDirectory,G))}catch(H){console.error(`Failed to delete temp file ${G}:`,H)}}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()?V0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||i0())return!1;let $=typeof R0.env.NO_COLOR<"u",J=R0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof R0.stderr<"u"&&R0.stderr.isTTY||typeof R0.stdout<"u"&&R0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:G="",tag:H="",message:A,level:z,showTimestamp:U=!0}=$,h=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(U)R.push(J);if(z==="warning")R.push("WARN");else if(z==="error")R.push("ERROR");else if(G)R.push(G.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(H)R.push(H.replace(/[[\]]/g,""));return R.push(A),R.join(" ")}let Y=R0.stdout.columns||120,Z="";if(z==="warning"||z==="error")Z=`${G} ${A}`;else if(z==="info"||z==="success")Z=`${G} ${H} ${A}`;else Z=`${G} ${H} ${V0.cyan(A)}`;if(!U)return Z.trim();let E=h(Z).trim().length,X=h(J).length,F=Math.max(1,Y-2-E-X);return`${Z.trim()}${" ".repeat(F)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(z,U)=>{let h=Number.parseInt(U,10);return h<J[0].length?String(J[0][h]):z});let G=/%([sdijfo%])/g,H=0,A=$.replace(G,(z,U)=>{if(U==="%")return"%";if(H>=J.length)return z;let h=J[H++];switch(U){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return z}});if(H<J.length)A+=` ${J.slice(H).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`;return A}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(G,H,A)=>{let z=V0.underline(V0.blue(H)),U=this.toAbsoluteFilePath(A);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(U)}`,Y="\x1B]8;;",Z="\x1B\\";return`\x1B]8;;${h}\x1B\\${z}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${A}\x1B\\${z}\x1B]8;;\x1B\\`;return z}),J=J.replace(/`([^`]+)`/g,(G,H)=>V0.bgGray(H)),J=J.replace(/\*\*([^*]+)\*\*/g,(G,H)=>V0.bold(H)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(G,H)=>V0.italic(H)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(G,H)=>V0.italic(H)),J=J.replace(/~([^~]+)~/g,(G,H)=>V0.strikethrough(H)),J}supportsHyperlinks(){if(i0())return!1;let $=R0.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 J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let G=R0.env.HOME||"";if(G)J=J.replace(/^~(?=$|\/)/,G)}if(D7(J)||J.startsWith("./")||J.startsWith("../"))J=Q7(J);else return null;return hH(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,G=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:G}}async log($,J,...G){if(!this.shouldLog($))return;let H=new Date,A=this.formatConsoleTimestamp(H),z=this.formatFileTimestamp(H),U,h;if(J instanceof Error)U=J.message,h=J.stack;else U=this.formatMessage(J,G);let{consoleText:Y,fileText:Z}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let X=this.options.showIcons===!1?"":qE[$],F=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"",R;switch($){case"debug":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:V0.gray(Y),level:$}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.warn(R);break;case"success":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:V0.green(Y),level:$}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.error(R),h){let C=h.split(`
46
- `);for(let W of C)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:A,message:V0.gray(` ${W}`),level:$,showTimestamp:!1}))}break}}else if(!i0()){if(console.error(`${z} ${this.environment}.${$.toUpperCase()}: ${U}`),h)console.error(h)}let E=`${z} ${this.environment}.${$.toUpperCase()}: ${Z}
47
- `;if(h)E+=`${h}
48
- `;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,J=""){let G={update:(h,Y)=>{},finish:(h)=>{},interrupt:(h,Y)=>{}};if(!this.enabled)return G;let H=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:J||"",barLength:H,lastRenderedLine:""},this.shouldStyleConsole()&&!i0()&&R0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,Y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),Y!==void 0)this.activeProgressBar.message=Y;if(this.shouldStyleConsole()&&!i0()&&R0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,Y="info")=>{if(!i0()&&R0.stdout.isTTY)R0.stdout.write(`
49
- `);if(this[Y==="warning"?"warn":Y](h),this.activeProgressBar&&this.shouldStyleConsole()&&!i0()&&R0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let J=performance.now();if(this.shouldStyleConsole()){let G=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"",H=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":V0.blue("\u25D0"),tag:G,message:`${V0.cyan($)}...`}))}return async(G)=>{if(!this.enabled)return;let H=performance.now(),A=Math.round(H-J),z=`${$} completed in ${A}ms`,U=new Date,h=this.formatConsoleTimestamp(U),Z=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${z}`;if(G)Z+=` ${JSON.stringify(G)}`;if(Z+=`
50
- `,Z=Z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":V0.green("\u2713"),tag:E,message:`${z}${G?` ${JSON.stringify(G)}`:""}`}))}else if(!i0())console.error(Z.trim());if(this.shouldWriteToFile())await this.writeToFile(Z)}}async debug($,...J){await this.log("debug",$,...J)}async info($,...J){await this.log("info",$,...J)}async success($,...J){await this.log("success",$,...J)}async warn($,...J){await this.log("warning",$,...J)}async error($,...J){await this.log("error",$,...J)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:J}=$;return!!J}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let J=`${this.name}:${$}`,G=new fH(J,{...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(G),G}createReadStream(){if(i0())throw Error("createReadStream is not supported in browser environments");if(!hH(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fU(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let J=this.config.rotation;if(!J.encrypt||typeof J.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let G=this.keys.get(this.currentKeyId);try{let H=d$.isBuffer($)?$:d$.from($,"base64"),A=H.subarray(0,16),z=H.subarray(H.length-16),U=H.subarray(16,H.length-16),h=W7("aes-256-gcm",G,A);h.setAuthTag(z);let Y=h.update(U),Z=h.final(),E=Y.length+Z.length,X=d$.allocUnsafe(E);return Y.copy(X,0),Z.copy(X,Y.length),X.toString("utf8")}catch(H){throw Error(`Decryption failed: ${H instanceof Error?H.message:String(H)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return i0()}isServerMode(){return!i0()}setTestEncryptionKey($,J){this.currentKeyId=$,this.keys.set($,J)}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 J=new Date,G=this.formatConsoleTimestamp(J),H=this.formatFileTimestamp(J),{consoleText:A,fileText:z}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let h=A.split(`
51
- `),Y=Math.max(...h.map((F)=>F.length))+2,Z=`\u250C${"\u2500".repeat(Y)}\u2510`,E=`\u2514${"\u2500".repeat(Y)}\u2518`,X=h.map((F)=>{return this.formatConsoleMessage({timestamp:G,message:V0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:G,message:V0.cyan(Z),showTimestamp:!1})),X.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:G,message:V0.cyan(E),showTimestamp:!1}))}else if(!i0())console.error(`${H} ${this.environment}.INFO: [BOX] ${z}`);let U=`${H} ${this.environment}.INFO: [BOX] ${z}
52
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(i0())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${V0.cyan("?")} ${$} (y/n) `);let G=(H)=>{let A=H.toString().trim().toLowerCase();R0.stdin.removeListener("data",G);try{if(typeof R0.stdin.setRawMode==="function")R0.stdin.setRawMode(!1)}catch{}R0.stdin.pause(),console.error(""),J(A==="y"||A==="yes")};try{if(typeof R0.stdin.setRawMode==="function")R0.stdin.setRawMode(!0)}catch{}R0.stdin.resume(),R0.stdin.once("data",G)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let G=$;if(J&&J.length>0){let Y=/%([sdijfo%])/g,Z=0;if(G=$.replace(Y,(E,X)=>{if(X==="%")return"%";if(Z>=J.length)return E;let F=J[Z++];switch(X){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}}),Z<J.length)G+=` ${J.slice(Z).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:H,fileText:A}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?V0.gray(this.formatTag(this.name)):"",Z=this.options.showIcons===!1?"":`${V0.blue("\u25D0")} `;console.error(`${Z}${Y} ${V0.cyan(H)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
53
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar($,J=!1){if(!this.enabled||!this.shouldStyleConsole()||!R0.stdout.isTTY)return;let G=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),H=Math.round($.barLength*G/100),A=$.barLength-H,z=V0.green("\u2501".repeat(H)),U=V0.gray("\u2501".repeat(A)),h=`[${z}${U}]`,Y=`${G}%`.padStart(4),Z=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":J||G===100?V0.green("\u2713"):V0.blue("\u25B6"),X=this.options.showTags!==!1&&this.name?` ${V0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${X} ${h} ${Y}${Z}`,R=R0.stdout.columns||80,C=" ".repeat(Math.max(0,R-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${C}`,R0.stdout.write($.lastRenderedLine),J)R0.stdout.write(`
54
- `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||i0()||!R0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(i0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await ZH(this.config.logDirectory),G=[];for(let H of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(H):H.startsWith(this.name))||!H.endsWith(".log"))continue;let z=GJ(this.config.logDirectory,H);if($.before)try{if((await JJ(z)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${z}:`,U);continue}G.push(z)}if(G.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${G.length} log file(s)...`);for(let H of G)try{await EH(H),console.warn(`Deleted log file: ${H}`)}catch(A){console.error(`Failed to delete log file ${H}:`,A)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}async function yE($,J={}){let{maxRetries:G=3,retryDelay:H=1000,isRetryable:A=()=>!0,fallback:z}=J,U=Error("Unknown error occurred");for(let h=0;h<=G;h++)try{return await $()}catch(Y){if(U=Y instanceof Error?Y:Error(String(Y)),h===G||!A(U))break;if(H>0)await new Promise((Z)=>setTimeout(Z,H))}if(z!==void 0)return z;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class cA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,J)=>J==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let J=$.toLowerCase();return["true","1","yes"].includes(J)}},{name:"number",canParse:($,J)=>J==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let J=Number($);if(Number.isNaN(J))throw TypeError(`Cannot parse "${$}" as number`);return J}},{name:"array",canParse:($,J)=>J==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let J=JSON.parse($);if(Array.isArray(J))return J}catch{}return $.split(",").map((J)=>J.trim())}},{name:"json",canParse:($,J)=>J==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(J){throw Error(`Cannot parse "${$}" as JSON: ${J}`)}}}]}async applyEnvironmentVariables($,J,G={}){let{prefix:H,useCamelCase:A=!0,useBackwardCompatibility:z=!0,customParsers:U={},verbose:h=!1,trackPerformance:Y=!0}=G,Z=async()=>{if(!$)return{config:J,source:{type:"environment",priority:50,timestamp:new Date}};let E=H||this.generateEnvPrefix($),X={...J};return this.processObject(X,[],E,{useCamelCase:A,useBackwardCompatibility:z,customParsers:U,verbose:h,configName:$}),{config:X,source:{type:"environment",priority:50,timestamp:new Date}}};if(Y)return kA.track("applyEnvironmentVariables",Z,{configName:$});return Z()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,J){if(!J)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,J,G,H){for(let[A,z]of Object.entries($)){let U=[...J,A],h=U.map((E)=>this.formatEnvKey(E,H.useCamelCase)),Y=`${G}_${h.join("_")}`,Z=H.useBackwardCompatibility?`${G}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(H.verbose);if(typeof z==="object"&&z!==null&&!Array.isArray(z))this.processObject(z,U,G,H);else{let E=jH.env[Y]||(Z?jH.env[Z]:void 0);if(E!==void 0){if(H.verbose){let X=jH.env[Y]?Y:Z}try{$[A]=this.parseEnvironmentValue(E,typeof z,Y,H.customParsers,H.configName)}catch(X){if(X instanceof mA)throw X;throw _1.envVar(Y,E,typeof z,H.configName)}}}}}parseEnvironmentValue($,J,G,H,A){for(let[z,U]of Object.entries(H))try{return U($)}catch{continue}for(let z of this.defaultParsers)if(z.canParse($,J))try{return z.parse($)}catch{throw _1.envVar(G,$,`${J} (via ${z.name} parser)`,A)}return $}getEnvironmentVariables($){let J={},G=$.toUpperCase();for(let[H,A]of Object.entries(jH.env))if(H.startsWith(G)&&A!==void 0)J[H]=A;return J}validateEnvironmentVariable($,J,G){let H=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))H.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(G)try{this.parseEnvironmentValue($,J,G,{})}catch(A){H.push(`Cannot parse value "${J}" as ${G}: ${A}`)}return{isValid:H.length===0,errors:H}}generateEnvVarDocs($,J,G={}){let{prefix:H,format:A="text"}=G,z=H||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(J,[],z,U),A){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,J,G,H){for(let[A,z]of Object.entries($)){let U=[...J,A],h=`${G}_${U.map((Y)=>this.formatEnvKey(Y,!0)).join("_")}`;if(typeof z==="object"&&z!==null&&!Array.isArray(z))this.extractEnvVarInfo(z,U,G,H);else H.push({key:h,type:Array.isArray(z)?"array":typeof z,description:`Configuration for ${U.join(".")}`,example:this.generateExample(z)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,J){let G=`Environment Variables for ${J}:
55
-
56
- `;for(let H of $)G+=`${H.key}
57
- `,G+=` Type: ${H.type}
58
- `,G+=` Description: ${H.description}
59
- `,G+=` Example: ${H.example}
60
-
61
- `;return G}formatAsMarkdown($,J){let G=`# Environment Variables for ${J}
62
-
63
- `;G+=`| Variable | Type | Description | Example |
64
- `,G+=`|----------|------|-------------|----------|
65
- `;for(let H of $)G+=`| \`${H.key}\` | ${H.type} | ${H.description} | \`${H.example}\` |
66
- `;return G}}function xE($,J,G={}){return yY($,J,G,new WeakMap)}function yY($,J,G,H){let{arrayMergeMode:A="replace",skipNullish:z=!1,customMerger:U}=G;if(J===null||J===void 0)return z?$:J;if(U){let h=U($,J);if(h!==void 0)return h}if(Array.isArray(J)||Array.isArray($))return xY($,J,A,H);if(!O$(J)||!O$($))return J;return bE($,J,G,H)}function xY($,J,G,H){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(G){case"replace":return J;case"concat":return fE($,J);case"smart":return vE($,J,H);default:return J}return J}function fE($,J){let G=[...J];for(let H of $)if(!G.some((A)=>TA(A,H)))G.push(H);return G}function vE($,J,G){if(J.length===0)return $;if($.length===0)return J;if(O$(J[0])&&O$($[0]))return gE($,J,G);if(J.every((H)=>typeof H==="string")&&$.every((H)=>typeof H==="string")){let H=[...J];for(let A of $)if(!H.includes(A))H.push(A);return H}return J}function gE($,J,G){let H=[...J];for(let A of $){if(!O$(A)){H.push(A);continue}let z=["id","name","key","path","type"],U=!1;for(let h of z)if(h in A){if(H.find((Z)=>O$(Z)&&(h in Z)&&Z[h]===A[h])){U=!0;break}}if(!U)H.push(A)}return H}function bE($,J,G,H){let A=J;if(O$(A)&&H.has(A))return H.get(A);let z={...$};if(O$(A))H.set(A,z);for(let U in A){if(!Object.prototype.hasOwnProperty.call(A,U))continue;let h=A[U],Y=z[U];if(G.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){z[U]=h;continue}if(O$(h)&&O$(Y))z[U]=yY(Y,h,G,H);else if(Array.isArray(h)||Array.isArray(Y))z[U]=xY(Y,h,G.arrayMergeMode||"smart",H);else z[U]=h}return z}function fY($,J,G="replace"){return xE($,J,{arrayMergeMode:G==="replace"?"replace":"smart",skipNullish:!0})}function TA($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let G=0;G<$.length;G++)if(!TA($[G],J[G]))return!1;return!0}if(O$($)&&O$(J)){let G=Object.keys($),H=Object.keys(J);if(G.length!==H.length)return!1;for(let A of G){if(!Object.prototype.hasOwnProperty.call(J,A))return!1;if(!TA($[A],J[A]))return!1}return!0}return!1}function O$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class vY{extensions=AY;async loadFromPath($,J,G={}){let{arrayStrategy:H="replace",useCache:A=!0,cacheTtl:z,trackPerformance:U=!0,verbose:h=!1}=G;if(A){let Z=QH.getWithFileCheck("file",$);if(Z){if(h)console.log(`Configuration loaded from cache: ${$}`);return Z}}let Y=async()=>{if(!WH($))return null;try{let Z=`?t=${Date.now()}`,E=await import($+Z),X=E.default||E,F="default"in E,R=Object.keys(E).length>0;if(!F&&!R)throw new TH($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof X!=="object"||X===null||Array.isArray(X))throw new TH($,Error("Configuration must export a valid object"),"unknown");let Q={config:fY(J,X,H),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(A)QH.setWithFileCheck("file",Q,$,z);return Q}catch(Z){throw Z instanceof Error?_1.configLoad($,Z):_1.configLoad($,Error(String(Z)))}};if(U)return kA.track("loadFromPath",Y,{path:$});return Y()}async tryLoadFromPaths($,J,G={}){for(let H of $)try{let A=await this.loadFromPath(H,J,G);if(A)return A}catch(A){if(A instanceof Error&&A.name==="ConfigLoadError")throw A;if(G.verbose)console.warn(`Failed to load config from ${H}:`,A)}return null}generateConfigPaths($,J,G){return qZ({name:$,directory:J,alias:G})}generateNamePatterns($,J){return zY({name:$,alias:J})}checkFileAccess($){return yE(async()=>{return WH($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,G){let H=[];if(!WH($))return H;if(J||G){let A=this.generateNamePatterns(J||"",G);for(let z of A)for(let U of this.extensions){let h=JY($,`${z}${U}`);if(await this.checkFileAccess(h))H.push(h)}}else try{let{readdirSync:A}=await import("fs"),z=A($);for(let U of z)if(this.looksLikeConfigFile(U)){let h=JY($,U);if(await this.checkFileAccess(h))H.push(h)}}catch{return[]}return H}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((G)=>G.test($))}async validateConfigFile($){let J=[];try{if(!WH($))return J.push("Configuration file does not exist"),J;let G=await import($),H=G.default||G;if(H===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof H!=="object"||H===null)J.push("Configuration must be an object");else if(Array.isArray(H))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:A}=await import("fs"),z=A($,"utf8");JSON.parse(z)}catch(A){J.push(`Invalid JSON syntax: ${A}`)}}catch(G){J.push(`Failed to load configuration file: ${G}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let G=new Map;return await Promise.allSettled($.map(async(H)=>{try{let A=await this.loadFromPath(H,{},J);if(A)G.set(H,A.config)}catch(A){if(J.verbose)console.warn(`Failed to preload ${H}:`,A)}})),G}}class gY{async validateConfiguration($,J,G={}){let{stopOnFirstError:H=!1,validateRequired:A=!0,validateTypes:z=!0,customRules:U=[],trackPerformance:h=!0,verbose:Y=!1}=G,Z=async()=>{let E=[],X=[],F={stopOnFirstError:H,validateRequired:A,validateTypes:z,customRules:U,trackPerformance:h,verbose:Y};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,F);else if(Array.isArray(J))return this.validateWithRules($,[...J,...U],F);else return this.validateWithJSONSchema($,J,F)}catch(R){return E.push({path:"",message:`Validation failed: ${R}`,rule:"system"}),{isValid:!1,errors:E,warnings:X}}};if(h)return await kA.track("validateConfiguration",Z);return Z()}async validateWithSchemaFile($,J,G){try{if(!mE(J))throw new kH(J,[{path:"",message:"Schema file does not exist"}]);let H=await import(J),A=H.default||H;if(Array.isArray(A))return this.validateWithRules($,A,G);else return this.validateWithJSONSchema($,A,G)}catch(H){throw new kH(J,[{path:"",message:`Failed to load schema: ${H}`}])}}validateWithJSONSchema($,J,G){let H=[],A=[];return this.validateObjectAgainstSchema($,J,"",H,A,G),{isValid:H.length===0,errors:H,warnings:A}}validateObjectAgainstSchema($,J,G,H,A,z){if(z.validateTypes&&J.type){let U=Array.isArray($)?"array":typeof $,h=Array.isArray(J.type)?J.type:[J.type];if(!h.includes(U)){if(H.push({path:G,message:`Expected type ${h.join(" or ")}, got ${U}`,expected:h.join(" or "),actual:U,rule:"type"}),z.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(H.push({path:G,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),z.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)H.push({path:G,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)H.push({path:G,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))H.push({path:G,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)H.push({path:G,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)H.push({path:G,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let U=0;U<$.length;U++){let h=G?`${G}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],J.items,h,H,A,z),z.stopOnFirstError&&H.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(z.validateRequired&&J.required){for(let h of J.required)if(!(h in U)){if(H.push({path:G?`${G}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),z.stopOnFirstError)return}}if(J.properties){for(let[h,Y]of Object.entries(J.properties))if(h in U){let Z=G?`${G}.${h}`:h;if(this.validateObjectAgainstSchema(U[h],Y,Z,H,A,z),z.stopOnFirstError&&H.length>0)return}}if(J.additionalProperties===!1){let h=new Set(Object.keys(J.properties||{}));for(let Y of Object.keys(U))if(!h.has(Y))A.push({path:G?`${G}.${Y}`:Y,message:`Additional property '${Y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,G){let H=[],A=[];for(let z of J)try{let U=this.getValueByPath($,z.path),h=this.validateWithRule(U,z,z.path);if(H.push(...h),G.stopOnFirstError&&H.length>0)break}catch(U){H.push({path:z.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:H.length===0,errors:H,warnings:A}}validateWithRule($,J,G){let H=[];if(J.required&&($===void 0||$===null))return H.push({path:G,message:J.message||`Property '${G}' is required`,expected:"required",rule:"required"}),H;if($===void 0||$===null)return H;if(J.type){let A=Array.isArray($)?"array":typeof $;if(A!==J.type)H.push({path:G,message:J.message||`Expected type ${J.type}, got ${A}`,expected:J.type,actual:A,rule:"type"})}if(J.min!==void 0){let A=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(A<J.min)H.push({path:G,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:A,rule:"min"})}if(J.max!==void 0){let A=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(A>J.max)H.push({path:G,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:A,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))H.push({path:G,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))H.push({path:G,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let A=J.validator($);if(A)H.push({path:G,message:J.message||A,rule:"custom"})}return H}getValueByPath($,J){if(!J)return $;let G=J.split("."),H=$;for(let A of G)if(H&&typeof H==="object"&&A in H)H=H[A];else return;return H}generateRulesFromInterface($){let J=[],G=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let H of G){let[,A,z,U]=H;J.push({path:A,required:!z,type:this.mapTypeScriptType(U)})}return J}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:cE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function dE($){if(!$)return"";let J=Array.isArray($)?$.filter(Boolean):[$];if(J.length===0)return"";if(J.length===1)return` or alias "${J[0]}"`;return` or aliases ${J.map((G)=>`"${G}"`).join(", ")}`}class bY{fileLoader=new vY;envProcessor=new cA;validator=new gY;async loadConfig($){let J=Date.now(),{cache:G,performance:H,schema:A,validate:z,...U}=$;try{if(G?.enabled){let Y=this.checkCache(U.name||"",U);if(Y)return Y}let h;try{h=await this.loadConfigurationStrategies(U,!0,G)}catch(Y){if(U.configFile)throw Y;let Z=U.__strictErrorHandling;if(Y instanceof Error&&Y.name==="ConfigNotFoundError"){if(Z)throw Y;h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Y instanceof Error&&Y.name==="ConfigLoadError"){let E=Y.message.includes("EACCES")||Y.message.includes("EPERM")||Y.message.includes("permission denied"),X=!E&&(Y.message.includes("syntax")||Y.message.includes("Expected")||Y.message.includes("Unexpected")||Y.message.includes("BuildMessage")||Y.message.includes("errors building")),F=Y.message.includes("Configuration must export a valid object")||Y.message.includes("Configuration file is empty and exports nothing");if(Z&&(F||E))throw Y;if(X&&(!Z||!F))h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Z)h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Y.message}`]};else throw Y}else h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Y instanceof Error?Y.message:String(Y)}`]}}if(A||z)await this.validateConfiguration(h.config,A,z,U.name);if(G?.enabled&&h)this.cacheResult(U.name||"",h,G,U);if(H?.enabled){let Y={operation:"loadConfig",duration:Date.now()-J,configName:U.name,timestamp:new Date};if(H.onMetrics)H.onMetrics(Y);if(H.slowThreshold&&Y.duration>H.slowThreshold)I$.warn(`Slow configuration loading detected: ${Y.duration}ms for ${U.name}`);h.metrics=Y}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let Y=Date.now()-J;throw I$.error(`Configuration loading failed after ${Y}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies($,J=!1,G){let{name:H="",alias:A,configFile:z,cwd:U,configDir:h,defaultConfig:Y,checkEnv:Z=!0,arrayStrategy:E="replace",verbose:X=!1}=$,F=U||qH.cwd(),R=[];if(z){let w=f$(F,z);R.push(w);let K=Z?nJ(H,Y,X):Y,V=await this.fileLoader.tryLoadFromPaths([w],K,{arrayStrategy:E,verbose:X,cacheTtl:G?.ttl,useCache:!G?.ttl||G.ttl>100});if(!V)throw _1.configNotFound(H||z,R,A);if(X)I$.success(`Configuration loaded from explicit path: ${w}`);return this.finalizeResult(V,R,Z,H,X)}let C=await this.loadLocalConfiguration(H,A,F,h,Y,E,X,Z,G);if(C)return R.push(...this.getLocalSearchPaths(H,A,F,h)),this.finalizeResult(C,R,Z,H,X);let W=await this.loadHomeConfiguration(H,A,Y,E,X,Z);if(W)return R.push(...this.getHomeSearchPaths(H,A)),this.finalizeResult(W,R,Z,H,X);let Q=await this.loadPackageJsonConfiguration(H,A,F,Y,E,X,Z);if(Q)return R.push(f$(F,"package.json")),this.finalizeResult(Q,R,Z,H,X);if(R.push(...this.getAllSearchPaths(H,A,F,h)),J)throw _1.configNotFound(H,R,A);return{...await this.applyEnvironmentVariables(H,Y,Z,X),warnings:[`No configuration file found for "${H}"${dE(A)}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,G,H,A,z,U,h,Y){let Z=h?nJ($,A,U):A,E=this.getLocalDirectories(G,H);for(let X of E){if(U)I$.info(`Searching for configuration in: ${X}`);let F=this.fileLoader.generateConfigPaths($,X,J),R=await this.fileLoader.tryLoadFromPaths(F,Z,{arrayStrategy:z,verbose:U,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(R){if(U)I$.success(`Configuration loaded from: ${R.source.path}`);return R}}return null}async loadHomeConfiguration($,J,G,H,A,z){if(!$)return null;let U=z?nJ($,G,A):G,h=[f$(r1(),".config",$),f$(r1(),".config"),r1()];for(let Y of h){if(A)I$.info(`Checking home directory: ${Y}`);let Z=this.fileLoader.generateConfigPaths($,Y,J),E=await this.fileLoader.tryLoadFromPaths(Z,U,{arrayStrategy:H,verbose:A});if(E){if(A)I$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,J,G,H,A,z,U){let h=U?nJ($,H,z):H;try{let Y=f$(G,"package.json");if(!xZ(Y))return null;let Z={};try{Z=JSON.parse(fZ(Y,"utf8"))}catch(F){if(z)I$.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let E=Z[$],X=$;if(!E&&J){let F=Array.isArray(J)?J:[J];for(let R of F){if(!R)continue;if(Z[R]){E=Z[R],X=R;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(z)I$.success(`Configuration loaded from package.json: ${X}`);return{config:fY(h,E,A),source:{type:"package.json",path:Y,priority:30,timestamp:new Date}}}}catch(Y){if(z)I$.warn("Failed to load package.json:",[Y instanceof Error?Y:Error(String(Y))])}return null}async applyEnvironmentVariables($,J,G,H){if(!G||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:nJ($,J,H),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,G,H,A){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,G,H){let A=[];if(G){let z=G($);if(z)A.push(...z)}if(J){let z=await this.validator.validateConfiguration($,J);if(!z.isValid)A.push(...z.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(A.length>0)throw _1.configValidation(H||"unknown",A,H)}checkCache($,J){let G=this.generateCacheKey($,J);return QH.get(G)||null}cacheResult($,J,G,H){let A=this.generateCacheKey($,H);QH.set(A,J,void 0,G.ttl)}generateCacheKey($,J){let G=[$];if(J.alias){let H=Array.isArray(J.alias)?J.alias.join(","):J.alias;G.push(`alias:${H}`)}if(J.cwd)G.push(`cwd:${J.cwd}`);if(J.configFile)G.push(`configFile:${J.configFile}`);if(J.configDir)G.push(`configDir:${J.configDir}`);if("checkEnv"in J)G.push(`checkEnv:${J.checkEnv}`);return G.join("|")}getLocalDirectories($,J){return yZ({cwd:$,configDir:J})}getAllSearchPaths($,J,G,H){let A=[];return A.push(...this.getLocalSearchPaths($,J,G,H)),A.push(...this.getHomeSearchPaths($,J)),A.push(f$(G,"package.json")),A}getLocalSearchPaths($,J,G,H){let A=this.getLocalDirectories(G,H),z=[];for(let U of A)z.push(...this.fileLoader.generateConfigPaths($,U,J));return z}getHomeSearchPaths($,J){if(!$)return[];let G=[f$(r1(),".config",$),f$(r1(),".config"),r1()],H=[];for(let A of G)H.push(...this.fileLoader.generateConfigPaths($,A,J));return H}async loadConfigWithResult($){return this.loadConfig($)}}async function mY($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},G="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let H;if(G)H=await QA.loadConfig($);else H=await QA.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return H?.config??J}catch(H){if($.configFile)throw H;let A=H instanceof Error?H.name:"UnknownError",z=H instanceof Error?H.message:String(H);if(!(A==="ConfigNotFoundError"||A==="ConfigLoadError"||A==="ConfigValidationError"||z.includes("config"))&&$.verbose)I$.warn("Unexpected error loading config, using defaults:",[H instanceof Error?H:Error(String(H))]);let h=G?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await QA.applyEnvironmentVariables(h.name||"",J,!0,h.verbose||!1))?.config??J;return J}}function nJ($,J,G=!1){let H=new cA,A=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function z(U,h=[]){let Y={...U};for(let[Z,E]of Object.entries(U)){let X=[...h,Z],F=[`${A}_${X.join("_").toUpperCase()}`,`${A}_${X.map((W)=>W.toUpperCase()).join("")}`,`${A}_${X.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],R,C;for(let W of F)if(R=qH.env[W],R!==void 0){C=W;break}if(R!==void 0&&C)if(typeof E==="boolean")Y[Z]=["true","1","yes"].includes(R.toLowerCase());else if(typeof E==="number"){let W=Number(R);if(!Number.isNaN(W))Y[Z]=W}else if(Array.isArray(E))try{Y[Z]=JSON.parse(R)}catch{Y[Z]=R.split(",").map((W)=>W.trim())}else Y[Z]=R;else if(E&&typeof E==="object"&&!Array.isArray(E))Y[Z]=z(E,X)}return Y}return z(J)}var QH,kA,AY,O7,M7=($)=>$,B7=($,J)=>{for(var G in J)O7($,G,{get:J[G],enumerable:!0,configurable:!0,set:K7.bind(J,G)})},C7=($,J)=>()=>($&&(J=$($=0)),J),hY,RY,AJ,aJ,DY,a7,e7,uU,LH,KA,e0,N0,$E,pU,JE,iU,GE,HE,FA,AE,nU,rU,LA,zE,UE,YE,hE,wH,QY,ZE,$$,EE,XE,lU,RH,BA,p0,D0,jE,sU,WE,oU,FE,LE,wA,wE,tU,aU,RE,RA,DE,QE,VE,OE,ME,DH,VY,KE,BE="0.15.6",W$,_H,oJ,CA,IA,PH,SA,_A,tJ,PA,NA,E1,OY,MY,S$,n$,KY,BY,CE,SE,CY,NH,xL,o0,V0,fL,PE,vL,NE,gL,bL,eU,mL,TE,kE,cL,$Y,dL,uL,pL,iL,nL,DA,qE,rL,_$,SY,TH,_Y,PY,mA,NY,TY,kH,kY,qY,_1,cE,I$,QA,aL,eL;var cY=a(()=>{QH=new GY,kA=new HY,AY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];O7=Object.defineProperty;hY={};B7(hY,{withErrorRecovery:()=>XY,tryLoadConfig:()=>l7,loadConfigWithResult:()=>n7,loadConfig:()=>wY,isRetryableError:()=>m7,isConfigNotFoundError:()=>b7,isBunfigError:()=>jY,globalPerformanceMonitor:()=>aJ,globalCache:()=>AJ,getEnvOrDefault:()=>c7,generateConfigTypes:()=>s7,defaultGeneratedDir:()=>BY,defaultConfigDir:()=>KY,deepMergeWithArrayStrategy:()=>vA,deepMerge:()=>WY,createLibraryConfig:()=>o7,config:()=>r7,bunfigPlugin:()=>t7,applyEnvVarsToConfig:()=>lJ,TypeGenerationError:()=>_A,SchemaValidationError:()=>tJ,PluginError:()=>NA,PerformanceMonitor:()=>yA,FileSystemError:()=>SA,ErrorFactory:()=>E1,EnvVarError:()=>PH,EnvProcessor:()=>yH,ConfigValidator:()=>gA,ConfigValidationError:()=>CA,ConfigNotFoundError:()=>_H,ConfigMergeError:()=>IA,ConfigLoader:()=>bA,ConfigLoadError:()=>oJ,ConfigFileLoader:()=>xH,ConfigCache:()=>qA,CacheUtils:()=>DY,BunfigError:()=>W$,BrowserConfigError:()=>PA,ArrayMergeStrategies:()=>OY});CE=C7(async()=>{RY=import.meta.require,AJ=new qA,aJ=new yA,DY={createKey:I7,isEquivalent:S7,estimateMemoryUsage:_7},a7=MH(OA.cwd(),"config"),e7=MH(OA.cwd(),"src/generated"),uU=OH.env.CLARITY_LOG_DIR||dZ(T7(),"logs"),LH={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},KA=await k7(),e0={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"},N0=e0,$E=e0.red,pU=e0.green,JE=e0.yellow,iU=e0.blue,GE=e0.magenta,HE=e0.cyan,FA=e0.white,AE=e0.gray,nU=e0.bgRed,rU=e0.bgYellow,LA=e0.bold,zE=e0.dim,UE=e0.italic,YE=e0.underline,hE=e0.reset,wH={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QY={debug:"\uD83D\uDD0D",info:iU("\u2139"),success:pU("\u2713"),warning:rU(FA(LA(" WARN "))),error:nU(FA(LA(" ERROR ")))},ZE=new CH("stacks"),$$=new CH("bunfig",{showTags:!0}),EE=z$(sJ.cwd(),"config"),XE=z$(sJ.cwd(),"src/generated"),lU=VH.env.CLARITY_LOG_DIR||mZ(f7(),"logs"),RH={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},BA=await v7(),p0={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"},D0=p0,jE=p0.red,sU=p0.green,WE=p0.yellow,oU=p0.blue,FE=p0.magenta,LE=p0.cyan,wA=p0.white,wE=p0.gray,tU=p0.bgRed,aU=p0.bgYellow,RE=p0.bgGray,RA=p0.bold,DE=p0.dim,QE=p0.italic,VE=p0.underline,OE=p0.strikethrough,ME=p0.reset,DH={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},VY={debug:"\uD83D\uDD0D",info:oU("\u2139"),success:sU("\u2713"),warning:aU(wA(RA(" WARN "))),error:tU(wA(RA(" ERROR ")))},KE=new SH("stacks"),W$=class extends Error{timestamp;context;constructor(J,G={}){super(J);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=G,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 J=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([G,H])=>`${G}: ${H}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${J}`}},_H=class extends W${code="CONFIG_NOT_FOUND";constructor(J,G,H){let A=H?` or alias "${H}"`:"";super(`Configuration "${J}"${A} not found`,{configName:J,alias:H,searchPaths:G,searchPathCount:G.length})}},oJ=class extends W${code="CONFIG_LOAD_ERROR";constructor(J,G,H){super(`Failed to load configuration from "${J}": ${G.message}`,{configPath:J,configName:H,originalError:G.name,originalMessage:G.message});this.cause=G}},CA=class extends W${code="CONFIG_VALIDATION_ERROR";constructor(J,G,H){super(`Configuration validation failed for "${J}"`,{configPath:J,configName:H,validationErrors:G,errorCount:G.length})}},IA=class extends W${code="CONFIG_MERGE_ERROR";constructor(J,G,H,A){super(`Failed to merge configuration from "${J}" with "${G}": ${H.message}`,{sourcePath:J,targetPath:G,configName:A,originalError:H.name,originalMessage:H.message});this.cause=H}},PH=class extends W${code="ENV_VAR_ERROR";constructor(J,G,H,A){super(`Failed to parse environment variable "${J}" with value "${G}" as ${H}`,{envKey:J,envValue:G,expectedType:H,configName:A})}},SA=class extends W${code="FILE_SYSTEM_ERROR";constructor(J,G,H){super(`File system ${J} failed for "${G}": ${H.message}`,{operation:J,path:G,originalError:H.name,originalMessage:H.message});this.cause=H}},_A=class extends W${code="TYPE_GENERATION_ERROR";constructor(J,G,H){super(`Failed to generate types from "${J}" to "${G}": ${H.message}`,{configDir:J,outputPath:G,originalError:H.name,originalMessage:H.message});this.cause=H}},tJ=class extends W${code="SCHEMA_VALIDATION_ERROR";constructor(J,G,H){super(`Schema validation failed${H?` for config "${H}"`:""}`,{schemaPath:J,configName:H,validationErrors:G,errorCount:G.length})}},PA=class extends W${code="BROWSER_CONFIG_ERROR";constructor(J,G,H,A){super(`Failed to fetch configuration from "${J}": ${G} ${H}`,{endpoint:J,status:G,statusText:H,configName:A})}},NA=class extends W${code="PLUGIN_ERROR";constructor(J,G,H){super(`Plugin "${J}" failed during ${G}: ${H.message}`,{pluginName:J,operation:G,originalError:H.name,originalMessage:H.message});this.cause=H}},E1={configNotFound($,J,G){return new _H($,J,G)},configLoad($,J,G){return new oJ($,J,G)},configValidation($,J,G){return new CA($,J,G)},configMerge($,J,G,H){return new IA($,J,G,H)},envVar($,J,G,H){return new PH($,J,G,H)},fileSystem($,J,G){return new SA($,J,G)},typeGeneration($,J,G){return new _A($,J,G)},schemaValidation($,J,G){return new tJ($,J,G)},browserConfig($,J,G,H){return new PA($,J,G,H)},plugin($,J,G){return new NA($,J,G)}},OY={replace:"replace",concat:"concat",smart:"smart"},MY=/^https?:\/\//,S$=new SH("bunfig",{showTags:!0}),n$=new bA,KY=U$(P1.cwd(),"config"),BY=U$(P1.cwd(),"src/generated")});SE=KH.env.CLARITY_LOG_DIR||E7(IE(),"logs"),CY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:SE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},NH={...CY},xL=(async()=>{try{let{loadConfig:$}=await CE().then(()=>hY),J=await $({name:"clarity",alias:"logging",defaultConfig:CY,cwd:KH.cwd()});if(J)Object.assign(NH,J)}catch{}return NH})();o0={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"},V0=o0,fL=o0.red,PE=o0.green,vL=o0.yellow,NE=o0.blue,gL=o0.magenta,bL=o0.cyan,eU=o0.white,mL=o0.gray,TE=o0.bgRed,kE=o0.bgYellow,cL=o0.bgGray,$Y=o0.bold,dL=o0.dim,uL=o0.italic,pL=o0.underline,iL=o0.strikethrough,nL=o0.reset,DA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qE={debug:"\uD83D\uDD0D",info:NE("\u2139"),success:PE("\u2713"),warning:kE(eU($Y(" WARN "))),error:TE(eU($Y(" ERROR ")))};rL=new fH("stacks");_$=class _$ extends Error{timestamp;context;constructor($,J={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=J,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([J,G])=>`${J}: ${G}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};SY=class SY extends _${code="CONFIG_NOT_FOUND";constructor($,J,G){let H=G===void 0?[]:Array.isArray(G)?G.filter(Boolean):[G],A="";if(H.length===1)A=` or alias "${H[0]}"`;else if(H.length>1)A=` or aliases ${H.map((z)=>`"${z}"`).join(", ")}`;super(`Configuration "${$}"${A} not found`,{configName:$,alias:G,searchPaths:J,searchPathCount:J.length})}};TH=class TH extends _${code="CONFIG_LOAD_ERROR";constructor($,J,G){super(`Failed to load configuration from "${$}": ${J.message}`,{configPath:$,configName:G,originalError:J.name,originalMessage:J.message});this.cause=J}};_Y=class _Y extends _${code="CONFIG_VALIDATION_ERROR";constructor($,J,G){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:G,validationErrors:J,errorCount:J.length})}};PY=class PY extends _${code="CONFIG_MERGE_ERROR";constructor($,J,G,H){super(`Failed to merge configuration from "${$}" with "${J}": ${G.message}`,{sourcePath:$,targetPath:J,configName:H,originalError:G.name,originalMessage:G.message});this.cause=G}};mA=class mA extends _${code="ENV_VAR_ERROR";constructor($,J,G,H){super(`Failed to parse environment variable "${$}" with value "${J}" as ${G}`,{envKey:$,envValue:J,expectedType:G,configName:H})}};NY=class NY extends _${code="FILE_SYSTEM_ERROR";constructor($,J,G){super(`File system ${$} failed for "${J}": ${G.message}`,{operation:$,path:J,originalError:G.name,originalMessage:G.message});this.cause=G}};TY=class TY extends _${code="TYPE_GENERATION_ERROR";constructor($,J,G){super(`Failed to generate types from "${$}" to "${J}": ${G.message}`,{configDir:$,outputPath:J,originalError:G.name,originalMessage:G.message});this.cause=G}};kH=class kH extends _${code="SCHEMA_VALIDATION_ERROR";constructor($,J,G){super(`Schema validation failed${G?` for config "${G}"`:""}`,{schemaPath:$,configName:G,validationErrors:J,errorCount:J.length})}};kY=class kY extends _${code="BROWSER_CONFIG_ERROR";constructor($,J,G,H){super(`Failed to fetch configuration from "${$}": ${J} ${G}`,{endpoint:$,status:J,statusText:G,configName:H})}};qY=class qY extends _${code="PLUGIN_ERROR";constructor($,J,G){super(`Plugin "${$}" failed during ${J}: ${G.message}`,{pluginName:$,operation:J,originalError:G.name,originalMessage:G.message});this.cause=G}};_1={configNotFound($,J,G){return new SY($,J,G)},configLoad($,J,G){return new TH($,J,G)},configValidation($,J,G){return new _Y($,J,G)},configMerge($,J,G,H){return new PY($,J,G,H)},envVar($,J,G,H){return new mA($,J,G,H)},fileSystem($,J,G){return new NY($,J,G)},typeGeneration($,J,G){return new TY($,J,G)},schemaValidation($,J,G){return new kH($,J,G)},browserConfig($,J,G,H){return new kY($,J,G,H)},plugin($,J,G){return new qY($,J,G)}};cE=/^https?:\/\//;I$=new fH("bunfig",{showTags:!0});QA=new bY;aL=f$(qH.cwd(),"config"),eL=f$(qH.cwd(),"src/generated")});import dY from"process";function A0($=g.dialect){return $==="mysql"||$==="singlestore"||$==="vitess"}function uY($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function dA($,J,G=new Set){let H={...$};G.add(J);for(let A of Object.keys(J)){if(nY.has(A))continue;let z=J[A];if(uY(z)&&!G.has(z)){let U=H[A];H[A]=dA(uY(U)?U:{},z,G)}else H[A]=z}return G.delete(J),H}function gH($){if($)return $;let J=dY.env.DB_DIALECT||dY.env.DB_CONNECTION;if(J)return J;return g.dialect||"postgres"}function l($){if(g.dialect==="postgres")return`$${$}`;return"?"}function b0($,J=1){if($<=0)return"";if(g.dialect==="postgres"){let G=`$${J}`;for(let H=1;H<$;H++)G+=`, $${J+H}`;return G}return $===1?"?":`?${", ?".repeat($-1)}`}async function bH(){if(!vH.fileLoaded){vH.fileLoaded=!0;let $=await mY({name:"query-builder",alias:"qb",defaultConfig:iY}),J={};for(let[G,H]of Object.entries($??{}))if(!vH.explicit.has(G))J[G]=H;rY(J)}return g}function rY($){let J=dA(g,$),G=g;for(let H of Object.keys(J)){if(nY.has(H))continue;G[H]=J[H]}}function lY($){if($.dialect&&eJ&&$.dialect!==eJ){let J=`${eJ}->${$.dialect}`;if(!pY.has(J))pY.add(J),console.warn(`[query-builder] Configuring dialect '${$.dialect}' overrides the previously configured dialect '${eJ}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if($.dialect)eJ=$.dialect;for(let J of Object.keys($))vH.explicit.add(J);rY($)}function Hw($){return $}var iY,nY,uE,g,pE,vH,eJ=null,pY;var m0=a(()=>{cY();iY={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},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}},nY=new Set(["__proto__","constructor","prototype"]);uE=Symbol.for("bun-query-builder.config"),g=globalThis[uE]??=dA({},iY),pE=Symbol.for("bun-query-builder.config-state"),vH=globalThis[pE]??={explicit:new Set,fileLoaded:!1};pY=new Set});function nE(){let $=g.sqlite?.pragmas;return Array.isArray($)?$:iE}function $G($){for(let J of nE())try{$.run(J)}catch{}}var iE;var mH=a(()=>{m0();iE=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:sY}=globalThis.Bun;import{Database as lE}from"bun:sqlite";import{mkdirSync as sE}from"fs";import{dirname as oE}from"path";import GG from"process";function JG($){return $}function rE($){return $!==null&&typeof $==="object"?$:null}function oY($,J){if(J.length===0||!/\$\d/.test($))return{sql:$,params:J};let G=[],H="",A=0;for(let z=0;z<$.length;z++){let U=$[z];if(U==="'"||U==='"'||U==="`"){let h=tE($,z,U);H+=$.slice(z,h),z=h-1;continue}if(U==="-"&&$[z+1]==="-"){let h=$.indexOf(`
67
- `,z),Y=h===-1?$.length:h;H+=$.slice(z,Y),z=Y-1;continue}if(U==="/"&&$[z+1]==="*"){let h=$.indexOf("*/",z+2),Y=h===-1?$.length:h+2;H+=$.slice(z,Y),z=Y-1;continue}if(U==="$"){let h=/^\d+/.exec($.slice(z+1))?.[0];if(h){let Y=Number(h);if(A=Math.max(A,Y),Y>=1&&Y<=J.length){G.push(J[Y-1]),H+="?",z+=h.length;continue}}}H+=U}if(A>J.length)throw Error(`SQL references $${A} but only ${J.length} value${J.length===1?" was":"s were"} provided`);if(G.length===0)return{sql:$,params:J};return{sql:H,params:G}}function tE($,J,G){for(let H=J+1;H<$.length;H++){if($[H]!==G)continue;if($[H+1]===G){H++;continue}return H+1}return $.length}class $6{db;constructor($){if($!==":memory:"&&!$.startsWith(":")){let J=oE($);if(J&&J!==".")sE(J,{recursive:!0})}this.db=new lE($),$G(this.db)}query($,J=[]){let G=oY($,J);return this.db.prepare(G.sql).all(...G.params)}run($,J=[]){let G=oY($,J);return this.db.prepare(G.sql).run(...G.params)}close(){this.db.close()}get database(){return this.db}}function tY($){return{__raw:!0,value:$,toString:()=>$}}function aY($){let J=$.trimStart();for(;;)if(J.startsWith("--")){let G=J.indexOf(`
68
- `);J=G===-1?"":J.slice(G+1).trimStart()}else if(J.startsWith("/*")){let G=J.indexOf("*/");J=G===-1?"":J.slice(G+2).trimStart()}else return J}function aE($){let J=[],G="",H=!1,A=!1,z=!1,U=!1;for(let Y=0;Y<$.length;Y++){let Z=$[Y],E=$[Y+1];if(!H&&!A&&!U&&Z==="-"&&E==="-"){z=!0,G+=Z;continue}if(z&&(Z===`
69
- `||Z==="\r")){z=!1,G+=Z;continue}if(!H&&!A&&!z&&Z==="/"&&E==="*"){U=!0,G+=Z;continue}if(U&&Z==="*"&&E==="/"){U=!1,G+=Z+E,Y++;continue}if(z||U){G+=Z;continue}if(Z==="'"&&!A){if(H&&E==="'"){G+=Z+E,Y++;continue}H=!H,G+=Z;continue}if(Z==='"'&&!H){A=!A,G+=Z;continue}if(Z===";"&&!H&&!A){let X=aY(G.trim());if(X)J.push(X);G="";continue}G+=Z}let h=aY(G.trim());if(h)J.push(h);return J}function eY($){let J=new $6($);function G(z,...U){let h=z[0],Y=[];for(let Z=0;Z<U.length;Z++){let E=U[Z],X=rE(E);if(X&&typeof X.sql==="string"&&Array.isArray(X.values))h+=X.sql+(z[Z+1]||""),Y.push(...X.values);else if(X&&(X.__raw||X.raw)){let F=X.raw,R=X.__raw?X.value:typeof F==="string"?F:F();h+=R+(z[Z+1]||"")}else if(Array.isArray(E)){let F=E.map(()=>"?").join(", ");h+=F+(z[Z+1]||""),Y.push(...E)}else h+=`?${z[Z+1]||""}`,Y.push(E)}return{sql:h,values:Y,execute:()=>{try{let Z=h.trim().toUpperCase();if(Z.startsWith("SELECT")||Z.startsWith("PRAGMA")||/\bRETURNING\b/.test(Z)){let E=J.query(h,JG(Y));return Promise.resolve(E)}else{let E=J.run(h,JG(Y));return Promise.resolve(E)}}catch(Z){return Promise.reject(Z)}},raw:()=>h,toString:()=>h,cancel:()=>{}}}function H(z,...U){if(Array.isArray(z)&&"raw"in z)return G(z,...U);if(typeof z==="string")return tY(z);return G([""])}H.raw=(z)=>tY(z),H.unsafe=(z,U=[])=>{let h=()=>{try{let Y=z.trim().toUpperCase();if(Y.startsWith("SELECT")||Y.startsWith("PRAGMA")||/\bRETURNING\b/.test(Y)){let Z=J.query(z,JG(U));return Promise.resolve(Z)}else{let Z=J.run(z,JG(U));return Promise.resolve(Z)}}catch(Y){return Promise.reject(Y)}};return{sql:z,values:U,execute:h,then:(Y,Z)=>h().then(Y,Z),raw:()=>z,toString:()=>z,cancel:()=>{}}},H.close=()=>{return J.close(),Promise.resolve()},H.query=(z,U)=>{try{let h=J.query(z,JG(U||[]));return Promise.resolve(h)}catch(h){return Promise.reject(h)}},H.file=async(z,U)=>{try{let{readFileSync:h}=await import("fs"),Y=h(z,"utf-8"),Z=aE(Y);for(let E of Z){let X=E.trim();if(!X||X.startsWith("--"))continue;let F=X.toUpperCase();if(F.startsWith("SELECT")||F.startsWith("PRAGMA"))J.query(E);else J.run(E)}return Promise.resolve([])}catch(h){return Promise.reject(h)}};let A=0;return H.begin=async(z,U)=>{let h=typeof z==="function"?z:U;if(typeof h!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let Y=A>0,Z=`qb_sp_${A}`;if(Y)J.run(`SAVEPOINT ${Z}`);else J.run("BEGIN");A++;try{let E=await h(H);if(A--,Y)J.run(`RELEASE SAVEPOINT ${Z}`);else J.run("COMMIT");return E}catch(E){A--;try{if(Y)J.run(`ROLLBACK TO SAVEPOINT ${Z}`),J.run(`RELEASE SAVEPOINT ${Z}`);else J.run("ROLLBACK")}catch{}throw E}},H.savepoint=H.begin,H.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},H._wrapper=J,H}function eE($){let J=$.replace(/^(?:sqlite|sqlite3|file):/i,"");if(J===$)return $;return(J.startsWith("///")?J.slice(2):J.startsWith("//")?J.slice(2):J)||":memory:"}function cH($=g.database){let J=GG.env.DB_DATABASE||$?.database||"";return String(J).replace(/^['"]|['"]$/g,"")}function $X($,J){if(($==="postgres"||$==="mysql"||$==="singlestore"||$==="vitess")&&GG.env.DB_CONNECTION===$){let Z=GG.env,E=(Z.DB_DATABASE||J.database||"").replace(/^['"]|['"]$/g,""),X=Z.DB_USERNAME||J.username,F=Z.DB_PASSWORD??J.password??"",R=Z.DB_HOST||J.host||"localhost",C=Z.DB_PORT||J.port,W=$==="postgres"?"postgres":"mysql",Q=Z.DB_SSL==="true"||Z.DB_SSL==="1"||J.ssl?"?ssl=true":"";return`${W}://${X}:${F}@${R}${C?`:${C}`:""}/${E}${Q}`}if(J.url)return $==="sqlite"?eE(J.url):J.url;let{database:G,username:H,password:A,host:z="localhost",port:U,ssl:h}=J,Y=h||GG.env.DB_SSL==="true"||GG.env.DB_SSL==="1"?"?ssl=true":"";switch($){case"postgres":return`postgres://${H}:${A}@${z}${U?`:${U}`:""}/${G}${Y}`;case"mysql":case"singlestore":case"vitess":return`mysql://${H}:${A}@${z}${U?`:${U}`:""}/${G}${Y}`;case"sqlite":if(G===":memory:")return":memory:";return G||":memory:";default:throw Error(`Unsupported dialect: ${$}`)}}function J6($){if(!$)return{};let J={},G=(H)=>Math.max(0,Math.round(H/1000));if(typeof $.max==="number"&&Number.isFinite($.max))J.max=$.max;if(typeof $.idleTimeoutMs==="number"&&Number.isFinite($.idleTimeoutMs))J.idleTimeout=G($.idleTimeoutMs);if(typeof $.acquireTimeoutMs==="number"&&Number.isFinite($.acquireTimeoutMs))J.connectionTimeout=G($.acquireTimeoutMs);if(typeof $.maxLifetimeMs==="number"&&Number.isFinite($.maxLifetimeMs))J.maxLifetime=G($.maxLifetimeMs);return J}function JX(){let $=g.dialect,J=$X($,g.database);try{if($==="sqlite")return eY(J);let G=J6(g.database.pool);return Object.keys(G).length>0?new sY(J,G):new sY(J)}catch(G){if(console.error(`[query-builder] Failed to create database connection for dialect '${$}': ${G.message}`),$==="sqlite")return eY(":memory:");throw G}}function GX(){let $=g.database;return JSON.stringify({dialect:g.dialect,database:$.database,username:$.username,password:$.password,host:$.host,port:$.port,url:$.url,pool:J6($.pool)})}function X1($=!1){let J=GX();if($||N1!==null&&uA!==J||!N1){if(N1)G6();N1=JX(),uA=J}return N1}function HX(){let $=N1;return N1=null,uA=null,$}async function AX($){if(!$||typeof $.close!=="function")return;await $.close()}function G6(){AX(HX()).catch((J)=>{console.error(`[query-builder] Failed to close database connection: ${J.message}`)})}async function pA($){try{return await $(X1())}catch(J){if(J?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||J?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let G=X1(!0);return await $(G)}throw J}}function zX(){return new Proxy(function(){},{get($,J){let G=X1(),H=G[J];if(typeof H==="function")return H.bind(G);return H},apply($,J,G){return X1()(...G)}})}var N1=null,uA=null,$0;var j1=a(()=>{m0();mH();$0=zX()});async function iA($={}){let J=$.iterations||1000,G=$.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${J}`),console.log(`-- Operations: ${G.join(", ")}`),console.log();let H=z0();console.log("-- Setting up test table...");try{await $0.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await $0.unsafe(`
70
- CREATE TABLE bench_users (
71
- id INTEGER PRIMARY KEY AUTOINCREMENT,
72
- name TEXT NOT NULL,
73
- email TEXT NOT NULL,
74
- active INTEGER DEFAULT 1,
75
- created_at TEXT
76
- )
77
- `).execute();for(let U=0;U<100;U++)await $0.unsafe(`
78
- INSERT INTO bench_users (name, email, created_at)
79
- VALUES (?, ?, ?)
80
- `,[`User ${U}`,`user${U}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(U){throw console.error("-- Failed to setup test table:",U),U}let A=[];if(G.includes("select")){let U=[];for(let h=0;h<J;h++){let Y=performance.now();await H.selectFrom("bench_users").where({active:1}).limit(10).execute(),U.push(performance.now()-Y)}A.push({operation:"SELECT with WHERE + LIMIT",avgTime:U.reduce((h,Y)=>h+Y,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:J})}if(G.includes("select")){let U=[];for(let h=0;h<J;h++){let Y=performance.now();await H.selectFrom("bench_users").where({id:1}).first(),U.push(performance.now()-Y)}A.push({operation:"SELECT by ID (first)",avgTime:U.reduce((h,Y)=>h+Y,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:J})}if(G.includes("count")){let U=[];for(let h=0;h<J;h++){let Y=performance.now();await H.selectFrom("bench_users").count(),U.push(performance.now()-Y)}A.push({operation:"COUNT",avgTime:U.reduce((h,Y)=>h+Y,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:J})}if(G.includes("insert")){let U=[];for(let h=0;h<J;h++){let Y=performance.now();await H.insertInto("bench_users").values({name:`Bench User ${h}`,email:`bench${h}@example.com`,created_at:new Date().toISOString()}).execute(),U.push(performance.now()-Y)}A.push({operation:"INSERT",avgTime:U.reduce((h,Y)=>h+Y,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:J})}if(G.includes("update")){let U=[];for(let h=0;h<J;h++){let Y=performance.now();await H.updateTable("bench_users").set({active:0}).where({id:1}).execute(),U.push(performance.now()-Y)}A.push({operation:"UPDATE by ID",avgTime:U.reduce((h,Y)=>h+Y,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:J})}if(G.includes("delete")){let U=[],h=[];for(let Y=0;Y<J;Y++){let Z=await H.insertInto("bench_users").values({name:"To Delete",email:`delete${Y}@example.com`,created_at:new Date().toISOString()}).execute();h.push(Z)}for(let Y=0;Y<J;Y++){let Z=performance.now();await H.deleteFrom("bench_users").where({id:h[Y]}).execute(),U.push(performance.now()-Z)}A.push({operation:"DELETE by ID",avgTime:U.reduce((Y,Z)=>Y+Z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:J})}console.log("-- Benchmark Results"),console.log();let z=Math.max(...A.map((U)=>U.operation.length));console.log("Operation".padEnd(z+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(z+2+12+12+12+12));for(let U of A){let h=U.operation.padEnd(z+2),Y=U.avgTime.toFixed(3).padStart(12),Z=U.minTime.toFixed(3).padStart(12),E=U.maxTime.toFixed(3).padStart(12),X=(1000/U.avgTime).toFixed(0).padStart(12);console.log(`${h}${Y}${Z}${E}${X}`)}console.log();try{await $0.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(U){console.error("-- Warning: Failed to cleanup test table:",U)}}var nA=a(()=>{j1();n0()});function rA($){let J=String($).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(J.endsWith("y")&&!/[aeou]y$/.test(J))return`${J.slice(0,-1)}ies`;if(J.endsWith("s")||J.endsWith("x")||J.endsWith("ch")||J.endsWith("sh"))return`${J}es`;return`${J}s`}function W1($){return typeof $?.table==="string"&&$.table.length>0?$.table:rA(String($?.name??""))}function UX($){return $.endsWith("s")?$.slice(0,-1):$}function YX($){if($.endsWith("ies")&&$.length>3){let J=$.slice(0,-3),G=J[J.length-1];if(G&&!"aeiou".includes(G))return`${J}y`}if($.endsWith("es")&&$.length>2){let J=$.slice(0,-2);if(J.endsWith("s")||J.endsWith("x")||J.endsWith("ch")||J.endsWith("sh"))return J}if($.endsWith("s")&&!$.endsWith("ss")&&!$.endsWith("us")&&!$.endsWith("is"))return $.slice(0,-1);return $}function F1($){if($==="none")return(J)=>J;if($==="inflect")return YX;return UX}function hX($){return F1(g.relations?.singularizeStrategy)($)}function T1($,J,G,H={}){let A=H.singularize??hX,U=$.relations?.[J]?.belongsToMany?.[G];if(U==null)return null;let h=typeof U==="object",Y=h?U:null,Z=h?Y.model:U,E=$.modelToTable[Z]||Z,X,F;if(Y?.table)X=Y.table;else if(Y?.through){if(F=Y.through,X=$.modelToTable[Y.through],!X)throw Error(`[query-builder] belongsToMany relation '${G}' on '${J}' references unknown through model '${Y.through}'. Make sure '${Y.through}' is registered via defineModels({...}).`)}else{let w=A(J),K=A(E);X=[w,K].sort().join("_")}let R=Y?.foreignKey??`${A(J)}_id`,C=Y?.relatedKey??`${A(E)}_id`,W={};if(Y?.pivot?.columns)Object.assign(W,Y.pivot.columns);if(F&&H.models){let w=H.models[F],K=w?.definition??w?.getDefinition?.()??w,V=K?.attributes??{};for(let[q,P]of Object.entries(V)){if(q===R||q===C||q===(K?.primaryKey??"id"))continue;W[q]={default:P?.default,nullable:P?.nullable,validation:P?.validation}}}let Q=Boolean(Y?.pivot?.timestamps),D=Object.keys(W);return{pivotTable:X,fkParent:R,fkRelated:C,pivotColumns:D,pivotColumnDefs:W,pivotModelName:F,timestamps:Q,relatedModelName:Z,relatedTable:E,hasConfig:h}}function*Ow($,J={}){let G=$.relations;if(!G)return;for(let[H,A]of Object.entries(G)){let z=A?.belongsToMany;if(!z)continue;for(let U of Object.keys(z)){let h=T1($,H,U,J);if(h)yield{parentTable:H,relationKey:U,resolved:h}}}}var lA=a(()=>{m0()});function k1($){if($.length===0)return"";let J=[];for(let G of $)if(G.conn==="OR"&&J.length>0)J[J.length-1].push(G);else J.push([G]);return J.map((G,H)=>{let A=G.map((U)=>U.sql).join(" OR "),z=G.length>1&&J.length>1?`(${A})`:A;return H===0?z:`${G[0].conn} ${z}`}).join(" ")}function F$($,J,G,H){if(J.length===0)return G?"1 = 1":"1 = 0";return`${$} ${G?"NOT IN":"IN"} (${H})`}function ZX($,J){if(J!=="postgres")return $;let G="",H=0,A=0;while(A<$.length){let z=$[A];if(z==="'"){let U=H6($,A,"'");G+=$.slice(A,U),A=U;continue}if(z==='"'){let U=H6($,A,'"');G+=$.slice(A,U),A=U;continue}if(z==="$"){let U=$.slice(A).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(U){let h=$.indexOf(U,A+U.length),Y=h===-1?$.length:h+U.length;G+=$.slice(A,Y),A=Y;continue}}if(z==="?"){H++,G+=`$${H}`,A++;continue}G+=z,A++}return G}function H6($,J,G){let H=J+1;while(H<$.length){if($[H]===G){if($[H+1]===G){H+=2;continue}return H+1}H++}return $.length}var A6="1 = 0";function l$($){return typeof $==="object"&&$!==null&&"raw"in $&&typeof $.raw==="string"}function dH($){return typeof $==="object"&&$!==null&&"sql"in $&&typeof $.sql==="string"&&(!("parameters"in $)||Array.isArray($.parameters))}function uH($,J){let G=$.parameters??[];if(g.dialect!=="postgres"||G.length===0)return{text:$.sql,parameters:G};let H=0,A=$.sql.replace(/\?/g,(z)=>{if(H>=G.length)return z;return l(J+H++)});if(H!==G.length)throw TypeError(`[query-builder] SQL expression declares ${G.length} parameters but contains only ${H} placeholders`);return{text:A,parameters:G}}function Pw($,...J){if(typeof $==="string")return{raw:$};let G=$[0];for(let H=0;H<J.length;H++)G+=r$(J[H])+$[H+1];return{raw:G}}function E$($){return A0(g.dialect)?`\`${$.replace(/`/g,"``")}\``:`"${$.replace(/"/g,'""')}"`}function pH($,J=1){let G=Object.keys($[0]??{}),H=[],A=J,z=$.map((U)=>{return`(${G.map((Y)=>{return H.push(U[Y]),l(A++)}).join(", ")})`});return{colsSql:G.map(E$).join(", "),valuesSql:z.join(", "),params:H,nextIndex:A}}function HG($){return Boolean($&&($.onSlowQuery||$.slowQueryThresholdMs!=null&&$.slowQueryThresholdMs>=0))}function z6($){if(typeof $==="string")return $;if(l$($))return $.raw;if($&&typeof $==="object"){let J=$;if(typeof J.raw==="function")return String(J.raw());if(typeof J.sql==="string")return J.sql;let G=String($);if(G!=="[object Object]")return G}throw TypeError(`[query-builder] select(): unsupported column ${String($)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function EX($){let J=/\(|\)|\bORDER\s+BY\b/gi,G=0,H;while(H=J.exec($))if(H[0]==="(")G++;else if(H[0]===")")G=Math.max(0,G-1);else if(G===0)return!0;return!1}function n($,J){if(!F0.IDENTIFIER.test($)){let G=J?` in ${J}`:"";throw Error(`[query-builder] Invalid identifier${G}: '${$}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function d0($,J){if(typeof $!=="string")throw TypeError(`[query-builder] ${J}: operator must be a string, got ${typeof $}`);let G=$.toLowerCase();if(!U6.has(G))throw TypeError(`[query-builder] ${J}: refusing to use '${$}' as a SQL operator \u2014 not in the allowed set (${[...U6].join(", ")})`);return $}function M$($,J){if(typeof $!=="string"||$.length===0)throw TypeError(`[query-builder] ${J}: identifier must be a non-empty string, got ${typeof $}`);if($.length>129)throw TypeError(`[query-builder] ${J}: identifier '${$}' too long`);let G=$.split(".");if(G.length>2)throw TypeError(`[query-builder] ${J}: identifier '${$}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let H of G)if(!/^[A-Z_][A-Z0-9_]*$/i.test(H))throw TypeError(`[query-builder] ${J}: identifier segment '${H}' contains characters outside [A-Za-z0-9_]`)}function q1($,J){if(typeof $==="string")return XX(J),$;if($===null||$===void 0)throw TypeError(`[query-builder] ${J}: fragment must be a SqlFragment, got ${$}`);if(l$($))return $.raw;if(typeof $==="object"){let G=$;if(typeof G.raw==="string")return G.raw;if(typeof G.raw==="function"){let A=G.raw();if(typeof A==="string")return A}if(typeof G.sql==="string")return G.sql;let H=String($);if(H!=="[object Object]"&&H!=="[object Promise]")return H}throw TypeError(`[query-builder] ${J}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function XX($){if(Y6.has($))return;Y6.add($),console.warn(`[query-builder] ${$}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function jX($,J=g.dialect){return A0(J)?$.replace(/\\/g,"\\\\").replace(/'/g,"''"):$.replace(/'/g,"''")}function r$($){if($===null)return"NULL";if(typeof $==="number"&&Number.isFinite($))return String($);if(typeof $==="boolean")return $?"1":"0";if(typeof $==="string")return`'${jX($)}'`;if($ instanceof Date)return`'${$.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof $}`)}function WX($,J){let G=Array.isArray($)?$:$?[$]:[],H=[];if(G.length)H.push(`PARTITION BY ${G.join(", ")}`);if(J&&J.length)H.push(`ORDER BY ${J.map(([A,z])=>`${A} ${z==="desc"?"DESC":"ASC"}`).join(", ")}`);return H.length?`OVER (${H.join(" ")})`:"OVER ()"}class h6{cache=new Map;maxSize=100;get($){let J=this.cache.get($);if(!J)return null;if(Date.now()>J.expiresAt)return this.cache.delete($),null;return this.cache.delete($),this.cache.set($,J),J.data}set($,J,G){if(this.cache.has($))this.cache.delete($);if(this.cache.size>=this.maxSize){let H=Date.now(),A=!1;for(let[z,U]of this.cache)if(H>U.expiresAt){if(this.cache.delete(z),A=!0,this.cache.size<this.maxSize)break}if(!A){let z=this.cache.keys().next().value;if(z!==void 0)this.cache.delete(z)}}this.cache.set($,{data:J,expiresAt:Date.now()+G})}clear(){this.cache.clear()}setMaxSize($){this.maxSize=Math.max(0,Math.floor($));while(this.cache.size>this.maxSize){let J=this.cache.keys().next().value;if(J===void 0)break;this.cache.delete(J)}}}function FX($){let J=String($?.message||"").toLowerCase();return J.includes("deadlock")||J.includes("serialization failure")||J.includes("could not serialize access")||J.includes("deadlock found when trying to get lock")||J.includes("lock wait timeout exceeded")||J.includes("database is locked")||J.includes("busy")}function LX($,J){if(!J||J.length===0)return!1;let G=$&&($.code||$.sqlState||$.sqlstate);if(!G)return!1;return J.includes(G)}function wX($){return new Promise((J)=>setTimeout(J,$))}function AG($){let J=iH.get($);if(J!==void 0)return J;let G=DX($);if(iH.size>=RX)iH.clear();return iH.set($,G),G}function DX($){let J=[{key:"GROUP_BY",tokens:/^GROUP\s+BY\b/i},{key:"ORDER_BY",tokens:/^ORDER\s+BY\b/i},{key:"HAVING",tokens:/^HAVING\b/i},{key:"OFFSET",tokens:/^OFFSET\b/i},{key:"LIMIT",tokens:/^LIMIT\b/i},{key:"WHERE",tokens:/^WHERE\b/i}],G=[],H=0,A=!1,z="";for(let E=0;E<$.length;E++){let X=$[E];if(A){if(X===z){if($[E+1]===z){E++;continue}A=!1}continue}if(X==="'"||X==='"'||X==="`"){A=!0,z=X;continue}if(X==="("){H++;continue}if(X===")"){H--;continue}if(H!==0)continue;if(E===0||!/\s/.test($[E-1]))continue;let F=$.charCodeAt(E)&-33;if(F!==71&&F!==79&&F!==72&&F!==76&&F!==87)continue;let R=$.slice(E);for(let{key:C,tokens:W}of J){let Q=R.match(W);if(!Q)continue;G.push({key:C,start:E}),E+=Q[0].length-1;break}}if(G.length<=1)return $;let U=$.slice(0,G[0].start).trimEnd(),h={};for(let E=0;E<G.length;E++){let X=G[E].start,F=E+1<G.length?G[E+1].start:$.length,R=$.slice(X,F).trim();if(!h[G[E].key])h[G[E].key]=[];h[G[E].key].push(R)}let Z=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((E)=>h[E]).map((E)=>h[E].join(" ")).join(" ");return Z?`${U} ${Z}`:U}function QX($,J){let G=Math.max(1,J?.baseMs??50),H=Math.max(1,J?.factor??2),A=Math.max(G,J?.maxMs??2000),z=Math.min(A,G*H**Math.max(0,$-1));if(J?.jitter)z=Math.min(A,z*(0.9+Math.random()*0.2));return Math.floor(z)}function z0($){let J=$?.sql??X1(),G=$?.meta,H=$?.schema;function A(W){if(typeof W==="number")return W;let Q=String(W),D=7;for(let w=0;w<Q.length;w++)D=D*31+Q.charCodeAt(w)|0;return Math.abs(D)}function z(){if(!$?.hooks)return g.hooks;return{...g.hooks,...$.hooks}}let U=new Map;function h(W){if(Array.isArray(W)){let[V,q,P]=W;n(V,"where(column)");let T=String(V);switch(q){case"in":if(Array.isArray(P)){let I=b0(P.length);return J.unsafe(`${T} IN (${I})`,P)}return J.unsafe(`${T} IN (${l(1)})`,[P]);case"not in":if(Array.isArray(P)){let I=b0(P.length);return J.unsafe(`${T} NOT IN (${I})`,P)}return J.unsafe(`${T} NOT IN (${l(1)})`,[P]);case"like":return J.unsafe(`${T} LIKE ${l(1)}`,[P]);case"is":case"is not":{if(P!==null&&P!==void 0)throw TypeError(`[query-builder] where(..., '${q}', ?): operator '${q}' only accepts NULL/undefined as value, got ${typeof P} (${String(P)})`);return J.unsafe(`${T} IS ${q==="is not"?"NOT ":""}NULL`)}case"!=":return J.unsafe(`${T} <> ${l(1)}`,[P]);case"<":case">":case"<=":case">=":case"=":return J.unsafe(`${T} ${q} ${l(1)}`,[P]);default:throw TypeError(`[query-builder] where(..., '${String(q)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in W)return W.raw;let Q=Object.keys(W);if(Q.length===0)return J.unsafe("");let D=[],w=[],K=1;for(let V of Q){n(V,"where(object key)");let q=W[V];if(Array.isArray(q)){let P=b0(q.length,K);D.push(`${V} IN (${P})`),w.push(...q),K+=q.length}else D.push(`${V} = ${l(K++)}`),w.push(q)}return J.unsafe(D.join(" AND "),w)}function Y(W,Q,D){if(!D)return Q;let w=h(D);return J`${Q} WHERE ${w}`}function Z(W){let Q=g.debug?.captureText;if(g.debug)g.debug.captureText=!0;let D=String(W);if(g.debug)g.debug.captureText=Q;return D}function E(W){if(!W||typeof W!=="object")return;if(Array.isArray(W.values))return W.values;if(Array.isArray(W.parameters))return W.parameters;if(Array.isArray(W.params))return W.params;return}function X(W,Q,D){let w=z(),K=w?.slowQueryThresholdMs,V=K!=null&&K>=0,q=Boolean(w?.onSlowQuery||V),P=w&&(w.onQueryStart||w.onQueryEnd||w.onQueryError||w.startSpan||q),T=D?.timeoutMs&&D.timeoutMs>0||D?.signal;if(!P&&!T)return W.execute();let I=Z(W),B=E(W),N=Date.now(),S;try{if(w?.onQueryStart?.({sql:I,params:B,kind:Q}),w?.startSpan)S=w.startSpan({sql:I,params:B,kind:Q})}catch{}let x=!1,u=(d,i)=>{if(x)return;x=!0;let f=Date.now()-N;try{if(d)w?.onQueryError?.({sql:I,params:B,error:d,durationMs:f,kind:Q});else if(w?.onQueryEnd?.({sql:I,params:B,durationMs:f,rowCount:i,kind:Q}),V&&f>=K)if(w?.onSlowQuery)w.onSlowQuery({sql:I,params:B,durationMs:f,kind:Q});else console.warn(`[query-builder] slow query (${f}ms >= ${K}ms): ${I}`)}catch{}try{S?.end(d)}catch{}},r=W.execute(),o=[r],y;if(D?.timeoutMs&&D.timeoutMs>0){let d=new Promise((i,f)=>{y=setTimeout(()=>{try{W.cancel?.()}catch{}let J0=Error(`Query timed out after ${D.timeoutMs}ms`);J0.code="EBQBTIMEOUT",f(J0)},D.timeoutMs)});o.push(d)}if(D?.signal){if(D.signal.aborted){try{W.cancel?.()}catch{}let i=Error("Query aborted");return i.code="EBQBABORT",u(i),Promise.reject(i)}let d=()=>{try{W.cancel?.()}catch{}};D.signal.addEventListener("abort",d,{once:!0}),r.finally(()=>{D.signal?.removeEventListener("abort",d)})}return Promise.race(o).then((d)=>{clearTimeout(y);let i=Array.isArray(d)?d.length:typeof d==="number"?d:void 0;return u(void 0,i),d}).catch((d)=>{throw clearTimeout(y),u(d),d})}function F(W){if(typeof W==="number")return Number.isFinite(W)?W:0;if(typeof W==="bigint")return Number(W);if(!W||typeof W!=="object")return 0;let Q=W;for(let D of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(Q[D]!==void 0&&Q[D]!==null)return F(Q[D]);if(Array.isArray(W))return W.reduce((D,w)=>D+F(w),0);return 0}function R(W,Q){let D=Q??Z(W);return{sql:D,toString:()=>D,execute:()=>W.execute(),values:()=>W.values(),raw:()=>W.raw()}}function C(W,Q){let D=J,w=Q&&Q.length>0?`SELECT ${Q.join(", ")} FROM ${String(W)}`:`SELECT * FROM ${String(W)}`,K=[],V=[],q=!1,P=null,T=()=>{if(P===null){let j=AG(x());P=V.length>0?J.unsafe(j,V):J.unsafe(j)}return P},I=(j,L)=>{K.push({conn:j,sql:L}),P=null},B=(j,L)=>{I(j==="OR"?"OR":"AND",L)},N=/\(|\)|\b(?:GROUP\s+BY|HAVING|ORDER\s+BY|LIMIT|OFFSET|WINDOW|UNION|INTERSECT|EXCEPT|FOR\s+UPDATE|FOR\s+SHARE|LOCK\s+IN\s+SHARE\s+MODE)\b/gi,S=(j)=>{N.lastIndex=0;let L=0,O;while(O=N.exec(j))if(O[0]==="(")L++;else if(O[0]===")")L=Math.max(0,L-1);else if(L===0)return O.index;return-1},x=(j)=>{let L=k1(j?[...K,j]:K);if(!L)return w;if(q){let M=F0.WHERE.test(w)?"AND":"WHERE";return`${w} ${M} ${L}`}let O=S(w);return O>=0?`${w.slice(0,O)}WHERE ${L} ${w.slice(O)}`:`${w} WHERE ${L}`},u=(j,L)=>{let O=C(W);L(O);let M=O.__whereState?.();if(!M||!M.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let _=V.length,k=_>0&&g.dialect==="postgres"?M.body.replace(/\$(\d+)/g,(b,m)=>`$${Number(m)+_}`):M.body;V.push(...M.params),I(j,`(${k})`)},r=(j,L,O,M,_,k)=>{if(typeof M==="string"&&_!==void 0){n(String(M),`${O}(column)`),d0(_,`${O}(operator)`);let b=V.length+1;return V.push(k),I(L,`${String(M)} ${String(_)} ${l(b)}`),j}if(Array.isArray(M)){let[b,m,p]=M,v=String(b);n(v,`${O}(column)`);let c=d0(m,`${O}(operator)`);if(c==="in"||c==="not in"){let s=Array.isArray(p)?p:[p],Y0=b0(s.length,V.length+1),v0=F$(v,s,c==="not in",Y0);V.push(...s),I(L,v0)}else{let s=V.length+1;V.push(p),I(L,`${v} ${c} ${l(s)}`)}return j}if(typeof M==="function")return u(L,M),j;if(M&&typeof M==="object"&&!("raw"in M)){let b=[];for(let m of Object.keys(M)){n(m,`${O}(column)`);let p=M[m];if(Array.isArray(p)){let v=b0(p.length,V.length+1);b.push(F$(m,p,!1,v)),V.push(...p)}else{let v=V.length+1;b.push(`${m} = ${l(v)}`),V.push(p)}}if(b.length>0)I(L,b.length>1?`(${b.join(" AND ")})`:b[0]);return j}if(M&&typeof M.raw<"u")return I(L,M.raw),j;return j},o=(j,L)=>{if(K.length>0)w=x(),K.length=0;q=!0;let O=L.__rawState?.();if(O){let M=V.length,_=g.dialect==="postgres"?O.sql.replace(/\$(\d+)/g,(k,b)=>`$${Number(b)+M}`):O.sql;w+=` ${j} ${_}`,V.push(...O.params)}else w+=` ${j} ${String(L.toSQL())}`;P=null},y=(j)=>{let L=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,O=0,M=-1,_;while(_=L.exec(w))if(_[0]==="(")O++;else if(_[0]===")")O=Math.max(0,O-1);else if(O===0){M=_.index;break}w=M>=0?`${w.slice(0,M)}${j} ${w.slice(M)}`:`${w} ${j}`,P=null},d=new Set,i,f,J0=!1,t=!1,_0=!1,L0=new Map,H$=new Set,Y1=60000,K0=(j)=>F1(g.relations.singularizeStrategy)(j),D$=(j)=>{if(!G)return null;return T1(G,String(W),j,{singularize:K0,models:G.models})},B1=(j)=>{if(!j||typeof j!=="object"||H$.size===0)return j;let L;for(let O of Object.keys(j))if(O.startsWith("pivot_")){if(!L)L={};L[O.slice(6)]=j[O],delete j[O]}if(L)j.pivot=L;return j},C1=(j)=>{if(H$.size===0||!j)return j;if(Array.isArray(j))for(let L=0;L<j.length;L++)B1(j[L]);else B1(j);return j},b$=(j)=>{if(!G)return;if(d.has(j.pivotTable))return;let L=String(W),O=G.primaryKeys[L]??"id";n(j.pivotTable,"wherePivot auto-join (pivot table)"),n(j.fkParent,"wherePivot auto-join (parent FK)"),n(L,"wherePivot auto-join (parent table)"),n(O,"wherePivot auto-join (parent PK)"),P=D`${T()} LEFT JOIN ${D(j.pivotTable)} ON ${D(`${j.pivotTable}.${j.fkParent}`)} = ${D(`${L}.${O}`)}`,w=`${w} LEFT JOIN ${j.pivotTable} ON ${j.pivotTable}.${j.fkParent} = ${L}.${O}`,d.add(j.pivotTable)},dJ=(j)=>{if(F0.SELECT_STAR.test(w))w=w.replace(F0.SELECT_STAR,`SELECT *, ${j}`);else if(F0.SELECT.test(w))w=w.replace(F0.SELECT_FROM,`SELECT $1, ${j} FROM`);let L=String(T());if(F0.SELECT_STAR.test(L)){let O=L.replace(F0.SELECT_STAR,`SELECT *, ${j}`);P=J.unsafe(O)}else if(F0.SELECT.test(L)){if(F0.SELECT_FROM.exec(L)){let M=L.replace(F0.SELECT_FROM,`SELECT $1, ${j} FROM`);P=J.unsafe(M)}}},q$=(j,L,O,M)=>{dJ(`${j} ${WX(O,M)} AS ${L}`)},nG=(j,L,O,M)=>{n(j,"relationship subquery (parent table)"),n(L,"relationship subquery (target table)"),n(O,"relationship subquery (primary key)");let _=`${j.endsWith("s")?j.slice(0,-1):j}_id`;n(_,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${L} WHERE ${L}.${_} = ${j}.${O}`;if(M){let m=M({where:(p,v,c)=>{return n(p,"relationship subquery condition"),`${L}.${p} ${d0(v,"whereHas callback")} ${r$(c)}`}});if(m)k+=` AND ${m}`}return k},rG=(j,L,O,M)=>{n(j,"relationship subquery (parent table)"),n(L,"relationship subquery (target table)"),n(O,"relationship subquery (primary key)");let _=`${L.endsWith("s")?L.slice(0,-1):L}_id`;n(_,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${L} WHERE ${L}.${O} = ${j}.${_}`;if(M){let m=M({where:(p,v,c)=>{return n(p,"relationship subquery condition"),`${L}.${p} ${d0(v,"whereHas callback")} ${r$(c)}`}});if(m)k+=` AND ${m}`}return k},lG=(j,L,O,M,_,k)=>{n(j,"relationship subquery (parent table)"),n(L,"relationship subquery (target table)"),n(O,"relationship subquery (primary key)"),n(M,"relationship subquery (target primary key)");let b=k&&G?T1(G,j,k,{singularize:K0,models:G.models}):null,m=K0(j),p=K0(L),v=b?.pivotTable??[m,p].sort().join("_"),c=b?.fkParent??`${m}_id`,s=b?.fkRelated??`${p}_id`;n(v,"relationship subquery (pivot table)"),n(c,"relationship subquery (foreign key A)"),n(s,"relationship subquery (foreign key B)");let Y0=`SELECT 1 FROM ${v} JOIN ${L} ON ${L}.${M} = ${v}.${s} WHERE ${v}.${c} = ${j}.${O}`;if(_){let e=_({where:(g0,A$,h$)=>{return n(g0,"relationship subquery condition"),`${L}.${g0} ${d0(A$,"whereHas callback")} ${r$(h$)}`}});if(e)Y0+=` AND ${e}`}return Y0},jZ=(j,L,O)=>{n(j,"withCount (parent table)"),n(L,"withCount (target table)"),n(O,"withCount (primary key)");let M=`${j.endsWith("s")?j.slice(0,-1):j}_id`;return n(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${M} = ${j}.${O})`},WZ=(j,L,O,M)=>{n(j,"withCount (parent table)"),n(L,"withCount (target table)"),n(O,"withCount (primary key)");let _=M&&G?T1(G,j,M,{singularize:K0,models:G.models}):null,k=K0(j),b=K0(L),m=_?.pivotTable??[k,b].sort().join("_"),p=_?.fkParent??`${k}_id`;return n(m,"withCount (pivot table)"),n(p,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${m} WHERE ${m}.${p} = ${j}.${O})`},sG=(j,L,O)=>{if(!G)return;n(O,`with${j[0]}${j.slice(1).toLowerCase()} (column)`);let M=String(W),_=G.relations?.[M];if(!_)return;let k=Object.entries(_).find(([e,g0])=>g0&&typeof g0==="object"&&(L in g0));if(!k)return;let[b,m]=k,p=m[L],v=typeof p==="string"?p:p?.model||p?.target||p,c=G.modelToTable[v]||v,s=G.primaryKeys[M]??"id";n(c,`with${j} (target table)`);let Y0=`${j}(${c}.${O})`,v0;if(b==="hasMany"||b==="hasOne"){let e=`${M.endsWith("s")?M.slice(0,-1):M}_id`;n(e,`with${j} (foreign key)`),v0=`(SELECT ${Y0} FROM ${c} WHERE ${c}.${e} = ${M}.${s})`}else if(b==="belongsToMany"){let e=G?T1(G,M,L,{singularize:K0,models:G.models}):null,g0=K0(M),A$=K0(c),h$=e?.pivotTable??[g0,A$].sort().join("_"),J$=e?.fkParent??`${g0}_id`,h0=e?.fkRelated??`${A$}_id`,uJ=G.primaryKeys[c]??"id";n(h$,`with${j} (pivot table)`),n(J$,`with${j} (foreign key)`),n(h0,`with${j} (related key)`),v0=`(SELECT ${Y0} FROM ${h$} JOIN ${c} ON ${c}.${uJ} = ${h$}.${h0} WHERE ${h$}.${J$} = ${M}.${s})`}else return;dJ(`${v0} AS ${L}_${j.toLowerCase()}_${O}`)},ez=()=>{if(L0.size===0)return;let j=[];for(let[L,O]of L0.entries()){let M=D$(L);if(!M)continue;for(let k of O)n(k,"withPivot");let _=O.map((k)=>`${M.pivotTable}.${k} AS pivot_${k}`);j.push(..._)}if(j.length>0){let L=j.join(", ");dJ(L)}};return new Proxy({distinct(){return w=w.replace(/^SELECT\s+/i,"SELECT DISTINCT "),P=null,this},distinctOn(...j){let L=j.map(String).join(", ");return w=w.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${L}) `),P=null,this},selectRaw(j){let L=q1(j,"selectRaw(fragment)"),O=w.indexOf(" FROM ");if(O!==-1)w=`${w.substring(0,O)}, ${L}${w.substring(O)}`;else w+=`, ${L}`;return P=null,this},rowNumber(j="row_number",L,O){let M=[];if(L){let m=Array.isArray(L)?L:[L];M.push(`PARTITION BY ${m.join(", ")}`)}if(O&&O.length)M.push(`ORDER BY ${O.map(([m,p])=>`${m} ${p==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${j}`,b=w.indexOf(" FROM ");if(b!==-1)w=`${w.substring(0,b)}, ${k}${w.substring(b)}`;else w+=`, ${k}`;return P=null,this},denseRank(j="dense_rank",L,O){let M=Array.isArray(L)?L:L?[L]:[],_=[];if(M.length)_.push(`PARTITION BY ${M.join(", ")}`);if(O&&O.length)_.push(`ORDER BY ${O.map(([p,v])=>`${p} ${v==="desc"?"DESC":"ASC"}`).join(", ")}`);let b=`DENSE_RANK() ${_.length?`OVER (${_.join(" ")})`:"OVER ()"} AS ${j}`,m=w.indexOf(" FROM ");if(m!==-1)w=`${w.substring(0,m)}, ${b}${w.substring(m)}`;else w+=`, ${b}`;return P=null,this},rank(j="rank",L,O){let M=Array.isArray(L)?L:L?[L]:[],_=[];if(M.length)_.push(`PARTITION BY ${M.join(", ")}`);if(O&&O.length)_.push(`ORDER BY ${O.map(([p,v])=>`${p} ${v==="desc"?"DESC":"ASC"}`).join(", ")}`);let b=`RANK() ${_.length?`OVER (${_.join(" ")})`:"OVER ()"} AS ${j}`,m=w.indexOf(" FROM ");if(m!==-1)w=`${w.substring(0,m)}, ${b}${w.substring(m)}`;else w+=`, ${b}`;return P=null,this},over(j,L,O={}){return q$(j,L,O.partitionBy,O.orderBy),this},lag(j,L={}){let O=[j,String(L.offset??1)];if(L.defaultValue!==void 0)O.push(String(L.defaultValue));return q$(`LAG(${O.join(", ")})`,L.alias??`${j}_lag`,L.partitionBy,L.orderBy),this},lead(j,L={}){let O=[j,String(L.offset??1)];if(L.defaultValue!==void 0)O.push(String(L.defaultValue));return q$(`LEAD(${O.join(", ")})`,L.alias??`${j}_lead`,L.partitionBy,L.orderBy),this},sumOver(j,L={}){return q$(`SUM(${j})`,L.alias??`${j}_sum`,L.partitionBy,L.orderBy),this},avgOver(j,L={}){return q$(`AVG(${j})`,L.alias??`${j}_avg`,L.partitionBy,L.orderBy),this},countOver(j="*",L={}){return q$(`COUNT(${j})`,L.alias??"count_over",L.partitionBy,L.orderBy),this},minOver(j,L={}){return q$(`MIN(${j})`,L.alias??`${j}_min`,L.partitionBy,L.orderBy),this},maxOver(j,L={}){return q$(`MAX(${j})`,L.alias??`${j}_max`,L.partitionBy,L.orderBy),this},firstValue(j,L={}){return q$(`FIRST_VALUE(${j})`,L.alias??`${j}_first`,L.partitionBy,L.orderBy),this},lastValue(j,L={}){return q$(`LAST_VALUE(${j})`,L.alias??`${j}_last`,L.partitionBy,L.orderBy),this},selectAll(){return this},select(j){if(!j)return this;let L=Array.isArray(j)?j:[j];if(L.length===0)return this;let O=L.map(z6),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(w),_=M?M[1]:"",k=w.indexOf(" FROM ");if(k!==-1)w=`SELECT ${_}${O.join(", ")}${w.substring(k)}`;else w=`SELECT ${_}${O.join(", ")} FROM ${W}`;return P=null,this},addSelect(...j){if(!j.length)return this;let L=j.map(z6),O=w.indexOf(" FROM ");if(O!==-1)w=`${w.substring(0,O)}, ${L.join(", ")}${w.substring(O)}`;else w+=`, ${L.join(", ")}`;return P=null,this},with(...j){if(!G||!j||j.length===0)return this;let L=[];for(let v of j){if(!v)continue;if(typeof v==="string")L.push({name:v});else if(typeof v==="object"&&!Array.isArray(v))for(let[c,s]of Object.entries(v))if(typeof s==="function")L.push({name:c,callback:s});else L.push({name:c})}if(L.length===0)return this;let O=g.relations.maxEagerLoad??50;if(L.length>O)throw Error(`[query-builder] Too many relationships to eager load (${L.length}). Maximum allowed: ${O}`);let M=String(W),_=new Set,k=new Set,b=new Map,m=(v)=>{let c=G.relations?.[v];if(!c)return[];return[...Object.keys(c.hasOne||{}),...Object.keys(c.hasMany||{}),...Object.keys(c.belongsTo||{}),...Object.keys(c.belongsToMany||{}),...Object.keys(c.hasOneThrough||{}),...Object.keys(c.hasManyThrough||{}),...Object.keys(c.morphOne||{}),...Object.keys(c.morphMany||{}),...Object.keys(c.morphToMany||{}),...Object.keys(c.morphedByMany||{})]},p=(v,c,s=0,Y0)=>{let v0=g.relations.maxDepth??10;if(s>=v0)throw Error(`[query-builder] Maximum relationship depth (${v0}) exceeded at '${c}'. Consider using separate queries or increasing maxDepth.`);let e=G.relations?.[v];if(!e)return v;let g0=(Z0)=>{if(g.softDeletes?.enabled&&g.softDeletes?.defaultFilter){let E0=g.softDeletes.column||"deleted_at";return` AND ${Z0}.${E0} IS NULL`}return""},A$=(Z0)=>{if(!Y0)return"";let E0=[],T0=(W0,Z$,y$)=>{n(String(W0),"with() constraint column");let u1=d0(Z$,"with() constraint operator");E0.push(`${Z0}.${String(W0)} ${u1} ${r$(y$)}`)},B0=(W0)=>()=>{throw Error(`[query-builder] with('${c}', ...): ${W0} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},y0={where:(W0,Z$,y$)=>{if(Array.isArray(W0))T0(W0[0],W0[1],W0[2]);else if(W0&&typeof W0==="object")for(let u1 of Object.keys(W0))T0(u1,"=",W0[u1]);else if(Z$!==void 0&&y$!==void 0)T0(W0,Z$,y$);else if(Z$!==void 0)T0(W0,"=",Z$);return y0},whereIn:(W0,Z$)=>{return n(String(W0),"with() constraint column"),E0.push(`${Z0}.${String(W0)} IN (${Z$.map(r$).join(", ")})`),y0},whereNull:(W0)=>{return n(String(W0),"with() constraint column"),E0.push(`${Z0}.${String(W0)} IS NULL`),y0},whereNotNull:(W0)=>{return n(String(W0),"with() constraint column"),E0.push(`${Z0}.${String(W0)} IS NOT NULL`),y0},orderBy:B0("orderBy()"),limit:B0("limit()"),offset:B0("offset()"),take:B0("take()")};return Y0(y0),E0.length?` AND ${E0.join(" AND ")}`:""},h$=()=>{let Z0=(B0)=>{let y0=B0?.[c];return y0?G.modelToTable[y0]:void 0},E0=(B0)=>{let y0=B0?.[c],W0=typeof y0==="string"?y0:y0?.model;return W0?G.modelToTable[W0]:void 0},T0=(B0)=>{let y0=B0?.[c];return y0?.target?G.modelToTable[y0.target]:void 0};return Z0(e?.hasOne)||Z0(e?.hasMany)||Z0(e?.belongsTo)||E0(e?.belongsToMany)||T0(e?.hasOneThrough)||T0(e?.hasManyThrough)||Z0(e?.morphOne)||Z0(e?.morphMany)||Z0(e?.morphToMany)||Z0(e?.morphedByMany)},J$=h$()??(G.modelToTable[c]||G.tableToModel[c]?G.modelToTable[c]??c:c),h0=String(J$);if(!J$||!h$()&&!G.modelToTable[c]&&!G.tableToModel[c]){let Z0=m(v);if(Z0.length>0&&!Z0.includes(c)){let E0=` Available relationships: ${Z0.join(", ")}`;throw Error(`[query-builder] Relationship '${c}' not found on table '${v}'.${E0}`)}}if(g.relations.detectCycles!==!1){let Z0=`${v}->${h0}`;if(_.has(Z0))throw Error(`[query-builder] Circular relationship detected: ${Z0}. This would cause an infinite loop.`);_.add(Z0)}if(!h0||h0===v)return v;let uJ=e?.hasOneThrough?.[c]||e?.hasManyThrough?.[c];if(uJ){let{through:Z0,target:E0}=uJ,T0=G.modelToTable[Z0]||Z0,B0=G.modelToTable[E0]||E0,y0=G.primaryKeys[v]??"id",W0=G.primaryKeys[T0]??"id",Z$=`${K0(v)}_id`,y$=`${K0(T0)}_id`;return y(`LEFT JOIN ${T0} ON ${T0}.${Z$} = ${v}.${y0} LEFT JOIN ${B0} ON ${B0}.${y$} = ${T0}.${W0}`),d.add(T0),d.add(B0),B0}if(Boolean(e?.belongsToMany?.[c])){let Z0=T1(G,v,c,{singularize:K0,models:G.models}),E0=Z0?.pivotTable??[K0(v),K0(h0)].sort().join("_"),T0=G.primaryKeys[v]??"id",B0=G.primaryKeys[h0]??"id",y0=Z0?.fkParent??`${K0(v)}_id`,W0=Z0?.fkRelated??`${K0(h0)}_id`;return y(`LEFT JOIN ${E0} ON ${E0}.${y0} = ${v}.${T0} LEFT JOIN ${h0} ON ${h0}.${B0} = ${E0}.${W0}${A$(h0)}`),d.add(E0),d.add(h0),h0}if(Boolean(e?.morphToMany?.[c])){let Z0=c,E0=`${K0(h0)}_${Z0}`,T0=G.primaryKeys[v]??"id",B0=G.primaryKeys[h0]??"id",y0=`${Z0}_type`,W0=`${Z0}_id`,Z$=`${K0(h0)}_id`,y$=r$(G.tableToModel[v]||v);return y(`LEFT JOIN ${E0} ON ${E0}.${W0} = ${v}.${T0} AND ${E0}.${y0} = ${y$} LEFT JOIN ${h0} ON ${h0}.${B0} = ${E0}.${Z$}`),d.add(E0),d.add(h0),h0}if(Boolean(e?.morphedByMany?.[c])){let Z0=e.morphedByMany?.[c]||c,E0=G.modelToTable[Z0]||Z0,T0=K0(v),B0=`${K0(E0)}_${T0}`,y0=G.primaryKeys[v]??"id",W0=G.primaryKeys[E0]??"id",Z$=`${T0}_type`,y$=`${T0}_id`,u1=`${K0(E0)}_id`,QZ=r$(G.tableToModel[E0]||E0);return y(`LEFT JOIN ${B0} ON ${B0}.${u1} = ${v}.${y0} LEFT JOIN ${E0} ON ${E0}.${W0} = ${B0}.${y$} AND ${B0}.${Z$} = ${QZ}`),d.add(B0),d.add(E0),E0}if(Boolean(e?.belongsTo?.[c])){let Z0=`${K0(h0)}_id`,E0=G.primaryKeys[h0]??"id";return y(`LEFT JOIN ${h0} ON ${v}.${Z0} = ${h0}.${E0}${A$(h0)}`),d.add(h0),h0}let FZ=Boolean(e?.morphOne?.[c]),LZ=Boolean(e?.morphMany?.[c]);if(FZ||LZ){let Z0=`${c}_type`,E0=`${c}_id`,T0=G.primaryKeys[v]??"id",B0=r$(G.tableToModel[v]||v);return y(`LEFT JOIN ${h0} ON ${h0}.${E0} = ${v}.${T0} AND ${h0}.${Z0} = ${B0}`),d.add(h0),h0}let wZ=`${K0(v)}_id`,RZ=G.primaryKeys[v]??"id",DZ=`${g0(h0)}${A$(h0)}`;return y(`LEFT JOIN ${h0} ON ${h0}.${wZ} = ${v}.${RZ}${DZ}`),d.add(h0),h0};for(let v of L){let c=v.name.trim();if(v.callback)b.set(c,v.callback);let s=c.split("."),Y0=M,v0=0;for(let e of s){if(!e||e.trim().length===0)continue;let g0=e.trim(),A$=b.get(g0);Y0=p(Y0,g0,v0,A$)||Y0,v0++}k.add(c)}if(L0.size>0){let v=[];for(let[c,s]of L0.entries()){let Y0=D$(c);if(!Y0)continue;let v0=s.map((e)=>`${Y0.pivotTable}.${e} AS pivot_${e}`);v.push(...v0)}if(v.length>0){let c=v.join(", ");dJ(c)}}return P=null,this},whereHas(j,L){if(!G)return this;let O=String(W),M=G.relations?.[O];if(!M)throw Error(`[query-builder] No relationships defined for table '${O}'`);let _=Object.entries(M).find(([s,Y0])=>Y0&&typeof Y0==="object"&&(j in Y0));if(!_)throw Error(`[query-builder] Relationship '${j}' not found on table '${O}'`);let[k,b]=_,m=b[j],p=typeof m==="string"?m:m?.model||m?.target||m,v=G.modelToTable[p]||p,c;if(k==="hasMany"||k==="hasOne"){let s=G.primaryKeys[O]??"id";c=nG(O,v,s,L)}else if(k==="belongsTo"){let s=G.primaryKeys[v]??"id";c=rG(O,v,s,L)}else if(k==="belongsToMany"){let s=G.primaryKeys[O]??"id",Y0=G.primaryKeys[v]??"id";c=lG(O,v,s,Y0,L,j)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereHas`);return B("WHERE",`EXISTS (${c})`),this},whereDoesntHave(j,L){if(!G)return this;let O=String(W),M=G.relations?.[O];if(!M)throw Error(`[query-builder] No relationships defined for table '${O}'`);let _=Object.entries(M).find(([s,Y0])=>Y0&&typeof Y0==="object"&&(j in Y0));if(!_)throw Error(`[query-builder] Relationship '${j}' not found on table '${O}'`);let[k,b]=_,m=b[j],p=typeof m==="string"?m:m?.model||m?.target||m,v=G.modelToTable[p]||p,c;if(k==="hasMany"||k==="hasOne"){let s=G.primaryKeys[O]??"id";c=nG(O,v,s,L)}else if(k==="belongsTo"){let s=G.primaryKeys[v]??"id";c=rG(O,v,s,L)}else if(k==="belongsToMany"){let s=G.primaryKeys[O]??"id",Y0=G.primaryKeys[v]??"id";c=lG(O,v,s,Y0,L,j)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereDoesntHave`);return B("WHERE",`NOT EXISTS (${c})`),this},has(j){if(!G)return this;let L=String(W),O=G.relations?.[L];if(!O)throw Error(`[query-builder] No relationships defined for table '${L}'`);let M=Object.entries(O).find(([c,s])=>s&&typeof s==="object"&&(j in s));if(!M)throw Error(`[query-builder] Relationship '${j}' not found on table '${L}'`);let[_,k]=M,b=k[j],m=typeof b==="string"?b:b?.model||b?.target||b,p=G.modelToTable[m]||m,v;if(_==="hasMany"||_==="hasOne"){let c=G.primaryKeys[L]??"id";v=nG(L,p,c)}else if(_==="belongsTo"){let c=G.primaryKeys[p]??"id";v=rG(L,p,c)}else if(_==="belongsToMany"){let c=G.primaryKeys[L]??"id",s=G.primaryKeys[p]??"id";v=lG(L,p,c,s,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${_}' for has`);return B("WHERE",`EXISTS (${v})`),this},doesntHave(j){if(!G)return this;let L=String(W),O=G.relations?.[L];if(!O)throw Error(`[query-builder] No relationships defined for table '${L}'`);let M=Object.entries(O).find(([c,s])=>s&&typeof s==="object"&&(j in s));if(!M)throw Error(`[query-builder] Relationship '${j}' not found on table '${L}'`);let[_,k]=M,b=k[j],m=typeof b==="string"?b:b?.model||b?.target||b,p=G.modelToTable[m]||m,v;if(_==="hasMany"||_==="hasOne"){let c=G.primaryKeys[L]??"id";v=nG(L,p,c)}else if(_==="belongsTo"){let c=G.primaryKeys[p]??"id";v=rG(L,p,c)}else if(_==="belongsToMany"){let c=G.primaryKeys[L]??"id",s=G.primaryKeys[p]??"id";v=lG(L,p,c,s,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${_}' for doesntHave`);return B("WHERE",`NOT EXISTS (${v})`),this},withCount(...j){if(!G||!j||j.length===0)return this;let L=String(W);for(let O of j){let M=G.relations?.[L];if(!M)continue;let _=Object.entries(M).find(([v0,e])=>e&&typeof e==="object"&&(O in e));if(!_)continue;let[k,b]=_,m=b[O],p=typeof m==="string"?m:m?.model||m?.target||m,v=G.modelToTable[p]||p,c=G.primaryKeys[L]??"id",s;if(k==="hasMany"||k==="hasOne")s=jZ(L,v,c);else if(k==="belongsToMany")s=WZ(L,v,c,O);else continue;let Y0=`${O}_count`;dJ(`${s} AS ${Y0}`)}return this},withSum(j,L){return sG("SUM",j,L),this},withAvg(j,L){return sG("AVG",j,L),this},withMax(j,L){return sG("MAX",j,L),this},withMin(j,L){return sG("MIN",j,L),this},applyPivotColumns(){return ez(),this},withPivot(j,...L){if(!G)return this;let O=String(W),M=D$(j);if(!M)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${O}'`);let _=L&&L.length>0?L:M.hasConfig?M.pivotColumns:[];if(_.length===0)return this;if(L0.set(j,_),M.hasConfig)H$.add(j);return ez(),this},wherePivot(j,L,O,M){if(!G)return this;let _=D$(j);if(!_)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(W)}'`);n(_.pivotTable,"wherePivot (pivot table)"),n(L,"wherePivot (column)"),b$(_);let k=M===void 0?"=":String(O),b=M===void 0?O:M,m=V.length+1,p=`${_.pivotTable}.${L} ${k} ${l(m)}`;if(V.push(b),I("AND",p),_.hasConfig)H$.add(j);return this},wherePivotIn(j,L,O){if(!G||!Array.isArray(O))return this;let M=D$(j);if(!M)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(W)}'`);n(M.pivotTable,"wherePivotIn (pivot table)"),n(L,"wherePivotIn (column)"),b$(M);let _=b0(O.length,V.length+1),k=F$(`${M.pivotTable}.${L}`,O,!1,_);if(V.push(...O),I("AND",k),M.hasConfig)H$.add(j);return this},wherePivotNotIn(j,L,O){if(!G||!Array.isArray(O)||O.length===0)return this;let M=D$(j);if(!M)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(W)}'`);n(M.pivotTable,"wherePivotNotIn (pivot table)"),n(L,"wherePivotNotIn (column)"),b$(M);let _=b0(O.length,V.length+1),k=`${M.pivotTable}.${L} NOT IN (${_})`;if(V.push(...O),I("AND",k),M.hasConfig)H$.add(j);return this},wherePivotNull(j,L){if(!G)return this;let O=D$(j);if(!O)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(W)}'`);if(n(O.pivotTable,"wherePivotNull (pivot table)"),n(L,"wherePivotNull (column)"),b$(O),I("AND",`${O.pivotTable}.${L} IS NULL`),O.hasConfig)H$.add(j);return this},wherePivotNotNull(j,L){if(!G)return this;let O=D$(j);if(!O)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(W)}'`);if(n(O.pivotTable,"wherePivotNotNull (pivot table)"),n(L,"wherePivotNotNull (column)"),b$(O),I("AND",`${O.pivotTable}.${L} IS NOT NULL`),O.hasConfig)H$.add(j);return this},where(j,L,O){if(typeof j==="string"&&L!==void 0){n(String(j),"where(column)"),d0(L,"where(operator)");let M=String(L).toLowerCase();if(M==="in"||M==="not in"){let k=Array.isArray(O)?O:[O],b=b0(k.length,V.length+1),m=F$(String(j),k,M==="not in",b);return V.push(...k),I("AND",m),this}let _=V.length+1;return V.push(O),I("AND",`${String(j)} ${String(L)} ${l(_)}`),this}if(Array.isArray(j)){let[M,_,k]=j,b=String(M);n(b,"where(column)");let m=d0(_,"where(operator)");if(m==="in"||m==="not in"){let p=Array.isArray(k)?k:[k],v=b0(p.length,V.length+1),c=F$(b,p,m==="not in",v);V.push(...p),I("AND",c)}else{let p=V.length+1;V.push(k),I("AND",`${b} ${m} ${l(p)}`)}return this}if(j&&typeof j==="object"&&!l$(j)){let M=j,_=Object.keys(M),k=[];for(let b of _){n(b,"where(column)");let m=M[b];if(Array.isArray(m)){let p=b0(m.length,V.length+1);k.push(F$(b,m,!1,p)),V.push(...m)}else{let p=V.length+1;k.push(`${b} = ${l(p)}`),V.push(m)}}if(k.length>0)I("AND",k.length>1?`(${k.join(" AND ")})`:k[0]);return this}if(l$(j))return I("AND",j.raw),this;if(typeof j==="function")return u("AND",j),this;if(j===void 0||j===null)throw TypeError("where() was called with no condition.");if(typeof j==="string")throw TypeError(`where(${JSON.stringify(j)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof j}.`)},whereNull(j){return n(String(j),"whereNull(column)"),I("AND",`${String(j)} IS NULL`),this},whereNotNull(j){return n(String(j),"whereNotNull(column)"),I("AND",`${String(j)} IS NOT NULL`),this},orWhereNull(j){return n(String(j),"orWhereNull(column)"),I("OR",`${String(j)} IS NULL`),this},orWhereNotNull(j){return n(String(j),"orWhereNotNull(column)"),I("OR",`${String(j)} IS NOT NULL`),this},whereBetween(j,L,O){n(String(j),"whereBetween(column)");let M=V.length+1;return V.push(L,O),I("AND",`${String(j)} BETWEEN ${l(M)} AND ${l(M+1)}`),this},orWhereBetween(j,L,O){n(String(j),"orWhereBetween(column)");let M=V.length+1;return V.push(L,O),I("OR",`${String(j)} BETWEEN ${l(M)} AND ${l(M+1)}`),this},whereExists(j){return I("AND",`EXISTS (${j.toSQL()})`),this},orWhereExists(j){return I("OR",`EXISTS (${j.toSQL()})`),this},whereGroup(j){return u("AND",j),this},orWhereGroup(j){return u("OR",j),this},__whereState(){return{body:k1(K),params:[...V]}},whereJsonContains(j,L){n(String(j),"whereJsonContains(column)");let O=g.dialect,M=V.length+1;if(O==="postgres"){let k=typeof L==="number"||typeof L==="boolean"?`to_jsonb(${l(M)})`:l(M);if(g.sql?.jsonContainsMode==="function")I("AND",`jsonb_contains(${j}, ${k})`);else I("AND",`${j} @> ${k}`);V.push(L)}else if(A0(O))I("AND",`JSON_CONTAINS(${j}, ${l(M)})`),V.push(JSON.stringify(L));else if(Array.isArray(L)){let _=L.map((k,b)=>`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${l(M+b)})`);I("AND",`(${_.join(" AND ")})`);for(let k of L)V.push(k)}else if(L!==null&&typeof L==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else I("AND",`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${l(M)})`),V.push(L);return this},whereJsonPath(j,L,O){if(d0(L,"whereJsonPath(op)"),typeof j!=="string"||j.length===0||j.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof j==="string"?`'${j.slice(0,32)}...'`:typeof j}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(j))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${j}' \u2014 contains characters outside the allowed JSON-path set`);let M=g.dialect,_=V.length+1;if(M==="postgres")I("AND",`${j} ${L} ${l(_)}`);else if(A0(M))I("AND",`JSON_EXTRACT(${j}) ${L} ${l(_)}`);else I("AND",`json_extract(${j}) ${L} ${l(_)}`);return V.push(O),this},whereLike(j,L,O=!1){let M=l(V.length+1);return B("WHERE",`${O?String(j):`LOWER(${String(j)})`} LIKE ${O?M:`LOWER(${M})`}`),V.push(L),P=null,this},whereILike(j,L){let O=l(V.length+1);if(g.dialect==="postgres")B("WHERE",`${String(j)} ILIKE ${O}`);else B("WHERE",`LOWER(${String(j)}) LIKE LOWER(${O})`);return V.push(L),P=null,this},orWhereLike(j,L,O=!1){let M=l(V.length+1);return B("OR",`${O?String(j):`LOWER(${String(j)})`} LIKE ${O?M:`LOWER(${M})`}`),V.push(L),P=null,this},orWhereILike(j,L){let O=l(V.length+1);if(g.dialect==="postgres")B("OR",`${String(j)} ILIKE ${O}`);else B("OR",`LOWER(${String(j)}) LIKE LOWER(${O})`);return V.push(L),P=null,this},whereNotLike(j,L,O=!1){let M=l(V.length+1);return B("WHERE",`${O?String(j):`LOWER(${String(j)})`} NOT LIKE ${O?M:`LOWER(${M})`}`),V.push(L),P=null,this},whereNotILike(j,L){let O=l(V.length+1);if(g.dialect==="postgres")B("WHERE",`${String(j)} NOT ILIKE ${O}`);else B("WHERE",`LOWER(${String(j)}) NOT LIKE LOWER(${O})`);return V.push(L),P=null,this},orWhereNotLike(j,L,O=!1){let M=l(V.length+1);return B("OR",`${O?String(j):`LOWER(${String(j)})`} NOT LIKE ${O?M:`LOWER(${M})`}`),V.push(L),P=null,this},orWhereNotILike(j,L){let O=l(V.length+1);if(g.dialect==="postgres")B("OR",`${String(j)} NOT ILIKE ${O}`);else B("OR",`LOWER(${String(j)}) NOT LIKE LOWER(${O})`);return V.push(L),P=null,this},whereAny(j,L,O){if(j.length===0)return I("AND",`(${A6})`),this;let M=V.length+1,_=j.map((k,b)=>`${k} ${L} ${l(M+b)}`);for(let k=0;k<j.length;k++)V.push(O);return I("AND",`(${_.join(" OR ")})`),this},whereAll(j,L,O){if(j.length===0)return this;let M=V.length+1,_=j.map((k,b)=>`${k} ${L} ${l(M+b)}`);for(let k=0;k<j.length;k++)V.push(O);return I("AND",`(${_.join(" AND ")})`),this},whereNone(j,L,O){if(j.length===0)return this;let M=V.length+1,_=j.map((k,b)=>`${k} ${L} ${l(M+b)}`);for(let k=0;k<j.length;k++)V.push(O);return I("AND",`NOT (${_.join(" OR ")})`),this},whereNotBetween(j,L,O){n(String(j),"whereNotBetween(column)");let M=V.length+1;return V.push(L,O),I("AND",`${j} NOT BETWEEN ${l(M)} AND ${l(M+1)}`),this},whereDate(j,L,O){n(j,"whereDate(column)");let M=O instanceof Date?O.toISOString():typeof O==="string"?O:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof O}`)})(),_=V.length+1;return V.push(M),I("AND",`${j} ${L} ${l(_)}`),this},whereRaw(j){return I("AND",q1(j,"whereRaw(fragment)")),this},orWhereRaw(j){return I("OR",q1(j,"orWhereRaw(fragment)")),this},whereColumn(j,L,O){return n(j,"whereColumn(left)"),n(O,"whereColumn(right)"),I("AND",`${j} ${L} ${O}`),this},orWhereColumn(j,L,O){return n(j,"orWhereColumn(left)"),n(O,"orWhereColumn(right)"),I("OR",`${j} ${L} ${O}`),this},whereIn(j,L){if(n(String(j),"whereIn(column)"),Array.isArray(L)){let O=b0(L.length,V.length+1),M=F$(j,L,!1,O);V.push(...L),I("AND",M)}else I("AND",`${j} IN (${String(L.toSQL())})`);return this},orWhereIn(j,L){if(n(String(j),"orWhereIn(column)"),Array.isArray(L)){let O=b0(L.length,V.length+1),M=F$(j,L,!1,O);V.push(...L),I("OR",M)}else I("OR",`${j} IN (${String(L.toSQL())})`);return this},whereNotIn(j,L){if(n(String(j),"whereNotIn(column)"),Array.isArray(L)){let O=b0(L.length,V.length+1),M=F$(j,L,!0,O);V.push(...L),I("AND",M)}else I("AND",`${j} NOT IN (${String(L.toSQL())})`);return this},orWhereNotIn(j,L){if(n(String(j),"orWhereNotIn(column)"),Array.isArray(L)){let O=b0(L.length,V.length+1),M=F$(j,L,!0,O);V.push(...L),I("OR",M)}else I("OR",`${j} NOT IN (${String(L.toSQL())})`);return this},whereNested(j){let L=j.toSQL?String(j.toSQL()):String(j);return I("AND",`(${L})`),this},orWhereNested(j){let L=j.toSQL?String(j.toSQL()):String(j);return I("OR",`(${L})`),this},andWhere(j,L,O){return r(this,"AND","andWhere",j,L,O)},orWhere(j,L,O){return r(this,"OR","orWhere",j,L,O)},orderBy(j,L="asc"){let O=L==="asc"?"ASC":"DESC";return w=F0.ORDER_BY.test(w)?`${w}, ${j} ${O}`:`${w} ORDER BY ${j} ${O}`,P=null,this},orderByDesc(j){return w=F0.ORDER_BY.test(w)?`${w}, ${j} DESC`:`${w} ORDER BY ${j} DESC`,P=null,this},inRandomOrder(){let j=g.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return w=F0.ORDER_BY.test(w)?`${w}, ${j}`:`${w} ORDER BY ${j}`,P=null,this},reorder(j,L="asc"){return w=w.replace(/ORDER BY[\s\S]*$/i,""),w+=` ORDER BY ${j} ${L==="asc"?"ASC":"DESC"}`,P=null,this},latest(j){let L=j??g.timestamps.defaultOrderColumn;return w=F0.ORDER_BY.test(w)?`${w}, ${L} DESC`:`${w} ORDER BY ${L} DESC`,P=null,this},oldest(j){let L=j??g.timestamps.defaultOrderColumn;return w=F0.ORDER_BY.test(w)?`${w}, ${L} ASC`:`${w} ORDER BY ${L} ASC`,P=null,this},limit(j){if(!Number.isFinite(j)||j<0||!Number.isInteger(j))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${j}`);return w=F0.LIMIT.test(w)?w.replace(F0.LIMIT,` LIMIT ${j}`):`${w} LIMIT ${j}`,P=null,this},offset(j){if(!Number.isFinite(j)||j<0||!Number.isInteger(j))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${j}`);return w=F0.OFFSET.test(w)?w.replace(F0.OFFSET,` OFFSET ${j}`):`${w} OFFSET ${j}`,P=null,this},join(j,L,O,M){return n(j,"join(table)"),M$(L,"join(onLeft)"),M$(M,"join(onRight)"),d0(O,"join(operator)"),y(`JOIN ${j} ON ${L} ${O} ${M}`),d.add(j),this},joinSub(j,L,O,M,_){return n(L,"joinSub(alias)"),M$(O,"joinSub(onLeft)"),M$(_,"joinSub(onRight)"),d0(M,"joinSub(operator)"),y(`JOIN (${String(j.toSQL())}) AS ${L} ON ${O} ${M} ${_}`),d.add(L),this},innerJoin(j,L,O,M){return n(j,"innerJoin(table)"),M$(L,"innerJoin(onLeft)"),M$(M,"innerJoin(onRight)"),d0(O,"innerJoin(operator)"),y(`INNER JOIN ${j} ON ${L} ${O} ${M}`),d.add(j),this},leftJoin(j,L,O,M){return n(j,"leftJoin(table)"),M$(L,"leftJoin(onLeft)"),M$(M,"leftJoin(onRight)"),d0(O,"leftJoin(operator)"),y(`LEFT JOIN ${j} ON ${L} ${O} ${M}`),d.add(j),this},leftJoinSub(j,L,O,M,_){return n(L,"leftJoinSub(alias)"),M$(O,"leftJoinSub(onLeft)"),M$(_,"leftJoinSub(onRight)"),d0(M,"leftJoinSub(operator)"),y(`LEFT JOIN (${String(j.toSQL())}) AS ${L} ON ${O} ${M} ${_}`),d.add(L),this},rightJoin(j,L,O,M){return n(j,"rightJoin(table)"),M$(L,"rightJoin(onLeft)"),M$(M,"rightJoin(onRight)"),d0(O,"rightJoin(operator)"),y(`RIGHT JOIN ${j} ON ${L} ${O} ${M}`),d.add(j),this},crossJoin(j){return n(j,"crossJoin(table)"),y(`CROSS JOIN ${j}`),d.add(j),this},crossJoinSub(j,L){return n(L,"crossJoinSub(alias)"),y(`CROSS JOIN (${String(j.toSQL())}) AS ${L}`),d.add(L),this},selectAllRelations(){if(!H)return this;let j=String(W),L=Object.keys(H[j]?.columns??{}),O=[];if(L.length>0)O.push(D`${D(j)}.*`);for(let M of d){let _=Object.keys(H[M]?.columns??{});for(let k of _){let b=g.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${k}`.replace(/_([a-z])/g,(m,p)=>p.toUpperCase()):g.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${k}`:`${M}_${k}`;O.push(D`${D(`${M}.${k}`)} AS ${D(b)}`)}}if(O.length>0){let M=L.length>0?`${j}.*`:"",_=[];for(let m of d){let p=Object.keys(H[m]?.columns??{});for(let v of p){let c=g.aliasing.relationColumnAliasFormat==="camelCase"?`${m}_${v}`.replace(/_([a-z])/g,(s,Y0)=>Y0.toUpperCase()):g.aliasing.relationColumnAliasFormat==="table.dot.column"?`${m}.${v}`:`${m}_${v}`;_.push(`${m}.${v} AS ${c}`)}}let k=[M,..._].filter(Boolean).join(", "),b=w.indexOf(" FROM ");if(b!==-1)w=`SELECT ${k}${w.substring(b)}`;else w=`SELECT ${k} FROM ${j}`;P=null}return this},groupBy(...j){if(j.length)w=F0.GROUP_BY.test(w)?`${w}, ${j.join(", ")}`:`${w} GROUP BY ${j.join(", ")}`,P=null;return this},groupByRaw(j){let L=q1(j,"groupByRaw(fragment)");return w=F0.GROUP_BY.test(w)?`${w}, ${L}`:`${w} GROUP BY ${L}`,P=null,this},having(j){let L=/\bHAVING\b/i.test(w)?"AND":"HAVING";if(Array.isArray(j)){let O=V.length+1;w=`${w} ${L} ${j[0]} ${j[1]} ${l(O)}`,V.push(j[2]),P=null}else if(j&&typeof j==="object"&&!("raw"in j)){let O=Object.keys(j),M=O.length;if(M){let _=V.length,k=Array.from({length:M});for(let b=0;b<M;b++){let m=O[b];k[b]=`${m} = ${l(_+b+1)}`,V.push(j[m])}w=`${w} ${L} ${k.join(" AND ")}`,P=null}}else if(j&&typeof j.raw<"u")w+=` ${L} ${j.raw}`,P=null;return this},havingRaw(j){let L=q1(j,"havingRaw(fragment)"),O=/\bHAVING\b/i.test(w)?"AND":"HAVING";return w+=` ${O} ${L}`,P=null,this},orderByRaw(j){let L=q1(j,"orderByRaw(fragment)");return w=F0.ORDER_BY.test(w)?`${w}, ${L}`:`${w} ORDER BY ${L}`,P=null,this},$call(j){return j(this),this},union(j){return o("UNION",j),this},unionAll(j){return o("UNION ALL",j),this},intersect(j){return o("INTERSECT",j),this},intersectAll(j){return o("INTERSECT ALL",j),this},except(j){return o("EXCEPT",j),this},exceptAll(j){return o("EXCEPT ALL",j),this},forPage(j,L){let O=Math.max(1,Math.floor(j)),M=Math.max(1,Math.floor(L));return w+=` LIMIT ${M} OFFSET ${(O-1)*M}`,P=null,this},toSQL(){let j=AG(x());return{sql:j,toString:()=>j,execute:()=>T().execute(),values:()=>T().values(),raw:()=>T().raw()}},async value(j){let L=D`${T()} LIMIT 1`,O=await X(L,"select",{signal:f,timeoutMs:i}),[M]=O;return M?.[j]},async pluck(j,L){let O=await X(T(),"select",{signal:f,timeoutMs:i});if(L){let M={};for(let _ of O){let k=String(_?.[L]);if(Object.prototype.hasOwnProperty.call(M,k))throw Error(`[query-builder] pluck(${j}, ${L}): duplicate key '${k}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);M[k]=_?.[j]}return M}return O.map((M)=>M?.[j])},async exists(){let j=D`SELECT EXISTS (${T()}) as e`,L=await X(j,"select",{signal:f,timeoutMs:i}),[O]=L;return Boolean(O?.e)},async doesntExist(){return!await this.exists()},async paginate(j,L=1,O={}){if(!Number.isFinite(j)||j<=0||!Number.isInteger(j))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${j}`);if(!Number.isFinite(L)||L<1||!Number.isInteger(L))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${L}`);if(O.tx){let s=AG(x()),Y0=[...V],v0=await O.tx.unsafe(`SELECT COUNT(*) as c FROM (${s}) as sub`,Y0),e=Number(v0?.[0]?.c??0),g0=Math.max(1,Math.ceil(e/j)),A$=Math.max(1,Math.min(L,g0)),h$=(A$-1)*j;return{data:await O.tx.unsafe(`${s} LIMIT ${j} OFFSET ${h$}`,Y0),meta:{perPage:j,page:A$,total:e,lastPage:g0}}}let M=D`SELECT COUNT(*) as c FROM (${T()}) as sub`,_=await X(M,"select",{signal:f,timeoutMs:i}),[k]=_,b=Number(k?.c??0),m=Math.max(1,Math.ceil(b/j)),p=Math.max(1,Math.min(L,m)),v=(p-1)*j;return{data:await X(D`${T()} LIMIT ${j} OFFSET ${v}`,"select",{signal:f,timeoutMs:i}),meta:{perPage:j,page:p,total:b,lastPage:m}}},async simplePaginate(j,L=1){let O=Math.max(1,L),M=(O-1)*j,_=await X(D`${T()} LIMIT ${j+1} OFFSET ${M}`,"select",{signal:f,timeoutMs:i}),k=_.length>j;return{data:k?_.slice(0,j):_,meta:{perPage:j,page:O,hasMore:k}}},async cursorPaginate(j,L,O="id",M="asc"){if(!Number.isInteger(j)||j<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${j}`);let _=(Array.isArray(O)?O:[O]).map(String);for(let J$ of _)n(J$,"cursorPaginate(column)");let k=M==="asc"?">":"<",b=M==="asc"?"ASC":"DESC",m=[...V],p="";if(L!==void 0&&L!==null)if(Array.isArray(O)){let J$=L.map((h0)=>{return m.push(h0),l(m.length)});p=`(${_.join(", ")}) ${k} (${J$.join(", ")})`}else m.push(L),p=`${_[0]} ${k} ${l(m.length)}`;let v=AG(p?x({conn:"AND",sql:p}):x()),c=_.map((J$)=>`${J$} ${b}`).join(", ");if(EX(v))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${c} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let s=m.length>0?J.unsafe(`${v} ORDER BY ${c} LIMIT ${j+1}`,m):J.unsafe(`${v} ORDER BY ${c} LIMIT ${j+1}`),Y0=await X(s,"select",{signal:f,timeoutMs:i}),v0=Y0.length>j,e=Y0.slice(0,j),g0=e[e.length-1],A$=v0&&g0?Array.isArray(O)?O.map((J$)=>g0[J$]):g0[O]:null,h$=e.length?Array.isArray(O)?O.map((J$)=>e[0]?.[J$]):e[0]?.[O]:null;return{data:e,meta:{perPage:j,nextCursor:A$??null,prevCursor:h$}}},async chunk(j,L){let O=1;while(!0){let{data:M,meta:_}=await this.paginate(j,O);if(M.length===0)break;if(await L(M),O>=_.lastPage)break;O+=1}},async chunkById(j,L="id",O){let M;while(!0){let{data:_,meta:k}=await this.cursorPaginate(j,M,L,"asc");if(_.length===0)break;if(O)await O(_);if(M=k.nextCursor,!M)break}},async eachById(j,L="id",O){await this.chunkById(j,L,async(M)=>{for(let _ of M)await O?.(_)})},withTimeout(j){return i=Math.max(1,Math.floor(j)),this},abort(j){return f=j,this},withTrashed(){return J0=!0,t=!1,this},onlyTrashed(){J0=!0,t=!0;let j=g.softDeletes?.column||"deleted_at",L=(_,k)=>{let b=_.toUpperCase(),m=0;for(let p=0;p<_.length;p++){let v=_[p];if(v==="(")m++;else if(v===")")m--;else if(m===0&&b.substring(p,p+5)==="WHERE"&&(p===0||/\s/.test(_[p-1]??""))&&/\s/.test(_[p+5]??""))return`${_.substring(0,p)}WHERE ${k} AND ${_.substring(p+6)}`}return`${_} WHERE ${k}`},O=`${W}.${j} IS NOT NULL`;w=L(w,O);let M=String(T());return P=D([L(M,O)]),this},scope(j,L){let O=String(W),_=G?.scopes?.[O]?.[j];if(_)return _(this,L);return this},when(j,L,O){if(j)return L(this);if(O)return O(this);return this},tap(j){return j(this),this},dump(){return console.log(String(T())),this},dd(){throw console.log(String(T())),Error("Dump and Die")},cache(j=60000){return Y1=j,_0=!0,this},async explain(){let j=D`EXPLAIN ${T()}`;return await X(j,"select",{signal:f,timeoutMs:i})},simple(){return T().simple()},toText(){return x()},async get(){let j=z(),L=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||HG(j));if(!g.softDeletes?.enabled&&!_0&&!i&&!f&&!L){let b=J._prepareStatement;if(b){let m=b(x());return C1(V.length>0?m.all(...V):m.all())}}let O=x();if(P=V.length>0?J.unsafe(O,V):J.unsafe(O),!g.softDeletes?.enabled&&!_0&&!i&&!f&&!L){let b=T()._stmt,m=T()._params;if(b)return C1(m&&m.length>0?b.all(...m):b.all());return C1(await T().execute())}if(!g.softDeletes?.enabled&&!_0&&!i&&!f)return C1(await X(T(),"select"));let M=T();if(g.softDeletes?.enabled&&g.softDeletes.defaultFilter&&!J0){let b=g.softDeletes.column,m=String(W);if((H?Boolean(H[m]?.columns?.[b]):!0)&&!F0.DELETED_AT.test(x()))B("WHERE",`${String(b)} IS ${t?"NOT ":""}NULL`),M=T()}let _=_0?`${String(M)}\x00${JSON.stringify(V)}`:"";if(_0){let b=nH.get(_);if(b)return b}let k=await X(M,"select",{signal:f,timeoutMs:i});if(_0)nH.set(_,k,Y1);return C1(k)},async executeTakeFirst(){let j=await X(T(),"select",{signal:f,timeoutMs:i});return B1(Array.isArray(j)?j[0]:j)},async executeTakeFirstOrThrow(){let j=await this.executeTakeFirst();if(!j)throw Error("Record not found");return j},async first(){let j=z(),L=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||HG(j));if(!g.softDeletes?.enabled&&!_0&&!i&&!f&&!L){let _=J._prepareStatement;if(_){let k=x(),b=k.includes(" LIMIT ")?k:`${k} LIMIT 1`,m=_(b),p=V.length>0?m.all(...V):m.all();return B1(p[0])}}let O=await X(D`${T()} LIMIT 1`,"select",{signal:f,timeoutMs:i}),[M]=O;return B1(M)},async firstOrFail(){let j=await this.first();if(!j)throw Error("Record not found");return j},async find(j){let L=G?.primaryKeys[String(W)]??"id",O=await X(D`${T()} WHERE ${D(L)} = ${j} LIMIT 1`,"select",{signal:f,timeoutMs:i}),[M]=O;return M},async findOrFail(j){let L=await this.find(j);if(!L)throw Error("Record not found");return L},async findMany(j){let L=G?.primaryKeys[String(W)]??"id";return await X(D`${T()} WHERE ${D(String(L))} IN ${D(j)}`,"select",{signal:f,timeoutMs:i})},async*lazy(){let j,L=G?.primaryKeys[String(W)]??"id";while(!0){let M=await(j==null?D`${T()} ORDER BY ${D(String(L))} ASC LIMIT 100`:D`${T()} WHERE ${D(String(L))} > ${j} ORDER BY ${D(String(L))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let _ of M)yield _;if(j=M[M.length-1]?.[L],j==null)break}},async*lazyById(){let j=G?.primaryKeys[String(W)]??"id",L;while(!0){let M=await(L==null?D`${T()} ORDER BY ${D(String(j))} ASC LIMIT 100`:D`${T()} WHERE ${D(String(j))} > ${L} ORDER BY ${D(String(j))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let _ of M)yield _;if(L=M[M.length-1]?.[j],L==null)break}},pipe(j){return j(this)},async count(){let j=x(),L=j.indexOf(" FROM "),O=/ GROUP BY /i.test(j),M;if(O)M=`SELECT COUNT(*) as c FROM (${j}) AS _bqb_count_sub`;else if(L!==-1)M=`SELECT COUNT(*) as c${j.substring(L)}`;else M=`SELECT COUNT(*) as c FROM ${W}`;let _=z(),k=_&&(_.onQueryStart||_.onQueryEnd||_.onQueryError||_.startSpan||HG(_));if(!g.softDeletes?.enabled&&!_0&&!i&&!f&&!k){let v=J._prepareStatement;if(v){let c=v(M),s=V.length>0?c.all(...V):c.all();return Number(s[0]?.c??0)}}let b=V.length>0?J.unsafe(M,V):J.unsafe(M),m=await X(b,"select",{signal:f,timeoutMs:i}),[p]=m;return Number(p?.c??0)},async avg(j){let L=x(),O=L.indexOf(" FROM "),M=O!==-1?`SELECT AVG(${j}) as a${L.substring(O)}`:`SELECT AVG(${j}) as a FROM ${W}`,_=z(),k=_&&(_.onQueryStart||_.onQueryEnd||_.onQueryError||_.startSpan||HG(_));if(!g.softDeletes?.enabled&&!_0&&!i&&!f&&!k){let v=J._prepareStatement;if(v){let c=v(M),s=V.length>0?c.all(...V):c.all();return Number(s[0]?.a??0)}}let b=V.length>0?J.unsafe(M,V):J.unsafe(M),m=await X(b,"select",{signal:f,timeoutMs:i}),[p]=m;return Number(p?.a??0)},async sum(j){let L=x(),O=L.indexOf(" FROM "),M=O!==-1?`SELECT SUM(${j}) as s${L.substring(O)}`:`SELECT SUM(${j}) as s FROM ${W}`,_=V.length>0?J.unsafe(M,V):J.unsafe(M),k=await X(_,"select",{signal:f,timeoutMs:i}),[b]=k;return Number(b?.s??0)},async max(j){let L=x(),O=L.indexOf(" FROM "),M=O!==-1?`SELECT MAX(${j}) as m${L.substring(O)}`:`SELECT MAX(${j}) as m FROM ${W}`,_=V.length>0?J.unsafe(M,V):J.unsafe(M),k=await X(_,"select",{signal:f,timeoutMs:i}),[b]=k;return b?.m},async min(j){let L=x(),O=L.indexOf(" FROM "),M=O!==-1?`SELECT MIN(${j}) as m${L.substring(O)}`:`SELECT MIN(${j}) as m FROM ${W}`,_=V.length>0?J.unsafe(M,V):J.unsafe(M),k=await X(_,"select",{signal:f,timeoutMs:i}),[b]=k;return b?.m},lockForUpdate(){return w+=" FOR UPDATE",P=null,this},sharedLock(){let j=g.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return w+=` ${j}`,P=null,this},withCTE(j,L){return n(j,"withCTE(name)"),w=`WITH ${j} AS (${String(L.toSQL())}) ${w}`,P=null,this},withRecursive(j,L){return n(j,"withRecursive(name)"),w=`WITH RECURSIVE ${j} AS (${String(L.toSQL())}) ${w}`,P=null,this},execute(){return X(T(),"select",{signal:f,timeoutMs:i})},values(){return T().values()},toParams(){return[...V]},__rawState(){return{sql:AG(x()),params:[...V]}},raw(){return T().raw()},get rows(){return},get row(){return},cancel(){try{T().cancel()}catch{}}},{get(j,L,O){let M=Reflect.get(j,L,O);if(M!==void 0)return M;if(typeof L==="string"&&(L.startsWith("where")||L.startsWith("orWhere")||L.startsWith("andWhere"))){let _=L.startsWith("orWhere"),k=L.startsWith("andWhere"),b=`${String(W)}|${L}`,m=U.get(b);if(m===void 0){let v=L.replace(/^(?:or|and)?where/i,"");if(!v)U.set(b,""),m="";else{let c=v.charAt(0).toLowerCase()+v.slice(1),s=v.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Y0=H?Object.keys(H[String(W)]?.columns??{}):[];m=[s,c,c.toLowerCase()].find((v0)=>Y0.includes(v0))??s,U.set(b,m)}}if(m==="")return()=>O;let p=m;return(v)=>{if(Array.isArray(v)){let c=b0(v.length,V.length+1);B(_?"OR":k?"AND":"WHERE",`${p} IN (${c})`),V.push(...v)}else{let c=l(V.length+1);B(_?"OR":k?"AND":"WHERE",`${p} = ${c}`),V.push(v)}return O}}return Reflect.get(j,L,O)}})}return{configure(W){return lY(W),this},id(W){if(!F0.IDENTIFIER.test(W))throw Error(`[query-builder] Invalid identifier: '${W}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return J(String(W))},ids(...W){for(let Q of W)if(!F0.IDENTIFIER.test(Q))throw Error(`[query-builder] Invalid identifier: '${Q}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return J(W)},select(W,...Q){return C(W,Q)},selectFrom(W){return C(W)},selectFromSub(W,Q){function D(B){return()=>{throw Error(`[query-builder] selectFromSub(...).${B}() is not supported. Apply ${B}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}n(String(Q),"selectFromSub(alias)");let w=typeof W.__rawState==="function"?W.__rawState():null,K=W.toSQL(),V=w?.sql??(typeof K==="string"?K:K?.sql??String(K)),q=w?.params??(Array.isArray(K?.values)?K.values:[]),P=`SELECT * FROM (${V}) AS ${String(Q)}`,T=(B,N,S,x)=>{let u=[...B],r=(y,d,i)=>{n(y,"selectFromSub where(column)");let f=d0(d,"selectFromSub where(operator)");if(f==="in"||f==="not in"){let t=Array.isArray(i)?i:[i],_0=b0(t.length,u.length+1);return u.push(...t),`${y} ${f.toUpperCase()} (${_0})`}let J0=l(u.length+1);return u.push(i),`${y} ${f} ${J0}`},o;if(typeof N==="string"&&S!==void 0)o=r(N,S,x);else if(Array.isArray(N)&&N.length===3)o=r(N[0],N[1],N[2]);else if(N&&typeof N==="object"){let y=Object.entries(N).map(([d,i])=>r(d,"=",i));o=y.length>1?`(${y.join(" AND ")})`:y[0]}else return{clause:null,params:B};return{clause:o,params:u}};function I(B,N,S,x=""){let u=k1(N),r=u?`${B} WHERE ${u}${x}`:`${B}${x}`,o=()=>S.length>0?J.unsafe(r,S):J.unsafe(r),y=(f,J0,t,_0)=>{let L0=T(S,J0,t,_0);return L0.clause===null?I(B,N,S,x):I(B,[...N,{conn:f,sql:L0.clause}],L0.params,x)},d=(f,J0)=>{let t=[],_0=[...S],L0=(K0)=>(D$,B1,C1)=>{let b$=T(_0,D$,B1,C1);if(b$.clause!==null)t.push({conn:K0,sql:b$.clause}),_0=b$.params;return H$},H$={where:L0("AND"),andWhere:L0("AND"),orWhere:L0("OR")};J0(H$);let Y1=k1(t);if(!Y1)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return I(B,[...N,{conn:f,sql:`(${Y1})`}],_0,x)},i={distinct(){return I(B.replace(/^SELECT\s+/i,"SELECT DISTINCT "),N,S,x)},distinctOn(...f){let J0=f.map(String).join(", ");return I(B.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${J0}) `),N,S,x)},selectRaw(f){let J0=q1(f,"selectFromSub.selectRaw(fragment)"),t=B.indexOf(" FROM "),_0=t!==-1?`${B.slice(0,t)}, ${J0}${B.slice(t)}`:`${B}, ${J0}`;return I(_0,N,S,x)},$call(f){return f(this)??this},where(f,J0,t){return y("AND",f,J0,t)},andWhere(f,J0,t){return y("AND",f,J0,t)},orWhere(f,J0,t){return y("OR",f,J0,t)},whereGroup(f){return d("AND",f)},orWhereGroup(f){return d("OR",f)},orderBy(f,J0="asc"){n(String(f),"selectFromSub.orderBy(column)");let t=J0==="asc"?"ASC":"DESC",_0=F0.ORDER_BY.test(x)?`${x}, ${f} ${t}`:`${x} ORDER BY ${f} ${t}`;return I(B,N,S,_0)},limit(f){if(!Number.isInteger(f)||f<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${f}`);let J0=F0.LIMIT.test(x)?x.replace(F0.LIMIT,` LIMIT ${f}`):`${x} LIMIT ${f}`;return I(B,N,S,J0)},offset(f){if(!Number.isInteger(f)||f<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${f}`);let J0=F0.OFFSET.test(x)?x.replace(F0.OFFSET,` OFFSET ${f}`):`${x} OFFSET ${f}`;return I(B,N,S,J0)},toSQL(){return R(o(),r)},async execute(){return X(o(),"select")},async executeTakeFirst(){let f=await X(o(),"select");return Array.isArray(f)?f[0]:f},async executeTakeFirstOrThrow(){let f=await X(o(),"select"),J0=Array.isArray(f)?f[0]:f;if(!J0)throw Error("Record not found");return J0},async get(){return X(o(),"select")},async first(){let f=await X(o(),"select");return Array.isArray(f)?f[0]:f},async firstOrFail(){let f=await X(o(),"select"),J0=Array.isArray(f)?f[0]:f;if(!J0)throw Error("No rows found");return J0},async count(){let f=S.length>0?J.unsafe(`SELECT COUNT(*) as c FROM (${r}) as sub`,S):J.unsafe(`SELECT COUNT(*) as c FROM (${r}) as sub`),J0=await X(f,"select");return Number(J0?.[0]?.c??0)},async exists(){let f=S.length>0?J.unsafe(`SELECT EXISTS(${r}) as e`,S):J.unsafe(`SELECT EXISTS(${r}) as e`),J0=await X(f,"select");return Boolean(J0?.[0]?.e)},async doesntExist(){return!await i.exists()},values(){return o().values()},raw(){return o().raw()},cancel(){try{o().cancel()}catch{}},whereRaw:D("whereRaw"),whereColumn:D("whereColumn"),orWhereColumn:D("orWhereColumn"),whereIn:D("whereIn"),orWhereIn:D("orWhereIn"),whereNotIn:D("whereNotIn"),orWhereNotIn:D("orWhereNotIn"),whereLike:D("whereLike"),whereILike:D("whereILike"),orWhereLike:D("orWhereLike"),orWhereILike:D("orWhereILike"),whereNotLike:D("whereNotLike"),whereNotILike:D("whereNotILike"),orWhereNotLike:D("orWhereNotLike"),orWhereNotILike:D("orWhereNotILike"),whereAny:D("whereAny"),whereAll:D("whereAll"),whereNone:D("whereNone"),whereNested:D("whereNested"),orWhereNested:D("orWhereNested"),whereDate:D("whereDate"),whereBetween:D("whereBetween"),whereNotBetween:D("whereNotBetween"),whereJsonContains:D("whereJsonContains"),whereJsonPath:D("whereJsonPath"),whereNull:D("whereNull"),orWhereNull:D("orWhereNull"),whereNotNull:D("whereNotNull"),orWhereNotNull:D("orWhereNotNull"),whereExists:D("whereExists"),orWhereExists:D("orWhereExists"),orWhereBetween:D("orWhereBetween"),orWhereRaw:D("orWhereRaw"),whereJsonDoesntContain:D("whereJsonDoesntContain"),whereJsonContainsKey:D("whereJsonContainsKey"),whereJsonDoesntContainKey:D("whereJsonDoesntContainKey"),whereJsonLength:D("whereJsonLength"),join:D("join"),joinSub:D("joinSub"),innerJoin:D("innerJoin"),leftJoin:D("leftJoin"),leftJoinSub:D("leftJoinSub"),rightJoin:D("rightJoin"),crossJoin:D("crossJoin"),crossJoinSub:D("crossJoinSub"),groupBy:D("groupBy"),groupByRaw:D("groupByRaw"),having:D("having"),havingRaw:D("havingRaw"),addSelect:D("addSelect"),select:D("select"),selectAll:D("selectAll"),orderByDesc:D("orderByDesc"),inRandomOrder:D("inRandomOrder"),reorder:D("reorder"),orderByRaw:D("orderByRaw"),union:D("union"),unionAll:D("unionAll"),forPage:D("forPage"),selectAllRelations:D("selectAllRelations"),with:D("with"),value:D("value"),pluck:D("pluck"),cursorPaginate:D("cursorPaginate"),paginate:D("paginate"),simplePaginate:D("simplePaginate"),chunk:D("chunk"),chunkById:D("chunkById"),eachById:D("eachById"),avg:D("avg"),sum:D("sum"),max:D("max"),min:D("min"),find:D("find"),findOrFail:D("findOrFail"),findMany:D("findMany"),latest:D("latest"),oldest:D("oldest"),lazy:D("lazy"),lazyById:D("lazyById"),pipe:(f)=>f(i),when:D("when"),tap:()=>i,dump:()=>i,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>o().simple(),toText:()=>r,toParams:()=>[...S],withTimeout:()=>i,abort:()=>i,lockForUpdate:()=>i,sharedLock:()=>i,withCTE:()=>i,withRecursive:()=>i,cache:()=>i,clone:()=>i,withTrashed:()=>i,onlyTrashed:()=>i,scope:()=>i,get rows(){return[]},get row(){return}};return i}return I(P,[],q)},insertInto(W){let Q,D="",w=[],K=!1,V=()=>P?[]:{changes:0,lastInsertRowid:0},q=()=>{let B=async()=>{return},N=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>q(),andWhere:()=>q(),orWhere:()=>q(),orderBy:()=>q(),limit:()=>q(),offset:()=>q(),toSQL:()=>R(null,""),execute:async()=>[],get:async()=>[],first:B,executeTakeFirst:B,firstOrFail:N,executeTakeFirstOrThrow:N}},P=g.dialect==="postgres",T=P?(B)=>`"${String(B).replace(/"/g,'""')}"`:A0(g.dialect)?(B)=>`\`${String(B).replace(/`/g,"``")}\``:(B)=>`"${String(B).replace(/"/g,'""')}"`,I=P?(B)=>`$${B+1}`:(B)=>"?";return{values(B){let N=Array.isArray(B)?B:[B],S=N.length;if(S===0)return K=!0,Q=null,D="",w.length=0,this;K=!1;let x=N[0],u=Object.keys(x),r=u.length,o=S*r;w.length=o;let y=P?u.map((d)=>T(d)).join(","):u.join(",");if(S===1)if(!P){let d=T(u[0]),i="?";w[0]=x[u[0]];for(let f=1;f<r;f++)d+=`,${T(u[f])}`,i+=",?",w[f]=x[u[f]];D=`INSERT INTO ${T(W)}(${d})VALUES(${i})`}else{D=`INSERT INTO ${T(W)}(${y})VALUES(`;for(let d=0;d<r;d++){if(d>0)D+=",";D+=I(d),w[d]=x[u[d]]}D+=")"}else{let d=u.map((f)=>T(f)).join(",");D=`INSERT INTO ${T(W)}(${d})VALUES`;let i=0;for(let f=0;f<S;f++){let J0=N[f];if(f===0)D+="(";else D+="),(";for(let t=0;t<r;t++){if(t>0)D+=",";D+=I(i),w[i++]=J0[u[t]]}}D+=")"}if(!J._prepareStatement)Q=J.unsafe(D,w);return this},returning(...B){if(K)return q();let N=`${D} RETURNING ${B.join(", ")}`,S=J.unsafe(N,w),x=async()=>{let u=await X(S,"insert");return Array.isArray(u)?u[0]:u};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>R(S,N),execute:()=>X(S,"insert"),get:()=>X(S,"insert"),first:x,executeTakeFirst:x,async firstOrFail(){let u=await x();if(!u)throw Error("Insert with RETURNING returned no rows");return u},async executeTakeFirstOrThrow(){let u=await x();if(!u)throw Error("Insert with RETURNING returned no rows");return u}}},toSQL(){if(K)return R(null,"");if(!Q)Q=J.unsafe(D,w);return R(Q,D)},execute(){if(K)return Promise.resolve(V());let B=z();if(!(B&&(B.onQueryStart||B.onQueryEnd||B.onQueryError||B.startSpan||B.beforeCreate||B.afterCreate||HG(B)))){let S=J._prepareStatement;if(S){let x=S(D);return w.length>0?x.run(...w):x.run()}}if(!Q)Q=J.unsafe(D,w);return X(Q,"insert")},async executeTakeFirst(){if(K)return V();if(!Q)Q=J.unsafe(D,w);return await X(Q,"insert")},async executeTakeFirstOrThrow(){if(K)throw Error("Insert failed");if(!Q)Q=J.unsafe(D,w);let B=await X(Q,"insert");if(!B)throw Error("Insert failed");return B},returningAll(){if(K)return q();let B=`${D} RETURNING *`,N=J.unsafe(B,w),S=async()=>{let x=await X(N,"insert");return Array.isArray(x)?x[0]:x};return{toSQL:()=>R(N,B),execute:()=>X(N,"insert"),get:()=>X(N,"insert"),first:S,executeTakeFirst:S,async firstOrFail(){let x=await S();if(!x)throw Error("Insert with RETURNING returned no rows");return x},async executeTakeFirstOrThrow(){let x=await S();if(!x)throw Error("Insert with RETURNING returned no rows");return x}}}}},updateTable(W){let Q,D=[],w=(V)=>{let q=String(V);if(A0(g.dialect))return`\`${q.replace(/`/g,"``")}\``;return`"${q.replace(/"/g,'""')}"`},K=`UPDATE ${w(String(W))}`;return{set(V){let q=Object.keys(V),P=q.length,T=Array.from({length:P});for(let I=0;I<P;I++){let B=q[I],N=V[B];if(l$(N))T[I]=`${w(B)} = ${N.raw}`;else if(dH(N)){let S=uH(N,D.length+1);T[I]=`${w(B)} = ${S.text}`,D.push(...S.parameters)}else T[I]=`${w(B)} = ${l(D.length+1)}`,D.push(N)}return K=`${K} SET ${T.join(", ")}`,Q=J.unsafe(K,D),this},where(V,q,P){let T=()=>F0.WHERE.test(K)?"AND":"WHERE";if(q!==void 0&&(typeof V==="string"||l$(V)||dH(V))){let I=d0(q,"updateTable.where"),B;if(typeof V==="string")B=w(V);else if(l$(V))B=V.raw;else{let S=uH(V,D.length+1);B=S.text,D.push(...S.parameters)}if(I.toLowerCase()==="in"||I.toLowerCase()==="not in"){let S=Array.isArray(P)?P:[P],x=b0(S.length,D.length+1);return K=`${K} ${T()} ${B} ${I.toUpperCase()} (${x})`,D.push(...S),Q=J.unsafe(K,D),this}let N=D.length+1;return K=`${K} ${T()} ${B} ${I} ${l(N)}`,D.push(P),Q=J.unsafe(K,D),this}if(Array.isArray(V)){let[I,B,N]=V,S=d0(B,"updateTable.where");if(S.toLowerCase()==="in"||S.toLowerCase()==="not in"){let u=Array.isArray(N)?N:[N],r=b0(u.length,D.length+1);return K=`${K} ${T()} ${w(String(I))} ${S.toUpperCase()} (${r})`,D.push(...u),Q=J.unsafe(K,D),this}let x=D.length+1;return K=`${K} ${T()} ${w(String(I))} ${S} ${l(x)}`,D.push(N),Q=J.unsafe(K,D),this}if(l$(V))return K=`${K} ${T()} ${V.raw}`,Q=J.unsafe(K,D),this;if(dH(V)){let I=uH(V,D.length+1);return K=`${K} ${T()} ${I.text}`,D.push(...I.parameters),Q=J.unsafe(K,D),this}if(V&&typeof V==="object"){let I=Object.keys(V);if(I.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let B=I.length,N=D.length,S=Array.from({length:B});for(let x=0;x<B;x++)S[x]=`${w(I[x])} = ${l(N+x+1)}`,D.push(V[I[x]]);return K=`${K} ${T()} ${S.join(" AND ")}`,Q=J.unsafe(K,D),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${V===null?"null":typeof V}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(V){let q=F0.WHERE.test(K)?"AND":"WHERE";return K=`${K} ${q} ${w(String(V))} IS NULL`,Q=J.unsafe(K,D),this},whereNotNull(V){let q=F0.WHERE.test(K)?"AND":"WHERE";return K=`${K} ${q} ${w(String(V))} IS NOT NULL`,Q=J.unsafe(K,D),this},returning(...V){let q=this,P=()=>`${K} RETURNING ${V.join(", ")}`,T=()=>D.length>0?J.unsafe(P(),D):J.unsafe(P()),I=async()=>{let S=await X(T(),"update");return Array.isArray(S)?S[0]:S},B=(S)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${S}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},N={where:(...S)=>{return q.where(...S),N},andWhere:(...S)=>{return q.where(...S),N},whereNull:(...S)=>{return q.whereNull(...S),N},whereNotNull:(...S)=>{return q.whereNotNull(...S),N},orWhere:B("orWhere"),orderBy:B("orderBy"),limit:B("limit"),offset:B("offset"),toSQL:()=>R(T(),P()),execute:()=>X(T(),"update"),get:()=>X(T(),"update"),first:I,executeTakeFirst:I,async firstOrFail(){let S=await I();if(!S)throw Error("Update with RETURNING returned no rows");return S},async executeTakeFirstOrThrow(){let S=await I();if(!S)throw Error("Update with RETURNING returned no rows");return S}};return N},toSQL(){if(!Q)Q=D.length>0?J.unsafe(K,D):J.unsafe(K);return R(Q,K)},async execute(){let V=await X(Q,"update");return F(V)},async executeTakeFirst(){return{numUpdatedRows:F(await X(Q,"update"))}},async executeTakeFirstOrThrow(){let V=F(await X(Q,"update"));if(V===0)throw Error("No rows updated");return{numUpdatedRows:V}},returningAll(){let V=()=>`${K} RETURNING *`,q=()=>D.length>0?J.unsafe(V(),D):J.unsafe(V());return{toSQL:()=>R(q(),V()),execute:()=>X(q(),"update"),async executeTakeFirst(){let P=await X(q(),"update");return Array.isArray(P)?P[0]:P},async executeTakeFirstOrThrow(){let P=await X(q(),"update"),T=Array.isArray(P)?P[0]:P;if(!T)throw Error("Update with RETURNING failed");return T}}}}},deleteFrom(W){let Q=(I)=>{let B=String(I);if(A0(g.dialect))return`\`${B.replace(/`/g,"``")}\``;return`"${B.replace(/"/g,'""')}"`},w=`DELETE FROM ${Q(String(W))}`,K=null,V=[],q=null,P=()=>F0.WHERE.test(w)?"AND":"WHERE",T=()=>{if(K===null)K=V.length>0?J.unsafe(w,V):J.unsafe(w);return K};return{where(I,B,N){if(q=I,typeof I==="string"&&B!==void 0){let S=d0(B,"deleteFrom.where");if(S.toLowerCase()==="in"||S.toLowerCase()==="not in"){let u=Array.isArray(N)?N:[N],r=b0(u.length,V.length+1);return w+=` ${P()} ${Q(I)} ${S.toUpperCase()} (${r})`,V.push(...u),K=null,this}let x=V.length+1;return w+=` ${P()} ${Q(I)} ${S} ${l(x)}`,V.push(N),K=null,this}if(Array.isArray(I)){let[S,x,u]=I,r=d0(x,"deleteFrom.where");if(r.toLowerCase()==="in"||r.toLowerCase()==="not in"){let y=Array.isArray(u)?u:[u],d=b0(y.length,V.length+1);return w+=` ${P()} ${Q(String(S))} ${r.toUpperCase()} (${d})`,V.push(...y),K=null,this}let o=V.length+1;return w+=` ${P()} ${Q(String(S))} ${r} ${l(o)}`,V.push(u),K=null,this}if(l$(I))return w+=` ${P()} ${I.raw}`,K=null,this;if(dH(I)){let S=uH(I,V.length+1);return w+=` ${P()} ${S.text}`,V.push(...S.parameters),K=null,this}if(I&&typeof I==="object"){let S=Object.keys(I);if(S.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let x=[];for(let u of S){let r=V.length+1;x.push(`${Q(u)} = ${l(r)}`),V.push(I[u])}return w+=` ${P()} ${x.join(" AND ")}`,K=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${I===null?"null":typeof I}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(I){return w+=` ${P()} ${Q(String(I))} IS NULL`,K=null,this},whereNotNull(I){return w+=` ${P()} ${Q(String(I))} IS NOT NULL`,K=null,this},returning(...I){let B=this,N=()=>`${w} RETURNING ${I.join(", ")}`,S=()=>V.length>0?J.unsafe(N(),V):J.unsafe(N()),x=async()=>{await z()?.beforeDelete?.({table:String(W),where:q});let y=await X(S(),"delete");try{await z()?.afterDelete?.({table:String(W),where:q,result:y})}catch{}return y},u=async()=>{let y=await x();return Array.isArray(y)?y[0]:y},r=(y)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${y}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},o={where:(...y)=>{return B.where(...y),o},andWhere:(...y)=>{return B.where(...y),o},whereNull:(...y)=>{return B.whereNull(...y),o},whereNotNull:(...y)=>{return B.whereNotNull(...y),o},orWhere:r("orWhere"),orderBy:r("orderBy"),limit:r("limit"),offset:r("offset"),toSQL:()=>R(S(),N()),execute:()=>x(),get:()=>x(),first:u,executeTakeFirst:u,async firstOrFail(){let y=await u();if(!y)throw Error("Delete with RETURNING returned no rows");return y},async executeTakeFirstOrThrow(){let y=await u();if(!y)throw Error("Delete with RETURNING returned no rows");return y}};return o},toSQL(){return R(T(),w)},async execute(){try{await z()?.beforeDelete?.({table:String(W),where:q})}catch(B){throw B}let I=F(await X(T(),"delete"));try{await z()?.afterDelete?.({table:String(W),where:q,result:I})}catch{}return I},async executeTakeFirst(){return{numDeletedRows:F(await X(T(),"delete"))}},async executeTakeFirstOrThrow(){let I=F(await X(T(),"delete"));if(I===0)throw Error("No rows deleted");return{numDeletedRows:I}},returningAll(){let I=()=>`${w} RETURNING *`,B=()=>V.length>0?J.unsafe(I(),V):J.unsafe(I());return{toSQL:()=>R(B(),I()),execute:()=>X(B(),"delete"),async executeTakeFirst(){let N=await X(B(),"delete");return Array.isArray(N)?N[0]:N},async executeTakeFirstOrThrow(){let N=await X(B(),"delete"),S=Array.isArray(N)?N[0]:N;if(!S)throw Error("Delete with RETURNING failed");return S}}}}},table(W){let Q=this;return{insert(D){return Q.insertInto(W).values(D)},update(D){return Q.updateTable(W).set(D)},delete(){return Q.deleteFrom(W)},select(...D){if(D.length===0)return Q.selectFrom(W);return Q.select(W,...D)}}},sql:J,raw(W,...Q){return J(W,...Q)},simple(W,...Q){return J(W,...Q).simple()},async advisoryLock(W){if(g.dialect==="postgres"){let Q=A(W),D=J`SELECT pg_advisory_lock(${Q})`;await X(D,"raw");return}if(A0(g.dialect)){let Q=`bqb:${String(W)}`,D=J`SELECT GET_LOCK(${Q}, -1) AS ok`;await X(D,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(W){if(g.dialect==="postgres"){let Q=A(W),D=J`SELECT pg_try_advisory_lock(${Q}) as ok`,w=await X(D,"raw");return Boolean(w?.[0]?.ok)}if(A0(g.dialect)){let Q=`bqb:${String(W)}`,D=J`SELECT GET_LOCK(${Q}, 0) AS ok`,w=await X(D,"raw");return Number(w?.[0]?.ok)===1}return!1},async advisoryUnlock(W){if(g.dialect==="postgres"){let Q=A(W),D=J`SELECT pg_advisory_unlock(${Q}) as ok`,w=await X(D,"raw");return Boolean(w?.[0]?.ok)}if(A0(g.dialect)){let Q=`bqb:${String(W)}`,D=J`SELECT RELEASE_LOCK(${Q}) AS ok`,w=await X(D,"raw");return Number(w?.[0]?.ok)===1}return!1},unsafe(W,Q){return J.unsafe(W,Q)},file(W,Q){return J.file(W,Q)},async reserve(){let W=await $0.reserve(),Q=z0({sql:W,meta:G,schema:H,hooks:$?.hooks});return Q.release=()=>W.release(),Q},async close(W){await $0.close(W)},async listen(W,Q){},async unlisten(W){},async notify(W,Q){},async copyTo(W,Q){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(W,Q,D){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let W=J`SELECT 1`;return await X(W,"select"),!0}catch{return!1}},async waitForReady(W){let Q=Math.max(1,W?.attempts??10),D=Math.max(10,W?.delayMs??100);for(let w=0;w<Q;w++){if(await this.ping())return;await new Promise((K)=>setTimeout(K,D))}throw Error("Database not ready after waiting")},async transaction(W,Q){let w={...$?.txDefaults,...Q},K=$?.sql??$0,V=$?.inTransaction===!0,q=V&&typeof K?.savepoint==="function"?"savepoint":"begin",P=async(B)=>{w.logger?.({type:"start",attempt:B});let N=Date.now();return await K[q](async(S)=>{let x=z0({sql:S,meta:G,schema:H,hooks:$?.hooks,inTransaction:!0});if(w?.isolation&&!V){let o=w.isolation,y=o==="read committed"?"READ COMMITTED":o==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(g.dialect==="postgres")await S.unsafe(`SET TRANSACTION ISOLATION LEVEL ${y}`);else if(A0(g.dialect))await S.unsafe(`SET TRANSACTION ISOLATION LEVEL ${y}`);else if(o!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${o}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(w?.readOnly)if(g.dialect==="postgres")await S.unsafe("SET TRANSACTION READ ONLY");else if(A0(g.dialect))await S.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let u=await W(x),r=Date.now()-N;return w.logger?.({type:"commit",attempt:B,durationMs:r}),u})},T=Math.max(0,w?.retries??0),I=0;for(;;)try{let B=await P(I+1);return w?.afterCommit?.(),B}catch(B){let N=FX(B)||LX(B,w.sqlStates);if(I<T&&N){I++,w?.onRetry?.(I,B);let S=QX(I,w.backoff);if(S>0)await wX(S);continue}try{w.onRollback?.(B)}catch{}try{w.afterRollback?.()}catch{}throw B}},async savepoint(W){if($?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let Q=J;if(!Q||typeof Q.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await Q.savepoint(async(D)=>{let w=z0({sql:D,meta:G,schema:H,hooks:$?.hooks,inTransaction:!0});return await W(w)})},async beginDistributed(W,Q){return await($?.sql??$0).beginDistributed(W,async(K)=>{let V=z0({sql:K,meta:G,schema:H,hooks:$?.hooks});return await Q(V)})},async commitDistributed(W){await $0.commitDistributed(W)},async rollbackDistributed(W){await $0.rollbackDistributed(W)},setTransactionDefaults(W){$={...$,txDefaults:{...$?.txDefaults,...W}}},transactional(W,Q){return(...D)=>{return this.transaction((w)=>W(w,...D),Q)}},async insertOrIgnore(W,Q){let D=Array.isArray(Q)?Q:[Q];if(!D.length)return;let{colsSql:w,valuesSql:K,params:V}=pH(D),q=E$(String(W)),P=A0(g.dialect)?`INSERT IGNORE INTO ${q} (${w}) VALUES ${K}`:`INSERT INTO ${q} (${w}) VALUES ${K} ON CONFLICT DO NOTHING`;return J.unsafe(P,V).execute()},async insertGetId(W,Q,D="id"){let{colsSql:w,valuesSql:K,params:V}=pH([Q]),q=E$(String(W));if(A0(g.dialect)){await J.unsafe(`INSERT INTO ${q} (${w}) VALUES ${K}`,V).execute();let[T]=await J.unsafe("SELECT LAST_INSERT_ID() as id").execute();return T?.id}if(g.dialect==="sqlite"){let T=await J.unsafe(`INSERT INTO ${q} (${w}) VALUES ${K}`,V).execute();if(T?.lastInsertRowid!=null)return T.lastInsertRowid;let[I]=await J.unsafe("SELECT last_insert_rowid() as id").execute();return I?.id}let[P]=await J.unsafe(`INSERT INTO ${q} (${w}) VALUES ${K} RETURNING ${E$(String(D))} as id`,V).execute();return P?.id},async updateOrInsert(W,Q,D){let w=E$(String(W)),K=Object.keys(Q),V=1,q=K.map((S)=>`${E$(S)} = ${l(V++)}`).join(" AND "),P=K.map((S)=>Q[S]);if((await J.unsafe(`SELECT 1 FROM ${w} WHERE ${q} LIMIT 1`,P).execute()).length){let S=Object.keys(D),x=1,u=S.map((y)=>`${E$(y)} = ${l(x++)}`).join(", "),r=K.map((y)=>`${E$(y)} = ${l(x++)}`).join(" AND "),o=[...S.map((y)=>D[y]),...K.map((y)=>Q[y])];return await J.unsafe(`UPDATE ${w} SET ${u} WHERE ${r}`,o).execute(),!0}let{colsSql:I,valuesSql:B,params:N}=pH([{...Q,...D}]);return await J.unsafe(`INSERT INTO ${w} (${I}) VALUES ${B}`,N).execute(),!0},async upsert(W,Q,D,w){let K=D.map((u)=>String(u)),V=(w??[]).map((u)=>String(u)),q=Q;if(!q.length)return;let{colsSql:P,valuesSql:T,params:I}=pH(q),B=E$(String(W)),N=`INSERT INTO ${B} (${P}) VALUES ${T}`;if(A0(g.dialect)){if(V.length===0)return J.unsafe(`INSERT IGNORE INTO ${B} (${P}) VALUES ${T}`,I).execute();let u=V.map((r)=>`${E$(r)} = VALUES(${E$(r)})`).join(", ");return J.unsafe(`${N} ON DUPLICATE KEY UPDATE ${u}`,I).execute()}let S=K.map(E$).join(", ");if(V.length===0)return J.unsafe(`${N} ON CONFLICT (${S}) DO NOTHING`,I).execute();let x=V.map((u)=>`${E$(u)} = EXCLUDED.${E$(u)}`).join(", ");return J.unsafe(`${N} ON CONFLICT (${S}) DO UPDATE SET ${x}`,I).execute()},async save(W,Q){let D=G?.primaryKeys[String(W)]??"id",w=Q[D];if(w!=null)if(await this.selectFrom(W).find(w)){await this.updateTable(W).set(Q).where({[D]:w}).execute();let V=await this.selectFrom(W).find(w);if(!V)throw Error("save() failed to retrieve updated row");return V}else return await this.create(W,Q);return await this.create(W,Q)},async remove(W,Q){return await this.deleteFrom(W).where({id:Q}).execute()},async find(W,Q){return await this.selectFrom(W).find(Q)},async findOrFail(W,Q){return await this.selectFrom(W).findOrFail(Q)},async findMany(W,Q){return await this.selectFrom(W).findMany(Q)},async latest(W,Q){return await this.selectFrom(W).latest(Q).first()},async oldest(W,Q){return await this.selectFrom(W).oldest(Q).first()},skip(W,Q){return this.selectFrom(W).offset(Q)},async rawQuery(W){let Q=Date.now();try{z()?.onQueryStart?.({sql:W,kind:"raw"});let D=await J.unsafe(W);return z()?.onQueryEnd?.({sql:W,durationMs:Date.now()-Q,kind:"raw"}),D}catch(D){throw z()?.onQueryError?.({sql:W,error:D,durationMs:Date.now()-Q,kind:"raw"}),D}},async create(W,Q){let D=G?.primaryKeys[String(W)]??"id";try{await z()?.beforeCreate?.({table:String(W),data:Q})}catch(w){throw w}if(g.dialect==="postgres"){let w=J`INSERT INTO ${J(String(W))} ${J(Q)} RETURNING ${J(String(D))} as id`,[K]=await w.execute();if(!K?.id)throw console.error(`create() failed to get insert ID for table ${String(W)}`),console.error("Inserted values:",Q),Error(`create() failed to get insert ID for table ${String(W)}`);let V=await this.selectFrom(W).find(K.id);if(!V)throw console.error(`create() failed to retrieve inserted row for table ${String(W)} with id ${K.id}`),console.error("Inserted values:",Q),Error(`create() failed to retrieve inserted row for table ${String(W)} with id ${K.id}`);try{await z()?.afterCreate?.({table:String(W),data:Q,result:V})}catch{}return V}else{let w=await this.insertGetId(W,Q,D);if(w==null)throw Error(`create() failed to get insert ID for table ${String(W)}`);let K=await this.selectFrom(W).find(w);if(!K)throw console.error(`create() failed to retrieve inserted row for table ${String(W)} with id ${w}`),console.error("Inserted values:",Q),Error(`create() failed to retrieve inserted row for table ${String(W)} with id ${w}`);try{await z()?.afterCreate?.({table:String(W),data:Q,result:K})}catch{}return K}},async createMany(W,Q){if(!Q?.length)return;let D=Q[0],w=Object.keys(D),K=w.length,V=Q.length,q=Array.from({length:V*K}),P=A0(g.dialect)?(B)=>`\`${String(B).replace(/`/g,"``")}\``:(B)=>`"${String(B).replace(/"/g,'""')}"`,T=`INSERT INTO ${P(String(W))}(${w.map(P).join(",")})VALUES`,I=0;for(let B=0;B<V;B++){if(B>0)T+=",";T+="(";let N=Q[B];for(let S=0;S<K;S++){if(S>0)T+=",";T+=l(I+1),q[I++]=N[w[S]]}T+=")"}return J.unsafe(T,q).execute()},async insertMany(W,Q){if(!Q?.length)return;let D=Q[0],w=Object.keys(D),K=w.length,V=Q.length,q=V*K,P=Array(q),T=g.dialect==="postgres",I;if(!T){let S=Array(K);for(let x=0;x<K;x++)S[x]="?";I=`(${S.join(",")})`}else I="";let B=Array(V+2);B[0]=`INSERT INTO ${W}(${w.join(",")})VALUES`;let N=0;if(!T){for(let S=0;S<V;S++){let x=Q[S];B[S+1]=I;for(let u=0;u<K;u++)P[N++]=x[w[u]]}return J.unsafe(B[0]+B.slice(1,V+1).join(","),P).execute()}for(let S=0;S<V;S++){let x=Q[S],u=Array(K);for(let r=0;r<K;r++)u[r]=`$${N+1}`,P[N++]=x[w[r]];B[S+1]=`(${u.join(",")})`}return J.unsafe(B[0]+B.slice(1,V+1).join(","),P).execute()},async updateMany(W,Q,D){let w=Object.keys(D),K=w.length;if(K===0)return 0;let V=[],q=Array.from({length:K});for(let T=0;T<K;T++)q[T]=`${w[T]}=${l(T+1)}`,V.push(D[w[T]]);let P=`UPDATE ${W} SET ${q.join(",")}`;if(Array.isArray(Q))P+=` WHERE ${Q[0]}${Q[1]}${l(V.length+1)}`,V.push(Q[2]);else if(Q&&typeof Q==="object"&&!("raw"in Q)){let T=Object.keys(Q),I=T.length;if(I>0){let B=V.length,N=Array.from({length:I});for(let S=0;S<I;S++)N[S]=`${T[S]}=${l(B+S+1)}`,V.push(Q[T[S]]);P+=` WHERE ${N.join(" AND ")}`}}return J.unsafe(P,V).execute()},async deleteMany(W,Q){if(!Array.isArray(Q)||Q.length===0)return 0;let D=G?.primaryKeys[String(W)]??"id",w=Q.length;if(g.dialect==="postgres"){let V=Array(w);for(let q=0;q<w;q++)V[q]=`$${q+1}`;return J.unsafe(`DELETE FROM ${W} WHERE ${D} IN (${V.join(",")})`,Q).execute()}let K=Array(w);for(let V=0;V<w;V++)K[V]="?";return J.unsafe(`DELETE FROM ${W} WHERE ${D} IN (${K.join(",")})`,Q).execute()},async firstOrCreate(W,Q,D){let w=await this.selectFrom(W).where(Q).first();if(w)return w;return await this.create(W,{...Q,...D})},async updateOrCreate(W,Q,D){let w=await this.selectFrom(W).where(Q).first();if(w){await this.updateTable(W).set(D).where(Q).execute();let K=G?.primaryKeys[String(W)]??"id",V=w[K],q=V!=null?await this.selectFrom(W).find(V):await this.selectFrom(W).where(Q).first();if(!q)throw Error("updateOrCreate() failed to retrieve updated row");return q}return await this.create(W,{...Q,...D})},async count(W,Q){let D=Q?J(String(Q)):J`*`,w=J`SELECT COUNT(${D}) as c FROM ${J(String(W))}`,[K]=await w.execute();return Number(K?.c??0)},async sum(W,Q){let D=J`SELECT SUM(${J(String(Q))}) as s FROM ${J(String(W))}`,[w]=await D.execute();return Number(w?.s??0)},async avg(W,Q){let D=J`SELECT AVG(${J(String(Q))}) as a FROM ${J(String(W))}`,[w]=await D.execute();return Number(w?.a??0)},async min(W,Q){let D=J`SELECT MIN(${J(String(Q))}) as m FROM ${J(String(W))}`,[w]=await D.execute();return w?.m},async max(W,Q){let D=J`SELECT MAX(${J(String(Q))}) as m FROM ${J(String(W))}`,[w]=await D.execute();return w?.m},getRelationships(W){if(!G?.relations)return{};let Q=G.relations[W];if(!Q)return{};let D={};for(let[w,K]of Object.entries(Q))if(K&&typeof K==="object"&&Object.keys(K).length>0)D[w]=K;return D},hasRelationship(W,Q){if(!G?.relations)return!1;let D=G.relations[W];if(!D)return!1;return Object.values(D).some((w)=>w&&typeof w==="object"&&(Q in w))},getRelationshipType(W,Q){if(!G?.relations)return null;let D=G.relations[W];if(!D)return null;for(let[w,K]of Object.entries(D))if(K&&typeof K==="object"&&Q in K)return w;return null},getRelationshipTarget(W,Q){if(!G?.relations)return null;let D=G.relations[W];if(!D)return null;for(let[w,K]of Object.entries(D))if(K&&typeof K==="object"&&Q in K){let V=K[Q];if(typeof V==="string")return G.modelToTable[V]||V;else if(V&&typeof V==="object"){if("model"in V)return G.modelToTable[V.model]||V.model;if("target"in V)return G.modelToTable[V.target]||V.target}}return null}}}function Z6(){nH.clear()}function E6($){nH.setMaxSize($)}var F0,U6,Y6,nH,iH,RX=500;var zG=a(()=>{m0();j1();lA();F0={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},U6=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);Y6=new Set;nH=new h6;iH=new Map});async function sA(){console.log("-- Clearing query cache..."),Z6(),console.log("-- \u2713 Query cache cleared")}async function oA(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function tA($={}){if(console.log("-- Configuring query cache..."),console.log(),$.size!==void 0){let J=Number($.size);if(Number.isNaN(J)||J<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");E6(J),console.log(`-- \u2713 Cache max size set to: ${J}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}var aA=a(()=>{zG()});import rH from"process";import{createInterface as VX}from"readline";async function lH(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let $=z0(),J=VX({input:rH.stdin,output:rH.stdout,prompt:"qb> "}),G="",H=!1,A=`
81
- Available Commands:
82
- .help Show this help message
83
- .exit Exit the console
84
- .tables List all tables
85
- .clear Clear the screen
86
-
87
- Query Examples:
88
- qb.selectFrom('users').where({ active: true }).limit(10).execute()
89
- qb.selectFrom('users').count()
90
- qb.insertInto('users').values({ name: 'John' }).execute()
91
- qb.selectFrom('users').where('id', '=', 1).first()
92
- qb.unsafe("SELECT * FROM users WHERE id = $1", [1]).execute()
93
-
94
- Tips:
95
- - Use 'qb' to access the query builder
96
- - Use 'await' for async operations
97
- - Multi-line input: end with \\ to continue on next line
98
- - Press Enter on an empty line to execute multi-line input
99
- `,z=async(h)=>{try{let E=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${h})`)($);if(E!==void 0)if(Array.isArray(E))console.log(`-- ${E.length} row(s) returned`),console.table(E);else if(typeof E==="object"&&E!==null)console.log(E);else console.log(E)}catch(Y){console.error("Error:",Y.message)}},U=async(h)=>{let Y=h.trim();if(Y.startsWith(".")){let Z=Y.toLowerCase();if(Z===".exit"||Z===".quit")console.log("Goodbye!"),J.close(),rH.exit(0);else if(Z===".help")console.log(A);else if(Z===".clear")console.clear();else if(Z===".tables")try{let E=await $.unsafe(`
100
- SELECT name FROM sqlite_master
101
- WHERE type = 'table'
102
- AND name NOT LIKE 'sqlite_%'
103
- ORDER BY name
104
- `);if(E.length>0){console.log("Tables:");for(let X of E)console.log(` - ${X.name}`)}else console.log("No tables found")}catch(E){console.error("Error listing tables:",E.message)}else console.log(`Unknown command: ${Y}`),console.log("Type .help for available commands");return}if(Y.endsWith("\\")){H=!0,G+=`${Y.slice(0,-1)}
105
- `;return}if(H){if(Y==="")await z(G),G="",H=!1;else G+=`${Y}
106
- `;return}if(Y)await z(Y)};J.on("line",async(h)=>{await U(h),J.prompt()}),J.on("SIGINT",()=>{if(H)console.log(`
107
- -- Multi-line input cancelled`),G="",H=!1,J.prompt();else console.log(`
108
- -- Type .exit to quit`),J.prompt()}),J.on("close",()=>{console.log(`
109
- Goodbye!`),rH.exit(0)}),J.prompt()}async function eA(){return lH()}var $9=a(()=>{n0()});import{existsSync as OX,readFileSync as MX,writeFileSync as UG}from"fs";async function J9($,J={}){let G=J.format||"json",H=J.output||`${$}.${G}`,A=J.limit;if(console.log(`-- Exporting data from table: ${$}`),console.log(`-- Format: ${G}`),console.log(`-- Output: ${H}`),A)console.log(`-- Limit: ${A} rows`);console.log();try{let U=z0().selectFrom($);if(A)U=U.limit(A);let h=await U.execute();if(console.log(`-- Retrieved ${h.length} rows`),G==="json")UG(H,JSON.stringify(h,null,2)),console.log(`-- \u2713 Exported to JSON: ${H}`);else if(G==="csv"){if(h.length===0){UG(H,""),console.log(`-- \u2713 Exported to CSV: ${H} (empty)`);return}let Y=Object.keys(h[0]),Z=[Y.join(",")];for(let E of h){let X=Y.map((F)=>{let R=E[F];if(R===null||R===void 0)return"";let C=String(R);if(C.includes(",")||C.includes('"')||C.includes(`
110
- `))return`"${C.replace(/"/g,'""')}"`;return C});Z.push(X.join(","))}UG(H,Z.join(`
111
- `)),console.log(`-- \u2713 Exported to CSV: ${H}`)}else if(G==="sql"){let Y=[];for(let Z of h){let E=Object.keys(Z),X=E.map((F)=>{let R=Z[F];if(R===null||R===void 0)return"NULL";if(typeof R==="number")return String(R);return`'${String(R).replace(/'/g,"''")}'`});Y.push(`INSERT INTO ${$} (${E.join(", ")}) VALUES (${X.join(", ")});`)}UG(H,Y.join(`
112
- `)),console.log(`-- \u2713 Exported to SQL: ${H}`)}}catch(z){throw console.error(`-- Failed to export data from ${$}:`,z),z}}async function G9($,J,G={}){if(!OX(J))throw console.error(`-- File not found: ${J}`),Error(`File not found: ${J}`);let H=G.format||(J.endsWith(".json")?"json":"csv"),A=G.truncate??!1;console.log(`-- Importing data into table: ${$}`),console.log(`-- Format: ${H}`),console.log(`-- File: ${J}`),console.log(`-- Truncate: ${A}`),console.log();try{let z=z0();if(A)await z.deleteFrom($).execute(),console.log("-- Table truncated");let U=MX(J,"utf8"),h=[];if(H==="json"){if(h=JSON.parse(U),!Array.isArray(h))throw TypeError("JSON file must contain an array of objects")}else if(H==="csv"){let E=U.split(`
113
- `).filter((F)=>F.trim());if(E.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let X=E[0].split(",").map((F)=>F.trim());for(let F=1;F<E.length;F++){let R=E[F].split(",").map((W)=>W.trim()),C={};for(let W=0;W<X.length;W++){let Q=R[W];if(Q.startsWith('"')&&Q.endsWith('"'))Q=Q.slice(1,-1).replace(/""/g,'"');if(Q==="")Q=null;else if(!Number.isNaN(Number(Q)))Q=Number(Q);C[X[W]]=Q}h.push(C)}}if(h.length===0){console.log("-- No data to import");return}let Y=100,Z=0;for(let E=0;E<h.length;E+=Y){let X=h.slice(E,E+Y);await z.insertInto($).values(X).execute(),Z+=X.length,console.log(`-- Imported ${Z}/${h.length} rows...`)}console.log(`-- \u2713 Successfully imported ${h.length} rows`)}catch(z){throw console.error(`-- Failed to import data into ${$}:`,z),z}}async function H9($={}){let J=g.dialect||"postgres",G=$.output||`dump-${Date.now()}.sql`,H=$.tables?.split(",").map((A)=>A.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${J}`),console.log(`-- Output: ${G}`),H)console.log(`-- Tables: ${H.join(", ")}`);console.log();try{let A=z0(),z=[];if(J==="sqlite")z=(await A.unsafe(`
114
- SELECT name FROM sqlite_master
115
- WHERE type = 'table'
116
- AND name NOT LIKE 'sqlite_%'
117
- ORDER BY name
118
- `)).map((Y)=>Y.name);else if(J==="postgres")z=(await A.unsafe(`
119
- SELECT table_name
120
- FROM information_schema.tables
121
- WHERE table_schema = 'public'
122
- AND table_type = 'BASE TABLE'
123
- ORDER BY table_name
124
- `)).map((Y)=>Y.table_name);else if(A0(J))z=(await A.unsafe(`
125
- SELECT table_name
126
- FROM information_schema.tables
127
- WHERE table_schema = DATABASE()
128
- AND table_type = 'BASE TABLE'
129
- ORDER BY table_name
130
- `)).map((Y)=>Y.table_name);if(H)z=z.filter((h)=>H.includes(h));if(z.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${z.length} table(s)`);let U=[];U.push("-- Database dump"),U.push(`-- Generated at: ${new Date().toISOString()}`),U.push(`-- Dialect: ${J}`),U.push("");for(let h of z){console.log(`-- Dumping table: ${h}`);let Y=await A.selectFrom(h).execute();U.push(`-- Table: ${h}`),U.push(`-- Rows: ${Y.length}`),U.push("");for(let Z of Y){let E=Object.keys(Z),X=E.map((F)=>{let R=Z[F];if(R===null||R===void 0)return"NULL";if(typeof R==="number")return String(R);return`'${String(R).replace(/'/g,"''")}'`});U.push(`INSERT INTO ${h} (${E.join(", ")}) VALUES (${X.join(", ")});`)}U.push("")}UG(G,U.join(`
131
- `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${G}`)}catch(A){throw console.error("-- Failed to dump database:",A),A}}var A9=a(()=>{m0();zG()});async function sH(){let $=g.dialect||"postgres",J=g.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${$}`),console.log(`-- Database: ${J}`),console.log();try{let G=z0(),H=[],A=[];if($==="postgres")A=(await G.unsafe(`
132
- SELECT table_name
133
- FROM information_schema.tables
134
- WHERE table_schema = 'public'
135
- AND table_type = 'BASE TABLE'
136
- ORDER BY table_name
137
- `)).map((h)=>h.table_name);else if(A0($))A=(await G.unsafe(`
138
- SELECT table_name
139
- FROM information_schema.tables
140
- WHERE table_schema = DATABASE()
141
- AND table_type = 'BASE TABLE'
142
- ORDER BY table_name
143
- `)).map((h)=>h.table_name);else if($==="sqlite")A=(await G.unsafe(`
144
- SELECT name
145
- FROM sqlite_master
146
- WHERE type = 'table'
147
- AND name NOT LIKE 'sqlite_%'
148
- ORDER BY name
149
- `)).map((h)=>h.name);for(let U of A)try{let h=await G.unsafe(`SELECT COUNT(*) as count FROM ${U}`),Y=Number(h[0]?.count||0),Z=0,E=0;if($==="postgres"){let X=await G.unsafe(`
150
- SELECT COUNT(*) as count
151
- FROM information_schema.columns
152
- WHERE table_name = $1
153
- `,[U]);Z=Number(X[0]?.count||0);let F=await G.unsafe(`
154
- SELECT COUNT(*) as count
155
- FROM pg_indexes
156
- WHERE tablename = $1
157
- `,[U]);E=Number(F[0]?.count||0)}else if(A0($)){let X=await G.unsafe(`
158
- SELECT COUNT(*) as count
159
- FROM information_schema.columns
160
- WHERE table_name = ?
161
- AND table_schema = DATABASE()
162
- `,[U]);Z=Number(X[0]?.count||0);let F=await G.unsafe(`
163
- SELECT COUNT(*) as count
164
- FROM information_schema.statistics
165
- WHERE table_name = ?
166
- AND table_schema = DATABASE()
167
- `,[U]);E=Number(F[0]?.count||0)}else if($==="sqlite")Z=(await G.unsafe(`PRAGMA table_info(${U})`)).length,E=(await G.unsafe(`PRAGMA index_list(${U})`)).length;H.push({name:U,rowCount:Y,columns:Z,indexes:E})}catch(h){console.error(`-- Error getting info for table ${U}:`,h)}let z=H.reduce((U,h)=>U+h.rowCount,0);if(console.log(`-- Total Tables: ${H.length}`),console.log(`-- Total Rows: ${z.toLocaleString()}`),console.log(),H.length>0){console.log("Tables:"),console.log();let U=Math.max(...H.map((Z)=>Z.name.length)),h=U+2,Y="Table".padEnd(h)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(Y),console.log("-".repeat(Y.length));for(let Z of H){let E=Z.name.padEnd(U+2),X=Z.rowCount.toLocaleString().padStart(12),F=(Z.columns||0).toString().padStart(10),R=(Z.indexes||0).toString().padStart(10);console.log(`${E}${X}${F}${R}`)}}else console.log("-- No tables found");return{dialect:$,database:J,tables:H,totalTables:H.length,totalRows:z}}catch(G){throw console.error("-- Failed to get database info:",G),G}}async function z9(){return sH()}var U9=a(()=>{m0();n0()});async function oH($={}){let J=gH($.dialect),G=$.aggressive||!1;if($.verbose)console.log(`Optimizing ${J} database${G?" (aggressive mode)":""}...`);try{if(J==="postgres"){if($.tables&&$.tables.length>0)for(let H of $.tables){if($.verbose)console.log(`Analyzing table: ${H}`);if(G)await $0`VACUUM FULL ANALYZE ${$0(H)}`;else await $0`VACUUM ANALYZE ${$0(H)}`}else{if($.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(G)await $0`VACUUM FULL`,await $0`ANALYZE`;else await $0`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(A0(J)){if($.tables&&$.tables.length>0)for(let H of $.tables){if($.verbose)console.log(`Optimizing table: ${H}`);await $0`OPTIMIZE TABLE ${$0(H)}`,await $0`ANALYZE TABLE ${$0(H)}`}else{let H=cH(),A=await $0`
168
- SELECT table_name
169
- FROM information_schema.tables
170
- WHERE table_schema = ${H}
171
- `;for(let z of A){let U=z.table_name||z.TABLE_NAME;if($.verbose)console.log(`Optimizing table: ${U}`);await $0`OPTIMIZE TABLE ${$0(U)}`,await $0`ANALYZE TABLE ${$0(U)}`}}console.log("\u2713 MySQL optimization complete")}else if(J==="sqlite"){if($.verbose)console.log("Running VACUUM on SQLite database...");if(await $0`VACUUM`,$.tables&&$.tables.length>0)for(let H of $.tables){if($.verbose)console.log(`Analyzing table: ${H}`);await $0`ANALYZE ${$0(H)}`}else await $0`ANALYZE`;if(G){if($.verbose)console.log("Running aggressive SQLite optimizations...");await $0`PRAGMA optimize`,await $0`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${J}`)}catch(H){throw console.error("Error optimizing database:",H.message),H}}var Y9=a(()=>{m0();j1()});async function tH($={}){let J=gH($.dialect);if($.verbose)console.log(`Wiping all tables from ${J} database...`);try{let G=[];if(J==="postgres")G=(await $0`
172
- SELECT tablename
173
- FROM pg_tables
174
- WHERE schemaname = 'public'
175
- `).map((A)=>A.tablename);else if(A0(J)){let H=cH();G=(await $0`
176
- SELECT table_name
177
- FROM information_schema.tables
178
- WHERE table_schema = ${H}
179
- `).map((z)=>z.table_name||z.TABLE_NAME)}else if(J==="sqlite")G=(await $0`
180
- SELECT name
181
- FROM sqlite_master
182
- WHERE type = 'table'
183
- AND name NOT LIKE 'sqlite_%'
184
- `).map((A)=>A.name);if(G.length===0){console.log("No tables found to drop.");return}if($.verbose)console.log(`Found ${G.length} tables: ${G.join(", ")}`);if(J==="postgres")for(let H of G){if($.verbose)console.log(`Dropping table: ${H}`);await $0`DROP TABLE IF EXISTS ${$0(H)} CASCADE`}else if(A0(J)){await $0`SET FOREIGN_KEY_CHECKS = 0`;for(let H of G){if($.verbose)console.log(`Dropping table: ${H}`);await $0`DROP TABLE IF EXISTS ${$0(H)}`}await $0`SET FOREIGN_KEY_CHECKS = 1`}else if(J==="sqlite"){await $0`PRAGMA foreign_keys = OFF`;for(let H of G){if($.verbose)console.log(`Dropping table: ${H}`);await $0`DROP TABLE IF EXISTS ${$0(H)}`}await $0`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${G.length} tables`)}catch(G){throw console.error("Error wiping database:",G.message),G}}var h9=a(()=>{m0();j1()});async function Z9($){let H=await(z0().raw([$]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(H,null,2)),H}var X6=a(()=>{n0()});async function E9($,J={}){let G=z0(),H=J.params?JSON.parse(J.params):void 0,A=await G.file($,H);return console.log(JSON.stringify(A)),A}var j6=a(()=>{n0()});async function aH($,J={}){let G=g.dialect||"postgres",H=J.verbose??!0;if(H)console.log(`-- Inspecting table: ${$}`),console.log(`-- Dialect: ${G}`),console.log();try{let A=z0(),z=[],U=[],h=await A.unsafe(`SELECT COUNT(*) as count FROM ${$}`),Y=Number(h[0]?.count||0);if(G==="postgres"){let Z=await A.unsafe(`
185
- SELECT
186
- c.column_name,
187
- c.data_type,
188
- c.is_nullable,
189
- c.column_default,
190
- CASE
191
- WHEN pk.column_name IS NOT NULL THEN true
192
- ELSE false
193
- END as is_primary_key,
194
- CASE
195
- WHEN fk.column_name IS NOT NULL THEN true
196
- ELSE false
197
- END as is_foreign_key
198
- FROM information_schema.columns c
199
- LEFT JOIN (
200
- SELECT ku.column_name
201
- FROM information_schema.table_constraints tc
202
- JOIN information_schema.key_column_usage ku
203
- ON tc.constraint_name = ku.constraint_name
204
- WHERE tc.constraint_type = 'PRIMARY KEY'
205
- AND tc.table_name = $1
206
- ) pk ON c.column_name = pk.column_name
207
- LEFT JOIN (
208
- SELECT ku.column_name
209
- FROM information_schema.table_constraints tc
210
- JOIN information_schema.key_column_usage ku
211
- ON tc.constraint_name = ku.constraint_name
212
- WHERE tc.constraint_type = 'FOREIGN KEY'
213
- AND tc.table_name = $1
214
- ) fk ON c.column_name = fk.column_name
215
- WHERE c.table_name = $1
216
- ORDER BY c.ordinal_position
217
- `,[$]);for(let X of Z)z.push({name:X.column_name,type:X.data_type,nullable:X.is_nullable==="YES",default:X.column_default,isPrimaryKey:X.is_primary_key,isForeignKey:X.is_foreign_key});let E=await A.unsafe(`
218
- SELECT
219
- i.indexname as name,
220
- i.indexdef,
221
- ix.indisunique as is_unique
222
- FROM pg_indexes i
223
- JOIN pg_class c ON c.relname = i.indexname
224
- JOIN pg_index ix ON ix.indexrelid = c.oid
225
- WHERE i.tablename = $1
226
- `,[$]);for(let X of E){let F=X.indexdef?.match(/\(([^)]+)\)/),C=(F?F[1]:"").split(",").map((W)=>W.trim());U.push({name:X.name,columns:C,unique:X.is_unique})}}else if(A0(G)){let Z=await A.unsafe(`
227
- SELECT
228
- COLUMN_NAME as column_name,
229
- DATA_TYPE as data_type,
230
- IS_NULLABLE as is_nullable,
231
- COLUMN_DEFAULT as column_default,
232
- COLUMN_KEY as column_key
233
- FROM information_schema.COLUMNS
234
- WHERE TABLE_NAME = ?
235
- AND TABLE_SCHEMA = DATABASE()
236
- ORDER BY ORDINAL_POSITION
237
- `,[$]);for(let F of Z)z.push({name:F.column_name,type:F.data_type,nullable:F.is_nullable==="YES",default:F.column_default,isPrimaryKey:F.column_key==="PRI",isForeignKey:F.column_key==="MUL"});let E=await A.unsafe(`
238
- SHOW INDEXES FROM ${$}
239
- `),X=new Map;for(let F of E){let R=F.Key_name;if(!X.has(R))X.set(R,{columns:[],unique:F.Non_unique===0});X.get(R).columns.push(F.Column_name)}for(let[F,R]of X)U.push({name:F,columns:R.columns,unique:R.unique})}else if(G==="sqlite"){let Z=await A.unsafe(`PRAGMA table_info(${$})`);for(let X of Z)z.push({name:X.name,type:X.type,nullable:X.notnull===0,default:X.dflt_value,isPrimaryKey:X.pk===1});let E=await A.unsafe(`PRAGMA index_list(${$})`);for(let X of E){let F=await A.unsafe(`PRAGMA index_info(${X.name})`);U.push({name:X.name,columns:F.map((R)=>R.name),unique:X.unique===1})}}if(H){console.log(`Table: ${$}`),console.log(`Rows: ${Y.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let Z=Math.max(...z.map((C)=>C.name.length),10),E=Math.max(...z.map((C)=>C.type.length),10),X=Z+2,F=E+2,R=`${"Name".padEnd(X)+"Type".padEnd(F)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(R),console.log("-".repeat(R.length));for(let C of z){let W=C.name.padEnd(X),Q=C.type.padEnd(F),D=(C.nullable?"YES":"NO").padEnd(10),w=String(C.default||"").padEnd(20),K=[C.isPrimaryKey?"PK":"",C.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${W}${Q}${D}${w}${K}`)}if(console.log(),U.length>0){console.log("Indexes:"),console.log();for(let C of U){let W=C.unique?" (UNIQUE)":"";console.log(` - ${C.name}${W}: [${C.columns.join(", ")}]`)}console.log()}}return{tableName:$,rowCount:Y,columns:z,indexes:U}}catch(A){throw console.error(`-- Failed to inspect table ${$}:`,A),A}}async function X9($,J={}){return aH($,J)}var j9=a(()=>{m0();n0()});async function W9($,J={}){let G=await P$({modelsDir:$}),H=eH(G);return console.log(JSON.stringify(H,null,2)),{models:G,schema:H}}var W6=a(()=>{n0()});function F6($){let J=$.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(J))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(J))return"number";if(/timestamp|datetime|date|time/.test(J))return"datetime";if(/json/.test(J))return"json";return"string"}function KX($){if(/ies$/i.test($))return $.replace(/ies$/i,"y");if(/ses$/i.test($))return $.replace(/es$/i,"");if(/s$/i.test($)&&!/ss$/i.test($))return $.replace(/s$/i,"");return $}function BX($){return $.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}function F9($){return BX(KX($))}async function L6($,J){if(J==="postgres")return(await $.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((A)=>A.table_name);if(A0(J))return(await $.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((A)=>A.table_name??A.TABLE_NAME);return(await $.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((H)=>H.name)}async function CX($,J,G){if(J==="sqlite")return(await $.unsafe(`PRAGMA table_info(${G})`)).map((z)=>({name:z.name,sqlType:String(z.type||""),nullable:Number(z.notnull)===0,isPrimaryKey:Number(z.pk)>0}));if(J==="postgres")return(await $.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
240
- (SELECT COUNT(*) FROM information_schema.table_constraints tc
241
- JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
242
- WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
243
- FROM information_schema.columns c
244
- WHERE c.table_name = $1 AND c.table_schema = 'public'
245
- ORDER BY c.ordinal_position`,[G])).map((z)=>({name:z.column_name,sqlType:String(z.data_type||""),nullable:String(z.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(z.is_pk)>0}));return(await $.unsafe(`SELECT column_name, data_type, is_nullable, column_key
246
- FROM information_schema.columns
247
- WHERE table_name = ? AND table_schema = DATABASE()
248
- ORDER BY ordinal_position`,[G])).map((A)=>({name:A.column_name??A.COLUMN_NAME,sqlType:String(A.data_type??A.DATA_TYPE??""),nullable:String(A.is_nullable??A.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(A.column_key??A.COLUMN_KEY).toUpperCase()==="PRI"}))}function w6($,J){let G=F9($),H=J.find((z)=>z.isPrimaryKey)?.name??"id",A=J.map((z)=>{let U=[`type: '${F6(z.sqlType)}'`];if(!z.nullable&&!z.isPrimaryKey)U.push("required: true");return` ${z.name}: { ${U.join(", ")} },`}).join(`
249
- `);return`export const ${G} = defineModel({
250
- name: '${G}',
251
- table: '${$}',
252
- primaryKey: '${H}',
253
- attributes: {
254
- ${A}
255
- },
256
- })
257
- `}async function YG($={}){let J=g.dialect||"postgres",G=z0(),H=$.tables?.length?$.tables:await L6(G,J),A=[];for(let z of H){let U=await CX(G,J,z);if(!U.length)continue;A.push({table:z,modelName:F9(z),primaryKey:U.find((h)=>h.isPrimaryKey)?.name??"id",columns:U,source:w6(z,U)})}return A}function L9($,J,G){if(G?.enumValues&&G.enumValues.length>0)return"enum";let H=String($||"").toLowerCase().trim(),A=H.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(A0(J)&&/^tinyint\(1\)/.test(H))return"boolean";if(/^bool/.test(A))return"boolean";if(A==="int8"||A==="bigint"||A==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(A))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(A)){let z=H.match(/\((\d+)\)/),U=z?Number(z[1]):void 0;if(A0(J))return"string";return U!==void 0&&U>255?"text":"string"}if(/text|clob/.test(A))return"text";if(A==="float8"||/^double/.test(A))return"double";if(/^(?:real|float4|float)/.test(A))return"float";if(/^(?:numeric|decimal|money)/.test(A))return"decimal";if(A==="date")return"date";if(A==="timestamptz"||/\bwith time zone\b/.test(H))return"timestamptz";if(/^(?:timestamp|datetime)/.test(A))return"datetime";if(/^time/.test(A))return"string";if(/json/.test(A))return"json";if(/^enum/.test(A))return"enum";return"string"}function IX($,J,G){return L9(String(J||$||""),"mysql",{enumValues:G})}function SX($){let J=String($||"").trim().match(/^varchar\((\d+)\)/i);if(!J)return;let G=Number(J[1]);return Number.isSafeInteger(G)&&G>0?G:void 0}function zJ($){let J=String($??"").toLowerCase().trim();if(J==="cascade"||J==="restrict"||J==="set null")return J;return}async function _X($,J){let G=await $.unsafe(`PRAGMA table_info(${JSON.stringify(J)})`),H=await $.unsafe(`PRAGMA index_list(${JSON.stringify(J)})`),A=await $.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(J)})`),z=await $.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[J]),U=String(z?.[0]?.sql??""),h=new Map;for(let X of A)h.set(String(X.from),{table:String(X.table),column:String(X.to??"id"),onDelete:zJ(X.on_delete),onUpdate:zJ(X.on_update)});let Y=[],Z=new Set;for(let X of H){let F=String(X.origin??""),R=String(X.name??"");if(F==="pk"||R.startsWith("sqlite_autoindex_"))continue;let W=(await $.unsafe(`PRAGMA index_info(${JSON.stringify(R)})`)).map((D)=>String(D.name)).filter(Boolean);if(W.length===0)continue;let Q=Number(X.unique)===1;if(Q&&W.length===1)Z.add(W[0]);Y.push({name:R,columns:W,type:Q?"unique":"index"})}let E=G.map((X)=>{let F=String(X.name),R=PX(U,F),C=Number(X.pk)>0,W=X.dflt_value,Q=W!==null&&W!==void 0;return{name:F,type:L9(String(X.type??""),"sqlite",{enumValues:R}),isPrimaryKey:C,isUnique:Z.has(F),isNullable:C?!1:Number(X.notnull)===0,hasDefault:Q,defaultValue:Q?w9(W):void 0,enumValues:R,references:h.get(F)}});return{table:J,columns:E,indexes:Y}}function PX($,J){if(!$)return;let G=new RegExp(`(?:"${J}"|\`${J}\`|\\b${J}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),H=$.match(G);if(!H)return;let A=H[1].split(",").map((z)=>z.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((z)=>z.length>0);return A.length>0?A:void 0}function w9($){if(typeof $==="number"||typeof $==="boolean")return $;return String($)}async function R6($){let J=await $.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
258
- FROM pg_type t
259
- JOIN pg_enum e ON e.enumtypid = t.oid
260
- JOIN pg_namespace n ON n.oid = t.typnamespace
261
- WHERE n.nspname = 'public'
262
- ORDER BY t.typname, e.enumsortorder`),G=new Map;for(let H of J){let A=String(H.type_name),z=G.get(A);if(z)z.push(String(H.label));else G.set(A,[String(H.label)])}return G}function NX($,J,G){let H=G.get(J),A=L9(String($||J||""),"postgres",{enumValues:H});return H?{type:A,enumValues:H,enumTypeName:J}:{type:A}}async function TX($,J,G){let H=G??await R6($),A=await $.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
263
- (SELECT COUNT(*) FROM information_schema.table_constraints tc
264
- JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
265
- WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
266
- FROM information_schema.columns c
267
- WHERE c.table_name = $1 AND c.table_schema = 'public'
268
- ORDER BY c.ordinal_position`,[J]),z=await $.unsafe(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
269
- a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
270
- pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
271
- FROM pg_class t
272
- JOIN pg_index ix ON t.oid = ix.indrelid
273
- JOIN pg_class i ON i.oid = ix.indexrelid
274
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
275
- WHERE t.relname = $1 AND t.relkind = 'r'
276
- ORDER BY i.relname, ord`,[J]),U=await $.unsafe(`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column,
277
- tc.constraint_name, rc.delete_rule, rc.update_rule
278
- FROM information_schema.table_constraints tc
279
- JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
280
- JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
281
- JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
282
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[J]),h=new Map,Y=new Map;for(let F of U){let R=String(F.constraint_name);Y.set(R,(Y.get(R)??0)+1)}for(let F of U){let R=String(F.column_name),C=h.get(R),W=String(F.constraint_name),Q=Y.get(W)===1?[...new Set([...C?.constraintNames??[],W])]:C?.constraintNames;h.set(R,C?{...C,constraintNames:Q}:{table:String(F.ref_table),column:String(F.ref_column??"id"),onDelete:zJ(F.delete_rule),onUpdate:zJ(F.update_rule),constraintNames:Q})}let{indexes:Z,uniqueColumns:E}=D6(J,z.map((F)=>({indexName:String(F.index_name),isUnique:F.is_unique===!0||F.is_unique==="t",isPrimary:F.is_primary===!0||F.is_primary==="t",column:String(F.column_name),where:F.where_clause?String(F.where_clause):void 0}))),X=A.map((F)=>{let R=String(F.column_name),C=Number(F.is_pk)>0,W=F.column_default==null?null:String(F.column_default),Q=W!=null&&/nextval\(/i.test(W),D=W!=null&&!Q;return{name:R,...NX(String(F.data_type??""),F.udt_name==null?"":String(F.udt_name),H),isPrimaryKey:C,isUnique:E.has(R),isNullable:C?!1:String(F.is_nullable).toUpperCase()==="YES",hasDefault:D,defaultValue:D?w9(W):void 0,references:h.get(R)}});return{table:J,columns:X,indexes:Z}}async function kX($,J){let G=await $.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
283
- FROM information_schema.columns
284
- WHERE table_name = ? AND table_schema = DATABASE()
285
- ORDER BY ordinal_position`,[J]),H=await $.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
286
- FROM information_schema.statistics
287
- WHERE table_name = ? AND table_schema = DATABASE()
288
- ORDER BY index_name, seq_in_index`,[J]),A=await $.unsafe(`SELECT kcu.column_name, kcu.referenced_table_name AS ref_table, kcu.referenced_column_name AS ref_column,
289
- kcu.constraint_name, rc.delete_rule, rc.update_rule
290
- FROM information_schema.key_column_usage kcu
291
- JOIN information_schema.referential_constraints rc
292
- ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
293
- WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[J]),z=new Map,U=new Map;for(let E of A){let X=String(E.constraint_name??E.CONSTRAINT_NAME);U.set(X,(U.get(X)??0)+1)}for(let E of A){let X=String(E.column_name??E.COLUMN_NAME),F=z.get(X),R=String(E.constraint_name??E.CONSTRAINT_NAME),C=U.get(R)===1?[...new Set([...F?.constraintNames??[],R])]:F?.constraintNames;z.set(X,F?{...F,constraintNames:C}:{table:String(E.ref_table??E.REF_TABLE),column:String(E.ref_column??E.REF_COLUMN??"id"),onDelete:zJ(E.delete_rule??E.DELETE_RULE),onUpdate:zJ(E.update_rule??E.UPDATE_RULE),constraintNames:C})}let{indexes:h,uniqueColumns:Y}=D6(J,H.map((E)=>({indexName:String(E.index_name??E.INDEX_NAME),isUnique:Number(E.non_unique??E.NON_UNIQUE)===0,isPrimary:String(E.index_name??E.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(E.column_name??E.COLUMN_NAME)}))),Z=G.map((E)=>{let X=String(E.column_name??E.COLUMN_NAME),F=String(E.column_type??E.COLUMN_TYPE??""),R=qX(F),W=String(E.column_key??E.COLUMN_KEY??"").toUpperCase()==="PRI",Q=E.column_default??E.COLUMN_DEFAULT,D=Q!=null;return{name:X,type:IX(E.data_type??E.DATA_TYPE,F,R),isPrimaryKey:W,isUnique:Y.has(X),isNullable:W?!1:String(E.is_nullable??E.IS_NULLABLE).toUpperCase()==="YES",hasDefault:D,defaultValue:D?w9(Q):void 0,enumValues:R,maxLength:SX(F),references:z.get(X)}});return{table:J,columns:Z,indexes:h}}function qX($){let J=$.match(/^enum\((.*)\)$/i);if(!J)return;return J[1].split(",").map((G)=>G.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((G)=>G.length>0)}function D6($,J){let G=new Map;for(let z of J){if(z.isPrimary)continue;let U=G.get(z.indexName)??{isUnique:z.isUnique,isPrimary:z.isPrimary,columns:[],where:z.where};U.columns.push(z.column),G.set(z.indexName,U)}let H=[],A=new Set;for(let[z,U]of G){if(U.columns.length===0)continue;if(U.isUnique&&U.columns.length===1)A.add(U.columns[0]);H.push({name:z,columns:U.columns,type:U.isUnique?"unique":"index",where:U.where})}return{indexes:H,uniqueColumns:A}}async function Q6($,J={}){let G=$||g.dialect||"postgres",H=z0(),z=((J.tables?.length)?J.tables:await L6(H,G)).filter((Y)=>Y!=="migrations"),U=G==="postgres"?await R6(H):void 0,h=[];for(let Y of z){let Z;if(G==="sqlite")Z=await _X(H,Y);else if(G==="postgres")Z=await TX(H,Y,U);else Z=await kX(H,Y);if(Z.columns.length>0)h.push(Z)}return{dialect:G,tables:h}}var $5=a(()=>{m0();n0()});import{existsSync as R9,mkdirSync as yX,writeFileSync as xX}from"fs";import{dirname as V6,join as D9}from"path";import O6 from"process";function fX($){let J=$;while(J!==V6(J)){if(R9(D9(J,"package.json")))return J;J=V6(J)}return O6.cwd()}async function Q9($,J={}){let G=fX(O6.cwd()),H=J.dir||D9(G,"app/Models");if(!R9(H))yX(H,{recursive:!0}),console.log(`-- Created models directory: ${H}`);let A=$.charAt(0).toUpperCase()+$.slice(1),z=J.table||`${$.toLowerCase()}s`,U=`${A}.ts`,h=D9(H,U);if(R9(h))throw console.error(`-- Model already exists: ${h}`),Error(`Model already exists: ${h}`);let Z=J.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
294
- updated_at: { validation: { rule: v.date() } },`:"",E=`import { v } from '@stacksjs/ts-validation'
295
- import { defineModel } from 'bun-query-builder'
296
-
297
- const model = defineModel({
298
- name: '${A}',
299
- table: '${z}',
300
- primaryKey: 'id',
301
- attributes: {
302
- id: { validation: { rule: v.integer() } },
303
- ${Z}
304
- // Add your model attributes here
305
- // Example:
306
- // name: { validation: { rule: v.string() } },
307
- // email: { unique: true, validation: { rule: v.string().email() } },
308
- // age: { default: 0, validation: { rule: v.number().min(0) } },
309
- },
310
- })
311
-
312
- export default model
313
- `;xX(h,E),console.log(`-- \u2713 Created model: ${h}`),console.log(`-- Table: ${z}`)}var V9=()=>{};function vX($){let J=2166136261;for(let G=0;G<$.length;G++)J^=$.charCodeAt(G),J=Math.imul(J,16777619)>>>0;return J.toString(36).padStart(7,"0").slice(-7)}function gX($,J=63){if($.length<=J)return $;let G=`_${vX($)}`;return $.slice(0,J-G.length)+G}function N$($,J){let G=`${$}_`,H=J.startsWith(G)?J:`${G}${J}`;return gX(H)}class r0{quoteIdentifier($){return`\`${$.replace(/`/g,"``")}\``}getColumnType($){switch($.type){case"string":return`varchar(${$.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if($.enumValues&&$.enumValues.length>0)return`ENUM(${$.enumValues.map((G)=>`'${G.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 J=$.defaultValue;if(typeof J==="string"){let G=J.toUpperCase();if(G==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(G))return`default ${G}`;let A=`'${J.replace(/'/g,"''")}'`;if($.type==="text"||$.type==="json"||$.type==="enum"&&!$.enumValues?.length)return`default (${A})`;return`default ${A}`}else if(typeof J==="number"||typeof J==="bigint")return`default ${J}`;else if(typeof J==="boolean")return`default ${J?1:0}`;else if(J instanceof Date)return`default '${J.toISOString()}'`;return""}createEnumType($,J){return""}foreignKeyClauses($){return $.columns.filter((J)=>J.references).map((J)=>{let G=J.references,H=`${$.table}_${J.name}_fk`,A=`CONSTRAINT ${this.quoteIdentifier(H)} FOREIGN KEY (${this.quoteIdentifier(J.name)}) REFERENCES ${this.quoteIdentifier(G.table)}(${this.quoteIdentifier(G.column)})`;if(G.onDelete)A+=` ON DELETE ${G.onDelete.toUpperCase()}`;if(G.onUpdate)A+=` ON UPDATE ${G.onUpdate.toUpperCase()}`;return A})}createTable($){let J=[...$.columns.map((G)=>this.renderColumn(G)),...this.foreignKeyClauses($)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
314
- ${J.join(`,
315
- `)}
316
- ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth($){let J=this.getColumnType($).toLowerCase();if(J.includes("text")||J.includes("blob")||J==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let G=J.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(G!==void 0)return{bytes:Number(G)*r0.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts($,J,G){let H=J.columns.map((z)=>{let U=G?.find((Z)=>Z.name===z),h=U?this.keyPartWidth(U):{bytes:0,indexableWhole:!0},Y=!h.indexableWhole;return{name:z,prefixed:Y,bytes:Y?r0.KEY_PREFIX_CHARACTERS*r0.BYTES_PER_CHARACTER:h.bytes,narrowable:!h.indexableWhole||h.bytes>r0.KEY_PREFIX_CHARACTERS*r0.BYTES_PER_CHARACTER}}),A=()=>H.reduce((z,U)=>z+U.bytes,0);while(A()>r0.MAX_KEY_BYTES){let z=H.filter((U)=>U.narrowable&&!U.prefixed).sort((U,h)=>h.bytes-U.bytes)[0];if(!z)throw Error(`[migrations] Index '${J.name}' on table '${$}' needs ${A()} bytes of key, over MySQL's ${r0.MAX_KEY_BYTES}. Every column in it is already at its ${r0.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);z.prefixed=!0,z.bytes=r0.KEY_PREFIX_CHARACTERS*r0.BYTES_PER_CHARACTER}return H.map((z)=>z.prefixed?`${this.quoteIdentifier(z.name)}(${r0.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(z.name))}createIndex($,J,G){if(J.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${J.name}' on table '${$}' uses WHERE clause: ${J.where}`);let H=J.type==="unique"?"UNIQUE ":"",A=N$($,J.name),z=this.keyParts($,J,G).join(", ");return`CREATE ${H}INDEX ${this.quoteIdentifier(A)} ON ${this.quoteIdentifier($)} (${z});`}addForeignKey($,J,G,H,A,z,U=[]){let h=`${$}_${J}_fk`,Y=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(h)} FOREIGN KEY (${this.quoteIdentifier(J)}) REFERENCES ${this.quoteIdentifier(G)}(${this.quoteIdentifier(H)})`;if(A)Y+=` ON DELETE ${A.toUpperCase()}`;if(z)Y+=` ON UPDATE ${z.toUpperCase()}`;let Z=[...new Set(U)].map((E)=>`ALTER TABLE ${this.quoteIdentifier($)} DROP FOREIGN KEY ${this.quoteIdentifier(E)};`).join(`
317
- `);return Z?`${Z}
318
- ${Y};`:`${Y};`}addColumn($,J){let G=this.getColumnType(J),H=[this.quoteIdentifier(J.name),G];if(!J.isNullable&&!J.isPrimaryKey)H.push("not null");let A=this.getDefaultValue(J);if(A)H.push(A);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${H.join(" ")};`}modifyColumn($,J){let G=this.getColumnType(J),H=[this.quoteIdentifier(J.name),G];if(!J.isNullable&&!J.isPrimaryKey)H.push("not null");let A=this.getDefaultValue(J);if(A)H.push(A);return`ALTER TABLE ${this.quoteIdentifier($)} MODIFY COLUMN ${H.join(" ")};`}renameColumn($,J,G){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME COLUMN ${this.quoteIdentifier(J)} TO ${this.quoteIdentifier(G)};`}renameTable($,J){return`RENAME TABLE ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(J)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,J){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(J)};`}dropIndex($,J){let G=N$($,J);return`DROP INDEX ${this.quoteIdentifier(G)} ON ${this.quoteIdentifier($)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
319
- id INT AUTO_INCREMENT PRIMARY KEY,
320
- migration VARCHAR(255) NOT NULL UNIQUE,
321
- executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
322
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract($,J){return`JSON_UNQUOTE(JSON_EXTRACT(${$}, CONCAT('$.', ${J})))`}dateBucket($,J,G=0){let H=G===0?$:`DATE_ADD(${$}, INTERVAL ${G} HOUR)`;switch(J){case"hour":return`DATE_FORMAT(${H}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${H}, INTERVAL WEEKDAY(${H}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${H}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${H}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${H}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral($){return $?"TRUE":"FALSE"}renderColumn($){let J=this.getColumnType($),G=[this.quoteIdentifier($.name),J];if($.isPrimaryKey){G.push("PRIMARY KEY");let A=this.getAutoIncrementClause($);if(A)G.push(A)}if(!$.isNullable&&!$.isPrimaryKey)G.push("not null");let H=this.getDefaultValue($);if(H)G.push(H);return G.join(" ")}}var hG=()=>{};class J5{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){switch($.type){case"string":return`varchar(${$.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"timestamp";case"timestamptz":return"timestamptz";case"json":return"jsonb";case"enum":if($.enumValues&&$.enumValues.length>0)return $.enumTypeName?this.quoteIdentifier($.enumTypeName):"text";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 J=$.defaultValue;if(typeof J==="string"){let G=J.toUpperCase();if(G==="UTC_TIMESTAMP")return"default (now() AT TIME ZONE 'utc')";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(G))return`default ${G}`;return`default '${J.replace(/'/g,"''")}'`}else if(typeof J==="number"||typeof J==="bigint")return`default ${J}`;else if(typeof J==="boolean")return`default ${J?"true":"false"}`;else if(J instanceof Date)return`default '${J.toISOString()}'`;return""}createEnumType($,J){let G=J.map((H)=>`'${H.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier($)} AS ENUM (${G});`}createTable($){let J=$.columns.map((G)=>this.renderColumn(G)).join(`,
323
- `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
324
- ${J}
325
- );`}createIndex($,J){let G=J.type==="unique"?"UNIQUE ":"",H=N$($,J.name),A=J.columns.map((U)=>this.quoteIdentifier(U)).join(", "),z=J.where?` WHERE ${J.where}`:"";return`CREATE ${G}INDEX IF NOT EXISTS ${this.quoteIdentifier(H)} ON ${this.quoteIdentifier($)} (${A})${z};`}addForeignKey($,J,G,H,A,z,U=[]){let h=`${$}_${J}_fk`,Y=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(h)} FOREIGN KEY (${this.quoteIdentifier(J)}) REFERENCES ${this.quoteIdentifier(G)}(${this.quoteIdentifier(H)})`;if(A)Y+=` ON DELETE ${A.toUpperCase()}`;if(z)Y+=` ON UPDATE ${z.toUpperCase()}`;let Z=[...new Set(U)].map((E)=>`ALTER TABLE ${this.quoteIdentifier($)} DROP CONSTRAINT ${this.quoteIdentifier(E)};`).join(`
326
- `);return Z?`${Z}
327
- ${Y};`:`${Y};`}addColumn($,J){let G=this.getColumnType(J),H=[this.quoteIdentifier(J.name),G];if(!J.isNullable&&!J.isPrimaryKey)H.push("not null");let A=this.getDefaultValue(J);if(A)H.push(A);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${H.join(" ")};`}modifyColumn($,J){let G=this.getColumnType(J),H=this.quoteIdentifier($),A=this.quoteIdentifier(J.name),z=[`ALTER TABLE ${H} ALTER COLUMN ${A} DROP DEFAULT;`,`ALTER TABLE ${H} ALTER COLUMN ${A} TYPE ${G} USING ${A}::${G};`];if(!J.isPrimaryKey)z.push(`ALTER TABLE ${H} ALTER COLUMN ${A} ${J.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let U=this.getDefaultValue(J);if(U)z.push(`ALTER TABLE ${H} ALTER COLUMN ${A} SET ${U};`);return z.join(`
328
- `)}renameColumn($,J,G){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME COLUMN ${this.quoteIdentifier(J)} TO ${this.quoteIdentifier(G)};`}renameTable($,J){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME TO ${this.quoteIdentifier(J)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}dropColumn($,J){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(J)};`}dropIndex($,J){let G=N$($,J);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(G)};`}dropEnumType($){return`DROP TYPE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
329
- id SERIAL PRIMARY KEY,
330
- migration VARCHAR(255) NOT NULL UNIQUE,
331
- executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
332
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract($,J){return`(${$}::jsonb ->> ${J})`}dateBucket($,J,G=0){let H=G===0?`${$}::timestamp`:`(${$}::timestamp ${G>=0?"+":"-"} interval '${Math.abs(G)} hours')`,A=J==="week"?`date_trunc('week', ${H})`:H;switch(J){case"hour":return`to_char(${A}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${A}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${A}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${A}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral($){return $?"TRUE":"FALSE"}renderColumn($){let J=$.isPrimaryKey?this.getPrimaryKeyType($):this.getColumnType($),G=[this.quoteIdentifier($.name),J];if($.isPrimaryKey)G.push("PRIMARY KEY");if(!$.isNullable&&!$.isPrimaryKey)G.push("not null");let H=this.getDefaultValue($);if(H)G.push(H);if($.references){let A=`REFERENCES ${this.quoteIdentifier($.references.table)}(${this.quoteIdentifier($.references.column)})`;if($.references.onDelete)A+=` ON DELETE ${$.references.onDelete.toUpperCase()}`;if($.references.onUpdate)A+=` ON UPDATE ${$.references.onUpdate.toUpperCase()}`;G.push(A)}return G.join(" ")}}var O9=()=>{};var G5;var M9=a(()=>{hG();G5=class G5 extends r0{createTable($){let J=$.columns.map((z)=>this.renderColumn(z)).join(`,
333
- `),G=[];if($.tableKind!=="reference"){let z=$.shardKey?.length?$.shardKey:$.columns.filter((U)=>U.isPrimaryKey).map((U)=>U.name);if(z&&z.length>0)G.push(`SHARD KEY (${z.map((U)=>this.quoteIdentifier(U)).join(", ")})`)}if($.tableKind!=="rowstore"&&$.tableKind!=="reference"){let z=$.sortKey?.length?$.sortKey:void 0;G.push(`SORT KEY (${(z??[]).map((U)=>this.quoteIdentifier(U)).join(", ")})`)}let H=[J,...G].join(`,
334
- `);return`CREATE${this.tableKindSuffix($.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
335
- ${H}
336
- );`}tableKindSuffix($){switch($){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex($,J,G){if(J.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${J.name}' on table '${$}' uses WHERE clause: ${J.where}`);return super.createIndex($,J,G)}}});var H5;var K9=a(()=>{hG();H5=class H5 extends r0{sharded;constructor($=!0){super();this.sharded=$}getAutoIncrementClause($){return this.sharded?"":super.getAutoIncrementClause($)}renderColumn($){if(!this.sharded||!$.references)return super.renderColumn($);let{references:J,...G}=$;return super.renderColumn(G)}foreignKeyClauses($){return this.sharded?[]:super.foreignKeyClauses($)}createTable($){return super.createTable($)}addForeignKey(...$){return this.sharded?"":super.addForeignKey(...$)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
337
- migration VARCHAR(255) NOT NULL PRIMARY KEY,
338
- executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
339
- )`}}});function UJ($){return $==="integer"||$==="bigint"||$==="float"||$==="double"||$==="decimal"}function M6($){if(typeof $!=="string")return;switch($.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function A5($){switch($){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}class z5{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){if($.name.endsWith("_id")&&UJ($.type))return"INTEGER";if($.type==="enum"){if($.enumValues&&$.enumValues.length>0){let J=$.enumValues.map((G)=>`'${G.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier($.name)} IN (${J}))`}return"TEXT"}return A5($.type)}getPrimaryKeyType($){return this.getColumnType($)}getAutoIncrementClause($){if($.isPrimaryKey&&($.type==="integer"||$.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let J=$.defaultValue;if(typeof J==="string"){if(J.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(J.toUpperCase()))return`default ${J.toUpperCase()}`;return`default '${J.replace(/'/g,"''")}'`}else if(typeof J==="number"||typeof J==="bigint")return`default ${J}`;else if(typeof J==="boolean")return`default ${J?1:0}`;else if(J instanceof Date)return`default '${J.toISOString()}'`;return""}createEnumType($,J){return""}createTable($){let J=$.columns.map((G)=>this.renderColumn(G)).join(`,
340
- `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
341
- ${J}
342
- );`}createIndex($,J){let G=J.type==="unique"?"UNIQUE ":"",H=N$($,J.name),A=J.columns.map((U)=>this.quoteIdentifier(U)).join(", "),z=J.where?` WHERE ${J.where}`:"";return`CREATE ${G}INDEX IF NOT EXISTS ${this.quoteIdentifier(H)} ON ${this.quoteIdentifier($)} (${A})${z};`}addForeignKey($,J,G,H,A,z){return""}addColumn($,J){let G=this.getColumnType(J),H=[this.quoteIdentifier(J.name),G];if(!J.isNullable&&!J.isPrimaryKey)H.push("not null");let A=this.getDefaultValue(J);if(A)H.push(A);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${H.join(" ")};`}modifyColumn($,J){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier($)}.${this.quoteIdentifier(J.name)}`}renameColumn($,J,G){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME COLUMN ${this.quoteIdentifier(J)} TO ${this.quoteIdentifier(G)};`}renameTable($,J){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME TO ${this.quoteIdentifier(J)};`}rebuildTable($){let{target:J,tempName:G,columnSource:H}=$,A=(Z)=>this.quoteIdentifier(Z),z=J.columns.map((Z)=>this.renderColumn(Z)).join(`,
343
- `),U=`CREATE TABLE ${A(G)} (
344
- ${z}
345
- );`,h=J.columns.map((Z)=>Z.name).filter((Z)=>H[Z]!==void 0),Y=["PRAGMA foreign_keys=OFF;","BEGIN;",U];if(h.length>0){let Z=h.map(A).join(", "),E=h.map((X)=>A(H[X])).join(", ");Y.push(`INSERT INTO ${A(G)} (${Z}) SELECT ${E} FROM ${A(J.table)};`)}Y.push(`DROP TABLE ${A(J.table)};`),Y.push(`ALTER TABLE ${A(G)} RENAME TO ${A(J.table)};`);for(let Z of J.indexes)Y.push(this.createIndex(J.table,Z));return Y.push("PRAGMA foreign_key_check;"),Y.push("COMMIT;"),Y.push("PRAGMA foreign_keys=ON;"),Y.join(`
346
- `)}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,J){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(J)};`}dropIndex($,J){let G=N$($,J);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(G)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
347
- id INTEGER PRIMARY KEY AUTOINCREMENT,
348
- migration TEXT NOT NULL UNIQUE,
349
- executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
350
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract($,J){return`json_extract(${$}, '$.' || ${J})`}dateBucket($,J,G=0){let H=G===0?$:`datetime(${$}, '${G>=0?"+":"-"}${Math.abs(G)} hours')`;switch(J){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${H})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${H}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${H})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${H})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${H})`}}booleanLiteral($){return $?"TRUE":"FALSE"}renderColumn($){let J=this.getColumnType($),G=[this.quoteIdentifier($.name),J];if($.isPrimaryKey){G.push("PRIMARY KEY");let A=this.getAutoIncrementClause($);if(A)G.push(A)}if(!$.isNullable&&!$.isPrimaryKey)G.push("not null");let H=this.getDefaultValue($);if(H)G.push(H);if($.references){if(G.push(`REFERENCES ${this.quoteIdentifier($.references.table)}(${this.quoteIdentifier($.references.column)})`),$.references.onDelete)G.push(`ON DELETE ${$.references.onDelete.toUpperCase()}`);if($.references.onUpdate)G.push(`ON UPDATE ${$.references.onUpdate.toUpperCase()}`)}return G.join(" ")}}var U5=()=>{};function v$($,J={}){switch($){case"postgres":return new J5;case"mysql":return new r0;case"singlestore":return new G5;case"vitess":return new H5(J.vitessSharded??g.vitess?.sharded??!0);case"sqlite":return new z5;default:throw Error(`Unsupported dialect: ${$}`)}}var ZG=a(()=>{m0();hG();O9();M9();K9();U5();hG();O9();M9();U5();K9()});import{existsSync as bX}from"fs";import{dirname as K6,isAbsolute as mX,join as C6}from"path";import B6 from"process";function B9($=B6.cwd()){let J=$;while(J!==K6(J)){if(bX(C6(J,"package.json")))return J;J=K6(J)}return B6.cwd()}function s$($,J="database/migrations"){let G=J||"database/migrations";return mX(G)?G:C6($??B9(),G)}var EG=()=>{};var m6={};r5(m6,{saveMigrationSnapshot:()=>x6,resetDatabase:()=>WG,generateMigration:()=>x1,executeMigration:()=>jG,deleteMigrationFiles:()=>v6,copyModelsToGenerated:()=>sX,clearGeneratedDirectory:()=>g6});import{existsSync as o$,mkdirSync as _6,mkdtempSync as cX,readdirSync as P6,readFileSync as XG,rmSync as N6,unlinkSync as C9,writeFileSync as T6}from"fs";import{tmpdir as dX}from"os";import{join as L$}from"path";import I9 from"process";async function uX($,J,G){if(G.length===0)return;let H=f6(y1());try{await b6($,J);for(let A of G)await Y5($,A,J),H0(`-- \u2713 Recorded applied migration: ${A}`)}catch(A){H0(`-- Could not record applied migrations (the schema change itself succeeded): ${A instanceof Error?A.message:String(A)}`)}}function k6($,J){try{return d6(XG(L$($,J),"utf8"))}catch{return!1}}function pX($){let J=$ instanceof Error?$.message:String($);return/duplicate column name/i.test(J)||/duplicate key name/i.test(J)||/\balready exists\b/i.test(J)}function H0($){if(g.verbose)console.log($)}function q6($){return L$($,g.snapshotDir||".qb")}function S9($,J){return L$(q6($),`model-snapshot.${J}.json`)}function iX($,J){let G=S9($,J);if(!o$(G))return;try{let H=XG(G,"utf8"),A=JSON.parse(H);if(A?.plan&&Array.isArray(A.plan.tables)&&A.plan.dialect)return A.plan;if(Array.isArray(A?.tables)&&A?.dialect)return A;H0("-- Invalid snapshot format, treating as no previous state");return}catch(H){H0(`-- Could not load snapshot, treating as no previous state: ${H instanceof Error?H.message:String(H)}`);return}}function y6($,J,G){let H=S9($,J),A=q6($),z=u6(G);if(o$(H))try{let h=JSON.parse(XG(H,"utf8"));if(h?.hash===z&&h?.dialect===J&&h?.plan){H0("-- Model snapshot unchanged");return}}catch{}if(!o$(A))_6(A,{recursive:!0}),H0(`-- Created snapshot directory: ${A}`);let U={plan:G,hash:z,dialect:J,updatedAt:new Date().toISOString()};T6(H,JSON.stringify(U,null,2)),H0(`-- Model snapshot saved to ${H}`)}function x6($,J={}){let G=J.dialect??$.dialect;y6(J.workspaceRoot??y1(),G,$)}function y1(){return B9()}function f6($){let J=s$($,g.migrationDir);if(!o$(J))_6(J,{recursive:!0}),H0(`-- Created SQL directory: ${J}`);return J}async function x1($,J={}){if(await bH(),!$)$=L$(I9.cwd(),"app/Models");let G=J.dialect||g.dialect||"postgres",H=y1(),A=await P$({modelsDir:$}),z=LG(A,{dialect:G,vitessSharded:J.vitessSharded}),U,h=!1;if(!J.full)if(U=iX(H,G),U)H0("-- Comparing with stored model snapshot");else{let R=L$($,`.qb-migrations.${G}.json`),C=String(J.state||R);if(o$(C))try{let W=XG(C,"utf8"),Q=JSON.parse(W);if(U=Q?.plan&&Q.plan.tables?Q.plan:Q?.tables?Q:void 0,U)H0("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!U||J.fromDb)try{let W=await Q6(G),Q=new Set(z.tables.map((w)=>w.table)),D=W.tables.filter((w)=>Q.has(w.table));if(D.length>0)U={dialect:W.dialect,tables:D},h=!0,H0(`-- No snapshot; reconciling against live database (${D.length} matching table${D.length===1?"":"s"})`)}catch(W){H0(`-- Could not introspect live database, treating as no previous state: ${W instanceof Error?W.message:String(W)}`)}if(!U)H0("-- No previous snapshot found, generating full migration")}else H0("-- Full migration requested, ignoring any previous state");let Y=J.full?{statements:h5(z,{dryRun:J.dryRun}),operations:z.tables.map((R)=>({kind:"create_table",table:R.table,destructive:!1,sql:""}))}:_9(U,z,{applyRenames:J.applyRenames,dryRun:J.dryRun,preserveUnknownColumns:h}),Z=Y.statements,E=Y.operations,X=Z.join(`
351
- `),F=Z.some((R)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(R));if(J.apply){let R=cX(L$(dX(),"qb-migrate-")),C=L$(R,"migration.sql");try{if(F){T6(C,X);let W=z0();await W.file(C),H0("-- Migration applied"),await uX(W,G,c6())}else H0("-- No changes; nothing to apply")}catch(W){throw console.error("-- Migration failed:",W),W}finally{N6(R,{recursive:!0,force:!0})}}if(!J.dryRun)y6(H,G,z);return{sql:X,sqlStatements:Z,hasChanges:F,plan:z,operations:E}}function S6($){return $==="postgres"||$==="sqlite"}async function rX($,J){if($==="sqlite")return await J();let G=z0(),H;try{H=await G.reserve()}catch{return await J()}let A=!1;try{return await H.advisoryLock(I6),A=!0,await J()}finally{try{if(A)await H.advisoryUnlock(I6)}finally{H.release?.()}}}async function jG($){await bH();let J=y1(),G=f6(J),H=g.dialect||"postgres",z=P6(G).filter((U)=>U.endsWith(".sql")).sort();if(z.length===0)return H0("-- No migration files found to execute"),!0;H0(`-- Found ${z.length} script files to execute`);try{let U=z0();return await rX(H,async()=>{await b6(U,H);let h=await oX(U,H),Y=z.filter((Z)=>!h.includes(Z));if(Y.length===0)return H0("-- No pending migrations to execute"),!0;H0(`-- Executing ${Y.length} migration${Y.length===1?"":"s"}`);for(let Z of Y){let E=L$(G,Z);H0(`-- Executing: ${Z}`);try{if(S6(H)&&!nX.test(XG(E,"utf-8")))await U.transaction(async(F)=>{await F.file(E),await Y5(F,Z,H)});else if(await U.file(E),await Y5(U,Z,H),!S6(H))H0(`-- (${H} commits DDL implicitly, so ${Z} was not applied atomically)`);else H0(`-- (${Z} contains a statement that cannot run in a transaction, so it was not applied atomically)`);H0(`-- \u2713 Migration ${Z} executed and recorded`)}catch(X){if(k6(G,Z)&&pX(X)){await Y5(U,Z,H),H0(`-- \u2713 Migration ${Z} was already applied; recorded it (${X instanceof Error?X.message:String(X)})`);continue}throw console.error(`-- \u2717 Migration ${Z} failed:`,X),X}}return H0("-- All migrations executed successfully"),!0})}catch(U){throw console.error("-- Migration execution failed:",U),U}return!0}async function WG($,J={}){if(await bH(),!$)$=L$(I9.cwd(),"app/Models");let G=J.dialect||g.dialect||"postgres",H=v$(G),A=y1(),z=async(U)=>{let h=H.dropTable(U);await pA(async(Y)=>{if(G==="sqlite")await Y.unsafe("PRAGMA foreign_keys = OFF").execute();if(G==="mysql"||G==="vitess")await Y.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await Y.unsafe(h).execute()}finally{if(G==="sqlite")await Y.unsafe("PRAGMA foreign_keys = ON").execute();if(G==="mysql"||G==="vitess")await Y.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await z("migrations"),H0("-- Dropped migrations table")}catch(Y){console.error(Y)}let U=[],h=[];try{let Y=await P$({modelsDir:$}),Z=LG(Y,{dialect:G});U=Z.tables.map((X)=>X.table);let E=new Set;for(let X of Z.tables)for(let F of X.columns)if(F.type==="enum"&&F.enumValues&&F.enumValues.length>0){let R=`${X.table}_${F.name}_type`;E.add(R)}h=Array.from(E)}catch(Y){console.error(Y),U=[],h=[]}if(U.length===0)H0("-- No tables found to drop");else{H0(`-- Dropping ${U.length} tables: ${U.join(", ")}`);for(let Y of U.reverse())try{await z(Y),H0(`-- Dropped table: ${Y}`)}catch(Z){console.error(Z),H0(`-- Table ${Y} may not exist, skipping drop`)}}if(h.length>0){H0(`-- Dropping ${h.length} enum types: ${h.join(", ")}`);for(let Y of h)try{let Z=H.dropEnumType(Y);if(Z)await pA(async(E)=>{await E.unsafe(Z).execute(),H0(`-- Dropped enum type: ${Y}`)})}catch(Z){console.error(Z),H0(`-- Enum type ${Y} may not exist, skipping drop`)}}else H0("-- No enum types found to drop");if(U.length>0&&!J.preserveMigrationState)try{await v6($,A,J)}catch(Y){console.error(Y),H0("-- Could not clean up migration files")}else if(U.length===0)H0("-- No models directory found; keeping committed migration files in place");else H0("-- Preserving migration files and model snapshot for fresh replay");if(!J.preserveMigrationState)try{await g6(A)}catch(Y){console.error(Y),H0("-- Could not clear generated directory")}return H0("-- Database reset completed successfully"),!0}catch(U){return console.error("-- Database reset failed:",U),!1}}async function v6($,J,G={}){if(!$)$=L$(I9.cwd(),"app/Models");if(!J)J=y1();let H=String(G.dialect||g.dialect||"postgres"),A=S9(J,H);if(o$(A))C9(A),H0(`-- Removed model snapshot file: ${A}`);let z=L$($,`.qb-migrations.${H}.json`),U=String(G.state||z);if(o$(U))C9(U),H0(`-- Removed legacy migration state file: ${U}`);lX(s$(J,g.migrationDir))}function lX($){if(!o$($))return;let J=0,G=[];for(let H of P6($).filter((A)=>A.endsWith(".sql"))){if(!k6($,H)){G.push(H);continue}C9(L$($,H)),H0(`-- Removed generated migration file: ${H}`),J+=1}if(H0(`-- Cleaned up ${J} generated migration file${J===1?"":"s"} from migrations directory`),G.length>0)H0(`-- Kept ${G.length} hand-written migration${G.length===1?"":"s"}: ${G.slice(0,5).join(", ")}${G.length>5?`, +${G.length-5} more`:""}`)}async function sX($,J){}async function g6($){if(!$)$=y1();let J=L$($,"generated");if(o$(J))try{N6(J,{recursive:!0,force:!0}),H0("-- Cleared generated directory")}catch(G){console.error("-- Failed to clear generated directory:",G)}}async function b6($,J){let H=v$(J).createMigrationsTable();try{await $.unsafe(H).execute(),H0("-- Migrations table ready")}catch(A){throw console.error("-- Failed to create migrations table:",A),A}}async function oX($,J){let G=v$(J);try{return(await $.unsafe(G.getExecutedMigrationsQuery()).execute()).map((A)=>A.migration)}catch(H){return console.error("-- Failed to get executed migrations:",H),[]}}async function Y5($,J,G){let H=v$(G);try{H0(`-- Recording migration: ${J}`),await $.unsafe(H.recordMigrationQuery(),[J]).execute(),H0(`-- Successfully recorded migration: ${J}`)}catch(A){throw console.error(`-- Failed to record migration ${J}:`,A),A}}var I6="bun-query-builder:migrate",nX;var FG=a(()=>{m0();j1();ZG();n0();$5();EG();nX=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im});async function P9($,J={}){return x1($,J)}var N9=a(()=>{FG()});import{existsSync as p6,readFileSync as tX,unlinkSync as aX}from"fs";import{join as eX}from"path";function $2($){let J=[],G="",H=null;for(let A=0;A<$.length;A++){let z=$[A];if(H){if(G+=z,z===H)if($[A+1]===H)G+=$[A+1],A++;else H=null;continue}if(z==="'"||z==='"'||z==="`"){H=z,G+=z;continue}if(z==="-"&&$[A+1]==="-"){let U=$.indexOf(`
352
- `,A);A=U===-1?$.length:U;continue}if(z==="/"&&$[A+1]==="*"){let U=$.indexOf("*/",A+2);A=U===-1?$.length:U+1;continue}if(z===";"){if(G.trim())J.push(G.trim());G="";continue}G+=z}if(G.trim())J.push(G.trim());return J}function J2($,J=g.dialect){let G=(z)=>A0(J)?`\`${z}\``:`"${z}"`,H=[],A=[];for(let z of $2($)){let U;if(U=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(z))H.push(`DROP TABLE IF EXISTS ${G(U[1])}`);else if(U=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(z))if(J==="sqlite")A.push(z);else if(A0(J)&&/\bFOREIGN\s+KEY\b/i.test(U[3]??""))H.push(`ALTER TABLE ${G(U[1])} DROP FOREIGN KEY ${G(U[2])}`);else H.push(`ALTER TABLE ${G(U[1])} DROP CONSTRAINT ${G(U[2])}`);else if(U=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(z)){let h=U[2]??U[3]??U[4];if(U[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(U[4]))A.push(z);else H.push(`ALTER TABLE ${G(U[1])} DROP COLUMN ${G(h)}`)}else if(U=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(z))H.push(A0(J)&&U[2]?`DROP INDEX ${G(U[1])} ON ${G(U[2])}`:`DROP INDEX IF EXISTS ${G(U[1])}`);else A.push(z)}return{down:H.reverse(),skipped:A}}async function T9($={}){let J=$.steps||1,G=$.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${J}`),console.log();try{let H=z0(),A=[];try{A=await H.unsafe(`
353
- SELECT migration, executed_at
354
- FROM migrations
355
- ORDER BY executed_at DESC, migration DESC
356
- `)}catch(Y){console.log("-- Migrations table not found. Nothing to rollback.",Y);return}if(A.length===0){console.log("-- No migrations to rollback");return}let z=A.slice(0,J);console.log(`-- Found ${A.length} executed migrations`),console.log(`-- Rolling back ${z.length} migration(s):`),console.log();for(let Y of z)console.log(` - ${Y.migration}`);console.log();let U=s$(void 0,g.migrationDir),h=!1;for(let Y of z)try{let Z=eX(U,Y.migration);if(G&&p6(Z)){let X=tX(Z,"utf8"),{down:F,skipped:R}=J2(X);for(let C of F)await H.unsafe(C),console.log(`-- \u21A9 ${C}`),h=!0;if(R.length>0)console.log(`-- \u26A0\uFE0F ${R.length} statement(s) in ${Y.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let E=`DELETE FROM migrations WHERE migration = ${l(1)}`;if(await H.unsafe(E,[Y.migration]),console.log(`-- \u2713 Removed migration record: ${Y.migration}`),$.deleteFiles&&p6(Z))aX(Z),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${Y.migration}`)}catch(Z){throw console.error(`-- \u2717 Failed to rollback migration ${Y.migration}:`,Z),Z}if(console.log(),G)console.log(h?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(H){throw console.error("-- Rollback failed:",H),H}}var k9=a(()=>{m0();n0();EG()});import{existsSync as G2,readdirSync as H2}from"fs";async function Z5(){let $=g.dialect||"postgres",J=v$($),G=s$(void 0,g.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${$}`),console.log(`-- SQL directory: ${G}`),console.log(),!G2(G))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let A=H2(G).filter((z)=>z.endsWith(".sql")).sort();if(A.length===0)return console.log("-- No migration files found"),[];try{let z=z0(),U=[];try{U=await z.unsafe(J.getExecutedMigrationsQuery())}catch(X){console.log("-- Migrations table not found. All migrations are pending.",X),console.log()}let h=new Map(U.map((X)=>[X.migration,X.executed_at])),Y=A.map((X)=>({file:X,status:h.has(X)?"executed":"pending",executedAt:h.get(X)})),Z=Y.filter((X)=>X.status==="executed"),E=Y.filter((X)=>X.status==="pending");if(console.log(`-- Total migrations: ${A.length}`),console.log(`-- Executed: ${Z.length}`),console.log(`-- Pending: ${E.length}`),console.log(),Z.length>0){console.log("\u2713 Executed Migrations:");for(let X of Z)console.log(` - ${X.file} ${X.executedAt?`(${new Date(X.executedAt).toLocaleString()})`:""}`);console.log()}if(E.length>0){console.log("\u25CB Pending Migrations:");for(let X of E)console.log(` - ${X.file}`);console.log()}return Y}catch(z){throw console.error("-- Failed to get migration status:",z),z}}async function q9(){return Z5()}var y9=a(()=>{m0();ZG();n0();EG()});import{readdirSync as A2}from"fs";import{extname as x9,join as i6}from"path";import z2 from"process";async function E5($,J={}){let G=J.dir||i6(z2.cwd(),"app/Models");try{let H=A2(G),A=H.find((E)=>{return E.replace(x9(E),"").toLowerCase()===$.toLowerCase()});if(!A){console.error(`Model "${$}" not found in ${G}`),console.log(`Available models: ${H.filter((E)=>[".ts",".js"].includes(x9(E))).map((E)=>E.replace(x9(E),"")).join(", ")}`);return}let U=await import(i6(G,A)),h=U.default||U[Object.keys(U)[0]];if(!h||!h.name){console.error(`Invalid model file: ${A}`);return}let Y={name:h.name,table:h.table||`${h.name.toLowerCase()}s`,primaryKey:h.primaryKey||"id",attributes:h.attributes||{},relations:h.relations,scopes:h.scopes,indexes:h.indexes,timestamps:h.timestamps!==!1,softDeletes:h.softDeletes===!0},Z=[];if(h.beforeCreate)Z.push("beforeCreate");if(h.afterCreate)Z.push("afterCreate");if(h.beforeUpdate)Z.push("beforeUpdate");if(h.afterUpdate)Z.push("afterUpdate");if(h.beforeDelete)Z.push("beforeDelete");if(h.afterDelete)Z.push("afterDelete");if(Z.length>0)Y.hooks=Z;if(J.json)return console.log(JSON.stringify(Y,null,2)),Y;console.log(`
357
- \uD83D\uDCE6 Model: ${Y.name}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Table: ${Y.table}`),console.log(`Primary Key: ${Y.primaryKey}`),console.log(`Timestamps: ${Y.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${Y.softDeletes?"\u2713":"\u2717"}`),console.log(`
358
- \uD83D\uDCCB Attributes (${Object.keys(Y.attributes).length}):`);for(let[E,X]of Object.entries(Y.attributes)){let F=X.type||"string",R=X.required?"(required)":"",C=X.unique?"(unique)":"",W=X.default!==void 0?`= ${JSON.stringify(X.default)}`:"";console.log(` \u2022 ${E}: ${F} ${R} ${C} ${W}`.trim())}if(Y.relations&&Object.keys(Y.relations).length>0){console.log(`
359
- \uD83D\uDD17 Relations (${Object.keys(Y.relations).length}):`);for(let[E,X]of Object.entries(Y.relations)){let F=X.type||"unknown",R=X.model||X.table||"unknown";console.log(` \u2022 ${E}: ${F} \u2192 ${R}`)}}if(Y.scopes&&Object.keys(Y.scopes).length>0){console.log(`
360
- \uD83D\uDD0D Scopes (${Object.keys(Y.scopes).length}):`);for(let E of Object.keys(Y.scopes))console.log(` \u2022 ${E}()`)}if(Y.hooks&&Y.hooks.length>0){console.log(`
361
- \uD83E\uDE9D Hooks (${Y.hooks.length}):`);for(let E of Y.hooks)console.log(` \u2022 ${E}`)}if(Y.indexes&&Y.indexes.length>0){console.log(`
362
- \uD83D\uDCC7 Indexes (${Y.indexes.length}):`);for(let E of Y.indexes){let X=Array.isArray(E.columns)?E.columns.join(", "):E.columns,F=E.unique?"(unique)":"";console.log(` \u2022 ${E.name||"unnamed"}: [${X}] ${F}`.trim())}}return console.log(),Y}catch(H){throw console.error(`Error loading model "${$}":`,H.message),H}}var f9=()=>{};async function v9(){let J=await z0().ping();return console.log(J?"OK":"NOT READY"),J}var n6=a(()=>{n0()});import{readdirSync as U2,readFileSync as r6,statSync as Y2}from"fs";import{extname as l6,join as h2}from"path";async function X5($,J={}){let G=[];try{let H=Y2($),A=[];if(H.isDirectory())A=U2($).filter((Y)=>l6(Y)===".sql").map((Y)=>h2($,Y));else if(H.isFile()&&l6($)===".sql")A=[$];else return console.error("Path must be a .sql file or directory containing .sql files"),G;if(A.length===0)return console.log("No .sql files found"),G;if(J.verbose)console.log(`Analyzing ${A.length} SQL file(s)...
363
- `);for(let h of A)try{let Y=r6(h,"utf8").trim();if(!Y){if(J.verbose)console.log(`\u2298 ${h}: empty file`);continue}if(J.verbose)console.log(`\uD83D\uDCC4 ${h}`),console.log(` Query: ${Y.substring(0,60)}${Y.length>60?"...":""}`);let Z=await $0`EXPLAIN ${$0.unsafe(Y)}`;if(G.push({file:h,query:Y,plan:Array.isArray(Z)?Z:[Z]}),J.verbose&&!J.json){if(console.log(" Plan:"),Array.isArray(Z))for(let E of Z)if(typeof E==="string")console.log(` ${E}`);else if(E["QUERY PLAN"])console.log(` ${E["QUERY PLAN"]}`);else if(E.plan)console.log(` ${JSON.stringify(E.plan)}`);else console.log(` ${JSON.stringify(E)}`);console.log()}}catch(Y){if(G.push({file:h,query:r6(h,"utf8").trim(),plan:[],error:Y.message}),J.verbose)console.log(` \u2717 Error: ${Y.message}
364
- `)}let z=G.filter((h)=>!h.error).length,U=G.filter((h)=>h.error).length;if(J.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${z} successful, ${U} failed`);if(J.json)console.log(JSON.stringify(G,null,2));return G}catch(H){throw console.error("Error explaining queries:",H.message),H}}var g9=a(()=>{j1()});import{writeFileSync as Z2}from"fs";import{join as E2}from"path";import X2 from"process";async function j5($={}){let J=$.dir||E2(X2.cwd(),"app/Models"),G=$.format||"mermaid";try{let H=await P$({modelsDir:J});if(!H||Object.keys(H).length===0)return console.error("No models found"),"";let A="";if(G==="mermaid")A=j2(H);else if(G==="dot")A=W2(H);else return console.error(`Unsupported format: ${G}`),"";if($.output)Z2($.output,A,"utf8"),console.log(`\u2713 Diagram written to: ${$.output}`);else console.log(A);return A}catch(H){throw console.error("Error generating diagram:",H.message),H}}function j2($){let J=["erDiagram"];for(let[G,H]of Object.entries($)){let A=H.table||`${G.toLowerCase()}s`,z=H.attributes||{};J.push(` ${A} {`);for(let[U,h]of Object.entries(z)){let Y=h.type||"string",Z=H.primaryKey===U?"PK":"",E=h.unique?"UK":"",X=[Z,E].filter(Boolean).join(","),F=X?` "${X}"`:"";J.push(` ${Y} ${U}${F}`)}J.push(" }")}for(let[G,H]of Object.entries($)){let A=H.table||`${G.toLowerCase()}s`,z=H.relations||{};for(let[U,h]of Object.entries(z)){let{type:Y,model:Z}=h,E=$[Z]?.table||`${Z?.toLowerCase()}s`||"unknown",X="";if(Y==="hasOne")X="||--||";else if(Y==="hasMany")X="||--o{";else if(Y==="belongsTo")X="}o--||";else if(Y==="belongsToMany"||Y==="manyToMany")X="}o--o{";else X="||--||";J.push(` ${A} ${X} ${E} : "${U}"`)}}return J.join(`
365
- `)}function W2($){let J=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[G,H]of Object.entries($)){let A=H.table||`${G.toLowerCase()}s`,z=H.attributes||{},U=[];for(let[Y,Z]of Object.entries(z)){let E=Z.type||"string",X=H.primaryKey===Y?" (PK)":"",F=Z.unique?" (UK)":"";U.push(`${Y}: ${E}${X}${F}`)}let h=`${U.join("\\l")}\\l`;J.push(` ${A} [label="{${A}|${h}}"];`)}J.push("");for(let[G,H]of Object.entries($)){let A=H.table||`${G.toLowerCase()}s`,z=H.relations||{};for(let[U,h]of Object.entries(z)){let{type:Y,model:Z}=h,E=$[Z]?.table||`${Z?.toLowerCase()}s`||"unknown",X="";if(Y==="hasOne")X="arrowhead=none, arrowtail=normal";else if(Y==="hasMany")X="arrowhead=crow, arrowtail=none";else if(Y==="belongsTo")X="arrowhead=normal, arrowtail=none";else if(Y==="belongsToMany"||Y==="manyToMany")X="arrowhead=crow, arrowtail=crow";J.push(` ${A} -> ${E} [label="${U}", ${X}];`)}}return J.push("}"),J.join(`
366
- `)}var b9=a(()=>{n0()});import{existsSync as W5,mkdirSync as F2,readdirSync as L2,writeFileSync as w2}from"fs";import{dirname as s6,join as L1}from"path";import wG from"process";function F5($){let J=$;while(J!==s6(J)){if(W5(L1(J,"package.json")))return J;J=s6(J)}return wG.cwd()}async function o6($){if(!W5($))return console.log(`-- Seeders directory not found: ${$}`),[];let G=L2($).sort((A,z)=>A.localeCompare(z)).filter((A)=>(A.endsWith(".ts")||A.endsWith(".js"))&&A!=="index.ts"&&A!=="index.js"),H=[];for(let A of G){let z=L1($,A);try{let U=await import(z),h=U.default||U[Object.keys(U)[0]];if(h&&typeof h==="function"){let Y=new h;if(Y&&typeof Y.run==="function")H.push({name:A.replace(/\.(ts|js)$/,""),className:String(h.name||""),instance:Y})}}catch(U){console.error(`-- Failed to load seeder ${A}:`,U)}}return H.sort((A,z)=>A.instance.order-z.instance.order),H}async function RG($={}){let J=F5(wG.cwd()),G=$.seedersDir||L1(J,"database/seeders"),H=$.verbose??!0;if(H)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${G}`);let A=await o6(G);if(A.length===0){console.log("-- No seeders found");return}if(H)console.log(`-- Found ${A.length} seeder(s)`);let z=z0();for(let{name:U,instance:h}of A)try{if(H)console.log(`-- Seeding: ${U}`);if(await h.run(z),H)console.log(`-- \u2713 Seeded: ${U}`)}catch(Y){throw console.error(`-- \u2717 Failed to seed ${U}:`,Y),Y}if(H)console.log("-- All seeders completed successfully")}async function L5($,J={}){let G=F5(wG.cwd()),H=L1(G,"database/seeders"),A=J.verbose??!0;if(A)console.log(`-- Running seeder: ${$}`);let z=await o6(H),U=z.find((Y)=>Y.className===$)??z.find((Y)=>Y.name===$);if(!U){let Y=z.map((Z)=>Z.className||Z.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${$}. Available: ${Y}`),Error(`Seeder not found: ${$}. Available: ${Y}`)}let h=z0();try{if(await U.instance.run(h),A)console.log(`-- \u2713 Seeder completed: ${$}`)}catch(Y){throw console.error(`-- \u2717 Seeder failed: ${$}`,Y),Y}}async function m9($){let J=F5(wG.cwd()),G=L1(J,"database/seeders");if(!W5(G))F2(G,{recursive:!0}),console.log(`-- Created seeders directory: ${G}`);let A=`${$.replace(/Seeder$/i,"")}Seeder`,z=`${A}.ts`,U=L1(G,z);if(W5(U))throw console.error(`-- Seeder already exists: ${U}`),Error(`Seeder already exists: ${U}`);let h=`import type { QueryBuilder } from 'bun-query-builder'
367
- import { Seeder } from 'bun-query-builder'
368
- import { faker } from '@stacksjs/ts-faker'
369
-
370
- export default class ${A} extends Seeder {
371
- /**
372
- * Run the database seeds.
373
- */
374
- async run(qb: QueryBuilder): Promise<void> {
375
- console.log('Seeding: ${A}')
376
-
377
- // Example: Create 10 records with faker
378
- const records = Array.from({ length: 10 }, () => ({
379
- name: faker.person.fullName(),
380
- email: faker.internet.email().toLowerCase(),
381
- age: faker.number.int({ min: 18, max: 80 }),
382
- created_at: faker.date.past(),
383
- updated_at: new Date(),
384
- }))
385
-
386
- // Option 1: Kysely-style API
387
- await qb.insertInto('table_name').values(records).execute()
388
-
389
- // Option 2: Laravel-style API (equivalent)
390
- // await qb.table('table_name').insert(records).execute()
391
-
392
- console.log(\`\u2713 Seeded \${records.length} records\`)
393
-
394
- // For large datasets, use batch inserts:
395
- // const batchSize = 100
396
- // for (let i = 0; i < records.length; i += batchSize) {
397
- // const batch = records.slice(i, i + batchSize)
398
- // await qb.insertInto('table_name').values(batch).execute()
399
- // // Or: await qb.table('table_name').insert(batch).execute()
400
- // }
401
- }
402
-
403
- /**
404
- * Specify the order in which this seeder should run.
405
- * Lower numbers run first. Default is 100.
406
- */
407
- get order(): number {
408
- return 100
409
- }
410
- }
411
- `;w2(U,h),console.log(`-- \u2713 Created seeder: ${U}`)}async function c9($={}){let J=F5(wG.cwd()),G=$.modelsDir||L1(J,"app/Models"),H=$.seedersDir||L1(J,"database/seeders"),A=$.verbose??!0;try{let{resetDatabase:z,generateMigration:U,executeMigration:h}=await Promise.resolve().then(() => (FG(),m6));if(A)console.log("-- Refreshing database...");if(await z(G),A)console.log("-- Running migrations...");if(await U(G,{full:!0}),await h(),A)console.log("-- Running seeders...");if(await RG({seedersDir:H,verbose:A}),A)console.log("-- \u2713 Database refreshed successfully")}catch(z){throw console.error("-- \u2717 Database refresh failed:",z),z}}var d9=a(()=>{n0()});function u9($,J,G={}){let H=P$({modelsDir:$}),A=eH(H);if(g.debug)g.debug.captureText=!0;let z=z0({schema:A}),U=z.selectFrom(J).limit(Number(G.limit||10)).toText?.()??"";return console.log(U||"[query]"),{sql:U,qb:z,schema:A}}var t6=a(()=>{m0();n0()});async function p9($,J={}){let G=z0(),H=J.params?JSON.parse(J.params):void 0,A=await G.unsafe($,H);return console.log(JSON.stringify(A)),A}var a6=a(()=>{n0()});import{existsSync as R2}from"fs";import{dirname as e6,join as $h}from"path";import Jh from"process";function D2($){let J=$;while(J!==e6(J)){if(R2($h(J,"package.json")))return J;J=e6(J)}return Jh.cwd()}async function w5($){if(!$)$=$h(D2(Jh.cwd()),"app/Models");let J=g.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${$}`),console.log(`-- Dialect: ${J}`),console.log();let G=[];try{let H=await P$({modelsDir:$}),A=LG(H,{dialect:J}),z=z0(),U=[];if(J==="sqlite")U=(await z.unsafe(`
412
- SELECT name FROM sqlite_master
413
- WHERE type = 'table'
414
- AND name NOT LIKE 'sqlite_%'
415
- AND name != 'migrations'
416
- `)).map((E)=>E.name);else if(J==="postgres")U=(await z.unsafe(`
417
- SELECT table_name
418
- FROM information_schema.tables
419
- WHERE table_schema = 'public'
420
- AND table_type = 'BASE TABLE'
421
- AND table_name != 'migrations'
422
- `)).map((E)=>E.table_name);else if(A0(J))U=(await z.unsafe(`
423
- SELECT table_name
424
- FROM information_schema.tables
425
- WHERE table_schema = DATABASE()
426
- AND table_type = 'BASE TABLE'
427
- AND table_name != 'migrations'
428
- `)).map((E)=>E.table_name);let h=A.tables.map((Z)=>Z.table);for(let Z of h)if(!U.includes(Z))G.push({type:"missing_table",severity:"error",table:Z,message:`Table '${Z}' defined in models but not found in database`});for(let Z of U)if(!h.includes(Z))G.push({type:"extra_table",severity:"warning",table:Z,message:`Table '${Z}' exists in database but not defined in models`});for(let Z of A.tables){if(!U.includes(Z.table))continue;let E=[];if(J==="sqlite")E=(await z.unsafe(`PRAGMA table_info(${Z.table})`)).map((C)=>({name:C.name,type:C.type.toLowerCase()}));else if(J==="postgres")E=(await z.unsafe(`
429
- SELECT column_name, data_type
430
- FROM information_schema.columns
431
- WHERE table_name = $1
432
- `,[Z.table])).map((C)=>({name:C.column_name,type:C.data_type.toLowerCase()}));else if(A0(J))E=(await z.unsafe(`
433
- SELECT column_name, data_type
434
- FROM information_schema.columns
435
- WHERE table_name = ?
436
- AND table_schema = DATABASE()
437
- `,[Z.table])).map((C)=>({name:C.column_name,type:C.data_type.toLowerCase()}));let X=E.map((R)=>R.name),F=Z.columns.map((R)=>R.name);for(let R of Z.columns)if(!X.includes(R.name))G.push({type:"missing_column",severity:"error",table:Z.table,column:R.name,expected:R.type,message:`Column '${Z.table}.${R.name}' defined in model but not found in database`});for(let R of E)if(!F.includes(R.name))G.push({type:"extra_column",severity:"warning",table:Z.table,column:R.name,actual:R.type,message:`Column '${Z.table}.${R.name}' exists in database but not defined in model`});for(let R of Z.columns){let C=E.find((W)=>W.name===R.name);if(C){let W=(w)=>{return w.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},Q=W(R.type),D=W(C.type);if(Q!==D)G.push({type:"type_mismatch",severity:"warning",table:Z.table,column:R.name,expected:R.type,actual:C.type,message:`Column '${Z.table}.${R.name}' type mismatch: expected '${R.type}', found '${C.type}'`})}}}let Y=G.filter((Z)=>Z.severity==="error").length===0;if(Y&&G.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${G.length} issue(s)`),console.log();let Z=G.filter((X)=>X.severity==="error"),E=G.filter((X)=>X.severity==="warning");if(Z.length>0){console.log(`\u2717 Errors (${Z.length}):`);for(let X of Z)console.log(` - ${X.message}`);console.log()}if(E.length>0){console.log(`\u26A0 Warnings (${E.length}):`);for(let X of E)console.log(` - ${X.message}`);console.log()}if(!Y)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:Y,issues:G}}catch(H){throw console.error("-- Schema validation failed:",H),H}}async function i9($){return w5($)}var n9=a(()=>{m0();zG();n0()});async function r9($={}){let J=Number($.attempts||10),G=Number($.delay||100),H=z0();try{return await H.waitForReady({attempts:J,delayMs:G}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var Gh=a(()=>{n0()});var l9=a(()=>{nA();aA();$9();A9();U9();Y9();h9();X6();j6();j9();W6();$5();V9();FG();N9();k9();y9();f9();n6();g9();b9();d9();t6();a6();n9();Gh()});function YJ($){if(typeof $==="number")return{length:$};return $}function s9($){if(typeof $==="number")return{max:$};return $}function Q2($){return typeof $==="function"}function V2($){return $.replace(/[A-Z]/g,(J)=>J.toLowerCase())}function Hh($,J){if(!J||typeof J.fractionDigits!=="number")return $;return Number($.toFixed(J.fractionDigits))}function w1($,J={}){if(!$)return J;return new Proxy($,{get(G,H){if(H in J)return J[H];let A=G[H];if(A!==void 0)return A;let z=G[V2(H)];if(Q2(z))return z.bind(G);return}})}function Ah($){let J=(E)=>{let X=Array.isArray(E)?E:[],F=Math.floor(Math.random()*X.length);return X[F]},G=()=>$.string,H=()=>$.number,A=()=>$.random,z=w1($.string,{alpha:(E)=>G()?.alpha?.(YJ(E)),alphanumeric:(E)=>G()?.alphanumeric?.(YJ(E)),numeric:(E)=>G()?.numeric?.(YJ(E)),sample:(E)=>G()?.sample?.(YJ(E)),hexadecimal:(E)=>G()?.hexadecimal?.(YJ(E))}),U=w1($.number,{int:(E)=>H()?.int?.(s9(E)),float:(E)=>{let X=s9(E);return Hh(Number(H()?.float?.(X)??0),X)}}),h=w1($.helpers,{arrayElement:J,arrayElements:(E,X)=>{let F=[...Array.isArray(E)?E:[]],R=typeof X==="number"?X:Math.max(1,Math.floor(Math.random()*F.length));for(let C=F.length-1;C>0;C-=1){let W=Math.floor(Math.random()*(C+1));[F[C],F[W]]=[F[W],F[C]]}return F.slice(0,Math.min(R,F.length))},shuffle:(E)=>{let X=[...Array.isArray(E)?E:[]];for(let F=X.length-1;F>0;F-=1){let R=Math.floor(Math.random()*(F+1));[X[F],X[R]]=[X[R],X[F]]}return X},maybe:(E,X)=>{let F=typeof X?.probability==="number"?X.probability:0.5;return Math.random()<F?E():void 0},slugify:(E)=>String(E??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),Z={string:z,number:U,helpers:h,datatype:{boolean:(E)=>{let X=typeof E==="number"?E:E?.probability;if(typeof X==="number")return Math.random()<X;return Boolean(A()?.boolean?.())},number:(E)=>Number(H()?.int?.(s9(E))??0),float:(E)=>Hh(Number(H()?.float?.(E)??0),E),uuid:()=>crypto.randomUUID(),string:(E)=>String(G()?.alphanumeric?.({length:E??10})??""),hexadecimal:(E)=>String(G()?.hexadecimal?.(YJ(E))??""),array:(E)=>Array.from({length:E??3},()=>G()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:G()?.alphanumeric?.({length:8})})},location:w1($.address),address:w1($.address),vehicle:w1($.vehicle,{vrm:()=>$.vehicle?.registration?.()}),company:w1($.company,{catchPhrase:()=>$.company?.catchphrase?.(),buzzPhrase:()=>$.company?.bs?.()??$.company?.buzzword?.()})};return new Proxy($,{get(E,X){if(X in Z)return Z[X];let F=E[X];if(F&&typeof F==="object")return w1(F);return F}})}function R5($){if(typeof $==="string")return{model:$};if($&&typeof $==="object"&&typeof $.model==="string"){let J=$;return{model:J.model,foreignKey:J.foreignKey,onDelete:J.onDelete}}return null}function hJ($){if(!$)return[];return(Array.isArray($)?$:typeof $==="object"?Object.values($):[]).map(R5).filter((G)=>G!==null)}import{existsSync as O2}from"fs";import{join as M2}from"path";import K2 from"process";import{existsSync as zh,statSync as Uh}from"fs";import{join as B2,relative as C2,resolve as Yh}from"path";import C5 from"process";import{Buffer as t$}from"buffer";import{createCipheriv as I2,createDecipheriv as S2,randomBytes as o9}from"crypto";import{closeSync as t9,createReadStream as hh,createWriteStream as _2,existsSync as D5,fsyncSync as Zh,openSync as Eh,writeFileSync as P2}from"fs";import{access as N2,constants as Xh,mkdir as T2,readdir as Q5,rename as jh,stat as ZJ,unlink as V5,writeFile as a9}from"fs/promises";import{isAbsolute as k2,join as EJ,resolve as q2}from"path";import M0 from"process";import{pipeline as y2}from"stream/promises";import{createGzip as Wh}from"zlib";import XJ from"process";import a$ from"process";import O5 from"process";import{existsSync as M5}from"fs";import{resolve as e9}from"path";import{existsSync as x2}from"fs";import{existsSync as zz,mkdirSync as f2,readdirSync as v2,readFileSync as g2,writeFileSync as b2}from"fs";import{homedir as jJ}from"os";import{dirname as Fh,resolve as Y$}from"path";import v1 from"process";import{existsSync as m2,readdirSync as c2}from"fs";import{extname as $z,resolve as Lh}from"path";import d2 from"process";import{spawnSync as qj}from"child_process";import{existsSync as WJ,readFileSync as yj}from"fs";import{join as FJ}from"path";import dh from"process";function i2($,J){this[$]=p2.bind(null,J)}class Wz{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let G=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${G}`}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(([,G],[,H])=>G.timestamp.getTime()-H.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let G=0;G<J;G++)this.cache.delete($[G][0])}set($,J,G,H){if(!this.options.enabled)return;let A=this.generateKey($,G),z=H??this.options.ttl,U=this.estimateSize(J);this.cache.set(A,{value:J,timestamp:new Date,ttl:z,hits:0,size:U}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let G=this.generateKey($,J),H=this.cache.get(G);if(!H){this.totalMisses++;return}if(this.isExpired(H)){this.cache.delete(G),this.totalMisses++;return}return H.hits++,this.totalHits++,H.value}isFileModified($,J){try{if(!zh($))return!0;return Uh($).mtime>J}catch{return!0}}getWithFileCheck($,J){let G=this.get($,J);if(!G)return;if(this.isFileModified(J,G.fileTimestamp)){this.delete($,J);return}return G.value}setWithFileCheck($,J,G,H){try{let A=zh(G)?Uh(G):null,z=A?A.mtime:new Date;this.set($,{value:J,fileTimestamp:z},G,H)}catch{this.set($,J,G,H)}}delete($,J){let G=this.generateKey($,J);return this.cache.delete(G)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,G]of this.cache.entries())if(this.isExpired(G))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((H,A)=>H+A.size,0),G=$.map((H)=>H.timestamp).sort();return{size:J,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:G[0],newestEntry:G[G.length-1]}}export(){let $={};for(let[J,G]of this.cache.entries())$[J]={value:G.value,timestamp:G.timestamp.toISOString(),ttl:G.ttl,hits:G.hits,size:G.size};return $}import($){this.cache.clear();for(let[J,G]of Object.entries($))if(typeof G==="object"&&G!==null){let H=G;this.cache.set(J,{value:H.value,timestamp:new Date(H.timestamp),ttl:H.ttl,hits:H.hits,size:H.size})}}}class Fz{metrics=[];maxMetrics=1000;async track($,J,G={}){let H=performance.now(),A=new Date;try{let z=await J(),U=performance.now()-H;return this.recordMetric({operation:$,duration:U,timestamp:A,...G}),z}catch(z){let U=performance.now()-H;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:A,...G}),z}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((A)=>A.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let G=J.map((A)=>A.duration),H=G.reduce((A,z)=>A+z,0);return{count:J.length,averageDuration:H/J.length,minDuration:Math.min(...G),maxDuration:Math.max(...G),totalDuration:H,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function l2($,J={}){let G=Object.keys(J).sort().map((H)=>`${H}:${J[H]}`).join("|");return G?`${$}:${G}`:$}function s2($,J){try{return JSON.stringify($)===JSON.stringify(J)}catch{return $===J}}function o2($){return $.getStats().size*2}function t2($,J={}){let G=C5.cwd();while(G.includes("storage"))G=Yh(G,"..");let H=Yh(G,$||"");if(J?.relative)return C2(C5.cwd(),H);return H}function l0(){if(a$.env.NODE_ENV==="test"||a$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function a2(){if(a$.env.NODE_ENV==="test"||a$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof a$<"u"){let $=a$.type;if($==="renderer"||$==="worker")return!1;return!!(a$.versions&&(a$.versions.node||a$.versions.bun))}return!1}class Bh{async format($){let J=await a2(),G=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:G})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:XJ.pid,hostname:J(),environment:XJ.env.NODE_ENV||"development",platform:XJ.platform,version:XJ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:XJ.env.NODE_ENV||XJ.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($,J={}){this.name=$,this.config={...VG},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new Bh,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??M0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let G={...J},H=J.timestamp!==void 0;if(H)delete G.timestamp;if(this.config={...this.config,...G,timestamp:H||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let A=this.generateKeyId(),z=this.generateKey();this.currentKeyId=A,this.keys.set(A,z),this.encryptionKeys.set(A,{key:z,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},G=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[G]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...B5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...B5};return{...B5,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:VG.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},G={...J,...Object.fromEntries(Object.entries($).filter(([,H])=>H!==void 0))};if(!G.level||!["debug","info","success","warning","error"].includes(G.level))G.level=J.level;return G}shouldWriteToFile(){return!l0()&&this.config.writeToFile===!0}async writeToFile($){let J=(async()=>{let H,A=0,z=3,U=1000;while(A<z)try{try{try{await N2(this.config.logDirectory,Xh.F_OK|Xh.W_OK)}catch(Y){if(Y instanceof Error&&"code"in Y)if(Y.code==="ENOENT")await T2(this.config.logDirectory,{recursive:!0,mode:493});else if(Y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Y;else throw Y}}catch(Y){throw console.error("Debug: [writeToFile] Failed to create log directory:",Y),Y}let h=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:t$.from($);try{if(!D5(this.currentLogFile))await a9(this.currentLogFile,"",{mode:420});if(H=Eh(this.currentLogFile,"a",420),P2(H,h,{flag:"a"}),Zh(H),H!==void 0)t9(H),H=void 0;if((await ZJ(this.currentLogFile)).size===0){if(await a9(this.currentLogFile,h,{flag:"w",mode:420}),(await ZJ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Y){let Z=Y;if(Z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Z.code)){if(A<z-1){let E=typeof Z.message==="string"?Z.message:"Unknown error";console.error(`Network error during write attempt ${A+1}/${z}:`,E);let X=U*2**A;await new Promise((F)=>setTimeout(F,X)),A++;continue}}if(Z?.code&&["ENOSPC","EDQUOT"].includes(Z.code))throw Error(`Disk quota exceeded or no space left on device: ${Z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Z),Z}finally{if(H!==void 0)try{t9(H)}catch(Y){console.error("Debug: [writeToFile] Error closing file descriptor:",Y)}}}catch(h){if(A===z-1){let Z=h,E=typeof Z.message==="string"?Z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),h}A++;let Y=U*2**(A-1);await new Promise((Z)=>setTimeout(Z,Y))}})();this.pendingOperations.push(J);let G=this.pendingOperations.length-1;try{await J}catch(H){throw console.error("Debug: [writeToFile] Error in operation:",H),H}finally{this.pendingOperations.splice(G,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 EJ(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 EJ(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return EJ(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(l0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let J=typeof $.interval==="number"?$.interval:60,G=Math.max(J,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((H)=>{console.error("Error rotating keys:",H)})},G)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date});let H=Array.from(this.encryptionKeys.entries()).sort(([,U],[,h])=>h.createdAt.getTime()-U.createdAt.getTime()),A=typeof $.maxKeys==="number"?$.maxKeys:1,z=Math.max(1,A);if(H.length>z)for(let[U]of H.slice(z))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return o9(16).toString("hex")}generateKey(){return o9(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:J}=this.getCurrentKey(),G=o9(16),H=I2("aes-256-gcm",J,G),A=t$.isBuffer($)?$:t$.from($,"utf8"),z=H.update(A),U=H.final(),h=z.length+U.length,Y=H.getAuthTag(),Z=t$.allocUnsafe(16+h+16);return G.copy(Z,0),z.copy(Z,16),U.copy(Z,16+z.length),Y.copy(Z,16+h),{encrypted:Z,iv:G}}async compressData($){return new Promise((J,G)=>{let H=Wh(),A=[];H.on("data",(z)=>A.push(z)),H.on("end",()=>J(t$.from(t$.concat(A)))),H.on("error",G),H.write($),H.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 J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(l0())return;if(!this.shouldWriteToFile())return;let $=await ZJ(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let G=this.currentLogFile,H=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let A=await Q5(this.config.logDirectory),z=A.filter((Y)=>Y.startsWith(this.name)&&/\.log\.\d+$/.test(Y)).sort((Y,Z)=>{let E=Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=z.length>0?Number.parseInt(z[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${G}.${U}`;if(await ZJ(G).catch(()=>null))try{if(await jh(G,h),J.compress)try{let Y=`${h}.gz`;await this.compressLogFile(h,Y),await V5(h)}catch(Y){console.error("Error compressing rotated file:",Y)}if(z.length===0&&!A.some((Y)=>Y.endsWith(".log.1")))try{let Y=`${G}.1`;await a9(Y,"")}catch(Y){console.error("Error creating backup file:",Y)}}catch(Y){console.error(`Error during rotation: ${Y instanceof Error?Y.message:String(Y)}`)}}else{let A=new Date().toISOString().replace(/[:.]/g,"-"),z=G.replace(/\.log$/,`-${A}.log`);if(await ZJ(G).catch(()=>null))await jh(G,z)}if(this.currentLogFile=H,J.maxFiles){let A=(await Q5(this.config.logDirectory)).filter((z)=>z.startsWith(this.name)).sort((z,U)=>U.localeCompare(z));for(let z of A.slice(J.maxFiles))await V5(EJ(this.config.logDirectory,z))}}}async compressLogFile($,J){let G=hh($),H=_2(J),A=Wh();await y2(G,A,H)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let G of this.logBuffer){let H=await this.formatter.format(G);if(this.shouldWriteToFile())await this.writeToFile(H);console.log(H)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),D5(this.currentLogFile))try{let $=Eh(this.currentLogFile,"r+");Zh($),t9($)}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(!l0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await Q5(this.config.logDirectory)).filter((J)=>(J.includes("temp")||J.includes(".tmp"))&&J.includes(this.name));for(let J of $)try{await V5(EJ(this.config.logDirectory,J))}catch(G){console.error(`Failed to delete temp file ${J}:`,G)}}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()?Q0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||l0())return!1;let $=typeof M0.env.NO_COLOR<"u",J=M0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof M0.stderr<"u"&&M0.stderr.isTTY||typeof M0.stdout<"u"&&M0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:G="",tag:H="",message:A,level:z,showTimestamp:U=!0}=$,h=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(U)R.push(J);if(z==="warning")R.push("WARN");else if(z==="error")R.push("ERROR");else if(G)R.push(G.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(H)R.push(H.replace(/[[\]]/g,""));return R.push(A),R.join(" ")}let Y=M0.stdout.columns||120,Z="";if(z==="warning"||z==="error")Z=`${G} ${A}`;else if(z==="info"||z==="success")Z=`${G} ${H} ${A}`;else Z=`${G} ${H} ${Q0.cyan(A)}`;if(!U)return Z.trim();let E=h(Z).trim().length,X=h(J).length,F=Math.max(1,Y-2-E-X);return`${Z.trim()}${" ".repeat(F)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(z,U)=>{let h=Number.parseInt(U,10);return h<J[0].length?String(J[0][h]):z});let G=/%([sdijfo%])/g,H=0,A=$.replace(G,(z,U)=>{if(U==="%")return"%";if(H>=J.length)return z;let h=J[H++];switch(U){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return z}});if(H<J.length)A+=` ${J.slice(H).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`;return A}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(G,H,A)=>{let z=Q0.underline(Q0.blue(H)),U=this.toAbsoluteFilePath(A);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(U)}`,Y="\x1B]8;;",Z="\x1B\\";return`\x1B]8;;${h}\x1B\\${z}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${A}\x1B\\${z}\x1B]8;;\x1B\\`;return z}),J=J.replace(/`([^`]+)`/g,(G,H)=>Q0.bgGray(H)),J=J.replace(/\*\*([^*]+)\*\*/g,(G,H)=>Q0.bold(H)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(G,H)=>Q0.italic(H)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(G,H)=>Q0.italic(H)),J=J.replace(/~([^~]+)~/g,(G,H)=>Q0.strikethrough(H)),J}supportsHyperlinks(){if(l0())return!1;let $=M0.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 J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let G=M0.env.HOME||"";if(G)J=J.replace(/^~(?=$|\/)/,G)}if(k2(J)||J.startsWith("./")||J.startsWith("../"))J=q2(J);else return null;return D5(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,G=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:G}}async log($,J,...G){if(!this.shouldLog($))return;let H=new Date,A=this.formatConsoleTimestamp(H),z=this.formatFileTimestamp(H),U,h;if(J instanceof Error)U=J.message,h=J.stack;else U=this.formatMessage(J,G);let{consoleText:Y,fileText:Z}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let X=this.options.showIcons===!1?"":Ch[$],F=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"",R;switch($){case"debug":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Q0.gray(Y),level:$}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.warn(R);break;case"success":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Q0.green(Y),level:$}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:A,icon:X,tag:F,message:Y,level:$}),console.error(R),h){let C=h.split(`
438
- `);for(let W of C)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:A,message:Q0.gray(` ${W}`),level:$,showTimestamp:!1}))}break}}else if(!l0()){if(console.error(`${z} ${this.environment}.${$.toUpperCase()}: ${U}`),h)console.error(h)}let E=`${z} ${this.environment}.${$.toUpperCase()}: ${Z}
439
- `;if(h)E+=`${h}
440
- `;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,J=""){let G={update:(A,z)=>{},finish:(A)=>{},interrupt:(A,z)=>{}};if(!this.enabled)return G;let H=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:J||"",barLength:H,lastRenderedLine:""},this.shouldStyleConsole()&&!l0()&&M0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(A,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,A),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!l0()&&M0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(A)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,A)},interrupt:(A,z="info")=>{if(!l0()&&M0.stdout.isTTY)M0.stdout.write(`
441
- `);if(this[z==="warning"?"warn":z](A),this.activeProgressBar&&this.shouldStyleConsole()&&!l0()&&M0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let J=performance.now();if(this.shouldStyleConsole()){let G=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"",H=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":Q0.blue("\u25D0"),tag:G,message:`${Q0.cyan($)}...`}))}return async(G)=>{if(!this.enabled)return;let H=performance.now(),A=Math.round(H-J),z=`${$} completed in ${A}ms`,U=new Date,h=this.formatConsoleTimestamp(U),Y=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${z}`;if(G)Y+=` ${JSON.stringify(G)}`;if(Y+=`
442
- `,Y=Y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":Q0.green("\u2713"),tag:Z,message:`${z}${G?` ${JSON.stringify(G)}`:""}`}))}else if(!l0())console.error(Y.trim());if(this.shouldWriteToFile())await this.writeToFile(Y)}}async debug($,...J){await this.log("debug",$,...J)}async info($,...J){await this.log("info",$,...J)}async success($,...J){await this.log("success",$,...J)}async warn($,...J){await this.log("warning",$,...J)}async error($,...J){await this.log("error",$,...J)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:J}=$;return!!J}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let J=`${this.name}:${$}`,G=new _5(J,{...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(G),G}createReadStream(){if(l0())throw Error("createReadStream is not supported in browser environments");if(!D5(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return hh(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let J=this.config.rotation;if(!J.encrypt||typeof J.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let G=this.keys.get(this.currentKeyId);try{let H=t$.isBuffer($)?$:t$.from($,"base64"),A=H.subarray(0,16),z=H.subarray(H.length-16),U=H.subarray(16,H.length-16),h=S2("aes-256-gcm",G,A);h.setAuthTag(z);let Y=h.update(U),Z=h.final(),E=Y.length+Z.length,X=t$.allocUnsafe(E);return Y.copy(X,0),Z.copy(X,Y.length),X.toString("utf8")}catch(H){throw Error(`Decryption failed: ${H instanceof Error?H.message:String(H)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return l0()}isServerMode(){return!l0()}setTestEncryptionKey($,J){this.currentKeyId=$,this.keys.set($,J)}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 J=new Date,G=this.formatConsoleTimestamp(J),H=this.formatFileTimestamp(J),{consoleText:A,fileText:z}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let h=A.split(`
443
- `),Y=Math.max(...h.map((F)=>F.length))+2,Z=`\u250C${"\u2500".repeat(Y)}\u2510`,E=`\u2514${"\u2500".repeat(Y)}\u2518`,X=h.map((F)=>{return this.formatConsoleMessage({timestamp:G,message:Q0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:G,message:Q0.cyan(Z),showTimestamp:!1})),X.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:G,message:Q0.cyan(E),showTimestamp:!1}))}else if(!l0())console.error(`${H} ${this.environment}.INFO: [BOX] ${z}`);let U=`${H} ${this.environment}.INFO: [BOX] ${z}
444
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(l0())return Promise.resolve(!0);return new Promise((J)=>{console.error(`${Q0.cyan("?")} ${$} (y/n) `);let G=(H)=>{let A=H.toString().trim().toLowerCase();M0.stdin.removeListener("data",G);try{if(typeof M0.stdin.setRawMode==="function")M0.stdin.setRawMode(!1)}catch{}M0.stdin.pause(),console.error(""),J(A==="y"||A==="yes")};try{if(typeof M0.stdin.setRawMode==="function")M0.stdin.setRawMode(!0)}catch{}M0.stdin.resume(),M0.stdin.once("data",G)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...J){if(!this.enabled)return;let G=$;if(J&&J.length>0){let U=/%([sdijfo%])/g,h=0;if(G=$.replace(U,(Y,Z)=>{if(Z==="%")return"%";if(h>=J.length)return Y;let E=J[h++];switch(Z){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 Y}}),h<J.length)G+=` ${J.slice(h).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`}let{consoleText:H,fileText:A}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${Q0.blue("\u25D0")} `;console.error(`${h}${U} ${Q0.cyan(H)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
445
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,J=!1){if(!this.enabled||!this.shouldStyleConsole()||!M0.stdout.isTTY)return;let G=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),H=Math.round($.barLength*G/100),A=$.barLength-H,z=Q0.green("\u2501".repeat(H)),U=Q0.gray("\u2501".repeat(A)),h=`[${z}${U}]`,Y=`${G}%`.padStart(4),Z=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":J||G===100?Q0.green("\u2713"):Q0.blue("\u25B6"),X=this.options.showTags!==!1&&this.name?` ${Q0.gray(this.formatTag(this.name))}`:"",F=`\r${E}${X} ${h} ${Y}${Z}`,R=M0.stdout.columns||80,C=" ".repeat(Math.max(0,R-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${C}`,M0.stdout.write($.lastRenderedLine),J)M0.stdout.write(`
446
- `)}finishProgressBar($,J){if(!this.enabled||!this.fancy||l0()||!M0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(J)$.message=J;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(l0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let J=await Q5(this.config.logDirectory),G=[];for(let H of J){if(!($.name?new RegExp($.name.replace("*",".*")).test(H):H.startsWith(this.name))||!H.endsWith(".log"))continue;let A=EJ(this.config.logDirectory,H);if($.before)try{if((await ZJ(A)).mtime>=$.before)continue}catch(z){console.error(`Failed to get stats for file ${A}:`,z);continue}G.push(A)}if(G.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${G.length} log file(s)...`);for(let H of G)try{await V5(H),console.warn(`Deleted log file: ${H}`)}catch(A){console.error(`Failed to delete log file ${H}:`,A)}console.warn("Log clearing process finished.")}catch(J){console.error("Error during log clearing process:",J)}}}async function Ih($,J={}){let{maxRetries:G=3,retryDelay:H=1000,isRetryable:A=()=>!0,fallback:z}=J,U=Error("Unknown error occurred");for(let h=0;h<=G;h++)try{return await $()}catch(Y){if(U=Y instanceof Error?Y:Error(String(Y)),h===G||!A(U))break;if(H>0)await new Promise((Z)=>setTimeout(Z,H))}if(z!==void 0)return z;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Sh($){return $ instanceof w$}function Lj($){return $ instanceof I5}function wj($){if(Sh($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((J)=>$.message.toLowerCase().includes(J.toLowerCase()))}class P5{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,J)=>J==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let J=$.toLowerCase();return["true","1","yes"].includes(J)}},{name:"number",canParse:($,J)=>J==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let J=Number($);if(Number.isNaN(J))throw TypeError(`Cannot parse "${$}" as number`);return J}},{name:"array",canParse:($,J)=>J==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let J=JSON.parse($);if(Array.isArray(J))return J}catch{}return $.split(",").map((J)=>J.trim())}},{name:"json",canParse:($,J)=>J==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(J){throw Error(`Cannot parse "${$}" as JSON: ${J}`)}}}]}async applyEnvironmentVariables($,J,G={}){let{prefix:H,useCamelCase:A=!0,useBackwardCompatibility:z=!0,customParsers:U={},verbose:h=!1,trackPerformance:Y=!0}=G,Z=async()=>{if(!$)return{config:J,source:{type:"environment",priority:50,timestamp:new Date}};let E=H||this.generateEnvPrefix($),X={...J};return this.processObject(X,[],E,{useCamelCase:A,useBackwardCompatibility:z,customParsers:U,verbose:h,configName:$}),{config:X,source:{type:"environment",priority:50,timestamp:new Date}}};if(Y)return qG.track("applyEnvironmentVariables",Z,{configName:$});return Z()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,J){if(!J)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,J,G,H){for(let[A,z]of Object.entries($)){let U=[...J,A],h=U.map((E)=>this.formatEnvKey(E,H.useCamelCase)),Y=`${G}_${h.join("_")}`,Z=H.useBackwardCompatibility?`${G}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(H.verbose);if(typeof z==="object"&&z!==null&&!Array.isArray(z))this.processObject(z,U,G,H);else{let E=O5.env[Y]||(Z?O5.env[Z]:void 0);if(E!==void 0){if(H.verbose){let X=O5.env[Y]?Y:Z}try{$[A]=this.parseEnvironmentValue(E,typeof z,Y,H.customParsers,H.configName)}catch(X){if(X instanceof S5)throw X;throw R1.envVar(Y,E,typeof z,H.configName)}}}}}parseEnvironmentValue($,J,G,H,A){for(let[z,U]of Object.entries(H))try{return U($)}catch{continue}for(let z of this.defaultParsers)if(z.canParse($,J))try{return z.parse($)}catch{throw R1.envVar(G,$,`${J} (via ${z.name} parser)`,A)}return $}getEnvironmentVariables($){let J={},G=$.toUpperCase();for(let[H,A]of Object.entries(O5.env))if(H.startsWith(G)&&A!==void 0)J[H]=A;return J}validateEnvironmentVariable($,J,G){let H=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))H.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(G)try{this.parseEnvironmentValue($,J,G,{})}catch(A){H.push(`Cannot parse value "${J}" as ${G}: ${A}`)}return{isValid:H.length===0,errors:H}}generateEnvVarDocs($,J,G={}){let{prefix:H,format:A="text"}=G,z=H||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(J,[],z,U),A){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,J,G,H){for(let[A,z]of Object.entries($)){let U=[...J,A],h=`${G}_${U.map((Y)=>this.formatEnvKey(Y,!0)).join("_")}`;if(typeof z==="object"&&z!==null&&!Array.isArray(z))this.extractEnvVarInfo(z,U,G,H);else H.push({key:h,type:Array.isArray(z)?"array":typeof z,description:`Configuration for ${U.join(".")}`,example:this.generateExample(z)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,J){let G=`Environment Variables for ${J}:
447
-
448
- `;for(let H of $)G+=`${H.key}
449
- `,G+=` Type: ${H.type}
450
- `,G+=` Description: ${H.description}
451
- `,G+=` Example: ${H.example}
452
-
453
- `;return G}formatAsMarkdown($,J){let G=`# Environment Variables for ${J}
454
-
455
- `;G+=`| Variable | Type | Description | Example |
456
- `,G+=`|----------|------|-------------|----------|
457
- `;for(let H of $)G+=`| \`${H.key}\` | ${H.type} | ${H.description} | \`${H.example}\` |
458
- `;return G}}function Rj($,J){let G=r2("process");if(typeof G>"u"||!G.env)return J;let H=G.env[$];return H!==void 0?H:J}function Ph($,J,G={}){return Nh($,J,G,new WeakMap)}function Nh($,J,G,H){let{arrayMergeMode:A="replace",skipNullish:z=!1,customMerger:U}=G;if(J===null||J===void 0)return z?$:J;if(U){let h=U($,J);if(h!==void 0)return h}if(Array.isArray(J)||Array.isArray($))return Th($,J,A,H);if(!B$(J)||!B$($))return J;return Oj($,J,G,H)}function Th($,J,G,H){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(G){case"replace":return J;case"concat":return Dj($,J);case"smart":return Qj($,J,H);default:return J}return J}function Dj($,J){let G=[...J];for(let H of $)if(!G.some((A)=>jz(A,H)))G.push(H);return G}function Qj($,J,G){if(J.length===0)return $;if($.length===0)return J;if(B$(J[0])&&B$($[0]))return Vj($,J,G);if(J.every((H)=>typeof H==="string")&&$.every((H)=>typeof H==="string")){let H=[...J];for(let A of $)if(!H.includes(A))H.push(A);return H}return J}function Vj($,J,G){let H=[...J];for(let A of $){if(!B$(A)){H.push(A);continue}let z=["id","name","key","path","type"],U=!1;for(let h of z)if(h in A){if(H.find((Y)=>B$(Y)&&(h in Y)&&Y[h]===A[h])){U=!0;break}}if(!U)H.push(A)}return H}function Oj($,J,G,H){let A=J;if(B$(A)&&H.has(A))return H.get(A);let z={...$};if(B$(A))H.set(A,z);for(let U in A){if(!Object.prototype.hasOwnProperty.call(A,U))continue;let h=A[U],Y=z[U];if(G.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){z[U]=h;continue}if(B$(h)&&B$(Y))z[U]=Nh(Y,h,G,H);else if(Array.isArray(h)||Array.isArray(Y))z[U]=Th(Y,h,G.arrayMergeMode||"smart",H);else z[U]=h}return z}function Lz($,J,G="replace"){return Ph($,J,{arrayMergeMode:G==="replace"?"replace":"smart",skipNullish:!0})}function jz($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let G=0;G<$.length;G++)if(!jz($[G],J[G]))return!1;return!0}if(B$($)&&B$(J)){let G=Object.keys($),H=Object.keys(J);if(G.length!==H.length)return!1;for(let A of G){if(!Object.prototype.hasOwnProperty.call(J,A))return!1;if(!jz($[A],J[A]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class N5{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,G={}){let{arrayStrategy:H="replace",useCache:A=!0,cacheTtl:z,trackPerformance:U=!0,verbose:h=!1}=G;if(A){let Z=qJ.getWithFileCheck("file",$);if(Z){if(h)console.log(`Configuration loaded from cache: ${$}`);return Z}}let Y=async()=>{if(!M5($))return null;try{let Z=`?t=${Date.now()}`,E=await import($+Z),X=E.default||E,F="default"in E,R=Object.keys(E).length>0;if(!F&&!R)throw new OG($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof X!=="object"||X===null||Array.isArray(X))throw new OG($,Error("Configuration must export a valid object"),"unknown");let C={config:Lz(J,X,H),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(A)qJ.setWithFileCheck("file",C,$,z);return C}catch(Z){throw Z instanceof Error?R1.configLoad($,Z):R1.configLoad($,Error(String(Z)))}};if(U)return qG.track("loadFromPath",Y,{path:$});return Y()}async tryLoadFromPaths($,J,G={}){for(let H of $)try{let A=await this.loadFromPath(H,J,G);if(A)return A}catch(A){if(A instanceof Error&&A.name==="ConfigLoadError")throw A;if(G.verbose)console.warn(`Failed to load config from ${H}:`,A)}return null}generateConfigPaths($,J,G){let H=this.generateNamePatterns($,G),A=[];for(let z of H)for(let U of this.extensions)A.push(e9(J,`${z}${U}`));return A}generateNamePatterns($,J){let G=[];if(G.push("config",".config"),$)G.push($,`.${$}.config`,`${$}.config`,`.${$}`);let H=J===void 0?[]:Array.isArray(J)?J:[J];for(let z of H){if(!z)continue;if(G.push(z,`.${z}.config`,`${z}.config`,`.${z}`),$)G.push(`${$}.${z}.config`,`.${$}.${z}.config`)}let A=new Set;return G.filter((z)=>{if(!z||A.has(z))return!1;return A.add(z),!0})}checkFileAccess($){return Ih(async()=>{return M5($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,G){let H=[];if(!M5($))return H;if(J||G){let A=this.generateNamePatterns(J||"",G);for(let z of A)for(let U of this.extensions){let h=e9($,`${z}${U}`);if(await this.checkFileAccess(h))H.push(h)}}else try{let{readdirSync:A}=await import("fs"),z=A($);for(let U of z)if(this.looksLikeConfigFile(U)){let h=e9($,U);if(await this.checkFileAccess(h))H.push(h)}}catch{return[]}return H}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((J)=>J.test($))}async validateConfigFile($){let J=[];try{if(!M5($))return J.push("Configuration file does not exist"),J;let G=await import($),H=G.default||G;if(H===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof H!=="object"||H===null)J.push("Configuration must be an object");else if(Array.isArray(H))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:A}=await import("fs"),z=A($,"utf8");JSON.parse(z)}catch(A){J.push(`Invalid JSON syntax: ${A}`)}}catch(G){J.push(`Failed to load configuration file: ${G}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let G=new Map;return await Promise.allSettled($.map(async(H)=>{try{let A=await this.loadFromPath(H,{},J);if(A)G.set(H,A.config)}catch(A){if(J.verbose)console.warn(`Failed to preload ${H}:`,A)}})),G}}class Rz{async validateConfiguration($,J,G={}){let{stopOnFirstError:H=!1,validateRequired:A=!0,validateTypes:z=!0,customRules:U=[],trackPerformance:h=!0,verbose:Y=!1}=G,Z=async()=>{let E=[],X=[],F={stopOnFirstError:H,validateRequired:A,validateTypes:z,customRules:U,trackPerformance:h,verbose:Y};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,F);else if(Array.isArray(J))return this.validateWithRules($,[...J,...U],F);else return this.validateWithJSONSchema($,J,F)}catch(R){return E.push({path:"",message:`Validation failed: ${R}`,rule:"system"}),{isValid:!1,errors:E,warnings:X}}};if(h)return await qG.track("validateConfiguration",Z);return Z()}async validateWithSchemaFile($,J,G){try{if(!x2(J))throw new MG(J,[{path:"",message:"Schema file does not exist"}]);let H=await import(J),A=H.default||H;if(Array.isArray(A))return this.validateWithRules($,A,G);else return this.validateWithJSONSchema($,A,G)}catch(H){throw new MG(J,[{path:"",message:`Failed to load schema: ${H}`}])}}validateWithJSONSchema($,J,G){let H=[],A=[];return this.validateObjectAgainstSchema($,J,"",H,A,G),{isValid:H.length===0,errors:H,warnings:A}}validateObjectAgainstSchema($,J,G,H,A,z){if(z.validateTypes&&J.type){let U=Array.isArray($)?"array":typeof $,h=Array.isArray(J.type)?J.type:[J.type];if(!h.includes(U)){if(H.push({path:G,message:`Expected type ${h.join(" or ")}, got ${U}`,expected:h.join(" or "),actual:U,rule:"type"}),z.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(H.push({path:G,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),z.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)H.push({path:G,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)H.push({path:G,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))H.push({path:G,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)H.push({path:G,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)H.push({path:G,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let U=0;U<$.length;U++){let h=G?`${G}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],J.items,h,H,A,z),z.stopOnFirstError&&H.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(z.validateRequired&&J.required){for(let h of J.required)if(!(h in U)){if(H.push({path:G?`${G}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),z.stopOnFirstError)return}}if(J.properties){for(let[h,Y]of Object.entries(J.properties))if(h in U){let Z=G?`${G}.${h}`:h;if(this.validateObjectAgainstSchema(U[h],Y,Z,H,A,z),z.stopOnFirstError&&H.length>0)return}}if(J.additionalProperties===!1){let h=new Set(Object.keys(J.properties||{}));for(let Y of Object.keys(U))if(!h.has(Y))A.push({path:G?`${G}.${Y}`:Y,message:`Additional property '${Y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,G){let H=[],A=[];for(let z of J)try{let U=this.getValueByPath($,z.path),h=this.validateWithRule(U,z,z.path);if(H.push(...h),G.stopOnFirstError&&H.length>0)break}catch(U){H.push({path:z.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:H.length===0,errors:H,warnings:A}}validateWithRule($,J,G){let H=[];if(J.required&&($===void 0||$===null))return H.push({path:G,message:J.message||`Property '${G}' is required`,expected:"required",rule:"required"}),H;if($===void 0||$===null)return H;if(J.type){let A=Array.isArray($)?"array":typeof $;if(A!==J.type)H.push({path:G,message:J.message||`Expected type ${J.type}, got ${A}`,expected:J.type,actual:A,rule:"type"})}if(J.min!==void 0){let A=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(A<J.min)H.push({path:G,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:A,rule:"min"})}if(J.max!==void 0){let A=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(A>J.max)H.push({path:G,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:A,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))H.push({path:G,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))H.push({path:G,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let A=J.validator($);if(A)H.push({path:G,message:J.message||A,rule:"custom"})}return H}getValueByPath($,J){if(!J)return $;let G=J.split("."),H=$;for(let A of G)if(H&&typeof H==="object"&&A in H)H=H[A];else return;return H}generateRulesFromInterface($){let J=[],G=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let H of G){let[,A,z,U]=H;J.push({path:A,required:!z,type:this.mapTypeScriptType(U)})}return J}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:yh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Mj($){if(!$)return"";let J=Array.isArray($)?$.filter(Boolean):[$];if(J.length===0)return"";if(J.length===1)return` or alias "${J[0]}"`;return` or aliases ${J.map((G)=>`"${G}"`).join(", ")}`}class Dz{fileLoader=new N5;envProcessor=new P5;validator=new Rz;async loadConfig($){let J=Date.now(),{cache:G,performance:H,schema:A,validate:z,...U}=$;try{if(G?.enabled){let Y=this.checkCache(U.name||"",U);if(Y)return Y}let h;try{h=await this.loadConfigurationStrategies(U,!0,G)}catch(Y){let Z=U.__strictErrorHandling;if(Y instanceof Error&&Y.name==="ConfigNotFoundError"){if(Z)throw Y;h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Y instanceof Error&&Y.name==="ConfigLoadError"){let E=Y.message.includes("EACCES")||Y.message.includes("EPERM")||Y.message.includes("permission denied"),X=!E&&(Y.message.includes("syntax")||Y.message.includes("Expected")||Y.message.includes("Unexpected")||Y.message.includes("BuildMessage")||Y.message.includes("errors building")),F=Y.message.includes("Configuration must export a valid object")||Y.message.includes("Configuration file is empty and exports nothing");if(Z&&(F||E))throw Y;if(X&&(!Z||!F))h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Z)h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Y.message}`]};else throw Y}else h={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Y instanceof Error?Y.message:String(Y)}`]}}if(A||z)await this.validateConfiguration(h.config,A,z,U.name);if(G?.enabled&&h)this.cacheResult(U.name||"",h,G,U);if(H?.enabled){let Y={operation:"loadConfig",duration:Date.now()-J,configName:U.name,timestamp:new Date};if(H.onMetrics)H.onMetrics(Y);if(H.slowThreshold&&Y.duration>H.slowThreshold)K$.warn(`Slow configuration loading detected: ${Y.duration}ms for ${U.name}`);h.metrics=Y}return h}catch(h){let Y=Date.now()-J;throw K$.error(`Configuration loading failed after ${Y}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies($,J=!1,G){let{name:H="",alias:A,cwd:z,configDir:U,defaultConfig:h,checkEnv:Y=!0,arrayStrategy:Z="replace",verbose:E=!1}=$,X=z||v1.cwd(),F=[],R=await this.loadLocalConfiguration(H,A,X,U,h,Z,E,Y,G);if(R)return F.push(...this.getLocalSearchPaths(H,A,X,U)),this.finalizeResult(R,F,Y,H,E);let C=await this.loadHomeConfiguration(H,A,h,Z,E,Y);if(C)return F.push(...this.getHomeSearchPaths(H,A)),this.finalizeResult(C,F,Y,H,E);let W=await this.loadPackageJsonConfiguration(H,A,X,h,Z,E,Y);if(W)return F.push(Y$(X,"package.json")),this.finalizeResult(W,F,Y,H,E);if(F.push(...this.getAllSearchPaths(H,A,X,U)),J)throw R1.configNotFound(H,F,A);return{...await this.applyEnvironmentVariables(H,h,Y,E),warnings:[`No configuration file found for "${H}"${Mj(A)}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,G,H,A,z,U,h,Y){let Z=h?QG($,A,U):A,E=this.getLocalDirectories(G,H);for(let X of E){if(U)K$.info(`Searching for configuration in: ${X}`);let F=this.fileLoader.generateConfigPaths($,X,J),R=await this.fileLoader.tryLoadFromPaths(F,Z,{arrayStrategy:z,verbose:U,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(R){if(U)K$.success(`Configuration loaded from: ${R.source.path}`);return R}}return null}async loadHomeConfiguration($,J,G,H,A,z){if(!$)return null;let U=z?QG($,G,A):G,h=[Y$(jJ(),".config",$),Y$(jJ(),".config"),jJ()];for(let Y of h){if(A)K$.info(`Checking home directory: ${Y}`);let Z=this.fileLoader.generateConfigPaths($,Y,J),E=await this.fileLoader.tryLoadFromPaths(Z,U,{arrayStrategy:H,verbose:A});if(E){if(A)K$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,J,G,H,A,z,U){let h=U?QG($,H,z):H;try{let Y=Y$(G,"package.json");if(!zz(Y))return null;let Z={};try{Z=JSON.parse(g2(Y,"utf8"))}catch(F){if(z)K$.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let E=Z[$],X=$;if(!E&&J){let F=Array.isArray(J)?J:[J];for(let R of F){if(!R)continue;if(Z[R]){E=Z[R],X=R;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(z)K$.success(`Configuration loaded from package.json: ${X}`);return{config:Lz(h,E,A),source:{type:"package.json",path:Y,priority:30,timestamp:new Date}}}}catch(Y){if(z)K$.warn("Failed to load package.json:",[Y instanceof Error?Y:Error(String(Y))])}return null}async applyEnvironmentVariables($,J,G,H){if(!G||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:QG($,J,H),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,G,H,A){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,G,H){let A=[];if(G){let z=G($);if(z)A.push(...z)}if(J){let z=await this.validator.validateConfiguration($,J);if(!z.isValid)A.push(...z.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(A.length>0)throw R1.configValidation(H||"unknown",A,H)}checkCache($,J){let G=this.generateCacheKey($,J);return qJ.get(G)||null}cacheResult($,J,G,H){let A=this.generateCacheKey($,H);qJ.set(A,J,void 0,G.ttl)}generateCacheKey($,J){let G=[$];if(J.alias){let H=Array.isArray(J.alias)?J.alias.join(","):J.alias;G.push(`alias:${H}`)}if(J.cwd)G.push(`cwd:${J.cwd}`);if(J.configDir)G.push(`configDir:${J.configDir}`);if("checkEnv"in J)G.push(`checkEnv:${J.checkEnv}`);return G.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,Y$($,"config"),Y$($,".config"),J?Y$($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,G,H){let A=[];return A.push(...this.getLocalSearchPaths($,J,G,H)),A.push(...this.getHomeSearchPaths($,J)),A.push(Y$(G,"package.json")),A}getLocalSearchPaths($,J,G,H){let A=this.getLocalDirectories(G,H),z=[];for(let U of A)z.push(...this.fileLoader.generateConfigPaths($,U,J));return z}getHomeSearchPaths($,J){if(!$)return[];let G=[Y$(jJ(),".config",$),Y$(jJ(),".config"),jJ()],H=[];for(let A of G)H.push(...this.fileLoader.generateConfigPaths($,A,J));return H}async loadConfigWithResult($){return this.loadConfig($)}}function Oh($){let J=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),G=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return J||G}async function Kj($){return e$.loadConfig({...$,__strictErrorHandling:!0})}async function Qz($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},G="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let H;if(G)H=await e$.loadConfig($);else H=await e$.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return H?.config??J}catch(H){let A=H instanceof Error?H.name:"UnknownError",z=H instanceof Error?H.message:String(H);if(!(A==="ConfigNotFoundError"||A==="ConfigLoadError"||A==="ConfigValidationError"||z.includes("config"))&&$.verbose)K$.warn("Unexpected error loading config, using defaults:",[H instanceof Error?H:Error(String(H))]);let U=G?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await e$.applyEnvironmentVariables(U.name||"",J,!0,U.verbose||!1))?.config??J;return J}}async function Bj($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:J}=await import("process");try{return(await e$.loadConfig({name:$,cwd:J(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(G){if(G instanceof Error&&(G.name==="ConfigNotFoundError"||G.name==="ConfigLoadError"&&Oh(G)))return(await e$.applyEnvironmentVariables($,{},!0,!1)).config;throw G}}try{return(await e$.loadConfig({...$,cwd:$.cwd||v1.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(J){if(J instanceof Error&&(J.name==="ConfigNotFoundError"||J.name==="ConfigLoadError"&&Oh(J)))return(await e$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw J}}async function Cj($,J,G="replace"){let H=new N5;try{let A=await H.loadFromPath($,J,{arrayStrategy:G,useCache:!1,trackPerformance:!1});return A?A.config:null}catch{return null}}function QG($,J,G=!1){let H=new P5,A=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function z(U,h=[]){let Y={...U};for(let[Z,E]of Object.entries(U)){let X=[...h,Z],F=[`${A}_${X.join("_").toUpperCase()}`,`${A}_${X.map((W)=>W.toUpperCase()).join("")}`,`${A}_${X.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],R,C;for(let W of F)if(R=v1.env[W],R!==void 0){C=W;break}if(R!==void 0&&C)if(typeof E==="boolean")Y[Z]=["true","1","yes"].includes(R.toLowerCase());else if(typeof E==="number"){let W=Number(R);if(!Number.isNaN(W))Y[Z]=W}else if(Array.isArray(E))try{Y[Z]=JSON.parse(R)}catch{Y[Z]=R.split(",").map((W)=>W.trim())}else Y[Z]=R;else if(E&&typeof E==="object"&&!Array.isArray(E))Y[Z]=z(E,X)}return Y}return z(J)}function Ij($){let J=Y$(v1.cwd(),$.configDir),G=Y$(v1.cwd(),$.generatedDir),H=Y$(G,"config-types.ts");if(!zz(Fh(H)))f2(Fh(H),{recursive:!0,mode:511});let A=zz(J)?v2(J).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],z=`// Generated by bunfig v${Wj}
459
- export type ConfigNames = ${A.length?`'${A.join("' | '")}'`:"string"}
460
- `;b2(H,z,{mode:438})}function Sj($){let J=null,G=null,H=()=>{if(!G)G=Qz($).then((z)=>{return J=z,z},(z)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(J=U,"verbose"in $&&$.verbose)K$.warn("Config loading failed, using defaults:",[z instanceof Error?z:Error(String(z))]);return U});return G},A="defaultConfig"in $?$.defaultConfig:{};return J=A,H(),new Proxy({},{get(z,U){if(J)return J[U];let h=A[U];return H(),h},has(z,U){return U in(J||A)},ownKeys(){return Object.keys(J||A)},getOwnPropertyDescriptor(z,U){return Object.getOwnPropertyDescriptor(J||A,U)},set(z,U,h){if(!J)J={...A};return J[U]=h,!0}})}function Pj($){let J=Lh(d2.cwd(),$?.configDir||"./config");function G(){if(!m2(J))return[];let A=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),z=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=c2(J).filter((Y)=>A.has($z(Y))).map((Y)=>({base:Y.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Y})),h=new Map;for(let{base:Y,file:Z}of U){let E=$z(Z).toLowerCase(),X=h.get(Y);if(!X){h.set(Y,Z);continue}let F=$z(X).toLowerCase();if(z.indexOf(E)<z.indexOf(F))h.set(Y,Z)}return Array.from(h.entries()).map(([Y,Z])=>({base:Y,file:Z})).sort((Y,Z)=>Y.base.localeCompare(Z.base))}function H(){let A=G(),z=A.map((Y)=>Y.base),U=z.length?z.map((Y)=>`'${Y}'`).join(" | "):"string",h=A.length?`{
461
- ${A.map((Y)=>{let Z=Lh(J,Y.file).replace(/\\/g,"/");return` '${Y.base}': typeof import('${Z}').default`}).join(`,
462
- `)}
463
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
464
- export type ConfigByName = ${h}
465
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
466
- export type ConfigOf = Config
467
- `}return{name:"bunfig-plugin",setup(A){A.onResolve({filter:/^virtual:bunfig-types$/},(z)=>{return{path:z.path,namespace:"bunfig-virtual"}}),A.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:H(),loader:"ts"}})}}}async function mh(){if(!Az)Az=await Qz({name:"faker",alias:"mock",defaultConfig:T5});return Az}function LJ($){let J=$.replace(/-/g,"_").split("_"),G=J[0].toLowerCase(),H=J[1]?.toUpperCase(),A=H?`${G}-${H.toLowerCase()}`:G;return{full:$,language:G,region:H,packageName:A,normalized:H?`${G}_${H}`:G}}function Tj($){let J=LJ($);if(J.region)return[J.normalized,J.language];return[J.language]}function kj($){return`@mock-locale/${LJ($).packageName}`}function ch($,J){let G={...$};for(let H in J){let A=J[H],z=$[H];if(A===void 0)continue;if(typeof A==="object"&&A!==null&&!Array.isArray(A)&&typeof z==="object"&&z!==null&&!Array.isArray(z))G[H]=ch(z,A);else G[H]=A}return G}function f1(){let $=dh.cwd(),J=FJ($,"package.json");if(!WJ(J))return!1;try{let G=JSON.parse(yj(J,"utf-8"));return!!(G.workspaces||G.workspace)}catch{return!1}}function Oz(){let $=dh.cwd();if(WJ(FJ($,"bun.lockb"))||WJ(FJ($,"bun.lock")))return"bun";if(WJ(FJ($,"pnpm-lock.yaml")))return"pnpm";if(WJ(FJ($,"yarn.lock")))return"yarn";if(WJ(FJ($,"package-lock.json")))return"npm";return"bun"}function Mz($,J={}){let G=Oz(),{silent:H=!1}=J;if(!H)console.log(`
468
- \uD83D\uDCE6 Installing ${$} using ${G}...`);let A={bun:{cmd:"bun",args:["add",$]},npm:{cmd:"npm",args:["install",$]},yarn:{cmd:"yarn",args:["add",$]},pnpm:{cmd:"pnpm",args:["add",$]}},{cmd:z,args:U}=A[G];try{let h=qj(z,U,{stdio:"pipe",shell:!0}),Y=h.stdout?.toString()||"",Z=h.stderr?.toString()||"",E=Y+Z;if(!H){if(Y)console.log(Y);if(Z)console.error(Z)}if(h.status===0){if(!H)console.log(`\u2713 Successfully installed ${$}`);return!0}else{let X=E;if(X.toLowerCase().includes("dependency loop")||X.includes("DependencyLoop")||X.includes("has a dependency loop")||X.includes("An internal error occurred (DependencyLoop)")){if(!H){if(console.log(`
469
- \u26A0\uFE0F Package ${$} is already available in the workspace and cannot be installed separately due to a dependency loop.`),f1())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!H)console.error(`\u2717 Failed to install ${$}`);return!1}}catch(h){if(!H)console.error(`\u2717 Error installing ${$}:`,h);return!1}}function xJ($,J){let G=[];for(let H of J.rules)if(!H.validator($)){let A=H.errorMessage||`Validation failed for value: ${$}`;if(G.push(A),J.strict)throw Error(A)}return{isValid:G.length===0,errors:G}}function fJ($,J){let{items:G}=J;if(G.length===0)throw Error("Cannot select from empty weighted items array");let H=G.reduce((U,h)=>U+h.weight,0);if(H<=0)throw Error("Total weight must be greater than 0");let A=$.number()*H,z=0;for(let U of G)if(z+=U.weight,A<=z)return U.item;return G[G.length-1].item}function uh($,J){return $.filter((G)=>{if(J.gender&&G.gender&&G.gender!==J.gender)return!1;if(J.country){let H=Array.isArray(J.country)?J.country:[J.country];if(G.country&&!H.includes(G.country))return!1}if(J.region){let H=Array.isArray(J.region)?J.region:[J.region];if(G.region&&!H.includes(G.region))return!1}if(J.locale&&G.locale&&G.locale!==J.locale)return!1;if(J.ageRange&&G.age){let{min:H,max:A}=J.ageRange;if(G.age<H||G.age>A)return!1}for(let[H,A]of Object.entries(J))if(H!=="gender"&&H!=="country"&&H!=="region"&&H!=="locale"&&H!=="ageRange"&&G[H]!==void 0){if(!(Array.isArray(A)?A:[A]).includes(G[H]))return!1}return!0})}function $1($,J){let G={...$};for(let H of J){let{field:A,dependsOn:z,mapping:U}=H;if(G[z]&&U[G[z]])G[A]=U[G[z]]}return G}function ph($,J={}){let G=$();if(J.relationships)return $1(G,J.relationships);return G}class k5{providers=new Map;register($){let{category:J,name:G}=$;if(!this.providers.has(J))this.providers.set(J,new Map);this.providers.get(J).set(G,$)}get($,J){return this.providers.get($)?.get(J)}getProvidersInCategory($){let J=this.providers.get($);return J?Array.from(J.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove($,J){let G=this.providers.get($);if(G)return G.delete(J);return!1}clear(){this.providers.clear()}}class wJ{random;locale;constructor($,J){this.random=$,this.locale=J}street(){let $=this.random.arrayElement(this.locale.address.street),J=this.streetSuffix();return`${$} ${J}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress($){let J=this.buildingNumber(),G=this.street();if($?.useFullAddress)return`${J} ${G}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${J} ${G}`}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 J=$?.min??-90,G=$?.max??90,H=$?.precision??4;return this.random.float(J,G,H)}longitude($){let J=$?.min??-180,G=$?.max??180,H=$?.precision??4;return this.random.float(J,G,H)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced($){let J;if($?.constraints?.country){let G=$.constraints.country,H=Array.isArray(G)?G:[G];J=this.city()}else J=this.city();if($?.weighted)J=fJ(this.random,$.weighted);if($?.relationships)J=$1({city:J,country:$?.constraints?.country},$.relationships).city||J;if($?.validation){let G=xJ(J,$.validation);if(!G.isValid){if($.validation.strict)throw Error(`Validation failed: ${G.errors.join(", ")}`);J=this.city()}}return J}countryAdvanced($){let J;if($?.constraints?.country){let G=$.constraints.country,H=Array.isArray(G)?G:[G];J=this.random.arrayElement(H)}else J=this.country();if($?.weighted)J=fJ(this.random,$.weighted);if($?.relationships)J=$1({country:J},$.relationships).country||J;if($?.validation){let G=xJ(J,$.validation);if(!G.isValid){if($.validation.strict)throw Error(`Validation failed: ${G.errors.join(", ")}`);J=this.country()}}return J}addressAdvanced($){let J=this.countryAdvanced($),G=this.cityAdvanced($),H=this.state(),A=this.stateAbbr(),z=this.zipCode(),U=this.street(),h=this.latitude(),Y=this.longitude(),Z={street:U,city:G,state:H,stateAbbr:A,country:J,countryCode:this.countryCode(),zipCode:z,latitude:h,longitude:Y};if($?.relationships)return $1(Z,$.relationships);return Z}neighborhood($){let J=$?.size||this.random.int(3,10),G=this.cityAdvanced($),H=this.state(),A=this.zipCode(),z=[];for(let U=0;U<J;U++)z.push({street:this.street(),city:G,state:H,zipCode:A,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 z}}class RJ{random;locale;constructor($,J){this.random=$,this.locale=J}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 DJ{random;locale;constructor($,J){this.random=$,this.locale=J}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 z=Array.from({length:9},()=>this.random.int(0,9)),U=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${z.slice(0,1).join("")}-${z.slice(1,4).join("")}-${z.slice(4,9).join("")}-${U}`}let $="978",J=this.random.int(0,9),G=Array.from({length:3},()=>this.random.int(0,9)).join(""),H=Array.from({length:5},()=>this.random.int(0,9)).join(""),A=this.random.int(0,9);return`${$}-${J}-${G}-${H}-${A}`}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 QJ{random;locale;constructor($,J){this.random=$,this.locale=J}hex($){let J=$?.prefix??"#",G=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return J+G}rgb($){let J=this.random.int(0,255),G=this.random.int(0,255),H=this.random.int(0,255);if($?.alpha){let A=this.random.float(0,1,2);if($?.format==="array")return[J,G,H,A];return`rgba(${J}, ${G}, ${H}, ${A})`}if($?.format==="array")return[J,G,H];return`rgb(${J}, ${G}, ${H})`}hsl($){let J=this.random.int(0,360),G=this.random.int(0,100),H=this.random.int(0,100);if($?.alpha){let A=this.random.float(0,1,2);if($?.format==="array")return[J,G,H,A];return`hsla(${J}, ${G}%, ${H}%, ${A})`}if($?.format==="array")return[J,G,H];return`hsl(${J}, ${G}%, ${H}%)`}css($){let J=$?.format??this.random.arrayElement(["hex","rgb","hsl"]);if(J==="hex")return this.hex();if(J==="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 VJ{random;locale;constructor($,J){this.random=$,this.locale=J}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"],J=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],G=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(J)} ${this.random.arrayElement(G)}`}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 J=$?.min??1,G=$?.max??1000,H=$?.dec??2,A=$?.symbol??"",z=this.random.float(J,G,H);return A+z.toFixed(H)}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}."],J=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],G=["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(J)).replace("{benefit}",this.random.arrayElement(G))}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"],J=this.random.int(10,99);return`${this.random.arrayElement($)}${J}`}sku(){let $=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),J=this.random.int(1e4,99999),G=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${$}-${J}-${G}`}}class OJ{random;locale;constructor($,J){this.random=$,this.locale=J}name(){let $=this.random.arrayElement(this.locale.company.name??["Company"]),J=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${$} ${J}`}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"]),J=this.random.arrayElement(this.locale.company.descriptor??["digital"]),G=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${J} ${G}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let $=this.buzzword(),J=this.random.arrayElement(this.locale.company.descriptor??["digital"]),G=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${J} ${G}`}}class KG{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 J=0;J<24;J++)$+="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 J=$?.engine??this.engine().toLowerCase().replace(/ /g,""),G="user",H="password",A="localhost",z=this.random.int(3000,9999),U=this.table(),h={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[J]||"jdbc";if(J==="mongodb")return`${h}://user:password@localhost:${z}/${U}`;return`${h}://user:password@localhost:${z}/${U}`}}class BG{random;constructor($){this.random=$}past($){let J=$?.years??1,G=$?.to??new Date,H=$?.from??new Date(G.getTime()-J*365*24*60*60*1000);return this.between({from:H,to:G})}future($){let J=$?.years??1,G=$?.from??new Date,H=$?.to??new Date(G.getTime()+J*365*24*60*60*1000);return this.between({from:G,to:H})}between($){let J=$.from??new Date(Date.now()-31536000000),G=$.to??new Date,H=J.getTime(),A=G.getTime(),z=this.random.int(H,A);return new Date(z)}recent($){let J=$?.days??1,G=new Date,H=new Date(G.getTime()-J*24*60*60*1000);return this.between({from:H,to:G})}soon($){let J=$?.days??1,G=new Date,H=new Date(G.getTime()+J*24*60*60*1000);return this.between({from:G,to:H})}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($)}birthdate($){let J=$?.mode??"age",G=$?.refDate??new Date;if(J==="year"){let Y=$?.min??1900,Z=$?.max??G.getUTCFullYear(),E=new Date(Date.UTC(Y,0,1)),X=new Date(Date.UTC(Z,11,31,23,59,59,999));return this.between({from:E,to:X})}let H=Math.max(0,$?.min??18),A=Math.max(H,$?.max??80),z=(Y)=>Y*365.25*24*60*60*1000,U=new Date(G.getTime()-z(A)),h=new Date(G.getTime()-z(H));return this.between({from:U,to:h})}}class CG{random;constructor($){this.random=$}amount($){let J=$?.min??0,G=$?.max??1e4,H=$?.dec??2,A=$?.symbol??"",z=this.random.float(J,G,H);return A+z.toFixed(H)}account($=8){let J="";for(let G=0;G<$;G++)J+=this.random.int(0,9);return J}accountName(){let $=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement($)} Account`}routingNumber(){return this.account(9)}creditCardNumber($){let J=$?.formatted??!0,G=$?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),H="",A=16;switch(G){case"visa":H="4",A=16;break;case"mastercard":H=`5${this.random.int(1,5)}`,A=16;break;case"amex":H=`3${this.random.arrayElement(["4","7"])}`,A=15;break;case"discover":H="6011",A=16;break}let z=H;while(z.length<A)z+=this.random.int(0,9);if(J){if(G==="amex")return`${z.slice(0,4)}-${z.slice(4,10)}-${z.slice(10)}`;return z.match(/.{1,4}/g)?.join("-")??z}return z}cvv(){return this.account(3)}iban($){let J=$?.countryCode??"GB",G=$?.formatted??!1,H=this.random.int(10,99).toString(),A="WEST",z=this.account(14),U=J+H+"WEST"+z;if(G)return U.match(/.{1,4}/g)?.join(" ")??U;return U}bic(){let $="";for(let J=0;J<4;J++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let J=0;J<2;J++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let J=0;J<2;J++)$+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(G,H)=>H.toString())]);return $}bitcoin(){let $=this.random.arrayElement(["1","3"]);for(let J=0;J<33;J++)$+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return $}ethereum(){let $="0x";for(let J=0;J<40;J++)$+="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 MJ{random;locale;constructor($,J){this.random=$,this.locale=J}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"],J=["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(J)}`}}class IG{random;constructor($){this.random=$}branch(){let $=["feature","bugfix","hotfix","refactor","chore","docs","test"],J=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],G=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],H=this.random.arrayElement($),A=this.random.arrayElement(J),z=this.random.arrayElement(G);return`${H}/${A}-${z}`}commitMessage(){let $=["feat","fix","docs","style","refactor","test","chore","perf"],J=["api","ui","auth","db","config","deps","core","utils"],G=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],H=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],A=this.random.arrayElement($),z=this.random.boolean(0.5)?`(${this.random.arrayElement(J)})`:"",U=this.random.arrayElement(G),h=this.random.arrayElement(H);return`${A}${z}: ${U} ${h}`}commitSha($){let J=$?.short?7:40,G="0123456789abcdef",H="";for(let A=0;A<J;A++)H+="0123456789abcdef"[this.random.int(0,15)];return H}commitEntry(){let $=this.commitSha({short:!0}),J=this.commitMessage();return`${$} ${J}`}commitAuthor($){let J=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],G=$?.name??this.random.arrayElement(J),H=$?.email??`${G.toLowerCase().replace(" ",".")}@example.com`;return`${G} <${H}>`}remote($){let J=$?.protocol??this.random.arrayElement(["https","ssh"]),G=$?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),H=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),A=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),z={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if(J==="ssh")return`git@${z[G]}:${H}/${A}.git`;return`https://${z[G]}/${H}/${A}.git`}tag(){let $=this.random.int(0,5),J=this.random.int(0,20),G=this.random.int(0,50),H=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${$}.${J}.${G}${H}`}}class KJ{random;locale;constructor($,J){this.random=$,this.locale=J}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 SG{random;constructor($){this.random=$}randomElement($){return this.random.arrayElement($)}arrayElement($){return this.random.arrayElement($)}arrayElements($,J){return this.random.arrayElements($,J)}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 J=Object.keys($);return this.random.arrayElement(J)}objectValue($){let J=this.objectKey($);return $[J]}multiple($,J=3){return Array.from({length:J},$)}maybe($,J=0.5){return this.random.boolean(J)?$():void 0}unique($,J=50){let G=new Set,H=0;while(H<J){let A=$();if(!G.has(A))return G.add(A),A;H++}throw Error(`Failed to generate unique value after ${J} retries`)}replaceCreditCardSymbols($="####-####-####-####",J="#"){return this.random.replaceCreditCardSymbols($,J)}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,(J,G)=>{return""})}}class _G{random;constructor($){this.random=$}url($){let J=$?.width??640,G=$?.height??480;return`https://via.placeholder.com/${J}x${G}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr($){let J=$?.width??640,G=$?.height??480,H=$?.category??"";if(H)return`https://loremflickr.com/${J}/${G}/${H}`;return`https://loremflickr.com/${J}/${G}`}urlPicsumPhotos($){let J=$?.width??640,G=$?.height??480,H=`https://picsum.photos/${J}/${G}`;if($?.grayscale)H+="?grayscale";if($?.blur)H+=$?.grayscale?`&blur=${$.blur}`:`?blur=${$.blur}`;return H}dataUri($){let J=$?.width??640,G=$?.height??480,H=$?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),A=`<svg xmlns="http://www.w3.org/2000/svg" width="${J}" height="${G}"><rect width="${J}" height="${G}" fill="#${H}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(A)}`}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 BJ{random;locale;domainWordsCache=null;constructor($,J){this.random=$,this.locale=J}getDomainWords(){if(!this.domainWordsCache){let $=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=$.map((J)=>J.toLowerCase().replace(/[^a-z0-9]/g,"")).filter((J)=>J.length>0)}return this.domainWordsCache}email($){let J;if($?.firstName)J=$.firstName.toLowerCase();else{let U=this.locale.person.firstNameMale.length,h=this.locale.person.firstNameFemale.length,Y=this.locale.person.firstNameNeutral?.length||0,Z=U+h+Y,E=this.random.int(0,Z-1);if(E<U)J=this.locale.person.firstNameMale[E].toLowerCase();else if(E<U+h)J=this.locale.person.firstNameFemale[E-U].toLowerCase();else J=this.locale.person.firstNameNeutral[E-U-h].toLowerCase()}let G=$?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),H=$?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),A=this.random.arrayElement(xj),z=this.random.arrayElement(this.getDomainWords());return`${J}${A}${G}@${z}.${H}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let $=this.locale.person.firstNameMale.length,J=this.locale.person.firstNameFemale.length,G=this.locale.person.firstNameNeutral?.length||0,H=$+J+G,A=this.random.int(0,H-1),z;if(A<$)z=this.locale.person.firstNameMale[A].toLowerCase();else if(A<$+J)z=this.locale.person.firstNameFemale[A-$].toLowerCase();else z=this.locale.person.firstNameNeutral[A-$-J].toLowerCase();let U=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),h=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),Y=[".","_",""],Z=this.random.arrayElement(Y);return`${z}${Z}${U}@${h}`}username($){let J;if($?.firstName)J=$.firstName.toLowerCase();else{let A=this.locale.person.firstNameMale.length,z=this.locale.person.firstNameFemale.length,U=this.locale.person.firstNameNeutral?.length||0,h=A+z+U,Y=this.random.int(0,h-1);if(Y<A)J=this.locale.person.firstNameMale[Y].toLowerCase();else if(Y<A+z)J=this.locale.person.firstNameFemale[Y-A].toLowerCase();else J=this.locale.person.firstNameNeutral[Y-A-z].toLowerCase()}let G=$?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),H=[`${J}${G}`,`${J}_${G}`,`${J}.${G}`,`${J}${this.random.int(10,999)}`,`${J}_${G}${this.random.int(10,99)}`];return this.random.arrayElement(H)}password($){let J=$?.length??12,G=$?.memorable??!1,H=$?.prefix??"";if(G){let U=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],h=[];for(let Y=0;Y<3;Y++)h.push(this.random.arrayElement(U));return H+h.join("-")+this.random.int(10,999)}let A="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",z=H;for(let U=H.length;U<J;U++)z+=A[this.random.int(0,A.length-1)];return z}url($){let J=$?.protocol??this.random.arrayElement(["http","https"]),G=$?.domain??this.domainName();return`${J}://${G}`}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 J=0;J<8;J++)$.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return $.join(":")}mac($=":"){let J=[];for(let G=0;G<6;G++)J.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return J.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 J=[];for(let G=0;G<$;G++)J.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return J.join("-").toLowerCase()}ip(){return this.ipv4()}}class PG{random;constructor($){this.random=$}word(){return this.random.arrayElement(fj)}words($=3){let J=[];for(let G=0;G<$;G++)J.push(this.word());return J.join(" ")}sentence($){let J=$??this.random.int(3,10),G=this.words(J);return`${G.charAt(0).toUpperCase()+G.slice(1)}.`}sentences($=3,J=" "){let G=[];for(let H=0;H<$;H++)G.push(this.sentence());return G.join(J)}paragraph($){let J=$??this.random.int(3,7);return this.sentences(J)}paragraphs($=3,J=`
470
-
471
- `){let G=[];for(let H=0;H<$;H++)G.push(this.paragraph());return G.join(J)}text($){let J=$??200,G="";while(G.length<J)G+=`${this.paragraph()} `;return G.trim().slice(0,J)}slug($=3){return this.words($).replace(/ /g,"-")}lines($=3){let J=[];for(let G=0;G<$;G++)J.push(this.sentence());return J.join(`
472
- `)}}class CJ{random;locale;constructor($,J){this.random=$,this.locale=J}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(),J=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${$}${J}`}tempo(){return this.random.int(60,200)}key(){let $=this.note(),J=this.random.arrayElement(["Major","Minor"]);return`${$} ${J}`}timeSignature(){let $=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement($)}}class NG{random;constructor($){this.random=$}int($){let J=$?.min??0,G=$?.max??100;return this.random.int(J,G)}float($){let J=$?.min??0,G=$?.max??1,H=$?.precision??2;return this.random.float(J,G,H)}bigInt($){let J=$?.min??0n,G=($?.max??1000000n)-J+1n,H=BigInt(Math.floor(this.random.number()*Number(G)));return J+H}binary($){let J=$?.length??8,G="";for(let H=0;H<J;H++)G+=this.random.int(0,1);return G}octal($){let J=$?.length??3,G="";for(let H=0;H<J;H++)G+=this.random.int(0,7);return G}hex($){let J=$?.length??6,G="0123456789ABCDEF",H="";for(let A=0;A<J;A++)H+="0123456789ABCDEF"[this.random.int(0,15)];return H}randomNumber($){return this.int($)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class IJ{random;locale;constructor($,J){this.random=$,this.locale=J}firstName($){if($?.gender==="male")return this.firstNameMale();if($?.gender==="female")return this.firstNameFemale();if($?.gender==="neutral")return this.firstNameNeutral();let J=this.locale.person.firstNameMale.length,G=this.locale.person.firstNameFemale.length,H=this.locale.person.firstNameNeutral?.length||0,A=J+G+H,z=this.random.int(0,A-1);if(z<J)return this.locale.person.firstNameMale[z];if(z<J+G)return this.locale.person.firstNameFemale[z-J];return this.locale.person.firstNameNeutral[z-J-G]}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 J=this.firstName({gender:$.gender}),G=this.lastName();if($.prefix&&$.suffix)return`${this.prefix()} ${J} ${G} ${this.suffix()}`;if($.prefix)return`${this.prefix()} ${J} ${G}`;if($.suffix)return`${J} ${G} ${this.suffix()}`;return`${J} ${G}`}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 J;if($?.constraints)J=this.firstName({gender:$.constraints.gender});else J=this.firstName({gender:$?.gender});if($?.weighted)J=fJ(this.random,$.weighted);if($?.relationships)J=$1({firstName:J,gender:$?.gender||$?.constraints?.gender},$.relationships).firstName||J;if($?.validation){let G=xJ(J,$.validation);if(!G.isValid){if($.validation.strict)throw Error(`Validation failed: ${G.errors.join(", ")}`);J=this.firstName({gender:$?.gender||$?.constraints?.gender})}}return J}fullNameAdvanced($){let J;if($?.constraints)J=this.fullName({gender:$.constraints.gender,prefix:$.prefix,suffix:$.suffix});else J=this.fullName($);if($?.weighted)J=fJ(this.random,$.weighted);if($?.relationships)J=$1({fullName:J,gender:$?.gender||$?.constraints?.gender},$.relationships).fullName||J;if($?.validation){let G=xJ(J,$.validation);if(!G.isValid){if($.validation.strict)throw Error(`Validation failed: ${G.errors.join(", ")}`);J=this.fullName({gender:$?.gender||$?.constraints?.gender,prefix:$?.prefix,suffix:$?.suffix})}}return J}profile($){let J=$?.constraints?.gender||$?.gender||this.gender(),G=this.firstNameAdvanced({...$,gender:J}),H=this.lastName(),A=`${G} ${H}`,z={firstName:G,lastName:H,fullName:A,gender:J,jobTitle:this.jobTitle(),age:$?.constraints?.ageRange?this.random.int($.constraints.ageRange.min,$.constraints.ageRange.max):this.random.int(18,80)};if($?.relationships)return $1(z,$.relationships);return z}family($){let J=$?.size||this.random.int(2,6),G=this.lastName(),H=["parent","parent","child","child","child","grandparent"],A=[];for(let z=0;z<J;z++){let U=H[z]||"relative",h=U==="parent"||U==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",Y=this.firstNameAdvanced({...$,gender:h,constraints:{...$?.constraints,gender:h}});A.push({firstName:Y,lastName:G,fullName:`${Y} ${G}`,gender:h,relationship:U})}return{members:A,lastName:G}}}class SJ{random;locale;constructor($,J){this.random=$,this.locale=J}number($){let J=$??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols(J)}phoneNumber($){return this.number($)}}class _J{random;locale;constructor($,J){this.random=$,this.locale=J}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 J=["A","T","C","G"],G="";for(let H=0;H<$;H++)G+=this.random.arrayElement(J);return G}rnaSequence($=12){let J=["A","U","C","G"],G="";for(let H=0;H<$;H++)G+=this.random.arrayElement(J);return G}hypothesis(){let $=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],J=["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(J)}`}}class PJ{random;locale;constructor($,J){this.random=$,this.locale=J}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 TG{random;constructor($){this.random=$}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let $="0123456789abcdef",J="";for(let G=0;G<36;G++)if(G===8||G===13||G===18||G===23)J+="-";else if(G===14)J+="4";else if(G===19){let H=this.random.int(0,15);J+=$[H&3|8]}else J+=$[this.random.int(0,15)];return J}nanoid($=21){let J="";for(let G=0;G<$;G++)J+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return J}alpha($){let J=$?.length??10,G=$?.casing??"mixed",H="abcdefghijklmnopqrstuvwxyz",A="ABCDEFGHIJKLMNOPQRSTUVWXYZ",z="";if(G==="lower")z="abcdefghijklmnopqrstuvwxyz";else if(G==="upper")z="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else z="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let U="";for(let h=0;h<J;h++)U+=z[this.random.int(0,z.length-1)];return U}alphanumeric($){let J=$?.length??10,G=$?.casing??"mixed",H="abcdefghijklmnopqrstuvwxyz",A="ABCDEFGHIJKLMNOPQRSTUVWXYZ",z="0123456789",U="0123456789";if(G==="lower")U+="abcdefghijklmnopqrstuvwxyz";else if(G==="upper")U+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else U+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let h="";for(let Y=0;Y<J;Y++)h+=U[this.random.int(0,U.length-1)];return h}numeric($=10){if(!this.random.isSeeded()){let G="";for(let H=0;H<$;H++)G+=Math.floor(Math.random()*10);return G}let J="";for(let G=0;G<$;G++)J+=this.random.int(0,9);return J}sample($=10){return this.alphanumeric({length:$})}symbol($=5){let J="";for(let G=0;G<$;G++)J+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return J}hexadecimal($){let J=$?.length??6,G=$?.prefix??"",H="0123456789abcdef",A=G;for(let z=0;z<J;z++)A+="0123456789abcdef"[this.random.int(0,15)];return A}}class NJ{random;locale;constructor($,J){this.random=$,this.locale=J}fileName($){let J;if(this.locale?.system?.fileName)J=this.locale.system.fileName;else J=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let G=this.random.arrayElement(J),H=$?.extension??this.fileExtension();return`${G}.${H}`}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),J=this.random.int(0,20),G=this.random.int(0,50);return`${$}.${J}.${G}`}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),J=this.random.boolean(0.5)?"*":this.random.int(0,23),G=this.random.boolean(0.5)?"*":this.random.int(1,31),H=this.random.boolean(0.5)?"*":this.random.int(1,12),A=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${$} ${J} ${G} ${H} ${A}`}}class TJ{random;locale;constructor($,J){this.random=$,this.locale=J}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(vj)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(gj)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(bj)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(mj)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(cj)}vin(){let $="";for(let J=0;J<17;J++)$+="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),J=this.manufacturer(),G=this.model();return`${$} ${J} ${G}`}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 kJ{random;locale;constructor($,J){this.random=$,this.locale=J}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"],J=this.random.arrayElement($);return this[J]()}words($=3){let J=[];for(let G=0;G<$;G++)J.push(this.sample());return J.join(" ")}}class kG{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,J=100){return Math.floor(this.number()*(J-$+1))+$}float($=0,J=1,G=2){let H=this.number()*(J-$)+$;return Number.parseFloat(H.toFixed(G))}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($,J){if($.length===0)return[];let G=J??this.int(1,$.length);return[...$].sort(()=>this.number()-0.5).slice(0,Math.min(G,$.length))}shuffle($){let J=[...$];for(let G=J.length-1;G>0;G--){let H=this.int(0,G);[J[G],J[H]]=[J[H],J[G]]}return J}boolean($=0.5){return this.number()<$}replaceSymbols($){if(this.seed===void 0){let J="";for(let G=0;G<$.length;G++){let H=$[G];if(H==="#")J+="0123456789"[Math.floor(Math.random()*10)];else if(H==="?")J+=Mh[Math.floor(Math.random()*26)];else J+=H}return J}return $.replace(/[#?]/g,(J)=>{if(J==="#")return String(this.int(0,9));return this.arrayElement(Mh)})}replaceCreditCardSymbols($="####-####-####-####",J="#"){return $.replace(new RegExp(J,"g"),()=>String(this.int(0,9)))}weightedArrayElement($){if($.length===0)throw Error("Cannot pick from empty weighted items array");let J=$.reduce((A,z)=>A+z.weight,0);if(J<=0)throw Error("Total weight must be greater than 0");let G=this.number()*J,H=0;for(let A of $)if(H+=A.weight,G<=H)return A.item;return $[$.length-1].item}weightedArrayElements($,J,G=!1){if($.length===0)return[];let H=J??this.int(1,$.length),A=[],z=[...$];for(let U=0;U<H&&z.length>0;U++){let h=this.weightedArrayElement(z);if(A.push(h),!G){let Y=z.findIndex((Z)=>Z.item===h);if(Y!==-1)z.splice(Y,1)}}return A}weightedBoolean($=0.5){return this.number()<$}weightedInt($,J,G){let H=J-$+1;if(G){if(G.length!==H)throw Error("Weights array length must match the range size");let A=G.map((z,U)=>({item:$+U,weight:z}));return this.weightedArrayElement(A)}return this.int($,J)}}class xG{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 J=$?.locale??"en",G=$?.seed;if(this._autoInstallLocales=$?.autoInstallLocales??!1,J!=="en"&&!X$.isCached(J))console.warn(`[ts-mocker] Locale '${J}' requires async loading. Use 'await Faker.create({ locale: "${J}" })' for better performance. Falling back to English.`),this._locale=X$.loadSync("en");else this._locale=X$.loadSync(J);this.random=new kG(G),this.person=new IJ(this.random,this._locale),this.address=new wJ(this.random,this._locale),this.internet=new BJ(this.random,this._locale),this.phone=new SJ(this.random,this._locale),this.company=new OJ(this.random,this._locale),this.lorem=new PG(this.random),this.date=new BG(this.random),this.number=new NG(this.random),this.string=new TG(this.random),this.color=new QJ(this.random,this._locale),this.finance=new CG(this.random),this.helpers=new SG(this.random),this.image=new _G(this.random),this.git=new IG(this.random),this.science=new _J(this.random,this._locale),this.music=new CJ(this.random,this._locale),this.database=new KG(this.random),this.food=new MJ(this.random,this._locale),this.commerce=new VJ(this.random,this._locale),this.book=new DJ(this.random,this._locale),this.animal=new RJ(this.random,this._locale),this.sport=new PJ(this.random,this._locale),this.hacker=new KJ(this.random,this._locale),this.system=new NJ(this.random,this._locale),this.word=new kJ(this.random,this._locale),this.vehicle=new TJ(this.random,this._locale)}static async create($){let J=$?.locale??"en";return await X$.load(J),new xG($)}seed($){return this.random=new kG($),Object.assign(this.person,new IJ(this.random,this._locale)),Object.assign(this.address,new wJ(this.random,this._locale)),Object.assign(this.internet,new BJ(this.random,this._locale)),Object.assign(this.phone,new SJ(this.random,this._locale)),Object.assign(this.company,new OJ(this.random,this._locale)),Object.assign(this.lorem,new PG(this.random)),Object.assign(this.date,new BG(this.random)),Object.assign(this.number,new NG(this.random)),Object.assign(this.string,new TG(this.random)),Object.assign(this.color,new QJ(this.random,this._locale)),Object.assign(this.finance,new CG(this.random)),Object.assign(this.helpers,new SG(this.random)),Object.assign(this.image,new _G(this.random)),Object.assign(this.git,new IG(this.random)),Object.assign(this.science,new _J(this.random,this._locale)),Object.assign(this.music,new CJ(this.random,this._locale)),Object.assign(this.database,new KG(this.random)),Object.assign(this.food,new MJ(this.random,this._locale)),Object.assign(this.commerce,new VJ(this.random,this._locale)),Object.assign(this.book,new DJ(this.random,this._locale)),Object.assign(this.animal,new RJ(this.random,this._locale)),Object.assign(this.sport,new PJ(this.random,this._locale)),Object.assign(this.hacker,new KJ(this.random,this._locale)),Object.assign(this.system,new NJ(this.random,this._locale)),Object.assign(this.word,new kJ(this.random,this._locale)),Object.assign(this.vehicle,new TJ(this.random,this._locale)),this}async setLocale($){return this._locale=await X$.load($),this.reinitializeLocaleModules(),this}setLocaleSync($){if(!X$.isCached($)&&$!=="en")return console.warn(`[ts-mocker] Locale '${$}' is not loaded. Use 'await faker.setLocale("${$}")' or preload it first.`),this;return this._locale=X$.loadSync($),this.reinitializeLocaleModules(),this}async preloadLocales($){return await X$.preload($),this}reinitializeLocaleModules(){Object.assign(this.person,new IJ(this.random,this._locale)),Object.assign(this.address,new wJ(this.random,this._locale)),Object.assign(this.internet,new BJ(this.random,this._locale)),Object.assign(this.phone,new SJ(this.random,this._locale)),Object.assign(this.company,new OJ(this.random,this._locale)),Object.assign(this.food,new MJ(this.random,this._locale)),Object.assign(this.animal,new RJ(this.random,this._locale)),Object.assign(this.sport,new PJ(this.random,this._locale)),Object.assign(this.music,new CJ(this.random,this._locale)),Object.assign(this.commerce,new VJ(this.random,this._locale)),Object.assign(this.book,new DJ(this.random,this._locale)),Object.assign(this.vehicle,new TJ(this.random,this._locale)),Object.assign(this.word,new kJ(this.random,this._locale)),Object.assign(this.hacker,new KJ(this.random,this._locale)),Object.assign(this.system,new NJ(this.random,this._locale)),Object.assign(this.color,new QJ(this.random,this._locale)),Object.assign(this.science,new _J(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return X$.getAvailableLocales()}static isLocaleLoaded($){return X$.isCached($)}static async preloadLocales($){await X$.preload($)}name(){return this.person.name()}email(){return this.internet.email()}}var u2,p2=($)=>$,n2=($,J)=>{for(var G in J)u2($,G,{get:J[G],enumerable:!0,configurable:!0,set:i2.bind(J,G)})},J1=($,J)=>()=>($&&(J=$($=0)),J),r2,qJ,qG,Kh,yG,wh,Jz,VG,e2,s0,Q0,$j,Rh,Jj,Dh,Gj,Hj,Gz,Aj,Qh,Vh,zj,Hz,Uj,Yj,hj,Zj,Ej,B5,Ch,Xj,jj,Wj="0.15.9",Fj=()=>{},w$,I5,OG,Uz,Yz,S5,hz,Zz,MG,Ez,Xz,R1,yJ,_h,kh,wz,qh,yh,xh,K$,e$,fh,vh,_j,Nj=()=>{},gh,bh,T5,Az=null,Vz,K5,T$,DG,X$,ih,nh,rh,lh,xj,fj,vj,gj,bj,mj,cj,Mh,Kz,sh;var oh=a(()=>{u2=Object.defineProperty;r2=import.meta.require;yG=J1(()=>{qJ=new Wz,qG=new Fz,Kh={createKey:l2,isEquivalent:s2,estimateMemoryUsage:o2}});jj=J1(()=>{wh=C5.env.CLARITY_LOG_DIR||B2(t2(),"logs"),Jz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},VG={...Jz},e2=(async()=>{try{let{loadConfig:$}=await Promise.resolve().then(()=>(bh(),gh)),J=await $({name:"clarity",alias:"logging",defaultConfig:Jz,cwd:C5.cwd()});if(J)Object.assign(VG,J)}catch{}return VG})(),s0={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"},Q0=s0,$j=s0.red,Rh=s0.green,Jj=s0.yellow,Dh=s0.blue,Gj=s0.magenta,Hj=s0.cyan,Gz=s0.white,Aj=s0.gray,Qh=s0.bgRed,Vh=s0.bgYellow,zj=s0.bgGray,Hz=s0.bold,Uj=s0.dim,Yj=s0.italic,hj=s0.underline,Zj=s0.strikethrough,Ej=s0.reset,B5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ch={debug:"\uD83D\uDD0D",info:Dh("\u2139"),success:Rh("\u2713"),warning:Vh(Gz(Hz(" WARN "))),error:Qh(Gz(Hz(" ERROR ")))},Xj=new _5("stacks")});yJ=J1(()=>{w$=class extends Error{timestamp;context;constructor($,J={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=J,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([J,G])=>`${J}: ${G}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},I5=class extends w${code="CONFIG_NOT_FOUND";constructor($,J,G){let H=G===void 0?[]:Array.isArray(G)?G.filter(Boolean):[G],A="";if(H.length===1)A=` or alias "${H[0]}"`;else if(H.length>1)A=` or aliases ${H.map((z)=>`"${z}"`).join(", ")}`;super(`Configuration "${$}"${A} not found`,{configName:$,alias:G,searchPaths:J,searchPathCount:J.length})}},OG=class extends w${code="CONFIG_LOAD_ERROR";constructor($,J,G){super(`Failed to load configuration from "${$}": ${J.message}`,{configPath:$,configName:G,originalError:J.name,originalMessage:J.message});this.cause=J}},Uz=class extends w${code="CONFIG_VALIDATION_ERROR";constructor($,J,G){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:G,validationErrors:J,errorCount:J.length})}},Yz=class extends w${code="CONFIG_MERGE_ERROR";constructor($,J,G,H){super(`Failed to merge configuration from "${$}" with "${J}": ${G.message}`,{sourcePath:$,targetPath:J,configName:H,originalError:G.name,originalMessage:G.message});this.cause=G}},S5=class extends w${code="ENV_VAR_ERROR";constructor($,J,G,H){super(`Failed to parse environment variable "${$}" with value "${J}" as ${G}`,{envKey:$,envValue:J,expectedType:G,configName:H})}},hz=class extends w${code="FILE_SYSTEM_ERROR";constructor($,J,G){super(`File system ${$} failed for "${J}": ${G.message}`,{operation:$,path:J,originalError:G.name,originalMessage:G.message});this.cause=G}},Zz=class extends w${code="TYPE_GENERATION_ERROR";constructor($,J,G){super(`Failed to generate types from "${$}" to "${J}": ${G.message}`,{configDir:$,outputPath:J,originalError:G.name,originalMessage:G.message});this.cause=G}},MG=class extends w${code="SCHEMA_VALIDATION_ERROR";constructor($,J,G){super(`Schema validation failed${G?` for config "${G}"`:""}`,{schemaPath:$,configName:G,validationErrors:J,errorCount:J.length})}},Ez=class extends w${code="BROWSER_CONFIG_ERROR";constructor($,J,G,H){super(`Failed to fetch configuration from "${$}": ${J} ${G}`,{endpoint:$,status:J,statusText:G,configName:H})}},Xz=class extends w${code="PLUGIN_ERROR";constructor($,J,G){super(`Plugin "${$}" failed during ${J}: ${G.message}`,{pluginName:$,operation:J,originalError:G.name,originalMessage:G.message});this.cause=G}},R1={configNotFound($,J,G){return new I5($,J,G)},configLoad($,J,G){return new OG($,J,G)},configValidation($,J,G){return new Uz($,J,G)},configMerge($,J,G,H){return new Yz($,J,G,H)},envVar($,J,G,H){return new S5($,J,G,H)},fileSystem($,J,G){return new hz($,J,G)},typeGeneration($,J,G){return new Zz($,J,G)},schemaValidation($,J,G){return new MG($,J,G)},browserConfig($,J,G,H){return new Ez($,J,G,H)},plugin($,J,G){return new Xz($,J,G)}}});_h=J1(()=>{yG(),yJ()});wz=J1(()=>{kh={replace:"replace",concat:"concat",smart:"smart"}});qh=J1(()=>{yG(),yJ(),wz()});xh=J1(()=>{yG(),yJ(),yh=/^https?:\/\//});_j=J1(()=>{jj(),Fj(),yG(),yJ(),_h(),qh(),xh(),wz(),K$=new _5("bunfig",{showTags:!0}),e$=new Dz,fh=Y$(v1.cwd(),"config"),vh=Y$(v1.cwd(),"src/generated")});gh={};n2(gh,{withErrorRecovery:()=>Ih,tryLoadConfig:()=>Cj,loadConfigWithResult:()=>Kj,loadConfig:()=>Qz,isRetryableError:()=>wj,isConfigNotFoundError:()=>Lj,isBunfigError:()=>Sh,globalPerformanceMonitor:()=>qG,globalCache:()=>qJ,getEnvOrDefault:()=>Rj,generateConfigTypes:()=>Ij,defaultGeneratedDir:()=>vh,defaultConfigDir:()=>fh,deepMergeWithArrayStrategy:()=>Lz,deepMerge:()=>Ph,createLibraryConfig:()=>Sj,config:()=>Bj,bunfigPlugin:()=>Pj,applyEnvVarsToConfig:()=>QG,TypeGenerationError:()=>Zz,SchemaValidationError:()=>MG,PluginError:()=>Xz,PerformanceMonitor:()=>Fz,FileSystemError:()=>hz,ErrorFactory:()=>R1,EnvVarError:()=>S5,EnvProcessor:()=>P5,ConfigValidator:()=>Rz,ConfigValidationError:()=>Uz,ConfigNotFoundError:()=>I5,ConfigMergeError:()=>Yz,ConfigLoader:()=>Dz,ConfigLoadError:()=>OG,ConfigFileLoader:()=>N5,ConfigCache:()=>Wz,CacheUtils:()=>Kh,BunfigError:()=>w$,BrowserConfigError:()=>Ez,ArrayMergeStrategies:()=>kh});bh=J1(()=>{_j(),yJ(),yG(),yJ(),Nj(),_h(),qh(),xh(),wz()});bh();T5={verbose:!1,locale:"en",autoInstallLocales:!1};Vz=T5,K5={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"]}};T$=new Map,DG=new Map;X$=class X${static AVAILABLE_BASE_LOCALES=["af","ar","az","cs","da","de","en","eo","es","fa","fi","fr","he","hi","it","ja","ko","nl","no","pl","pt","sv","tl","tr","uk","zh","zu"];static AVAILABLE_LOCALE_VARIANTS=["af_ZA","de_AT","de_CH","de_DE","en_AU","en_CA","en_GB","en_GH","en_HK","en_IE","en_IN","en_NG","en_US","en_ZA","es_ES","es_MX","fr_BE","fr_CA","fr_CH","fr_FR","fr_LU","fr_SN","pt_BR","pt_MZ","pt_PT","zh_CN","zh_TW","zu_ZA"];static getAvailableLocales(){return[...this.AVAILABLE_BASE_LOCALES,...this.AVAILABLE_LOCALE_VARIANTS]}static getAvailableBaseLocales(){return this.AVAILABLE_BASE_LOCALES}static getAvailableLocaleVariants(){return this.AVAILABLE_LOCALE_VARIANTS}static async load($){let J=LJ($).normalized;if(J==="en"){if(!T$.has("en"))T$.set("en",K5);return K5}if(T$.has(J))return T$.get(J);if(DG.has(J))return DG.get(J);let G=this.loadLocaleWithFallback(J);DG.set(J,G);try{let H=await G;return T$.set(J,H),H}finally{DG.delete(J)}}static loadSync($){let J=LJ($).normalized;if(J==="en"){if(!T$.has("en"))T$.set("en",K5);return K5}if(T$.has(J))return T$.get(J);throw Error(`Locale '${$}' is not loaded. Please use async loading with faker.setLocale('${$}') or preload it.`)}static isCached($){let J=LJ($).normalized;return T$.has(J)}static async preload($){await Promise.all($.map((J)=>this.load(J)))}static clearCache(){T$.clear(),DG.clear()}static async loadLocaleWithFallback($){let J=Tj($);for(let G=0;G<J.length;G++){let H=J[G],A=G===0&&J.length>1,z=!A;try{if(A){let U=await this.loadLocaleModule(H),h=J[1];try{let Y=await this.loadLocaleModule(h);return ch(Y,U)}catch{return U}}else return await this.loadLocaleModule(H)}catch(U){if(G===J.length-1)throw U;continue}}throw Error(`Failed to load locale '${$}' with fallback chain: ${J.join(" \u2192 ")}`)}static async tryWorkspaceImport($,J){if(!f1())return null;try{let G=await import(`../../${J.packageName}/dist/index.js`);return G[J.normalized]||G[J.language]||G.default}catch{try{let G=K2.cwd(),H=M2(G,"packages",J.packageName,"dist","index.js");if(!O2(H))return null;let A=await import(`file://${H}`);return A[J.normalized]||A[J.language]||A.default}catch{return null}}}static async loadLocaleModule($){let J=kj($),G=LJ($);try{let H=await import(J);return H[G.normalized]||H[G.language]||H.default}catch(H){let A=H instanceof Error?H.message:String(H);if(A.includes("Cannot find")||A.includes("not found")||A.includes("ModuleNotFound")){if(f1()&&J.startsWith("@mock-locale/")){let z=await this.tryWorkspaceImport($,G);if(z)return z}if(Vz.autoInstallLocales)if(console.log(`
473
- \uD83D\uDD0D Locale '${$}' not found. Auto-installing ${J}...`),Mz(J)){if(f1()&&J.startsWith("@mock-locale/")){let z=await this.tryWorkspaceImport($,G);if(z)return z}try{let z=await import(J);return z[G.normalized]||z[G.language]||z.default}catch(z){if(f1()&&J.startsWith("@mock-locale/")){let U=await this.tryWorkspaceImport($,G);if(U)return U;throw Error(`Locale '${$}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${J.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${$}' after installation: ${z instanceof Error?z.message:String(z)}`)}}else throw Error(`Failed to auto-install locale '${$}'. Please install manually with: bun add ${J}`);throw Error(`Locale '${$}' is not installed. Install it with: bun add ${J}
474
- 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}
475
- Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${$}': ${A}`)}}};ih=new k5,nh={email:($)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test($)},phone:($)=>{let J=/^\+?[1-9]\d{0,15}$/,G=$.replace(/[\s\-()]/g,"");return G.length>=7&&J.test(G)},name:($)=>{return/^[a-z\s\-']+$/i.test($)&&$.length>=2&&$.length<=50},age:($)=>{return Number.isInteger($)&&$>=0&&$<=150},url:($)=>{try{let J=new URL($);return $.startsWith("http://")||$.startsWith("https://")}catch{return!1}},regex:($)=>(J)=>{return $.test(J)},length:($,J)=>(G)=>{return G.length>=$&&G.length<=J},range:($,J)=>(G)=>{return G>=$&&G<=J}},rh={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"]}}},lh={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}]}};xj=[".","_","-",""];fj=["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"];vj=["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"],gj=["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"],bj=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],mj=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],cj=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"];Mh="abcdefghijklmnopqrstuvwxyz".split("");Kz=new xG,sh=Kz});var th={};r5(th,{validateData:()=>xJ,selectWeightedItem:()=>fJ,isInWorkspace:()=>f1,installPackage:()=>Mz,globalProviderRegistry:()=>ih,getConfig:()=>mh,generateRealisticData:()=>ph,faker:()=>Kz,detectPackageManager:()=>Oz,defaultConfig:()=>T5,default:()=>sh,config:()=>Vz,applyRelationships:()=>$1,applyConstraints:()=>uh,WordModule:()=>kJ,WeightedSelections:()=>lh,VehicleModule:()=>TJ,ValidationRules:()=>nh,SystemModule:()=>NJ,StringModule:()=>TG,SportModule:()=>PJ,ScienceModule:()=>_J,Random:()=>kG,PhoneModule:()=>SJ,PersonModule:()=>IJ,NumberModule:()=>NG,MusicModule:()=>CJ,LoremModule:()=>PG,LocaleLoader:()=>X$,InternetModule:()=>BJ,ImageModule:()=>_G,HelpersModule:()=>SG,HackerModule:()=>KJ,GitModule:()=>IG,FoodModule:()=>MJ,FinanceModule:()=>CG,Faker:()=>xG,DateModule:()=>BG,DatabaseModule:()=>KG,DataRelationships:()=>rh,DataProviderRegistry:()=>k5,CompanyModule:()=>OJ,CommerceModule:()=>VJ,ColorModule:()=>QJ,BookModule:()=>DJ,AnimalModule:()=>RJ,AddressModule:()=>wJ});var ah=a(()=>{oh()});import{Database as _z}from"bun:sqlite";function m1(){let $=new Date().toISOString();return A0(g.dialect)?$.slice(0,19).replace("T"," "):$}function G1($,J){if(typeof $!=="string"||$.length===0)throw TypeError(`[bun-query-builder] ${J}: identifier must be a non-empty string, got ${typeof $}`);if($.length>64)throw TypeError(`[bun-query-builder] ${J}: identifier '${$}' exceeds 64 chars`);if(!U8.test($))throw TypeError(`[bun-query-builder] ${J}: identifier '${$}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Y8($,J){if(typeof $!=="string"||$.length===0)throw TypeError(`[bun-query-builder] ${J}: identifier must be a non-empty string, got ${typeof $}`);let G=$.split(".");if(G.length>2||G.some((H)=>H.length===0||H.length>64||!U8.test(H)))throw TypeError(`[bun-query-builder] ${J}: invalid ORDER BY column '${$}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function dj($,J){Nz.set($,J),vJ.clear()}function h8(){Nz.clear(),vJ.clear()}function R$($){if(!q5)try{q5=(gG(),BZ(F8)).getModel}catch{q5=()=>{return}}return q5($)??Nz.get($)}function eh($){let J=y5.get($);if(J!==void 0)return J;let G=0,H=$.replace(/\?/g,()=>`$${++G}`);if(y5.size>=uj)y5.clear();return y5.set($,H),H}function $8($){if($==null)return 0;if(typeof $.affectedRows==="number")return $.affectedRows;if(typeof $.count==="number")return $.count;if(Array.isArray($))return $.length;return 0}function J8($){if($==null||typeof $!=="object")return null;if("insertId"in $&&$.insertId!=null)return $.insertId;if("lastInsertRowid"in $&&$.lastInsertRowid!=null)return $.lastInsertRowid;return null}class Pz{sqliteDb;dialect="sqlite";constructor($){this.sqliteDb=$}all($,J){return Promise.resolve(this.sqliteDb.query($).all(...J))}get($,J){return Promise.resolve(this.sqliteDb.query($).get(...J)??void 0)}run($,J){let G=this.sqliteDb.run($,J);return Promise.resolve({changes:G.changes,lastInsertId:G.lastInsertRowid})}insert($,J){return this.run($,J)}}class Z8{dialect;constructor($){this.dialect=$}conn(){return X1()}text($){return this.dialect==="postgres"?eh($):$}async all($,J){let G=await this.conn().unsafe(this.text($),J);return Array.isArray(G)?G:[]}async get($,J){let G=await this.conn().unsafe(this.text($),J);if(Array.isArray(G))return G[0]??void 0;return G??void 0}async run($,J){let G=await this.conn().unsafe(this.text($),J);return{changes:$8(G),lastInsertId:J8(G)}}async insert($,J,G){if(this.dialect==="postgres"){let z=await this.conn().unsafe(`${eh($)} RETURNING ${G}`,J),U=Array.isArray(z)?z[0]:z;return{changes:1,lastInsertId:U?U[G]??null:null}}let H=await this.conn().unsafe($,J),A=J8(H);if(A==null){let z=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);A=(Array.isArray(z)?z[0]:z)?.id??null}return{changes:$8(H)||1,lastInsertId:A}}}function OQ($){if($.database instanceof _z)b1=$.database;else b1=new _z($.database||":memory:",{create:!0}),$G(b1);H1=null,vG=null}function I0(){if(b1){if(!H1||vG!==b1)H1=new Pz(b1),vG=b1,Bz="sqlite",Cz=null;return H1}let $=g.dialect,J=g.database?.database??null;if(H1&&vG===null&&Bz===$&&Cz===J)return H1;if(vG=null,Bz=$,Cz=J,$==="sqlite"){let G=new _z(J||":memory:",{create:!0});$G(G),H1=new Pz(G)}else H1=new Z8($);return H1}function MQ(){let $=I0();if($.sqliteDb)return $.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${$.dialect}'. Use the async model API instead.`)}function gJ($){let J=$.traits;return Boolean(J?.useSoftDeletes||J?.softDeletable)}function c1($){let J=$.traits;return Boolean(J?.useTimestamps||J?.timestampable)}function pj($){let J=G8.get($);if(J)return J;let G=new Set,H=$.belongsToMany;if(H){if(Array.isArray(H)){for(let A of H)if(typeof A==="string")G.add(A.toLowerCase());else if(A&&typeof A==="object"&&A.model)G.add(A.model.toLowerCase())}else if(typeof H==="object")for(let A of Object.keys(H))G.add(A)}return G8.set($,G),G}function E8($){let J={};for(let[G,H]of Object.entries($))J[S0(G)]=H;return J}function ij($){for(let J in $)if(S0(J)!==J)return E8($);return $}function nj($,J){if($[J])return $[J];let G=S0(J);if($[G])return $[G];for(let H of Object.keys($))if(S0(H)===G)return $[H];return}class j${_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor($,J={}){this._definition=$,this._attributes=ij({...J}),this._original=null;let G=pj($);if(G.size===0)return;let H=this;return new Proxy(this,{get(A,z,U){if(typeof z==="string"&&G.has(z)&&!(z in A))return()=>{let h=X8($,z);if(!h||h.type!=="belongsToMany")throw Error(`[orm] relation '${z}' did not resolve to a belongsToMany on '${$.name}'`);let Y=R$(h.relatedModelName),Z=Y?.getDefinition?.()||Y?.definition;if(!Z)throw Error(`[orm] related model '${h.relatedModelName}' is not registered`);return new j8(H,$,h,Z)};return Reflect.get(A,z,U)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get($){let J=this._definition.get?.[$];if(J)try{let G=J(this._attributes);if(G!==void 0)return G}catch{}return this._attributes[S0($)]}getAttribute($){return this._attributes[S0($)]}getAttributes(){return{...this._attributes}}set($,J){if(this._original===null)this._original={...this._attributes};this._attributes[S0($)]=J}only($){let J={};for(let G of $)J[G]=this._attributes[S0(G)];return J}except($){let J=new Set($.map((H)=>S0(H))),G={};for(let H of Object.keys(this._attributes))if(!J.has(H))G[H]=this._attributes[H];return G}getRelation($){return this._relations[$]}setRelation($,J){this._relations[$]=J}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($){let J=S0($);return this._attributes[J]!==this._original[J]}return Object.keys(this._attributes).some((J)=>this._attributes[J]!==this._original[J])}isClean($){return!this.isDirty($)}getOriginal($){return this.getOriginalAttributes()[S0($)]}getChanges(){if(this._original===null)return{};let $={};for(let J of Object.keys(this._attributes))if(this._attributes[J]!==this._original[J])$[J]=this._attributes[J];return $}fill($){let J=this._definition.attributes;for(let[G,H]of Object.entries($)){let A=nj(J,G),z=!A&&S0(G).endsWith("_id");if(A?.fillable&&!A?.guarded||z){if(this._original===null)this._original={...this._attributes};this._attributes[S0(G)]=H}}return this}forceFill($){if(this._original===null)this._original={...this._attributes};let J=E8($);Object.assign(this._attributes,J);for(let G of Object.keys(J))this._forced.add(G);return this}async save(){let $=I0(),J=this._definition.primaryKey||"id",G=this._definition.hooks,H=this._definition.set||{};for(let[A,z]of Object.entries(H))if(this.isDirty(A))this._attributes[S0(A)]=z(this._attributes);if(this._attributes[J]){await G?.beforeUpdate?.(this,this.getChanges());let A=this.getChanges(),z=Object.keys(A);if(z.length>0){let U=z.map((Y)=>`${Y} = ?`).join(", "),h=[...Object.values(A),this._attributes[J]];if(c1(this._definition)){let Y=m1();await $.run(`UPDATE ${this._definition.table} SET ${U}, updated_at = ? WHERE ${J} = ?`,[...Object.values(A),Y,this._attributes[J]])}else await $.run(`UPDATE ${this._definition.table} SET ${U} WHERE ${J} = ?`,h)}await G?.afterUpdate?.(this)}else{let A=this._definition.attributes,z={};for(let[Z,E]of Object.entries(A)){if(E.guarded&&!this._forced.has(S0(Z)))continue;let X=S0(Z);if(this._attributes[X]!==void 0)z[X]=this._attributes[X]}for(let Z of Object.keys(this._attributes))if(Z.endsWith("_id")&&Z!==J&&!(Z in z))z[Z]=this._attributes[Z];if(c1(this._definition)){let Z=m1();z.created_at=Z,z.updated_at=Z}if(this._definition.traits?.useUuid&&!z.uuid)z.uuid=crypto.randomUUID();await G?.beforeCreate?.(z);let U=Object.keys(z),h=U.map(()=>"?").join(", "),Y=await $.insert(`INSERT INTO ${this._definition.table} (${U.join(", ")}) VALUES (${h})`,Object.values(z),J);for(let[Z,E]of Object.entries(z))this._attributes[Z]=E;if(Y.lastInsertId!=null)this._attributes[J]=Y.lastInsertId;await G?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update($){return this.fill($),this.save()}async fresh(){let $=I0(),J=this._definition.primaryKey||"id",G=this._attributes[J];if(G==null)return null;let H=await $.get(`SELECT * FROM ${this._definition.table} WHERE ${J} = ?`,[G]);if(!H)return null;return new j$(this._definition,H)}async delete(){let $=I0(),J=this._definition.primaryKey||"id",G=this._attributes[J],H=this._definition.hooks;if(!G)throw Error("Cannot delete a model without a primary key");if(await H?.beforeDelete?.(this),gJ(this._definition)){let A=m1();await $.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${J} = ?`,[A,G]),this._attributes[D1]=A}else await $.run(`DELETE FROM ${this._definition.table} WHERE ${J} = ?`,[G]);return await H?.afterDelete?.(this),!0}async restore(){if(!gJ(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let $=this._definition.primaryKey||"id",J=this._attributes[$];if(!J)throw Error("Cannot restore a model without a primary key");return await I0().run(`UPDATE ${this._definition.table} SET ${D1} = ? WHERE ${$} = ?`,[null,J]),this._attributes[D1]=null,this._original=null,this}trashed(){return this._attributes[D1]!=null}async refresh(){let $=I0(),J=this._definition.primaryKey||"id",G=this._attributes[J];if(!G)throw Error("Cannot refresh a model without a primary key");let H=await $.get(`SELECT * FROM ${this._definition.table} WHERE ${J} = ?`,[G]);if(!H)return null;return this._attributes=H,this._original=null,this}replicate(){let $=this._definition.primaryKey||"id",J={...this._attributes};return delete J[$],delete J.uuid,delete J.created_at,delete J.updated_at,new j$(this._definition,J)}toArray(){let $={...this._attributes};for(let[J,G]of Object.entries(this._relations))if(Array.isArray(G))$[J]=G.map((H)=>H.toArray());else if(G)$[J]=G.toArray();else $[J]=null;return $}toJSON(){let $=new Set;for(let[G,H]of Object.entries(this._definition.attributes))if(H.hidden)$.add(G);let J={};for(let[G,H]of Object.entries(this._attributes))if(!$.has(G))J[G]=H;for(let[G,H]of Object.entries(this._relations))if(Array.isArray(H))J[G]=H.map((A)=>A.toJSON());else if(H)J[G]=H.toJSON();else J[G]=null;return J}}function k$($){return S0($)}function S0($){let J=H8.get($);if(J!==void 0)return J;return J=$.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),H8.set($,J),J}function g1($){let J=A8.get($);if(J!==void 0)return J;return J=rA($),A8.set($,J),J}function z8($,J){let G=$[J];if(!G)return[];if(Array.isArray(G))return G.map((H)=>typeof H==="string"?H:String(H?.model??"")).filter(Boolean);if(typeof G==="object")return Object.keys(G);if(typeof G==="string")return[G];return[]}function sj($,J){let G=$.name??$.table??"model",A=lj.filter((U)=>z8($,U).some((h)=>h.toLowerCase()===J.toLowerCase())).filter((U)=>!x5.includes(U));if(A.length>0)return`[orm] '${G}' declares '${J}' as ${A.join("/")}, which eager loading does not support yet. Supported kinds: ${x5.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let z=x5.flatMap((U)=>z8($,U));return z.length>0?`[orm] '${G}' has no relation '${J}'. Available: ${z.join(", ")}.`:`[orm] '${G}' has no relation '${J}' \u2014 it declares no relations at all.`}function X8($,J){let{name:G,table:H}=$,A=$.primaryKey||"id";function z(W){if(!W)return null;if(Array.isArray(W)){for(let Q of W){let D=typeof Q==="string"?Q:Q?.model||"";if(D&&D.toLowerCase()===J.toLowerCase())return D}return null}if(typeof W==="object"){for(let[Q,D]of Object.entries(W))if(Q===J||Q.toLowerCase()===J.toLowerCase())return typeof D==="string"?D:D?.model||D?.target||Q}return null}function U(){let W=$.belongsTo;if(!W)return null;let Q=J.toLowerCase(),D=(w)=>{if(typeof w==="string")return{model:w};if(w&&typeof w==="object"&&typeof w.model==="string")return{model:w.model,foreignKey:w.foreignKey};return null};if(Array.isArray(W)){for(let w of W){let K=D(w);if(K&&K.model.toLowerCase()===Q)return K}return null}if(typeof W==="object"){for(let[w,K]of Object.entries(W))if(w===J||w.toLowerCase()===Q)return D(K)}return null}function h(){let W=$.belongsToMany;if(!W)return null;if(Array.isArray(W)){for(let Q of W)if(typeof Q==="string"){if(Q.toLowerCase()===J.toLowerCase())return{entry:Q}}else if(Q&&typeof Q==="object"&&Q.model){if(Q.model.toLowerCase()===J.toLowerCase())return{entry:Q}}return null}if(typeof W==="object"){for(let[Q,D]of Object.entries(W))if(Q===J||Q.toLowerCase()===J.toLowerCase())return{entry:D}}return null}let Y=z($.hasMany);if(Y){let Q=R$(Y)?.getTable?.()||g1(Y),D=S0(G)+"_id";return{type:"hasMany",relatedModelName:Y,relatedTable:Q,foreignKey:D,localKey:A}}let Z=z($.hasOne);if(Z){let Q=R$(Z)?.getTable?.()||g1(Z),D=S0(G)+"_id";return{type:"hasOne",relatedModelName:Z,relatedTable:Q,foreignKey:D,localKey:A}}let E=U();if(E){let W=E.model,Q=R$(W),D=Q?.getTable?.()||g1(W),w=Q?.getDefinition?.()?.primaryKey||"id",K=E.foreignKey||`${S0(W)}_id`;return{type:"belongsTo",relatedModelName:W,relatedTable:D,foreignKey:K,localKey:w}}let X=h();if(X){let W=typeof X.entry==="object",Q=W?X.entry.model:X.entry,w=R$(Q)?.getTable?.()||g1(Q),K=W?X.entry:null,V,q;if(K?.table)V=K.table;else if(K?.through){q=K.through;let B=R$(K.through);if(!B)throw Error(`[orm] belongsToMany relation '${J}' on '${G}' references unknown through model '${K.through}'. Make sure '${K.through}' is registered.`);V=B.getTable?.()||B.getDefinition?.()?.table||g1(K.through)}else{let B=fG(H),N=fG(w);V=[B,N].sort().join("_")}let P=K?.foreignKey||`${fG(H)}_id`,T=K?.relatedKey||`${fG(w)}_id`,I=[];if(K?.pivot?.columns)for(let B of Object.keys(K.pivot.columns))I.push(B);if(q){let B=R$(q),N=B?.getDefinition?.()||B?.definition,S=N?.attributes??{},x=N?.primaryKey??"id";for(let u of Object.keys(S)){if(u===P||u===T||u===x)continue;if(!I.includes(u))I.push(u)}}return{type:"belongsToMany",relatedModelName:Q,relatedTable:w,foreignKey:P,localKey:A,pivotTable:V,pivotFkParent:P,pivotFkRelated:T,pivotColumns:I,pivotModelName:q,pivotTimestamps:Boolean(K?.pivot?.timestamps)}}let F=(W,Q)=>{if(!W||typeof W!=="object"||Array.isArray(W))return null;let D=W[J]??W[Object.keys(W).find((N)=>N.toLowerCase()===J.toLowerCase())??""];if(!D||typeof D!=="object")return null;let{through:w,target:K}=D;if(!w||!K)return null;let V=R$(w),q=V?.getDefinition?.()||V?.definition,P=V?.getTable?.()||q?.table||g1(w),T=q?.primaryKey||"id",B=R$(K)?.getTable?.()||g1(K);return{type:Q,relatedModelName:K,relatedTable:B,foreignKey:`${S0(G)}_id`,localKey:A,throughTable:P,throughForeignKey:`${S0(G)}_id`,throughLocalKey:T,targetForeignKey:`${fG(P)}_id`}},R=F($.hasManyThrough,"hasManyThrough");if(R)return R;let C=F($.hasOneThrough,"hasOneThrough");if(C)return C;return null}function Sz($,J){let G=new Set;for(let H of $){let A=H.get(J);if(A!=null)G.add(A)}return[...G]}function fG($){return F1(g.relations?.singularizeStrategy)($)}class j8{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor($,J,G,H){this._parent=$,this._parentDef=J,this._resolved=G,this._relatedDef=H}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($,J,G){if(G===void 0)this._wheres.push({sql:`${this.relatedTable}.${$} = ?`,params:[J]});else this._wheres.push({sql:`${this.relatedTable}.${$} ${String(J)} ?`,params:[G]});return this}wherePivot($,J,G){if(G===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${$} = ?`,params:[J]});else this._pivotWheres.push({sql:`${this.pivotTable}.${$} ${String(J)} ?`,params:[G]});return this}wherePivotIn($,J){if(!J.length)return this;let G=J.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IN (${G})`,params:[...J]}),this}wherePivotNotIn($,J){if(!J.length)return this;let G=J.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} NOT IN (${G})`,params:[...J]}),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($,J="asc"){if(Y8($,"orderBy(column)"),J!=="asc"&&J!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${J}'`);return this._orderBy.push(`${$} ${J.toUpperCase()}`),this}limit($){if(!Number.isFinite($)||$<0||!Number.isInteger($))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${$}`);return this._limit=$,this}offset($){if(!Number.isFinite($)||$<0||!Number.isInteger($))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${$}`);return this._offset=$,this}relatedSelectColumns(){let $=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),J=this._relatedDef.traits;if(J?.useTimestamps||J?.timestampable)$.add("created_at"),$.add("updated_at");if(J?.useSoftDeletes||J?.softDeletable)$.add("deleted_at");if(J?.useUuid)$.add("uuid");return[...$]}buildSelect(){let $=[],G=`SELECT ${this.relatedSelectColumns().map((H)=>`${this.relatedTable}.${H} AS ${Iz}${H}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;G+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,G+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,$.push(this.parentId);for(let H of this._pivotWheres)G+=` AND ${H.sql}`,$.push(...H.params);for(let H of this._wheres)G+=` AND ${H.sql}`,$.push(...H.params);if(this._orderBy.length>0)G+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)G+=` LIMIT ${this._limit}`;if(this._offset!==void 0)G+=` OFFSET ${this._offset}`;return{sql:G,params:$}}hydrateRows($){let J=this.fkParent,G=this.fkRelated;return $.map((H)=>{let A={},z={};for(let[h,Y]of Object.entries(H))if(h.startsWith(Iz))A[h.slice(Iz.length)]=Y;else if(h!==J&&h!==G)z[h]=Y;let U=new j$(this._relatedDef,A);return U.pivot=z,U})}async get(){let $=I0(),{sql:J,params:G}=this.buildSelect(),H=await $.all(J,G);return this.hydrateRows(H)}async first(){return this._limit=1,(await this.get())[0]}async count(){let $=I0(),J=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,G=[this.parentId];for(let A of this._pivotWheres)J+=` AND ${A.sql}`,G.push(...A.params);let H=await $.get(J,G);return Number(H?.count??0)}async exists(){return await this.count()>0}now(){return m1()}async attach($,J={}){let G=I0(),H=Array.isArray($)?$:[$];if(H.length===0)return 0;let A=this._resolved.pivotTimestamps?this.now():null,z=0;for(let U of H){let h={[this.fkParent]:this.parentId,[this.fkRelated]:U,...J};if(A){if(h.created_at===void 0)h.created_at=A;if(h.updated_at===void 0)h.updated_at=A}let Y=Object.keys(h),Z=Y.map(()=>"?").join(", "),E=`INSERT INTO ${this.pivotTable} (${Y.join(", ")}) VALUES (${Z})`,X=Y.map((F)=>h[F]);await G.run(E,X),z++}return z}async detach($){let J=I0(),G=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,H=[this.parentId];if($!==void 0&&$!==null){let A=Array.isArray($)?$:[$];if(A.length===0)return 0;let z=A.map(()=>"?").join(", ");G+=` AND ${this.fkRelated} IN (${z})`,H.push(...A)}return(await J.run(G,H)).changes}async updateExistingPivot($,J){let G=I0(),H={...J};if(this._resolved.pivotTimestamps&&H.updated_at===void 0)H.updated_at=this.now();let A=Object.keys(H);if(A.length===0)return 0;let z=A.map((Y)=>`${Y} = ?`).join(", "),U=`UPDATE ${this.pivotTable} SET ${z} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,h=[...A.map((Y)=>H[Y]),this.parentId,$];return(await G.run(U,h)).changes}async sync($){let J=I0(),G=new Map;for(let Z of $)if(Z!=null&&typeof Z==="object"&&"id"in Z){let{id:E,...X}=Z;G.set(E,X)}else G.set(Z,{});let H=await J.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),A=new Set(H.map((Z)=>Z[this.fkRelated])),z=[],U=[],h=[],Y=[...A].filter((Z)=>!G.has(Z));if(Y.length>0)await this.detach(Y),U.push(...Y);for(let[Z,E]of G)if(!A.has(Z))await this.attach(Z,E),z.push(Z);else if(Object.keys(E).length>0)await this.updateExistingPivot(Z,E),h.push(Z);return{attached:z,detached:U,updated:h}}async toggle($){let J=I0(),G=Array.isArray($)?$:[$];if(G.length===0)return{attached:[],detached:[]};let H=G.map(()=>"?").join(", "),A=await J.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${H})`,[this.parentId,...G]),z=new Set(A.map((Y)=>Y[this.fkRelated])),U=G.filter((Y)=>!z.has(Y)),h=G.filter((Y)=>z.has(Y));if(U.length>0)await this.attach(U);if(h.length>0)await this.detach(h);return{attached:U,detached:h}}}class X0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor($){this._definition=$}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where($,J,G){if(G===void 0)this._wheres.push({column:$,operator:"=",value:J,boolean:"and"});else this._wheres.push({column:$,operator:J,value:G,boolean:"and"});return this}orWhere($,J,G){if(G===void 0)this._wheres.push({column:$,operator:"=",value:J,boolean:"or"});else this._wheres.push({column:$,operator:J,value:G,boolean:"or"});return this}whereIn($,J){return this._wheres.push({column:$,operator:"in",value:J,boolean:"and"}),this}orWhereIn($,J){return this._wheres.push({column:$,operator:"in",value:J,boolean:"or"}),this}whereNotIn($,J){return this._wheres.push({column:$,operator:"not in",value:J,boolean:"and"}),this}orWhereNotIn($,J){return this._wheres.push({column:$,operator:"not in",value:J,boolean:"or"}),this}whereNull($){return G1($,"whereNull(column)"),this._wheres.push({column:$,operator:"=",value:null,boolean:"and"}),this}orWhereNull($){return G1($,"orWhereNull(column)"),this._wheres.push({column:$,operator:"=",value:null,boolean:"or"}),this}whereNotNull($){return G1($,"whereNotNull(column)"),this._wheres.push({column:$,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull($){return G1($,"orWhereNotNull(column)"),this._wheres.push({column:$,operator:"!=",value:null,boolean:"or"}),this}whereLike($,J){return this._wheres.push({column:$,operator:"like",value:J,boolean:"and"}),this}orWhereLike($,J){return this._wheres.push({column:$,operator:"like",value:J,boolean:"or"}),this}whereNotLike($,J){return this._wheres.push({column:$,operator:"not like",value:J,boolean:"and"}),this}orWhereNotLike($,J){return this._wheres.push({column:$,operator:"not like",value:J,boolean:"or"}),this}whereRaw($,...J){return this._wheres.push({raw:$,rawParams:J,boolean:"and"}),this}orWhereRaw($,...J){return this._wheres.push({raw:$,rawParams:J,boolean:"or"}),this}whereGroup($){return this._addGroup("and",$)}orWhereGroup($){return this._addGroup("or",$)}_addGroup($,J){let G=new X0(this._definition);if(J(G),G._wheres.length===0)return this;let H=[],A=G.buildWhereClauses(H);if(!A)return this;return this._wheres.push({raw:`(${A})`,rawParams:H,boolean:$}),this}whereBetween($,J){return G1($,"whereBetween(column)"),this._wheres.push({column:$,operator:">=",value:J[0],boolean:"and"}),this._wheres.push({column:$,operator:"<=",value:J[1],boolean:"and"}),this}whereNotBetween($,J){G1($,"whereNotBetween(column)");let G=k$($);return this._wheres.push({raw:`(${G} < ? OR ${G} > ?)`,rawParams:[J[0],J[1]],boolean:"and"}),this}when($,J){if($)return J(this);return this}orderBy($,J="asc"){if(Y8($,"orderBy(column)"),J!=="asc"&&J!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${J}'`);return this._orderBy.push({column:$,direction:J}),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(...$){for(let J of $)if(!this._withRelations.includes(J))this._withRelations.push(J);return this}getWithRelations(){return this._withRelations}buildWhereClauses($){let J=[];for(let G of this._wheres){let H;if(G.raw){if(H=G.raw,G.rawParams&&G.rawParams.length>0)$.push(...G.rawParams)}else if(G.value===null){let A=k$(G.column);H=G.operator==="="?`${A} IS NULL`:`${A} IS NOT NULL`}else if(G.operator==="in"||G.operator==="not in"){let A=G.value;H=F$(k$(G.column),A,G.operator==="not in",A.map(()=>"?").join(", ")),$.push(...A)}else H=`${k$(G.column)} ${G.operator} ?`,$.push(G.value);J.push({conn:G.boolean==="or"?"OR":"AND",sql:H})}return k1(J)}softDeleteClause(){if(this._trashed==="include"||!gJ(this._definition))return"";return this._trashed==="only"?`${D1} IS NOT NULL`:`${D1} IS NULL`}assertNoUnappliedClauses($){let J=[];if(this._limit!==void 0)J.push("limit()");if(this._offset!==void 0)J.push("offset()");if(this._orderBy.length>0)J.push("orderBy()");if(J.length>0)throw TypeError(`[orm] ${$}() cannot apply ${J.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere($){let J=this._wheres.length>0?this.buildWhereClauses($):"",G=this.softDeleteClause();if(J&&G)return`(${J}) AND ${G}`;return J||G}buildQuery(){let $=[],G=`SELECT ${this._select.map((A)=>A==="*"?A:k$(A)).join(", ")} FROM ${this._definition.table}`,H=this.composeWhere($);if(H)G+=` WHERE ${H}`;if(this._orderBy.length>0)G+=` ORDER BY ${this._orderBy.map((A)=>`${k$(A.column)} ${A.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)G+=` LIMIT ${this._limit}`;if(this._offset!==void 0)G+=` OFFSET ${this._offset}`;return{sql:G,params:$}}toSql(){return this.buildQuery()}async eagerLoadRelations($){if($.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((J)=>this.eagerLoadRelation(J,$)))}async eagerLoadRelation($,J){let G=I0(),H=this._definition.primaryKey||"id",A=`${this._definition.name}:${$}`,z=vJ.get(A);if(z===void 0){if(z=X8(this._definition,$),vJ.size>=rj)vJ.clear();vJ.set(A,z)}if(!z)throw Error(sj(this._definition,$));if(z.type==="hasMany"||z.type==="hasOne"){let U=Sz(J,H);if(U.length===0)return;let h=U.map(()=>"?").join(", "),Y=await G.all(`SELECT * FROM ${z.relatedTable} WHERE ${z.foreignKey} IN (${h})`,U),Z=R$(z.relatedModelName),E=Z?.getDefinition?.()||Z?.definition||this._definition;if(z.type==="hasMany"){let X=new Map;for(let F of Y){let R=F[z.foreignKey];if(!X.has(R))X.set(R,[]);X.get(R).push(F)}for(let F of J){let R=X.get(F.get(H))||[];F.setRelation($,R.map((C)=>new j$(E,C)))}}else{let X=new Map;for(let F of Y){let R=F[z.foreignKey];if(!X.has(R))X.set(R,F)}for(let F of J){let R=X.get(F.get(H));F.setRelation($,R?new j$(E,R):null)}}}if(z.type==="belongsTo"){let U=new Set;for(let R of J){let C=R._attributes[z.foreignKey];if(C!=null)U.add(C)}let h=[...U];if(h.length===0)return;let Y=h.map(()=>"?").join(", "),Z=await G.all(`SELECT * FROM ${z.relatedTable} WHERE ${z.localKey} IN (${Y})`,h),E=R$(z.relatedModelName),X=E?.getDefinition?.()||E?.definition||this._definition,F=new Map;for(let R of Z)F.set(R[z.localKey],R);for(let R of J){let C=R._attributes[z.foreignKey],W=F.get(C);R.setRelation($,W?new j$(X,W):null)}}if(z.type==="belongsToMany"){let U=Sz(J,H);if(U.length===0)return;if(!z.pivotTable||!z.pivotFkParent||!z.pivotFkRelated)return;let h=U.map(()=>"?").join(", "),Y=await G.all(`SELECT * FROM ${z.pivotTable} WHERE ${z.pivotFkParent} IN (${h})`,U);if(Y.length===0){for(let w of J)w.setRelation($,[]);return}let Z=new Set;for(let w of Y){let K=w[z.pivotFkRelated];if(K!=null)Z.add(K)}let E=[...Z],X=R$(z.relatedModelName),F=X?.getDefinition?.()||X?.definition||this._definition,R=F?.primaryKey||"id",C=[];if(E.length>0){let w=E.map(()=>"?").join(", ");C=await G.all(`SELECT * FROM ${z.relatedTable} WHERE ${R} IN (${w})`,E)}let W=new Map;for(let w of C)W.set(w[R],w);let Q=new Map;for(let w of Y){let K=w[z.pivotFkParent];if(!Q.has(K))Q.set(K,[]);Q.get(K).push(w)}let D=new Set([z.pivotFkParent,z.pivotFkRelated]);for(let w of J){let K=w.get(H),q=(Q.get(K)||[]).map((P)=>{let T=W.get(P[z.pivotFkRelated]);if(!T)return null;let I=new j$(F,T),B={};for(let[N,S]of Object.entries(P))if(!D.has(N))B[N]=S;return I.pivot=B,I}).filter((P)=>P!==null);w.setRelation($,q)}}if(z.type==="hasManyThrough"||z.type==="hasOneThrough"){let U=Sz(J,H);if(U.length===0)return;let h=z.throughLocalKey||"id",Y=U.map(()=>"?").join(", "),Z=await G.all(`SELECT ${h}, ${z.throughForeignKey} FROM ${z.throughTable} WHERE ${z.throughForeignKey} IN (${Y})`,U);if(Z.length===0){for(let D of J)D.setRelation($,z.type==="hasManyThrough"?[]:null);return}let E=new Map;for(let D of Z)E.set(D[h],D[z.throughForeignKey]);let X=[...new Set(Z.map((D)=>D[h]))],F=X.map(()=>"?").join(", "),R=await G.all(`SELECT * FROM ${z.relatedTable} WHERE ${z.targetForeignKey} IN (${F})`,X),C=R$(z.relatedModelName),W=C?.getDefinition?.()||C?.definition||this._definition,Q=new Map;for(let D of R){let w=E.get(D[z.targetForeignKey]);if(w==null)continue;if(!Q.has(w))Q.set(w,[]);Q.get(w).push(new j$(W,D))}for(let D of J){let w=Q.get(D.get(H))||[];D.setRelation($,z.type==="hasManyThrough"?w:w[0]??null)}}}async get(){let $=I0(),{sql:J,params:G}=this.buildQuery(),A=(await $.all(J,G)).map((z)=>new j$(this._definition,z));if(this._withRelations.length>0)await this.eagerLoadRelations(A);return A}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let $=await this.first();if(!$)throw Error(`No ${this._definition.name} found`);return $}async last(){let $=this._definition.primaryKey||"id";return this._orderBy=[{column:$,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let $=I0(),J=[],G=`SELECT COUNT(*) as count FROM ${this._definition.table}`,H=this.composeWhere(J);if(H)G+=` WHERE ${H}`;let A=await $.get(G,J);return Number(A?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let $=await 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]}async increment($,J=1){G1($,"increment(column)"),this.assertNoUnappliedClauses("increment");let G=I0(),H=[J],A=k$($),z=`UPDATE ${this._definition.table} SET ${A} = ${A} + ?`;if(c1(this._definition))z+=", updated_at = ?",H.push(m1());let U=this.composeWhere(H);if(U)z+=` WHERE ${U}`;return(await G.run(z,H)).changes}decrement($,J=1){return this.increment($,-J)}async chunk($,J){let G=0;while(!0){let H=new X0(this._definition);H._wheres=[...this._wheres],H._orderBy=[...this._orderBy],H._select=[...this._select],H._withRelations=[...this._withRelations],H._trashed=this._trashed,H._limit=$,H._offset=G*$;let A=await H.get();if(A.length===0)break;if(await J(A)===!1)break;if(A.length<$)break;G++}}async paginate($=1,J=15){let G=await this.count(),H=Math.ceil(G/J);this._limit=J,this._offset=($-1)*J;let A=await this.get();return{data:A,total:G,page:$,perPage:J,lastPage:H,hasMorePages:$<H,isEmpty:A.length===0,from:A.length>0?($-1)*J+1:null,to:A.length>0?($-1)*J+A.length:null}}async pluck($){G1($,"pluck(column)");let J=I0(),G=[],H=k$($),A=`SELECT ${H} FROM ${this._definition.table}`,z=this.composeWhere(G);if(z)A+=` WHERE ${z}`;if(this._orderBy.length>0)A+=` ORDER BY ${this._orderBy.map((h)=>`${k$(h.column)} ${h.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)A+=` LIMIT ${this._limit}`;if(this._offset!==void 0)A+=` OFFSET ${this._offset}`;return(await J.all(A,G)).map((h)=>h[H])}async aggregate($,J){G1(J,`${$}(column)`);let G=I0(),H=[],A=`SELECT ${$}(${k$(J)}) as v FROM ${this._definition.table}`,z=this.composeWhere(H);if(z)A+=` WHERE ${z}`;let h=(await G.get(A,H))?.v;if(h==null)return null;if(typeof h==="string"){let Y=Number(h);return h.trim()!==""&&!Number.isNaN(Y)?Y:h}return h}max($){return this.aggregate("MAX",$)}min($){return this.aggregate("MIN",$)}async avg($){return Number(await this.aggregate("AVG",$)??0)||0}async sum($){return Number(await this.aggregate("SUM",$)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let $=I0(),J=[],G=`DELETE FROM ${this._definition.table}`,H=this.composeWhere(J);if(H)G+=` WHERE ${H}`;return(await $.run(G,J)).changes}async update($){this.assertNoUnappliedClauses("update");let J=I0(),G=Object.entries($),H=G.map(([h])=>`${k$(h)} = ?`).join(", "),A=G.map(([,h])=>h);if(c1(this._definition))A.push(m1());let z=`UPDATE ${this._definition.table} SET ${H}${c1(this._definition)?", updated_at = ?":""}`,U=this.composeWhere(A);if(U)z+=` WHERE ${U}`;return(await J.run(z,A)).changes}}function oj($){let J={query:()=>new X0($),where(G,H,A){return new X0($).where(G,H,A)},orWhere(G,H,A){return new X0($).orWhere(G,H,A)},whereIn(G,H){return new X0($).whereIn(G,H)},whereNotIn(G,H){return new X0($).whereNotIn(G,H)},whereNull(G){return new X0($).whereNull(G)},whereNotNull(G){return new X0($).whereNotNull(G)},whereLike(G,H){return new X0($).whereLike(G,H)},orderBy(G,H="asc"){return new X0($).orderBy(G,H)},orderByDesc(G){return new X0($).orderByDesc(G)},select(...G){return new X0($).select(...G)},with(...G){return new X0($).with(...G)},limit:(G)=>new X0($).limit(G),take:(G)=>new X0($).take(G),skip:(G)=>new X0($).skip(G),withTrashed:()=>new X0($).withTrashed(),onlyTrashed:()=>new X0($).onlyTrashed(),async find(G){let H=I0(),A=$.primaryKey||"id",z=gJ($)?` AND ${D1} IS NULL`:"",U=await H.get(`SELECT * FROM ${$.table} WHERE ${A} = ?${z}`,[G]);return U?new j$($,U):void 0},async findOrFail(G){let H=await J.find(G);if(!H)throw Error(`${$.name} with id ${G} not found`);return H},async findMany(G){let H=I0(),A=$.primaryKey||"id",z=gJ($)?` AND ${D1} IS NULL`:"";return(await H.all(`SELECT * FROM ${$.table} WHERE ${A} IN (${G.map(()=>"?").join(", ")})${z}`,G)).map((h)=>new j$($,h))},all:()=>new X0($).get(),first:()=>new X0($).first(),firstOrFail:()=>new X0($).firstOrFail(),last:()=>new X0($).last(),count:()=>new X0($).count(),exists:()=>new X0($).exists(),doesntExist:()=>new X0($).doesntExist(),paginate:(G,H)=>new X0($).paginate(G,H),whereBetween(G,H){return new X0($).whereBetween(G,H)},whereNotBetween(G,H){return new X0($).whereNotBetween(G,H)},async create(G){let H=new j$($,G);return await H.save(),H},async createMany(G){let H=[];for(let A of G)H.push(await this.create(A));return H},async updateOrCreate(G,H){let A=new X0($);for(let[U,h]of Object.entries(G))A=A.where(U,h);let z=await A.first();if(z)return await z.update(H),z;return this.create({...G,...H})},async firstOrCreate(G,H){let A=new X0($);for(let[U,h]of Object.entries(G))A=A.where(U,h);return await A.first()||this.create({...G,...H})},async destroy(G){let H=I0(),A=$.primaryKey||"id";return(await H.run(`DELETE FROM ${$.table} WHERE ${A} = ?`,[G])).changes>0},remove(G){return this.destroy(G)},async truncate(){await I0().run(`DELETE FROM ${$.table}`,[])},getDefinition:()=>$,getTable:()=>$.table,make(G={}){return new j$($,G)},latest:(G="created_at")=>new X0($).orderByDesc(G),oldest:(G="created_at")=>new X0($).orderBy(G,"asc"),max:(G)=>new X0($).max(G),min:(G)=>new X0($).min(G),avg:(G)=>new X0($).avg(G),sum:(G)=>new X0($).sum(G),pluck(G){return new X0($).pluck(G)}};return new Proxy(J,{get(G,H){if(typeof H==="string"&&H.startsWith("where")&&H.length>5){let A=H.slice(5),z=A.charAt(0).toLowerCase()+A.slice(1);if(z in $.attributes||z==="id"||z===$.primaryKey)return(U)=>new X0($).where(z,U)}return Reflect.get(G,H)}})}function W8($){let J=oj($);if($?.name)dj($.name,J);return J}async function KQ($){let J=I0(),G=S0($.primaryKey||"id"),H=[],A=new Set([G]);if(H.push($.autoIncrement!==!1?`${G} INTEGER PRIMARY KEY AUTOINCREMENT`:`${G} INTEGER PRIMARY KEY`),$.traits?.useUuid)H.push("uuid TEXT UNIQUE"),A.add("uuid");for(let[z,U]of Object.entries($.attributes)){let h=S0(z);if(A.has(h))continue;A.add(h);let Y=M6(U.type),Z=A5(Y);if(h.endsWith("_id")&&(Y===void 0||UJ(Y)))Z="INTEGER";let E=`${h} ${Z}`;if(U.unique)E+=" UNIQUE";if(typeof U.foreignKey==="object"&&U.foreignKey!==null){let X=U.foreignKey;if(E+=` REFERENCES ${X.table}(${X.column??"id"})`,X.onDelete)E+=` ON DELETE ${X.onDelete.toUpperCase()}`;if(X.onUpdate)E+=` ON UPDATE ${X.onUpdate.toUpperCase()}`}H.push(E)}for(let z of hJ($.belongsTo)){let U=z.foreignKey??`${S0(z.model)}_id`;if(A.has(U))continue;A.add(U),H.push(`${U} INTEGER`)}if(c1($))for(let z of["created_at","updated_at"]){if(A.has(z))continue;A.add(z),H.push(`${z} TEXT`)}if(gJ($)&&!A.has("deleted_at"))A.add("deleted_at"),H.push("deleted_at TEXT");await J.run(`CREATE TABLE IF NOT EXISTS ${$.table} (${H.join(", ")})`,[])}async function BQ($,J,G){let H=I0(),A=$.traits?.useSeeder,z=J??(typeof A==="object"&&A?A.count:10);if(!G)try{let U=await Promise.resolve().then(() => (ah(),th));G=Ah(U.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let U=0;U<z;U++){let h={};for(let[Z,E]of Object.entries($.attributes))if(E.factory)h[S0(Z)]=E.factory(G);if(c1($)){let Z=m1();h.created_at=Z,h.updated_at=Z}if($.traits?.useUuid)h.uuid=crypto.randomUUID();let Y=Object.keys(h);await H.run(`INSERT INTO ${$.table} (${Y.join(", ")}) VALUES (${Y.map(()=>"?").join(", ")})`,Object.values(h))}}var U8,q5=null,Nz,y5,uj=500,b1=null,H1=null,vG=null,Bz=null,Cz=null,D1="deleted_at",Iz="__btm_rel__",G8,H8,A8,vJ,rj=1000,x5,lj;var Tz=a(()=>{m0();j1();mH();U8=/^[A-Z_][A-Z0-9_]*$/i;Nz=new Map;y5=new Map;G8=new WeakMap;H8=new Map,A8=new Map,vJ=new Map;x5=["hasMany","hasOne","belongsTo","belongsToMany"],lj=[...x5,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var F8={};r5(F8,{registerModel:()=>kz,registerBrowserModels:()=>aj,hasModel:()=>D8,getModelRegistry:()=>R8,getModel:()=>L8,getAllModels:()=>w8,defineModel:()=>V8,clearModelRegistry:()=>Q8});function L8($){return bJ.get($)}function w8(){return[...bJ.values()]}function R8(){return Object.fromEntries(bJ)}function D8($){return bJ.has($)}function Q8(){bJ.clear(),h8()}function kz($,J){return bJ.set($,J),J}function tj(){return typeof window<"u"&&typeof document<"u"}function V8($){let J;if(tj())J=HU($);else{let G=W8($);J=Object.assign(G,{definition:$,getDefinition:()=>$,getTable:()=>$.table,getName:()=>$.name})}return kz($.name,J),J}function aj($){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...$}}var bJ;var gG=a(()=>{l5();Tz();bJ=new Map});class Q1{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor($){this.driver=C$($.config),this.client=$.client,this.tableName=$.config.tableName??""}table($){return this.tableName=$,this}index($){return this.indexName=$,this}entity($){return this.entityType=$,this}whereKey($,J,G){return this.keyConditions.push({attribute:$,operator:J,value:G}),this}wherePartitionKey($,J){return this.whereKey($,"=",J)}whereSortKey($,J){return this.whereKey($,"=",J)}whereSortKeyBeginsWith($,J){return this.keyConditions.push({attribute:$,operator:"begins_with",value:J}),this}whereSortKeyBetween($,J,G){return this.keyConditions.push({attribute:$,operator:"BETWEEN",values:[J,G]}),this}where($,J,G){return this.filterConditions.push({attribute:$,operator:J,value:G}),this}whereEquals($,J){return this.where($,"=",J)}whereLessThan($,J){return this.where($,"<",J)}whereLessThanOrEqual($,J){return this.where($,"<=",J)}whereGreaterThan($,J){return this.where($,">",J)}whereGreaterThanOrEqual($,J){return this.where($,">=",J)}whereBetween($,J,G){return this.filterConditions.push({attribute:$,operator:"BETWEEN",values:[J,G]}),this}whereBeginsWith($,J){return this.filterConditions.push({attribute:$,operator:"begins_with",value:J}),this}whereContains($,J){return this.where($,"contains",J)}whereExists($){return this.where($,"attribute_exists")}whereNotExists($){return this.where($,"attribute_not_exists")}whereIn($,J){return this.filterConditions.push({attribute:$,operator:"IN",values:J}),this}select(...$){return this.projectionAttrs.push(...$),this}limit($){return this.limitValue=$,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead($=!0){return this.consistentReadValue=$,this}startFrom($){return this.startKey=$,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let $=this.buildQueryParams(),J={TableName:$.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if($.indexName)J.IndexName=$.indexName;let G=0;if($.keyConditions.length>0){let H=[];for(let A of $.keyConditions){let z=`#key${G}`;if(J.ExpressionAttributeNames[z]=A.attribute,A.operator==="begins_with"){let U=`:keyval${G}`;J.ExpressionAttributeValues[U]=this.driver.marshall({v:A.value}).v,H.push(`begins_with(${z}, ${U})`)}else if(A.operator==="BETWEEN"){let U=`:keyval${G}a`,h=`:keyval${G}b`;J.ExpressionAttributeValues[U]=this.driver.marshall({v:A.values?.[0]}).v,J.ExpressionAttributeValues[h]=this.driver.marshall({v:A.values?.[1]}).v,H.push(`${z} BETWEEN ${U} AND ${h}`)}else{let U=`:keyval${G}`;J.ExpressionAttributeValues[U]=this.driver.marshall({v:A.value}).v,H.push(`${z} ${A.operator} ${U}`)}G++}J.KeyConditionExpression=H.join(" AND ")}if($.filterConditions&&$.filterConditions.length>0){let H=[];for(let A of $.filterConditions){let z=`#flt${G}`;if(J.ExpressionAttributeNames[z]=A.attribute,A.operator==="attribute_exists")H.push(`attribute_exists(${z})`);else if(A.operator==="attribute_not_exists")H.push(`attribute_not_exists(${z})`);else if(A.operator==="begins_with"||A.operator==="contains"){let U=`:fltval${G}`;J.ExpressionAttributeValues[U]=this.driver.marshall({v:A.value}).v,H.push(`${A.operator}(${z}, ${U})`)}else if(A.operator==="BETWEEN"){let U=`:fltval${G}a`,h=`:fltval${G}b`;J.ExpressionAttributeValues[U]=this.driver.marshall({v:A.values?.[0]}).v,J.ExpressionAttributeValues[h]=this.driver.marshall({v:A.values?.[1]}).v,H.push(`${z} BETWEEN ${U} AND ${h}`)}else if(A.operator==="IN"){let U=(A.values??[]).map((h,Y)=>`:fltval${G}_${Y}`);A.values?.forEach((h,Y)=>{J.ExpressionAttributeValues[`:fltval${G}_${Y}`]=this.driver.marshall({v:h}).v}),H.push(`${z} IN (${U.join(", ")})`)}else{let U=`:fltval${G}`;J.ExpressionAttributeValues[U]=this.driver.marshall({v:A.value}).v,H.push(`${z} ${A.operator} ${U}`)}G++}J.FilterExpression=H.join(" AND ")}if($.projectionAttributes&&$.projectionAttributes.length>0){let H=[];for(let A of $.projectionAttributes){let z=`#proj${G}`;J.ExpressionAttributeNames[z]=A,H.push(z),G++}J.ProjectionExpression=H.join(", ")}if($.limit!==void 0)J.Limit=$.limit;if($.scanIndexForward!==void 0)J.ScanIndexForward=$.scanIndexForward;if($.exclusiveStartKey)J.ExclusiveStartKey=this.driver.marshall($.exclusiveStartKey);if($.consistentRead)J.ConsistentRead=$.consistentRead;if(Object.keys(J.ExpressionAttributeNames).length===0)delete J.ExpressionAttributeNames;if(Object.keys(J.ExpressionAttributeValues).length===0)delete J.ExpressionAttributeValues;return J}toScanRequest(){let $=this.buildScanParams(),J={TableName:$.tableName};if($.indexName)J.IndexName=$.indexName;if($.filterConditions&&$.filterConditions.length>0){let{expression:G,expressionAttributeNames:H,expressionAttributeValues:A}=this.driver.buildFilterExpression($.filterConditions);J.FilterExpression=G,J.ExpressionAttributeNames=H,J.ExpressionAttributeValues=A}if($.projectionAttributes&&$.projectionAttributes.length>0){let{expression:G,expressionAttributeNames:H}=this.driver.buildProjectionExpression($.projectionAttributes);J.ProjectionExpression=G,J.ExpressionAttributeNames={...J.ExpressionAttributeNames,...H}}if($.limit!==void 0)J.Limit=$.limit;if($.exclusiveStartKey)J.ExclusiveStartKey=this.driver.marshall($.exclusiveStartKey);if($.consistentRead)J.ConsistentRead=$.consistentRead;return J}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let $=this.toQueryRequest(),J=await this.client.query($);return{items:J.Items?.map((G)=>this.driver.unmarshall(G)),count:J.Count,scannedCount:J.ScannedCount,lastEvaluatedKey:J.LastEvaluatedKey?this.driver.unmarshall(J.LastEvaluatedKey):void 0,consumedCapacity:J.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let $=this.toScanRequest(),J=await this.client.scan($);return{items:J.Items?.map((G)=>this.driver.unmarshall(G)),count:J.Count,scannedCount:J.ScannedCount,lastEvaluatedKey:J.LastEvaluatedKey?this.driver.unmarshall(J.LastEvaluatedKey):void 0,consumedCapacity:J.ConsumedCapacity}}async getAll(){let $=[],J;do{if(J)this.startFrom(J);let G=this.keyConditions.length>0?await this.query():await this.scan();if(G.items)$.push(...G.items);J=G.lastEvaluatedKey}while(J);return $}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return $.Select="COUNT",(this.keyConditions.length>0?await this.client.query($):await this.client.scan($)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class g${driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor($){this.driver=C$($.config),this.client=$.client,this.tableName=$.config.tableName??""}table($){return this.tableName=$,this}key($){return this.keyData=$,this}item($){return this.itemData=$,this}set($,J){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[$]=J,this}setMany($){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,$),this}remove($){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push($),this}add($,J){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[$]=J,this}deleteFromSet($,J){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[$]=J,this}condition($){return this.conditionExpr=$,this}ifNotExists($="pk"){return this.conditionExpr=`attribute_not_exists(${$})`,this}ifExists($="pk"){return this.conditionExpr=`attribute_exists(${$})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let $={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)$.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")$.ReturnValues=this.returnValuesOption;return $}toUpdateRequest(){let $={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:J,expressionAttributeNames:G,expressionAttributeValues:H}=this.driver.buildUpdateExpression(this.updateExpressions);if(J)$.UpdateExpression=J,$.ExpressionAttributeNames=G,$.ExpressionAttributeValues=H;if(this.conditionExpr)$.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")$.ReturnValues=this.returnValuesOption;return $}toDeleteRequest(){let $={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)$.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")$.ReturnValues=this.returnValuesOption;return $}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toPutRequest(),J=await this.client.putItem($);if(J.Attributes)return this.driver.unmarshall(J.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toUpdateRequest(),J=await this.client.updateItem($);if(J.Attributes)return this.driver.unmarshall(J.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toDeleteRequest(),J=await this.client.deleteItem($);if(J.Attributes)return this.driver.unmarshall(J.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toGetRequest(),J=await this.client.getItem($);if(J.Item)return this.driver.unmarshall(J.Item);return}}function NQ($){return new Q1($)}function TQ($){return new g$($)}function kQ($){let J=C$($.config);return{query:()=>new Q1($),item:()=>new g$($),driver:J,registerEntity:(G)=>J.registerEntity(G),buildKey:(G,H)=>J.buildPrimaryKey(G,H)}}var f5=()=>{};class O8{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor($){this.config=$,this.pkAttribute=$.pkAttribute??"pk",this.skAttribute=$.skAttribute??"sk",this.typeAttribute=$.typeAttribute??"_type";for(let J of $.entities)this.entities.set(J.name,J)}getEntity($){return this.entities.get($)}registerEntity($){this.entities.set($.name,$)}buildKey($,J){let G=this.entities.get($);if(!G)throw Error(`Entity not found: ${$}`);let H=this.interpolatePattern(G.pkPattern,J),A=this.interpolatePattern(G.skPattern,J);return{pk:H,sk:A}}buildGSIKey($,J,G){let H=this.entities.get($);if(!H)throw Error(`Entity not found: ${$}`);let A=H.indexes?.find((h)=>h.name===J);if(!A)throw Error(`GSI not found: ${J} for entity ${$}`);let z=this.interpolatePattern(A.pkPattern,G),U=A.skPattern?this.interpolatePattern(A.skPattern,G):void 0;return{pk:z,sk:U}}createItem($,J){let{pk:G,sk:H}=this.buildKey($,J),A=this.entities.get($),z={[this.pkAttribute]:G,[this.skAttribute]:H,[this.typeAttribute]:$,...J};if(A.indexes)for(let U of A.indexes){let h=this.buildGSIKey($,U.name,J),Y=this.config.indexes?.find((Z)=>Z.name===U.name);if(Y){if(z[Y.pkAttribute]=h.pk,Y.skAttribute&&h.sk)z[Y.skAttribute]=h.sk}}return z}parseEntityType($){if($[this.typeAttribute])return $[this.typeAttribute];let J=$[this.pkAttribute];if(!J)return;for(let[G,H]of this.entities){let A=H.pkPattern.split("${")[0];if(J.startsWith(A))return G}return}parseItem($){let J=this.parseEntityType($);if(!J)return;let{[this.pkAttribute]:G,[this.skAttribute]:H,[this.typeAttribute]:A,...z}=$;return{type:J,data:z}}getEntityPrefix($){let J=this.entities.get($);if(!J)throw Error(`Entity not found: ${$}`);return J.pkPattern.split("${")[0]}generateTableDefinition(){let $=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],J=[];if(this.config.indexes)for(let G of this.config.indexes){if(!$.find((H)=>H.name===G.pkAttribute))$.push({name:G.pkAttribute,type:"S"});if(G.skAttribute&&!$.find((H)=>H.name===G.skAttribute))$.push({name:G.skAttribute,type:"S"});J.push({indexName:G.name,keySchema:{partitionKey:G.pkAttribute,sortKey:G.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:$,globalSecondaryIndexes:J.length>0?J:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern($,J){return $.replace(/\$\{(\w+)\}/g,(G,H)=>{if(!(H in J))throw Error(`Missing value for pattern key: ${H}`);return String(J[H])})}}class M8{manager;entityName;options;constructor($,J,G){this.manager=$,this.entityName=J,this.options=G}async create($){let J=this.manager.createItem(this.entityName,$),G=new g$(this.options).table(this.options.config.tableName).item(J).ifNotExists("pk");if(this.options.client)await G.put();return $}async get($){let{pk:J,sk:G}=this.manager.buildKey(this.entityName,$),H=new g$(this.options).table(this.options.config.tableName).key({pk:J,sk:G});if(!this.options.client)throw Error("DynamoDB client not provided");let A=await H.get();if(!A)return;return this.manager.parseItem(A)?.data}async update($,J){let{pk:G,sk:H}=this.manager.buildKey(this.entityName,$),A=new g$(this.options).table(this.options.config.tableName).key({pk:G,sk:H}).setMany(J).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let z=await A.update();if(!z)return;return this.manager.parseItem(z)?.data}async delete($){let{pk:J,sk:G}=this.manager.buildKey(this.entityName,$),H=new g$(this.options).table(this.options.config.tableName).key({pk:J,sk:G});if(!this.options.client)throw Error("DynamoDB client not provided");return await H.delete(),!0}query(){return new K8(this.manager,this.entityName,this.options)}async findAll(){let $=this.manager.typeAttribute??"_type",J=new Q1(this.options).table(this.options.config.tableName).whereEquals($,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await J.getAll()).map((H)=>this.manager.parseItem(H)).filter((H)=>H!==void 0).map((H)=>H.data)}}class K8{manager;entityName;options;builder;pkValue;skConditions=[];constructor($,J,G){this.manager=$,this.entityName=J,this.options=G,this.builder=new Q1(G).table(G.config.tableName)}wherePartitionKey($){let{pk:J}=this.manager.buildKey(this.entityName,$);this.pkValue=J;let G=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(G,J),this}whereSortKey($){let{sk:J}=this.manager.buildKey(this.entityName,$),G=this.manager.skAttribute??"sk";return this.builder.whereSortKey(G,J),this}whereSortKeyBeginsWith($){let J=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(J,$),this}useIndex($,J){let G=this.manager.buildGSIKey(this.entityName,$,J),H=this.manager.config.indexes?.find((A)=>A.name===$);if(!H)throw Error(`GSI configuration not found: ${$}`);return this.builder.index($),this.builder.wherePartitionKey(H.pkAttribute,G.pk),this}where($,J,G){return this.builder.where($,J,G),this}select(...$){return this.builder.select(...$),this}limit($){return this.builder.limit($),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map((J)=>this.manager.parseItem(J)).filter((J)=>J!==void 0).map((J)=>J.data)}async first(){return this.limit(1),(await this.execute())[0]}}function B8($){return new O8($)}function C8($,J,G){return new M8($,J,G)}var xQ;var qz=a(()=>{f5();xQ={simpleEntity:($,J="id")=>({name:$,pkPattern:`${$.toUpperCase()}#\${${J}}`,skPattern:"METADATA",keyFields:[J]}),oneToMany:($,J,G="id",H="id")=>({parent:{name:$,pkPattern:`${$.toUpperCase()}#\${${G}}`,skPattern:"METADATA",keyFields:[G]},child:{name:J,pkPattern:`${$.toUpperCase()}#\${${G}}`,skPattern:`${J.toUpperCase()}#\${${H}}`,keyFields:[G,H]}}),manyToMany:($,J,G="id",H="relatedId")=>({entity:{name:$,pkPattern:`${$.toUpperCase()}#\${${G}}`,skPattern:"METADATA",keyFields:[G]},relation:{name:J,pkPattern:`${$.toUpperCase()}#\${${G}}`,skPattern:`${J.toUpperCase()}#\${${H}}`,keyFields:[G,H],indexes:[{name:"GSI1",pkPattern:`${$.toUpperCase()}#\${${H}}`,skPattern:`${J.toUpperCase()}#\${${G}}`}]}}),hierarchical:($,J="rootId",G="path")=>({name:$,pkPattern:`ROOT#\${${J}}`,skPattern:`PATH#\${${G}}`,keyFields:[J,G]})}});function I8($,J){let G={};for(let[H,A]of Object.entries($))if(A)G[H]=A.replace(/\{([^}]+)\}/g,(z,U)=>{return J[U]!==void 0?String(J[U]):`{${U}}`});return G}async function ej($){return{models:new Map}}function vQ($){return $}function gQ($){return $}function bQ($){return $}function mQ($){return $}class S8{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor($){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...$};let J={region:$.region,endpoint:$.endpoint,credentials:$.credentials,tableName:$.tableName};this.driver=C$(J);let G={tableName:$.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=B8(G),this.queryBuilderOptions={config:J}}setClient($){return this.queryBuilderOptions.client=$,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let $=await ej({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),J=[];for(let[,G]of $.models)this.registerParsedModel(G),J.push(G);return J}registerModel($){let J=this.parseWithTooling($);return this.registerParsedModel(J)}registerParsedModel($){this.models.set($.name,$);let J=this.toSingleTableEntity($);this.singleTableManager.registerEntity(J);let G=this.toEntityMapping($);return this.driver.registerEntity(G),$}registerModels($){return $.map((J)=>this.registerModel(J))}getModel($){return this.models.get($)}getAllModels(){return Array.from(this.models.values())}repository($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return C8(this.singleTableManager,$,this.queryBuilderOptions)}query($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return new Q1(this.queryBuilderOptions).table(this.config.tableName).entity($)}item($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return new g$(this.queryBuilderOptions).table(this.config.tableName)}buildKey($,J){let G=this.models.get($);if(!G)throw Error(`Model not found: ${$}`);let H=I8(G.keyPatterns,J);return{pk:H.pk,sk:H.sk}}createItem($,J){let G=this.models.get($);if(!G)throw Error(`Model not found: ${$}`);let H=I8(G.keyPatterns,J),A=H.pk,z=H.sk,U={[this.config.pkAttribute]:A,[this.config.skAttribute]:z,[this.config.entityTypeAttribute]:G.name,...J};if(G.hasTimestamps){let h=new Date().toISOString();if(!U.createdAt)U.createdAt=h;U.updatedAt=h}if(G.hasVersioning){if(!U._v)U._v=1}return U}parseItem($){let J=$[this.config.entityTypeAttribute];if(!J)return;let{[this.config.pkAttribute]:G,[this.config.skAttribute]:H,[this.config.entityTypeAttribute]:A,...z}=$;return{type:J,data:z}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns($){let J=this.models.get($);if(!J)throw Error(`Model not found: ${$}`);return J.accessPatterns}parseWithTooling($){let J=$.name.toUpperCase(),G=$.primaryKey??"id",H=this.config.keyDelimiter,A=this.parseAttributes($),z=this.parseRelationships($,G),U={pk:`${J}${H}{${G}}`,sk:`${J}${H}{${G}}`,...this.deriveGSIKeyPatterns(J,G,H,z)},h=this.deriveAccessPatterns($.name,J,G,z);return{name:$.name,entityType:J,primaryKey:G,attributes:A,relationships:z,keyPatterns:U,accessPatterns:h,traits:$.traits??{},hasTimestamps:$.traits?.useTimestamps??!1,hasSoftDeletes:$.traits?.useSoftDeletes??!1,hasUuid:$.traits?.useUuid??!1,hasTtl:$.traits?.useTtl??!1,hasVersioning:$.traits?.useVersioning??!1,original:$}}parseAttributes($){let J=[];if(J.push({name:$.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),$.attributes)for(let[G,H]of Object.entries($.attributes))J.push({name:G,fillable:H.fillable??!0,required:H.required??!1,nullable:H.nullable??!0,unique:H.unique??!1,hidden:H.hidden??!1,defaultValue:H.default,cast:H.cast,dynamoDbType:this.inferDynamoDBType(H)});if($.traits?.useTimestamps)J.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if($.traits?.useSoftDeletes)J.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return J}inferDynamoDBType($){if($.cast){let J=$.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(J))return"N";if(["boolean","bool"].includes(J))return"BOOL";if(["array","list"].includes(J))return"L";if(["object","json","map"].includes(J))return"M"}if($.validation?.rule){let J=String($.validation.rule);if(J.includes("integer")||J.includes("numeric")||J.includes("number"))return"N";if(J.includes("boolean"))return"BOOL";if(J.includes("array"))return"L";if(J.includes("object"))return"M"}return"S"}parseRelationships($,J){let G=[];if($.hasOne)for(let H of $.hasOne)G.push({type:"hasOne",relatedModel:H,foreignKey:`${$.name.toLowerCase()}Id`,localKey:J,requiresGsi:!0});if($.hasMany)for(let H of $.hasMany)G.push({type:"hasMany",relatedModel:H,foreignKey:`${$.name.toLowerCase()}Id`,localKey:J,requiresGsi:!1});if($.belongsTo)for(let H of $.belongsTo)G.push({type:"belongsTo",relatedModel:H,foreignKey:`${H.toLowerCase()}Id`,localKey:J,requiresGsi:!0});if($.belongsToMany){let H=Array.isArray($.belongsToMany)?$.belongsToMany:Object.values($.belongsToMany);for(let A of H){let z=typeof A==="string"?A:A?.model;if(!z)continue;let U=[$.name,z].sort();G.push({type:"belongsToMany",relatedModel:z,foreignKey:`${$.name.toLowerCase()}Id`,localKey:J,pivotEntity:U.join(""),requiresGsi:!0})}}return G}deriveGSIKeyPatterns($,J,G,H){let A={},z=1;for(let U of H)if(U.requiresGsi&&z<=5)A[`gsi${z}pk`]=`${U.relatedModel.toUpperCase()}${G}{${U.foreignKey}}`,A[`gsi${z}sk`]=`${$}${G}{${J}}`,U.gsiIndex=z,z++;return A}deriveAccessPatterns($,J,G,H){let A=[];A.push({name:`Get ${$} by ID`,description:`Retrieve a single ${$} by its primary key`,entityType:J,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${J}#123`,exampleSk:`${J}#123`,efficient:!0}),A.push({name:`List all ${$}s`,description:`Scan all ${$} entities`,entityType:J,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:J,efficient:!1});for(let z of H){if(z.type==="hasMany")A.push({name:`Get ${z.relatedModel}s for ${$}`,description:`Query ${z.relatedModel}s related to a ${$}`,entityType:J,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${J}#123`,exampleSk:`${z.relatedModel.toUpperCase()}#`,efficient:!0});if(z.gsiIndex){let U=`GSI${z.gsiIndex}`;A.push({name:`Get ${$}s by ${z.relatedModel}`,description:`Query ${$}s by their related ${z.relatedModel}`,entityType:J,operation:"query",index:U,keyCondition:`gsi${z.gsiIndex}pk = :pk`,examplePk:`${z.relatedModel.toUpperCase()}#123`,efficient:!0})}}return A}toSingleTableEntity($){let J=this.extractKeyFields($.keyPatterns.pk);return{name:$.name,pkPattern:$.keyPatterns.pk,skPattern:$.keyPatterns.sk,keyFields:J,indexes:this.extractGSIPatterns($.keyPatterns)}}extractKeyFields($){let J=$.match(/\{([^}]+)\}/g);if(!J)return[];return J.map((G)=>G.slice(1,-1))}extractGSIPatterns($){let J=[];for(let G=1;G<=5;G++){let H=`gsi${G}pk`,A=`gsi${G}sk`;if($[H])J.push({name:`GSI${G}`,pkPattern:$[H],skPattern:$[A]})}return J.length>0?J:void 0}toEntityMapping($){return{entityType:$.name,pkPattern:$.keyPatterns.pk,skPattern:$.keyPatterns.sk}}buildGSIConfig(){let $=this.config.gsiConfig??{},J=[];if($.gsi1pk)J.push({name:"GSI1",pkAttribute:$.gsi1pk,skAttribute:$.gsi1sk});if($.gsi2pk)J.push({name:"GSI2",pkAttribute:$.gsi2pk,skAttribute:$.gsi2sk});if($.gsi3pk)J.push({name:"GSI3",pkAttribute:$.gsi3pk,skAttribute:$.gsi3sk});return J}}function nQ($){return new S8($)}function rQ($){return $.accessPatterns}function lQ($,J="#"){let G=$.name.toUpperCase(),H=$.primaryKey??"id";return{name:$.name,pkPattern:`${G}${J}\${${H}}`,skPattern:`${G}${J}\${${H}}`}}var _8=a(()=>{f5();qz()});function eH($){let J={};for(let G of Object.keys($)){let H=$[G],A=H.definition??H.getDefinition?.()??H,z=W1(A),U=A.attributes??{},h={};for(let Y of Object.keys(U))h[Y]=void 0;J[z]={columns:h,primaryKey:A.primaryKey??"id"}}return J}var P8=()=>{};import{readdirSync as $W}from"fs";import{basename as N8,extname as T8,isAbsolute as JW,join as k8}from"path";import GW from"process";function AW($){let J=T8($);if(!HW.has(J))return!1;let G=N8($,J);if(G.startsWith("_")||G==="index")return!1;return!G.endsWith(".d")}function zW($){if(!$||typeof $!=="object")return!1;let J=$;return typeof J.name==="string"||typeof J.table==="string"}function q8($){let J=[],G=$W($,{withFileTypes:!0}).sort((H,A)=>H.name.localeCompare(A.name));for(let H of G){let A=k8($,H.name);if(H.isDirectory()){J.push(...q8(A));continue}if(AW(H.name))J.push(A)}return J}async function P$($){let J=$.cwd??GW.cwd(),G=JW($.modelsDir)?$.modelsDir:k8(J,$.modelsDir),H={};for(let A of q8(G)){let z=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,U=await import(`${A}${z}`),h=U.default??U,Y=h.definition??h.getDefinition?.()??h;if(!zW(Y))continue;let Z=Y.name??N8(A,T8(A));H[Z]={...Y,name:Z}}return H}var HW;var y8=a(()=>{HW=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"])});function x8($){let J={},G={},H={},A={},z={};for(let U of Object.keys($)){let h=$[U],Y=h.definition??h.getDefinition?.()??h,Z=W1(Y);J[U]=Z,G[Z]=U,H[Z]=Y.primaryKey??"id";let E=(R)=>{if(!R)return{};let C={};if(Array.isArray(R)){for(let W of R){let Q=R5(W);if(Q)C[Q.model]=Q.model}return C}if(typeof R==="object"){for(let[W,Q]of Object.entries(R)){let D=R5(Q);if(D)C[W]=D.model}return C}return{}},X=(R)=>{if(!R)return{};if(Array.isArray(R)){let C={};for(let W of R)if(typeof W==="string")C[W]=W;else if(W&&typeof W==="object"&&typeof W.model==="string")C[W.model]=W;return C}return R},F=(R)=>{if(!R)return{};return R};if(A[Z]={hasOne:E(Y.hasOne),hasMany:E(Y.hasMany),belongsTo:E(Y.belongsTo),belongsToMany:X(Y.belongsToMany),hasOneThrough:F(Y.hasOneThrough),hasManyThrough:F(Y.hasManyThrough),morphOne:E(Y.morphOne),morphMany:E(Y.morphMany),morphTo:Y.morphTo,morphToMany:E(Y.morphToMany),morphedByMany:E(Y.morphedByMany)},Y.scopes&&typeof Y.scopes==="object"){z[Z]={};for(let R of Object.keys(Y.scopes)){let C=Y.scopes[R];if(typeof C==="function")z[Z][R]=C}}}return{modelToTable:J,tableToModel:G,primaryKeys:H,relations:A,scopes:z,models:$}}var yz=()=>{};import{existsSync as cz,mkdirSync as UW,readdirSync as YW,readFileSync as hW,writeFileSync as ZW}from"fs";import{dirname as f8,join as v5}from"path";import c8 from"process";function t0($){if(g.verbose)console.log($)}function V1($){return $.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function xz($){return F1(g.relations?.singularizeStrategy)($)}function c6(){return[...b5]}function EW($){let J=$;while(J!==f8(J)){if(cz(v5(J,"package.json")))return J;J=f8(J)}return c8.cwd()}function XW(){let $=EW(c8.cwd()),J=s$($,g.migrationDir);if(!cz(J))UW(J,{recursive:!0}),t0(`-- Created SQL directory: ${J}`);return J}function d6($){return $.trimStart().startsWith(d8)}function u8($){return $.split(`
476
- `).filter((J)=>!J.trimStart().startsWith("--")).join(`
477
- `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function jW($){let J=new Set,G;try{G=YW($).filter((H)=>H.endsWith(".sql"))}catch{return J}for(let H of G)try{J.add(u8(hW(v5($,H),"utf8")))}catch{}return J}function p8($,J){if(!$)return!1;let G=XW();if(mJ===null)mJ=jW(G);let H=u8($);if(H.length>0&&mJ.has(H))return t0(`-- Migration already in the corpus, not writing it again: ${J}`),!1;mG++;let A=g5?String(mG).padStart(10,"0"):String(Math.floor(Date.now()/1000)+mG),z=`${A}-${J}.sql`;if(!g5){let h=Number(A);while(cz(v5(G,z)))h+=1,A=String(h),z=`${A}-${J}.sql`}let U=v5(G,z);return ZW(U,`${d8}
478
- ${$}`),t0(`-- Migration file created: ${z}`),z1++,b5.push(z),mJ?.add(H),!0}function WW($,J){return $==="integer"&&J==="bigint"||$==="string"&&J==="text"}function v8($){if($.endsWith("_id"))return"bigint";if($.endsWith("_at"))return"datetime";if($.startsWith("is_")||$.startsWith("has_"))return"boolean";return}function g8($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="bigint"||$ instanceof Date)return $;return}function FW($){if($&&typeof $==="object"&&"name"in $){let J=$;if(J.name==="enum"||J.getRules&&Array.isArray(J.getRules())){if(J.enumValues&&Array.isArray(J.enumValues))return J.enumValues.map((G)=>String(G));if(J._values&&Array.isArray(J._values))return J._values.map((G)=>String(G));if(J.values&&Array.isArray(J.values))return J.values.map((G)=>String(G))}}if($&&typeof $==="object"){let J=$,G=J.allowedValues||J.enumValues||J._values||J.values;if(Array.isArray(G)&&G.length>0)return G.map((H)=>String(H))}return}function vz($){if(!$?.rules||!Array.isArray($.rules))return;for(let J of $.rules)if(J?.name==="max"||J?.name==="maxLength"){if(J.params&&typeof J.params.max==="number")return J.params.max;if(Array.isArray(J.args)&&typeof J.args[0]==="number")return J.args[0];if(typeof J.value==="number")return J.value;if(typeof J.expectedValue==="number")return J.expectedValue}return}function LW($){if(!$||typeof $!=="object")return;let J=$;if(J.name)switch(String(J.name).toLowerCase()){case"string":{let H=vz(J);return H&&H>gz?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if(J.type){let G=String(J.type).toLowerCase();if(G==="string"||G==="text")return"string";if(G==="integer"||G==="int")return"integer";if(G==="bigint")return"bigint";if(G==="float")return"float";if(G==="number")return"integer";if(G==="boolean")return"boolean";if(G==="date")return"date";if(G==="datetime")return"datetime";if(G==="timestamptz"||G==="timestamp_tz")return"timestamptz";if(G==="json")return"json"}return}function wW($){if(typeof $!=="string")return;switch($.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function LG($,J){let G=x8($),H=[];for(let h of Object.keys($)){let Y=$[h],Z=W1(Y),E=Y.primaryKey??"id",X=Y.autoIncrement!==!1,F=Y.attributes??{},R=[],C=[];if(!F[E])R.push({name:V1(E),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let W=new Map,Q=hJ(Y.belongsTo).length>0,D=new Set(Object.keys(F).map((S)=>V1(S))),w=new Set;for(let S of D){if(!S.endsWith("_type"))continue;let x=`${S.slice(0,-5)}_id`;if(D.has(x))w.add(x)}for(let S of hJ(Y.belongsTo)){let x=S.foreignKey??`${V1(S.model)}_id`,u=G.modelToTable[S.model];if(u)W.set(x,{table:u,onDelete:S.onDelete})}for(let S of Object.keys(F)){let x=F[S],u=V1(S),r=Boolean(x.validation?.rule?.isRequired),o=S===E?!1:x.nullable??!(x.required??r),y,d,i=S===E;if(y=wW(x.type)??LW(x.validation?.rule),y==="string"){let t=vz(x.validation?.rule);if(t&&t>gz)y="text"}if(!y||y==="enum"){let t=FW(x.validation?.rule);if(t&&t.length>0)y="enum",d=t}if(!y)y=v8(u);if(!y){let t=g8(x.default);if(typeof t==="string")y=t.length>255?"text":"string";else if(typeof t==="number")y=Number.isInteger(t)?"integer":"float";else if(typeof t==="boolean")y="boolean";else if(typeof t==="bigint")y="bigint";else if(t instanceof Date)y="datetime"}if(!y)y=i?"bigint":"string";let f=y==="string"?vz(x.validation?.rule):void 0,J0={name:u,type:y,isPrimaryKey:i,isUnique:Boolean(x.unique),isNullable:o,hasDefault:typeof x.default<"u",defaultValue:g8(x.default),enumValues:d,maxLength:typeof f==="number"&&f>0&&f<=gz?f:void 0};if(u.endsWith("_id")&&x.foreignKey!==!1&&!w.has(u))if(typeof x.foreignKey==="object"&&x.foreignKey!==null){let t=x.foreignKey;if(J0.references={table:t.table,column:t.column??"id",onDelete:t.onDelete,onUpdate:t.onUpdate},t.nullable!==void 0)J0.isNullable=t.nullable}else{let t=W.get(u),L0=u.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(Y1,K0,D$)=>D$.toUpperCase()),H$=t?.table??(Q?void 0:G.modelToTable[L0]);if(H$){let Y1=G.primaryKeys[H$]??"id";J0.references={table:H$,column:Y1,onDelete:t?.onDelete}}}R.push(J0)}let K=hJ(Y.belongsTo);for(let S of K){let x=S.foreignKey??`${V1(S.model)}_id`;if(R.some((o)=>o.name===x))continue;let u=G.modelToTable[S.model],r=u?G.primaryKeys[u]??"id":void 0;R.push({name:x,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:u&&r&&!w.has(x)?{table:u,column:r,onDelete:S.onDelete}:void 0})}let V=Y.traits;if(V?.useTimestamps??V?.timestampable??!1){if(!R.some((S)=>S.name==="created_at"))R.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:A1});if(!R.some((S)=>S.name==="updated_at"))R.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(V?.useSoftDeletes??V?.softDeletable??!1){if(!R.some((S)=>S.name==="deleted_at"))R.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(V?.useUuid??!1){if(!R.some((S)=>S.name==="uuid"))R.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let S of Y.indexes??[])C.push({name:S.name,columns:S.columns.map((x)=>V1(x)),type:S.unique?"unique":"index",where:S.where});for(let S of R)if(S.isUnique&&!S.isPrimaryKey)C.push({name:`${Z}_${S.name}_unique`,columns:[S.name],type:"unique"});let I=Array.isArray(Y.shardKey)?Y.shardKey.map(V1):void 0,B=Array.isArray(Y.sortKey)?Y.sortKey.map(V1):void 0,N=Y.tableKind;H.push({table:Z,columns:R,indexes:C,shardKey:I,sortKey:B,tableKind:N})}let A=new Set(H.map((h)=>h.table));function z(h){if(!A.has(h.table))A.add(h.table),H.push(h)}for(let h of Object.keys($)){let Y=$[h],Z=Y?.traits??{},E=W1(Y),X=xz(E);if(Z.likeable){let F=typeof Z.likeable==="object"?Z.likeable:{},R=F.table||`${E}_likes`,C=F.foreignKey||`${X}_id`;z({table:R,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:C,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:E,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:A1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${R}_user_target_unique`,columns:["user_id",C],type:"unique"}]})}if(Z.taggable)z({table:"taggables",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:!0,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:A1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),z({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{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:A1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(Z.categorizable)z({table:"categorizables",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:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{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:A1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),z({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:"categorizables",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:A1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let h of Object.keys($)){let Y=$[h],Z=Y?.belongsToMany;if(!Z||typeof Z!=="object"||Array.isArray(Z))continue;let E=W1(Y),X=xz(E);for(let[F,R]of Object.entries(Z)){let C=R;if(!C||typeof C!=="object")continue;if(C.through)continue;let W=C.pivot;if(!W||!W.columns&&!W.timestamps&&!W.uniques)continue;let Q=C.model,w=$[Q]?.table||`${String(Q).toLowerCase()}s`,K=xz(w),V=C.table||[X,K].sort().join("_"),q=C.foreignKey||`${X}_id`,P=C.relatedKey||`${K}_id`,T=new Set([q,P,...Object.keys(W.columns??{})]),I=new Set;for(let u of T){if(!u.endsWith("_type"))continue;let r=`${u.slice(0,-5)}_id`;if(T.has(r))I.add(r)}let B=(u,r)=>I.has(u)?void 0:{table:r,column:"id"},N=[{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:B(q,E)},{name:P,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:B(P,w)}];if(W.columns)for(let[u,r]of Object.entries(W.columns)){let o=r,y=v8(u)??"string";N.push({name:u,type:y,isPrimaryKey:!1,isUnique:!1,isNullable:o?.nullable??!1,hasDefault:o?.default!==void 0,defaultValue:o?.default})}if(W.timestamps)N.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:A1}),N.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let S=[],x=W.uniques&&W.uniques.length>0?W.uniques:[[q,P]];for(let u=0;u<x.length;u++){let r=x[u];S.push({name:`${V}_${r.join("_")}_unique${u>0?`_${u}`:""}`,columns:[...r],type:"unique"})}z({table:V,columns:N,indexes:S})}}let U=new Map(H.map((h)=>[h.table,h]));for(let h of H)for(let Y of h.columns){if(!Y.references)continue;let Z=U.get(Y.references.table)?.columns.find((E)=>E.name===Y.references.column);if(!Z||Y.type===Z.type)continue;Y.type=Z.type,Y.maxLength=Z.maxLength,Y.enumValues=Z.enumValues,Y.enumTypeName=Z.enumTypeName}return{dialect:J.dialect,vitessSharded:J.vitessSharded,tables:H}}function h5($,J={}){mG=0,z1=0,O1=0,b5=[],mJ=null,g5=!0;let G=J.dryRun?()=>!1:p8,H=[],A=v$($.dialect,{vitessSharded:$.vitessSharded}),{tables:z,deferredForeignKeys:U}=i8($.tables,$.dialect);for(let[Y,Z]of z.entries()){let E={...Z,columns:Z.columns.map((W)=>U.has(cJ(Z.table,W.name))?{...W,references:void 0}:W)},X=[],F=new Set;for(let W of E.columns)if(W.type==="enum"&&W.enumValues&&W.enumValues.length>0){let Q=`${E.table}_${W.name}_type`;if(W.enumTypeName=Q,!F.has(Q)){let D=A.createEnumType(Q,W.enumValues);if(D)X.push(D);F.add(Q)}}let R=A.createTable(E);X.push(R);for(let W of E.indexes)X.push(A.createIndex(E.table,W,E.columns));if(Y===z.length-1)for(let W of z)for(let Q of W.columns){if(!Q.references||!U.has(cJ(W.table,Q.name)))continue;let D=A.addForeignKey(W.table,Q.name,Q.references.table,Q.references.column,Q.references.onDelete,Q.references.onUpdate);if(D)X.push(D)}H.push(...X);let C=X.join(`
479
-
480
- `);G(C,`create-${E.table}-table`)}if(z1+O1===0)t0("-- Nothing to migrate");else{let Y=[];if(z1>0)Y.push(`${z1} created`);if(O1>0)Y.push(`${O1} updated`);t0(`-- Migration files: ${Y.join(", ")}`)}return H}function cJ($,J){return`${$}\x00${J}`}function i8($,J){if(J==="sqlite"||$.length<2)return{tables:$,deferredForeignKeys:new Set};let G=new Map($.map((Y)=>[Y.table,Y])),H=new Map;for(let Y of $)H.set(Y.table,new Set(Y.columns.map((Z)=>Z.references?.table).filter((Z)=>Boolean(Z&&Z!==Y.table&&G.has(Z)))));let A=[],z=new Set;while(A.length<$.length){let Y=$.find((Z)=>!z.has(Z.table)&&[...H.get(Z.table)??[]].every((E)=>z.has(E)));if(!Y)break;A.push(Y),z.add(Y.table)}let U=new Set($.filter((Y)=>!z.has(Y.table)).map((Y)=>Y.table)),h=new Set;for(let Y of $){if(!U.has(Y.table))continue;for(let Z of Y.columns)if(Z.references&&U.has(Z.references.table)&&Z.references.table!==Y.table)h.add(cJ(Y.table,Z.name))}return A.push(...$.filter((Y)=>U.has(Y.table))),{tables:A,deferredForeignKeys:h}}function wV($){return h5($).join(`
481
- `)}function RV($,J){return OW($,J).join(`
482
- `)}function u6($){let J=G0("crypto");function G(A){if(A==null||typeof A!=="object"||A instanceof Date)return A;if(Array.isArray(A))return A.map((U)=>G(U));let z={};for(let U of Object.keys(A).sort())z[U]=G(A[U]);return z}let H=JSON.stringify(G($));return J.createHash("sha256").update(H).digest("hex")}function b8($){let J={};for(let G of $)J[G.table]=G;return J}function bG($){let J={};for(let G of $)J[G.name]=G;return J}function bz($,J){if(J==="sqlite"){if($.name.endsWith("_id")&&UJ($.type))return"INTEGER";switch($.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if(J==="mysql"||J==="vitess"||J==="singlestore")switch($.type){case"string":return`VARCHAR(${$.maxLength??255})`;case"text":return"TEXT";case"boolean":return"TINYINT(1)";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"float":return"REAL";case"double":return"DOUBLE";case"decimal":return"DECIMAL";case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return $.type}return $.type}function mz($,J){if(!$.hasDefault||$.defaultValue===void 0)return;let G=$.defaultValue;if(G instanceof Date)return G.toISOString();if(typeof G==="boolean")return G?"1":"0";if(typeof G==="bigint"||typeof G==="number")return String(G);let H=String(G).trim();if(H=H.replace(/::[\w ]+$/i,"").trim(),H.startsWith("'")&&H.endsWith("'")||H.startsWith('"')&&H.endsWith('"'))H=H.slice(1,-1);let A=H.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(A.replace(/\s+/g," ")))return A1;if(J==="sqlite"&&A==="CURRENT_TIMESTAMP")return A1;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(A))return A==="NOW()"?"CURRENT_TIMESTAMP":A;if($.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(H))return"1";if(/^(?:0|f|false|no)$/i.test(H))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(H))return String(Number(H));return H}function RW($,J,G){if(bz($,G)!==bz(J,G))return!0;if($.isNullable!==J.isNullable)return!0;if($.hasDefault!==J.hasDefault)return!0;if(mz($,G)!==mz(J,G))return!0;if($.isUnique!==J.isUnique)return!0;if($.type==="enum"&&J.type==="enum"){let H=($.enumValues||[]).slice().sort().join(","),A=(J.enumValues||[]).slice().sort().join(",");if(H!==A)return!0}return!1}function m8($,J){return JSON.stringify([bz($,J),$.isPrimaryKey,$.isUnique,$.isNullable,$.hasDefault,mz($,J)??null,($.enumValues??[]).slice().sort(),$.references?[$.references.table,$.references.column,$.references.onDelete??null,$.references.onUpdate??null]:null])}function DW($,J,G){let H=Object.keys($).filter((E)=>!J[E]),A=Object.keys(J).filter((E)=>!$[E]),z=new Map,U=new Map;for(let E of H){let X=m8($[E],G),F=z.get(X)??[];F.push(E),z.set(X,F)}for(let E of A){let X=m8(J[E],G),F=U.get(X)??[];F.push(E),U.set(X,F)}let h=[],Y=new Set,Z=new Set;for(let[E,X]of z){let F=U.get(E);if(X.length===1&&F&&F.length===1)h.push({from:X[0],to:F[0]}),Y.add(X[0]),Z.add(F[0])}return{renames:h,removed:H.filter((E)=>!Y.has(E)),added:A.filter((E)=>!Z.has(E))}}function QW($,J){let G=$.columns.find((H)=>H.name===J);if(G&&(G.isPrimaryKey||G.isUnique||G.references))return!0;return $.indexes.some((H)=>H.columns.includes(J))}function VW($,J){if(Boolean($)!==Boolean(J))return!0;if(!$||!J)return!1;if(($.constraintNames?.length??0)>1)return!0;let G=(H)=>(H??"no action").toLowerCase();return $.table!==J.table||$.column!==J.column||G($.onDelete)!==G(J.onDelete)||G($.onUpdate)!==G(J.onUpdate)}function n8($,J){return`${$.type}:${N$(J,$.name)}:${$.columns.join(",")}`}function fz($,J){let G={};for(let H of $)G[n8(H,J)]=H;return G}function _9($,J,G={}){if(!$||$.dialect!==J.dialect){let w=h5(J,{dryRun:G.dryRun}),K=J.tables.map((V)=>({kind:"create_table",table:V.table,destructive:!1,sql:""}));return{statements:w,operations:K}}let H=G.applyRenames!==!1,A=G.preserveUnknownColumns===!0,z=G.dryRun?()=>!1:p8;mG=0,z1=0,O1=0,b5=[],mJ=null,g5=!1;let U=[],h=[],Y=v$(J.dialect,{vitessSharded:J.vitessSharded}),Z=J.dialect,E=b8($.tables),X=b8(J.tables);for(let w of Object.keys(E))if(!X[w]){let K=Y.dropTable(w);U.push(K),h.push({kind:"drop_table",table:w,destructive:!0,sql:K}),z(K,`drop-${w}-table`),t0(`-- Detected dropped table: ${w}`)}let F=Object.keys(X).filter((w)=>!E[w]).map((w)=>X[w]),{tables:R,deferredForeignKeys:C}=i8(F,Z);for(let[w,K]of R.entries()){let V={...K,columns:K.columns.map((B)=>C.has(cJ(K.table,B.name))?{...B,references:void 0}:B)},q=[],P=new Set;for(let B of V.columns)if(B.type==="enum"&&B.enumValues&&B.enumValues.length>0){let N=`${V.table}_${B.name}_type`;if(B.enumTypeName=N,!P.has(N)){let S=Y.createEnumType(N,B.enumValues);if(S)q.push(S);P.add(N)}}let T=Y.createTable(V);q.push(T);for(let B of V.indexes){let N=Y.createIndex(V.table,B,V.columns);q.push(N),h.push({kind:"create_index",table:V.table,column:B.name,destructive:!1,sql:N})}for(let B of K.columns)if(B.references&&!C.has(cJ(K.table,B.name)))h.push({kind:"add_foreign_key",table:K.table,column:B.name,destructive:!1,sql:T});if(w===R.length-1)for(let B of R)for(let N of B.columns){if(!N.references||!C.has(cJ(B.table,N.name)))continue;let S=Y.addForeignKey(B.table,N.name,N.references.table,N.references.column,N.references.onDelete,N.references.onUpdate);if(!S)continue;q.push(S),h.push({kind:"add_foreign_key",table:B.table,column:N.name,destructive:!1,sql:S})}U.push(...q),h.push({kind:"create_table",table:V.table,destructive:!1,sql:T});let I=q.join(`
483
-
484
- `);z(I,`create-${V.table}-table`)}let W=new Set;for(let w of Object.keys(X)){let K=E[w],V=X[w];if(!K)continue;let q=bG(K.columns),P=bG(V.columns);for(let T of Object.keys(P)){let I=P[T];if(I.type!=="enum"||!I.enumValues||I.enumValues.length===0)continue;let B=`${V.table}_${I.name}_type`;if(I.enumTypeName=B,q[T])continue;if(!W.has(B)){let N=Y.createEnumType(B,I.enumValues);if(N)U.push(N),h.push({kind:"create_enum",table:V.table,column:I.name,destructive:!1,sql:N}),z(N,`create-${B}-enum`);W.add(B)}}}for(let w of Object.keys(X)){let K=E[w],V=X[w];if(!K)continue;let q=bG(K.columns),P=fz(K.indexes,K.table),T=bG(V.columns),I=fz(V.indexes,V.table),B=[],N=Object.keys(q).filter((y)=>!T[y]),S=Object.keys(T).filter((y)=>!q[y]);if(H&&!A){let y=DW(q,T,Z);B=y.renames,N=y.removed,S=y.added}if(A){let y=N.map((i)=>q[i]),d=K.indexes.filter((i)=>!I[n8(i,K.table)]);if(y.length>0||d.length>0){if(y.length>0)t0(`-- Keeping ${y.length} column(s) on "${V.table}" no model declares: ${N.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(d.length>0)t0(`-- Keeping ${d.length} index(es) on "${V.table}" no model declares: ${d.map((i)=>i.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);V={...V,columns:[...V.columns,...y],indexes:[...V.indexes,...d]},T=bG(V.columns),I=fz(V.indexes,V.table)}N=[]}let x=Object.keys(T).filter((y)=>q[y]&&RW(q[y],T[y],Z)),u=Object.keys(T).filter((y)=>q[y]&&VW(q[y].references,T[y].references));if(Z==="sqlite"){if(x.length>0||u.length>0||N.some((d)=>QW(K,d))){let d={},i=new Map(B.map((L0)=>[L0.to,L0.from]));for(let L0 of V.columns)if(q[L0.name])d[L0.name]=L0.name;else if(i.has(L0.name))d[L0.name]=i.get(L0.name);let f=`_qb_tmp_${V.table}`,J0=0;while((E[f]||X[f])&&J0<100)J0+=1,f=`_qb_tmp_${V.table}_${J0}`;let t=Y.rebuildTable({target:V,tempName:f,columnSource:d});U.push(t);let _0=x.some((L0)=>q[L0].type!==T[L0].type);h.push({kind:"rebuild_table",table:V.table,destructive:N.length>0||_0,sql:t});for(let L0 of B)h.push({kind:"rename_column",table:V.table,from:L0.from,to:L0.to,destructive:!1,confidence:"high",sql:t});for(let L0 of N)h.push({kind:"drop_column",table:V.table,column:L0,destructive:!0,sql:t});t0(`-- Detected SQLite table rebuild required: ${V.table}`),z(t,`alter-${V.table}-table`);continue}}let r=[],o=!1;for(let y of Object.keys(P))if(!I[y]){let d=P[y],i=Y.dropIndex(V.table,d.name);r.push(i),U.push(i),h.push({kind:"drop_index",table:V.table,column:d.name,destructive:!1,sql:i}),t0(`-- Detected dropped index: ${d.name} from ${V.table}`),o=!0}for(let y of B){let d=Y.renameColumn(V.table,y.from,y.to);r.push(d),U.push(d),h.push({kind:"rename_column",table:V.table,from:y.from,to:y.to,destructive:!1,confidence:"high",sql:d}),t0(`-- Detected renamed column: ${V.table}.${y.from} -> ${y.to}`),o=!0}for(let y of N){let d=Y.dropColumn(V.table,y);r.push(d),U.push(d),h.push({kind:"drop_column",table:V.table,column:y,destructive:!0,sql:d}),t0(`-- Detected dropped column: ${V.table}.${y}`),o=!0}for(let y of x){let d=q[y],i=T[y],f=Y.modifyColumn(V.table,i);r.push(f),U.push(f),h.push({kind:"modify_column",table:V.table,column:y,destructive:d.type!==i.type&&!WW(d.type,i.type),sql:f}),t0(`-- Detected column change: ${V.table}.${y} (${d.type} -> ${i.type})`),o=!0}for(let y of u){let d=T[y];if(!d.references)continue;let i=Y.addForeignKey(V.table,d.name,d.references.table,d.references.column,d.references.onDelete,d.references.onUpdate,q[y].references?.constraintNames);if(!i)continue;r.push(i),U.push(i),h.push({kind:"add_foreign_key",table:V.table,column:y,destructive:!1,sql:i}),t0(`-- Detected foreign-key change: ${V.table}.${y} -> ${d.references.table}(${d.references.column})`),o=!0}for(let y of S){let d=T[y],i=Y.addColumn(V.table,d);if(r.push(i),U.push(i),h.push({kind:"add_column",table:V.table,column:d.name,destructive:!1,sql:i}),t0(`-- Detected new column: ${V.table}.${d.name}`),o=!0,d.references){let f=Y.addForeignKey(V.table,d.name,d.references.table,d.references.column,d.references.onDelete,d.references.onUpdate);if(f)r.push(f),U.push(f),h.push({kind:"add_foreign_key",table:V.table,column:d.name,destructive:!1,sql:f})}}for(let y of Object.keys(I))if(!P[y]){let d=I[y],i=Y.createIndex(V.table,d,V.columns);r.push(i),U.push(i),h.push({kind:"create_index",table:V.table,column:d.name,destructive:!1,sql:i}),t0(`-- Detected new index: ${d.name} in ${V.table}`),o=!0}if(o){let y=r.join(`
485
-
486
- `);z(y,`alter-${V.table}-table`)}}if(z1+O1===0)t0("-- Nothing to migrate");else{let w=[];if(z1>0)w.push(`${z1} created`);if(O1>0)w.push(`${O1} updated`);t0(`-- Migration files: ${w.join(", ")}`)}return{statements:U.length===0?["-- No changes detected"]:U,operations:h}}function OW($,J,G={}){return _9($,J,G).statements}var mG=0,z1=0,O1=0,g5=!0,b5,mJ=null,d8="-- qb:generated",gz=767,A1="UTC_TIMESTAMP";var r8=a(()=>{m0();ZG();U5();yz();EG();b5=[]});function QV($){return $}class MW{get order(){return 100}get description(){return}}function OV($){return $}function l8($){switch($){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":case"timestamptz":return"date";case"json":return"json";default:return"other"}}function s8($){let J=String($??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(J)||J==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(J))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(J))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test(J))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(J))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(J))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(J)||/^float\d*\b/.test(J))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(J)||/^int\d*\b/.test(J))return"integer";return"other"}function o8($,J,G){if($===J)return!0;if(G==="sqlite"){if($==="boolean"&&J==="integer")return!0;if(($==="date"||$==="json")&&J==="text")return!0}if(A0(G)&&$==="boolean"&&J==="integer")return!0;if($==="varchar"&&J==="text")return!0;if($==="integer"&&J==="fractional")return!0;if($==="other"||J==="other")return!0;return!1}async function KW($,J={}){let G=J.dialect??g.dialect,H=$.tables.map((Z)=>Z.table),A=await YG({tables:H}),z=new Map(A.map((Z)=>[Z.table.toLowerCase(),Z])),U=[],h=[],Y=[];for(let Z of $.tables){let E=z.get(Z.table.toLowerCase());if(!E){U.push(Z.table);continue}let X=new Map(E.columns.map((F)=>[F.name.toLowerCase(),F]));for(let F of Z.columns){let R=X.get(F.name.toLowerCase()),C=l8(F.type);if(!R){h.push({table:Z.table,column:F.name,expected:C});continue}let W=s8(R.sqlType);if(!o8(C,W,G))Y.push({table:Z.table,column:F.name,expected:C,actual:W,actualSqlType:R.sqlType})}}return{missingTables:U,missingColumns:h,typeMismatches:Y,clean:U.length===0&&h.length===0&&Y.length===0}}function BW($){if($.clean)return"";let J=[];if($.missingTables.length>0)J.push(` Missing tables: ${$.missingTables.join(", ")}`);for(let A of $.missingColumns.slice(0,10))J.push(` \u2022 ${A.table}.${A.column} is missing (models declare ${A.expected})`);for(let A of $.typeMismatches.slice(0,10))J.push(` \u2022 ${A.table}.${A.column} is ${A.actualSqlType}, models declare ${A.expected}`);let G=Math.min($.missingColumns.length,10)+Math.min($.typeMismatches.length,10),H=$.missingColumns.length+$.typeMismatches.length;if(H>G)J.push(` + ${H-G} more`);return["The live schema does not match the models.",...J,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
487
- `)}var t8=a(()=>{m0();$5()});var n0=a(()=>{gG();gG();t8();l9();l5();zG();gG();m0();ZG();f5();qz();_8();FU();P8();y8();yz();r8();lA();Tz();mH()});import{existsSync as CW}from"fs";import dz from"fs/promises";import a8 from"os";import uz from"path";import d1 from"process";import{EventEmitter as IW}from"events";import M1 from"process";import e8 from"process";import rz from"process";import d5 from"process";import uG from"process";import GZ from"tty";import W4,{stdin as RO,stdout as DO}from"process";import AZ,{stdin as w4,stdout as R4}from"process";import D4 from"readline";class UZ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=a8.homedir(),J=uz.join($,".config","clapp");this.configPath=uz.join(J,"telemetry.json")}async isEnabled(){if(d1.env.DO_NOT_TRACK==="1"||d1.env.DO_NOT_TRACK==="true")return!1;if(d1.env.NO_TELEMETRY==="1"||d1.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,J){if(!await this.isEnabled())return;let H={event:$,...J,timestamp:Date.now(),platform:a8.platform(),nodeVersion:d1.version};if(this.events.push(H),this.events.length>=10)await this.send()}async trackCommand($,J){await this.track("command",{command:$,duration:J})}async trackError($,J){await this.track("error",{error:$,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((J)=>setTimeout(J,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:d1.env.DO_NOT_TRACK==="1"||d1.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(CW(this.configPath)){let $=await dz.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let J=uz.dirname(this.configPath);await dz.mkdir(J,{recursive:!0}),await dz.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${$}-${J}`}}var zO=new UZ;function nz($){return $.replace(/[<[].+/,"").trim()}function SW($){let J=/<([^>]+)>/g,G=/\[([^\]]+)\]/g,H=[],A=(h)=>{let Y=!1,Z=h[1];if(Z.startsWith("..."))Z=Z.slice(3),Y=!0;return{required:h[0].startsWith("<"),value:Z,variadic:Y}},z;while(z=J.exec($))H.push(A(z));let U;while(U=G.exec($))H.push(A(U));return H}function _W($){let J={alias:{},boolean:[]};for(let[G,H]of $.entries()){if(H.names.length>1)J.alias[H.names[0]]=H.names.slice(1);if(H.isBoolean)if(H.negated){if(!$.some((z,U)=>{return U!==G&&z.names.some((h)=>H.names.includes(h))&&typeof z.required==="boolean"}))J.boolean.push(H.names[0])}else J.boolean.push(H.names[0])}return J}function $Z($){return $.reduce((J,G)=>J.length>=G.length?J:G,"")}function pz($,J){return $.length>=J?$:`${$}${" ".repeat(J-$.length)}`}function c5($){return $.replace(/([a-z])-([a-z])/g,(J,G,H)=>{return G+H.toUpperCase()})}function PW($,J,G){let H=0,A=J.length,z=$,U;for(;H<A;++H)U=z[J[H]],z=z[J[H]]=H===A-1?G:U!=null?U:!!~J[H+1].indexOf(".")||!(+J[H+1]>-1)?{}:[]}function NW($,J){for(let G of Object.keys(J)){let H=J[G];if(H.shouldTransform){if($[G]=Array.prototype.concat.call([],$[G]),typeof H.transformFunction==="function")$[G]=$[G].map(H.transformFunction)}}}function TW($){let J=/([^\\/]+)$/.exec($);return J?J[1]:""}function pG($){return $.split(".").map((J,G)=>{return G===0?c5(J):J}).join(".")}class iG extends Error{exitCode=2;isUsageError=!0;usage;constructor($,J){super($);if(this.name=this.constructor.name,J!==void 0)this.usage=J;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
3
+ import{B as V6,C as W6,D as D6,E as L6,F as M6,G as w6,H as P6,I as N6,J as O6,K as T6,L as x6,M as B6,N as E6,O as b6,P as I6,Q as A6,R as R6,V as C6,W as k6,ca as l,da as r,ea as a,ia as h6,ja as v6,ka as y6,la as S6,ma as g6,n as K6,na as _6,oa as f6,pa as m6,qa as s,ra as t,sa as d6,ta as u6,ua as i6,va as c6,wa as n6,xa as p6,ya as l6}from"../chunk-yw12p1mp.js";import"../chunk-fkjeeh31.js";import"../chunk-605xwkdk.js";import{qc as K}from"../chunk-c6mb5jxz.js";import{existsSync as r6}from"fs";import S from"fs/promises";import e from"os";import g from"path";import T from"process";import{EventEmitter as a6}from"events";import N from"process";import z6 from"process";import d from"process";import k from"process";import E from"process";import Z6 from"tty";import S4,{stdin as Dz,stdout as Lz}from"process";import Q6,{stdin as f4,stdout as m4}from"process";import d4 from"readline";class j6{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let z=e.homedir(),q=g.join(z,".config","clapp");this.configPath=g.join(q,"telemetry.json")}async isEnabled(){if(T.env.DO_NOT_TRACK==="1"||T.env.DO_NOT_TRACK==="true")return!1;if(T.env.NO_TELEMETRY==="1"||T.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let z=await this.loadConfig();if(z.enabled=!0,!z.userId)z.userId=this.generateUserId();await this.saveConfig(z)}async disable(){let z=await this.loadConfig();z.enabled=!1,await this.saveConfig(z)}async track(z,q){if(!await this.isEnabled())return;let Z={event:z,...q,timestamp:Date.now(),platform:e.platform(),nodeVersion:T.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand(z,q){await this.track("command",{command:z,duration:q})}async trackError(z,q){await this.track("error",{error:z,command:q})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let q=await this.loadConfig();return q.lastSent=Date.now(),await this.saveConfig(q),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let q=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(q),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(z){return new Promise((q)=>setTimeout(q,z))}async status(){let z=await this.loadConfig();return{enabled:z.enabled,doNotTrack:T.env.DO_NOT_TRACK==="1"||T.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(r6(this.configPath)){let z=await S.readFile(this.configPath,"utf-8");return this.config=JSON.parse(z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(z){this.config=z;try{let q=g.dirname(this.configPath);await S.mkdir(q,{recursive:!0}),await S.writeFile(this.configPath,JSON.stringify(z,null,2),"utf-8")}catch{}}generateUserId(){let z=Math.random().toString(36).substring(2,15),q=Date.now().toString(36);return`${z}-${q}`}}var $z=new j6;function m(z){return z.replace(/[<[].+/,"").trim()}function s6(z){let q=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Z=[],$=(X)=>{let Q=!1,j=X[1];if(j.startsWith("..."))j=j.slice(3),Q=!0;return{required:X[0].startsWith("<"),value:j,variadic:Q}},Y;while(Y=q.exec(z))Z.push($(Y));let F;while(F=J.exec(z))Z.push($(F));return Z}function t6(z){let q={alias:{},boolean:[]};for(let[J,Z]of z.entries()){if(Z.names.length>1)q.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!z.some((Y,F)=>{return F!==J&&Y.names.some((X)=>Z.names.includes(X))&&typeof Y.required==="boolean"}))q.boolean.push(Z.names[0])}else q.boolean.push(Z.names[0])}return q}function q6(z){return z.reduce((q,J)=>q.length>=J.length?q:J,"")}function _(z,q){return z.length>=q?z:`${z}${" ".repeat(q-z.length)}`}function C(z){return z.replace(/([a-z])-([a-z])/g,(q,J,Z)=>{return J+Z.toUpperCase()})}function o6(z,q,J){let Z=0,$=q.length,Y=z,F;for(;Z<$;++Z)F=Y[q[Z]],Y=Y[q[Z]]=Z===$-1?J:F!=null?F:!!~q[Z+1].indexOf(".")||!(+q[Z+1]>-1)?{}:[]}function e6(z,q){for(let J of Object.keys(q)){let Z=q[J];if(Z.shouldTransform){if(z[J]=Array.prototype.concat.call([],z[J]),typeof Z.transformFunction==="function")z[J]=z[J].map(Z.transformFunction)}}}function z4(z){let q=/([^\\/]+)$/.exec(z);return q?q[1]:""}function b(z){return z.split(".").map((q,J)=>{return J===0?C(q):q}).join(".")}class I extends Error{exitCode=2;isUsageError=!0;usage;constructor(z,q){super(z);if(this.name=this.constructor.name,q!==void 0)this.usage=q;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(z).stack}format(z=!1){if(z&&this.stack)return`${this.message}
488
4
 
489
5
  Stack trace:
490
- ${this.stack}`;return this.message}}function kW($){if($ instanceof iG)return!0;return!!$&&typeof $==="object"&&$.name==="ClappError"&&typeof $.message==="string"}function qW(){let{env:$}=e8,{TERM:J,TERM_PROGRAM:G}=$;if(e8.platform!=="win32")return J!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||G==="Terminus-Sublime"||G==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var i5="\x1B",c0=`${i5}[`;var U1={to($,J){if(!J)return`${c0}${$+1}G`;return`${c0}${J+1};${$+1}H`},move($,J){let G="";if($<0)G+=`${c0}${-$}D`;else if($>0)G+=`${c0}${$}C`;if(J<0)G+=`${c0}${-J}A`;else if(J>0)G+=`${c0}${J}B`;return G},up:($=1)=>`${c0}${$}A`,down:($=1)=>`${c0}${$}B`,forward:($=1)=>`${c0}${$}C`,backward:($=1)=>`${c0}${$}D`,nextLine:($=1)=>`${c0}E`.repeat($),prevLine:($=1)=>`${c0}F`.repeat($),left:`${c0}G`,hide:`${c0}?25l`,show:`${c0}?25h`,save:`${i5}7`,restore:`${i5}8`};var iz={screen:`${c0}2J`,up:($=1)=>`${c0}1J`.repeat($),down:($=1)=>`${c0}J`.repeat($),line:`${c0}2K`,lineEnd:`${c0}K`,lineStart:`${c0}1K`,lines($){let J="";for(let G=0;G<$;G++)J+=this.line+(G<$-1?U1.up():"");if($)J+=U1.left;return J}},ZO={screen:`${i5}c`};function yW($,J){let G=[];for(let H=0;H<=J.length;H++)G[H]=[H];for(let H=0;H<=$.length;H++)G[0][H]=H;for(let H=1;H<=J.length;H++)for(let A=1;A<=$.length;A++)if(J.charAt(H-1)===$.charAt(A-1))G[H][A]=G[H-1][A-1];else G[H][A]=Math.min(G[H-1][A-1]+1,G[H][A-1]+1,G[H-1][A]+1);return G[J.length][$.length]}function YZ($,J,G=2,H=3){return J.map((A)=>({cmd:A,distance:yW($,A)})).filter(({distance:A})=>A<=G).sort((A,z)=>A.distance-z.distance).slice(0,H).map(({cmd:A})=>A)}function xW($,J={}){let G={_:[]},H=J.alias||{},A=new Set(J.boolean||[]),z={};for(let h of Object.keys(H))for(let Y of H[h])z[Y]=h;for(let h of A)if(H[h])for(let Y of H[h])A.add(Y);function U(h,Y){let Z=z[h]||h;if(G[Z]=Y,H[Z])for(let E of H[Z])G[E]=Y;if(z[h]&&H[z[h]])for(let E of H[z[h]])G[E]=Y;G[h]=Y}for(let h=0;h<$.length;h++){let Y=$[h];if(Y==="--"){G._.push(...$.slice(h+1));break}if(Y.startsWith("--")){let Z=Y.indexOf("=");if(Z!==-1){let E=c5(Y.slice(2,Z)),X=Y.slice(Z+1);U(E,X)}else{let E=Y.slice(2);if(E.startsWith("no-")){let R=c5(E.slice(3));U(R,!1);continue}let X=c5(E),F=z[X]||X;if(A.has(F)||A.has(X))U(X,!0);else{let R=$[h+1];if(R!==void 0&&!R.startsWith("-"))U(X,R),h++;else U(X,!0)}}}else if(Y.startsWith("-")&&Y.length>1){let Z=Y.slice(1);for(let E=0;E<Z.length;E++){let X=Z[E],F=z[X]||X;if(E===Z.length-1&&!A.has(F)&&!A.has(X)){let R=$[h+1];if(R!==void 0&&!R.startsWith("-"))U(X,R),h++;else U(X,!0)}else U(X,!0)}}else G._.push(Y)}return G}class hZ{rawName;description;name;names;isBoolean;required;config;negated;constructor($,J,G){if(this.rawName=$,this.description=J,this.config=Object.assign({},G),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=nz($).split(",").map((H)=>{let A=H.trim().replace(/^-{1,2}/,"");if(A.startsWith("no-"))this.negated=!0,A=A.replace(/^no-/,"");return pG(A)}).sort((H,A)=>H.length>A.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var XO=rz.argv,fW=`${rz.platform}-${rz.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,JZ=d5.argv,vW=`${d5.platform}-${d5.arch} node-${d5.version}`;class lz{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,J,G,H){this.rawName=$,this.description=J,this.config=G,this.cli=H,this.options=[],this.aliasNames=[],this.name=nz($);let A=nz($),z=A.indexOf(":");if(z>0)this.namespace=A.substring(0,z),this.name=A.substring(z+1);if(this.args=SW($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!G)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,J="-v, --version"){return this.versionNumber=$,this.option(J,"Display version number"),this}example($){return this.examples.push($),this}option($,J,G){let H=new hZ($,J,G);return this.options.push(H),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof sz}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){let J=pG($.split(".")[0]);return!!this.options.find((G)=>{return G.names.some((H)=>pG(H)===J)})}outputHelp(){let{name:$,commands:J}=this.cli,{versionNumber:G,options:H,helpCallback:A}=this.cli.globalCommand,z=[{body:`${$}${G?`/${G}`:""}`}];if(z.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let Z=$Z(J.map((C)=>C.rawName)),E=new Map,X=[];for(let C of J)if(C.namespace){if(!E.has(C.namespace))E.set(C.namespace,[]);E.get(C.namespace).push(C)}else X.push(C);let F="";if(X.sort((C,W)=>C.rawName<W.rawName?-1:C.rawName>W.rawName?1:0),X.length>0)F+=X.map((C)=>{return` ${pz(C.rawName,Z.length)} ${C.description}`}).join(`
491
- `);let R=Array.from(E.keys()).sort();for(let C of R){let W=E.get(C);if(F.length>0)F+=`
492
-
493
- `;F+=` ${C}:
494
- `,F+=W.map((Q)=>{return` ${pz(Q.rawName,Z.length-2)} ${Q.description}`}).join(`
495
- `)}z.push({title:"Commands",body:F}),z.push({body:`Run \`${$} <command> --help\` for command details.`})}let h=new Set(this.options.flatMap((Z)=>Z.names)),Y=this.isGlobalCommand?H:[...this.options,...(H||[]).filter((Z)=>!Z.names.some((E)=>h.has(E)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)Y=Y.filter((Z)=>Z.name!=="version");if(Y.length>0){let Z=$Z(Y.map((E)=>E.rawName));z.push({title:"Options",body:Y.map((E)=>{return` ${pz(E.rawName,Z.length)} ${E.description} ${E.config.default===void 0?"":`(default: ${E.config.default})`}`}).join(`
496
- `)})}if(this.examples.length>0)z.push({title:"Examples",body:this.examples.map((Z)=>{if(typeof Z==="function")return Z($);return Z}).join(`
497
- `)});if(A)z=A(z)||z;console.log(z.map((Z)=>{return Z.title?`${Z.title}:
498
- ${Z.body}`:Z.body}).join(`
499
-
500
- `))}outputVersion(){let{name:$}=this.cli,{versionNumber:J}=this.cli.globalCommand;if(J)console.log(`${$}/${J} ${typeof Bun<"u"?fW:vW}`)}get usageLine(){return`$ ${this.cli.name} ${this.usageText||this.rawName}`}checkRequiredArgs(){let $=this.args.filter((J)=>J.required).length;if(this.cli.args.length<$){let G=this.args.filter((A)=>A.required).slice(this.cli.args.length),H=G.map((A)=>`<${A.value}>`).join(" ");throw new iG(`Missing required argument${G.length>1?"s":""}: ${H}
501
-
502
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:$,globalCommand:J}=this.cli;if(!this.config.allowUnknownOptions){for(let G of Object.keys($))if(G!=="--"&&!this.hasOption(G)&&!J.hasOption(G)){let A=[...J.options,...this.options].flatMap((Z)=>Z.names),z=pG(G.split(".")[0]),U=G.length>1?`--${G}`:`-${G}`,h=YZ(z,A),Y=`Unknown option \`${U}\``;if(h.length>0)Y+=`
503
-
504
- Did you mean one of these?`,h.forEach((Z)=>{let E=Z.length>1?`--${Z}`:`-${Z}`;Y+=`
505
- \u2022 ${E}`});throw Y+=`
506
-
507
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new iG(Y,this.usageLine)}}}checkOptionValue(){let{options:$,globalCommand:J}=this.cli,G=[...J.options,...this.options];for(let H of G){let A=$[H.name.split(".")[0]];if(H.required){let z=G.some((U)=>U.negated&&U.names.includes(H.name));if(A===!0||A===!1&&!z)throw new iG(`Option \`${H.rawName}\` requires a value.
508
-
509
- Example: ${this.cli.name} ${this.rawName} ${H.rawName} <value>`,this.usageLine)}}}}class sz extends lz{constructor($){super("@@global@@","",{},$)}}var gW=lz,K1={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var cG={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function bW(){return!0}function mW(){let $={};$.supportsColor=bW();function J(H,A=[]){let z=H===""?[]:[...A,H],U=function(Y){if(!$.supportsColor)return Y;let Z="",E="";for(let X of z)if(X in cG&&cG[X]in K1){let F=cG[X];Z+=K1[F][0],E=K1[F][1]+E}else if(X in K1)Z+=K1[X][0],E=K1[X][1]+E;return Z+Y+E},h=[...Object.keys(K1),...Object.keys(cG)];for(let Y of h)if(!(Y in U))Object.defineProperty(U,Y,{get(){return J(Y,z)}});return U}let G=[...Object.keys(K1),...Object.keys(cG)];for(let H of G)if(!(H in $))Object.defineProperty($,H,{get(){return J(H)}});return $}var dG=mW();class oz extends IW{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new sz(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let J=async(G)=>{if(console.log(`
510
-
511
- Received ${G}, cleaning up...`),$)try{await $()}catch(H){console.error("Error during cleanup:",H)}M1.exit(0)};return M1.on("SIGINT",()=>J("SIGINT")),M1.on("SIGTERM",()=>J("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,J,G){if(!G)G={};let H=new gW($,J||"",G,this);return H.globalCommand=this.globalCommand,this.commands.push(H),H}option($,J,G){return this.globalCommand.option($,J,G),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,J="-v, --version"){return this.globalCommand.version($,J),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:J},G,H){if(this.args=$,this.options=J,G)this.matchedCommand=G;if(H)this.matchedCommandName=H;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(dG.red(`
512
- \u2717 Command "${$}" not found.
513
- `)),this.enableDidYouMean){let J=[];for(let H of this.commands){if(H.displayName)J.push(H.displayName);if(H.aliasNames)J.push(...H.aliasNames)}let G=YZ($,J);if(G.length>0)console.log(dG.yellow("Did you mean one of these?")),G.forEach((H)=>console.log(` ${dG.dim("\u2022")} ${this.name} ${H}`)),console.log("")}console.log(dG.dim("Run"),`${this.name} --help`,dG.dim("to see all available commands")),M1.exit(1)}async parse($=JZ,J={}){let{run:G=!0,exitOnError:H=!1}=J;if(H)try{return await this.parse($,{run:G})}catch(Y){throw this.handleUsageError(Y),Y}if(this.rawArgs=$,!this.name)this.name=$[1]?TW($[1]):"cli";let A=!0,z=$.slice(2),U=z[0];if(U&&!U.startsWith("-")){for(let Y of this.commands)if(Y.isMatched(U)){let Z=this.mri(z,Y);A=!1;let E={...Z,args:Z.args.slice(1)};this.setParsedInfo(E,Y,U),this.emit(`command:${U}`,Y);break}if(A){let Y=z[1];if(Y&&!Y.startsWith("-")){let Z=`${U}:${Y}`;for(let E of this.commands)if(E.isMatched(Z)){let X=this.mri(z,E);A=!1;let F={...X,args:X.args.slice(2)};this.setParsedInfo(F,E,Z),this.emit(`command:${Z}`,E);break}}}}if(A){for(let Y of this.commands)if(Y.name===""){A=!1;let Z=this.mri(z,Y);this.setParsedInfo(Z,Y),this.emit("command:!",Y);break}}if(A){let Y=this.mri($.slice(2));this.setParsedInfo(Y)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),G=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),G=!1,this.unsetMatchedCommand();let h={args:this.args,options:this.options};if(G)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return h}mri($,J){let G=[...this.globalCommand.options,...J?J.options:[]],H=_W(G),A=[],z=$.indexOf("--");if(z>-1)A=$.slice(z+1),$=$.slice(0,z);let U=xW($,H),h={_:U._};for(let F of Object.keys(U))if(F!=="_")h[pG(F)]=U[F];let Y=h._,Z={"--":A},E=J&&J.config.ignoreOptionDefaultValue?J.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,X=Object.create(null);for(let F of G){if(!E&&F.config.default!==void 0)for(let R of F.names)Z[R]=F.config.default;if(Array.isArray(F.config.type)){if(X[F.name]===void 0)X[F.name]={shouldTransform:!0,transformFunction:F.config.type[0]}}}for(let F of Object.keys(h))if(F!=="_"){let R=F.split(".");PW(Z,R,h[F]),NW(Z,X)}return{args:Y,options:Z}}async run($=JZ){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!kW($)||$.isUsageError===!1)return;let J=$.message||"command-line error",G=this.name?`${this.name}: `:"",H=/--help/.test(J)?"":$.usage?`
514
- Usage: ${$.usage}`:`
515
- Run \`${this.name??"cli"} --help\` for usage.`;M1.stderr.write(`${G}${J}${H}
516
- `),M1.exit($.exitCode??2)}async runMatchedCommand(){let{args:$,options:J,matchedCommand:G}=this;if(!G||!G.commandAction)return;G.checkUnknownOptions(),G.checkOptionValue(),G.checkRequiredArgs();let H=[];G.args.forEach((h,Y)=>{if(h.variadic)H.push($.slice(Y));else H.push($[Y])}),H.push(J);let A={command:G,args:H,options:J};for(let h of G.beforeHooks)await h(A);let z,U=async()=>{let h=G.commandAction.apply(this,H);if(h instanceof Promise)z=await h;else z=h;return z};if(G.middleware.length>0){let h=0,Y=async()=>{if(h<G.middleware.length){let Z=G.middleware[h++];await Z({...A,next:Y})}else await U()};await Y()}else await U();for(let h of G.afterHooks)await h(A);return z}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return M1.removeAllListeners("SIGINT"),M1.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class ZZ{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let J=this.cache.get($);if(!J){this.misses++;return}if(Date.now()-J.timestamp>J.ttl){this.cache.delete($),this.misses++;return}return this.hits++,J.value}set($,J,G=5000){if(!this.enabled)return;this.cache.set($,{value:J,timestamp:Date.now(),ttl:G})}has($){if(!this.enabled)return!1;let J=this.cache.get($);if(!J)return!1;if(Date.now()-J.timestamp>J.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[J,G]of this.cache.entries())if($-G.timestamp>G.ttl)this.cache.delete(J)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var WO=new ZZ;function cW(){if("FORCE_COLOR"in uG.env)return uG.env.FORCE_COLOR!=="0";if("NO_COLOR"in uG.env||uG.env.TERM==="dumb")return!1;if(uG.platform==="win32")return!0;return GZ.isatty(1)&&GZ.isatty(2)}var EZ=cW();function x0($,J){if(!EZ)return(G)=>G;return(G)=>$+G+J}var dW=x0("\x1B[0m","\x1B[0m"),uW=x0("\x1B[31m","\x1B[39m"),pW=x0("\x1B[32m","\x1B[39m"),iW=x0("\x1B[33m","\x1B[39m"),nW=x0("\x1B[34m","\x1B[39m"),rW=x0("\x1B[35m","\x1B[39m"),lW=x0("\x1B[36m","\x1B[39m"),sW=x0("\x1B[37m","\x1B[39m"),oW=x0("\x1B[90m","\x1B[39m"),tW=x0("\x1B[1m","\x1B[22m"),aW=x0("\x1B[3m","\x1B[23m"),eW=x0("\x1B[4m","\x1B[24m"),$4=x0("\x1B[2m","\x1B[22m"),J4=x0("\x1B[7m","\x1B[27m"),G4=x0("\x1B[8m","\x1B[28m"),H4=x0("\x1B[9m","\x1B[29m"),A4=x0("\x1B[41m","\x1B[49m"),z4=x0("\x1B[42m","\x1B[49m"),U4=x0("\x1B[43m","\x1B[49m"),Y4=x0("\x1B[44m","\x1B[49m"),h4=x0("\x1B[45m","\x1B[49m"),Z4=x0("\x1B[46m","\x1B[49m"),E4=x0("\x1B[47m","\x1B[49m"),X4=EZ,j4={reset:dW,red:uW,green:pW,yellow:iW,blue:nW,magenta:rW,cyan:lW,white:sW,gray:oW,bold:tW,italic:aW,underline:eW,dim:$4,inverse:J4,hidden:G4,strikethrough:H4,bgRed:A4,bgGreen:z4,bgYellow:U4,bgBlue:Y4,bgMagenta:h4,bgCyan:Z4,bgWhite:E4,isColorSupported:X4},u5=j4,F4=["up","down","left","right","space","enter","cancel"],p5={actions:new Set(F4),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function XZ($,J){if(typeof $==="string")return p5.aliases.get($)===J;for(let G of $){if(G===void 0)continue;if(XZ(G,J))return!0}return!1}function L4($,J){if($===J)return[];let G=$.split(`
517
- `),H=J.split(`
518
- `),A=[];for(let z=0;z<Math.max(G.length,H.length);z++)if(G[z]!==H[z])A.push(z);return A}var QO=W4.platform.startsWith("win"),HZ=Symbol("clapp:cancel");function m5($,J){let G=$;if(G.isTTY)G.setRawMode(J)}function Q4($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function V4($){return Q4($).length}function zZ($,J,G){if(!J||J<1)return $;let H=G?.hard??!1,A=G?.trim??!0,z=$.split(`
519
- `),U=[];for(let h of z){if(V4(h)<=J){U.push(A?h.trimEnd():h);continue}if(H){let Y="",Z=0,E=0;while(E<h.length){let X=h.slice(E).match(/^\x1b\[[0-9;]*m/);if(X){Y+=X[0],E+=X[0].length;continue}if(Z>=J)U.push(A?Y.trimEnd():Y),Y="",Z=0;Y+=h[E],Z++,E++}if(Y)U.push(A?Y.trimEnd():Y)}else U.push(A?h.trimEnd():h)}return U.join(`
520
- `)}class tz{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,J=!0){let{input:G=w4,output:H=R4,render:A,signal:z,...U}=$;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=A.bind(this),this._track=J,this._abortSignal=z,this.input=G,this.output=H}unsubscribe(){this._subscribers.clear()}setSubscriber($,J){let G=this._subscribers.get($)??[];G.push(J),this._subscribers.set($,G)}on($,J){return this.setSubscriber($,{cb:J}),this}once($,J){return this.setSubscriber($,{cb:J,once:!0}),this}emit($,...J){let G=this._subscribers.get($)??[],H=[];for(let A of G)if(A.cb(...J),A.once)H.push(()=>G.splice(G.indexOf(A),1));for(let A of H)A();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(HZ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=D4.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),m5(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(U1.show),this.output.off("resize",this.render),m5(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(U1.show),this.output.off("resize",this.render),m5(this.input,!1),$(HZ)})})}_isActionKey($,J){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,J){if(this.userInput=$??"",this.emit("userInput",this.userInput),J&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,J){if(this._track&&J.name!=="return"){if(J.name&&this._isActionKey($,J))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let G=J.name==="tab"||J.name==="escape"||J.name==="backspace"||J.name==="delete"||J.name==="enter"||J.name==="return"||J.name&&["up","down","left","right"].includes(J.name);if($&&!G&&$.length===1&&$>=" ")this._manualLine+=$;else if(J.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let H=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(H)}if(this.state==="error")this.state="active",this.error="";if(J?.name){if(!this._track&&p5.aliases.has(J.name))this.emit("cursor",p5.aliases.get(J.name));if(p5.actions.has(J.name))this.emit("cursor",J.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let G=this.opts.validate(this.value);if(G)this.error=G instanceof Error?G.message:G,this.state="error"}if(this.state!=="error")this.state="submit"}if(XZ([$,J?.name,J?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
521
- `),m5(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=zZ(this._prevFrame,AZ.stdout.columns,{hard:!0,trim:!1}).split(`
522
- `).length-1;this.output.write(U1.move(-999,$*-1))}render(){let $=zZ(this._render(this)??"",AZ.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(U1.hide);else{let J=L4(this._prevFrame,$);if(this.restoreCursor(),J&&J?.length===1){let G=J[0];this.output.write(U1.move(0,G)),this.output.write(iz.lines(1));let H=$.split(`
523
- `);this.output.write(H[G]),this._prevFrame=$,this.output.write(U1.move(0,H.length-G-1));return}if(J&&J?.length>1){let G=J[0];this.output.write(U1.move(0,G)),this.output.write(iz.down());let A=$.split(`
524
- `).slice(G);this.output.write(A.join(`
525
- `)),this._prevFrame=$;return}this.output.write(iz.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function O4($,J){if($===void 0)return 0;if(J.length===0)return 0;let H=J.findIndex((A)=>A.value===$);return H!==-1?H:0}function M4($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function K4($,J){if(!J)return;if($)return J;return J[0]}class B4 extends tz{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#G="";#H;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return u5.inverse(u5.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let $=this.userInput.slice(0,this._cursor),[J,...G]=this.userInput.slice(this._cursor);return`${$}${u5.inverse(J)}${G.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#H=$.filter??M4;let G;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)G=$.initialValue;else G=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)G=[this.options[0].value];if(G)for(let H of G){let A=J.findIndex((z)=>z.value===H);if(A!==-1)this.toggleSelected(H),this.#$=A}this.focusedValue=this.options[this.#$]?.value,this.on("key",(H,A)=>this.#A(H,A)),this.on("userInput",(H)=>this.#z(H))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#A($,J){let G=J.name==="up",H=J.name==="down",A=J.name==="return";if(G||H){if(this.#$=Math.max(0,Math.min(this.#$+(G?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(A)this.value=K4(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#z($){if($!==this.#G){this.#G=$;let J=this.options;if($)this.filteredOptions=J.filter((G)=>this.#H($,G));else this.filteredOptions=[...J];if(this.#$=O4(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class C4 extends tz{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),G=this.value;if(G===void 0)return!1;return J.every((H)=>G.includes(H.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=String($.value),G=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((H)=>G.findIndex((A)=>A.value===H)===-1);else this.value=[...this.value,...G.map((H)=>H.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((G)=>G!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([G,H])=>[{value:G,group:!0,label:G},...H.map((A)=>({...A,group:G}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:G})=>G===$.cursorAt),this.#$?0:1),this.on("cursor",(G)=>{switch(G){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let H=this.options[this.cursor]?.group===!0;if(!this.#$&&H)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let H=this.options[this.cursor]?.group===!0;if(!this.#$&&H)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var I4=qW();var q0=($,J)=>I4?$:J,MO=q0("\u25C6","*"),KO=q0("\u25A0","x"),BO=q0("\u25B2","x"),CO=q0("\u25C7","o"),IO=q0("\u250C","T"),S4=q0("\u2502","|"),SO=q0("\u2514","\u2014"),_O=q0("\u25CF",">"),PO=q0("\u25CB"," "),NO=q0("\u25FB","[\u2022]"),TO=q0("\u25FC","[+]"),kO=q0("\u25FB","[ ]"),qO=q0("\u25AA","\u2022"),yO=q0("\u2500","-"),xO=q0("\u256E","+"),fO=q0("\u251C","+"),vO=q0("\u256F","+"),gO=q0("\u25CF","\u2022"),bO=q0("\u25C6","*"),mO=q0("\u25B2","!"),cO=q0("\u25A0","x");var dO={light:q0("\u2500","-"),heavy:q0("\u2501","="),block:q0("\u2588","#")};function _4(){return`${u5.gray(S4)} `}var uO=_4();var az="0.2.52";l9();nA();aA();$9();A9();U9();Y9();h9();j9();V9();FG();N9();k9();y9();f9();g9();b9();d9();n9();var U0=new oz("query-builder");U0.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async($,J)=>{await W9($,J)});U0.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async($)=>{let J=$?.table,G=J?Array.isArray(J)?J:[J]:void 0,H=await YG({tables:G});console.log(`import { defineModel } from 'bun-query-builder'
526
-
527
- ${H.map((A)=>A.source).join(`
528
- `)}`)});U0.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async($,J,G)=>{await u9($,J,G)});U0.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await v9()});U0.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async($)=>{try{await r9($)}catch{let J=await import("process");J.default.exitCode=1}});U0.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async($,J)=>{await p9($,J)});U0.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async($,J)=>{await E9($,J)});U0.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate ./app/Models --dialect postgres").action(async($,J)=>{try{await x1($,{dialect:J.dialect,state:J.state,apply:J.apply,full:J.full}),await jG()}catch(G){console.error("-- Migration failed:",G);let H=await import("process");H.default.exitCode=1}});U0.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async($)=>{await Z9($)});U0.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async($,J)=>{try{await X5($,{verbose:J.verbose,json:J.json})}catch(G){console.error("-- Explain all failed:",G);let H=await import("process");H.default.exitCode=1}});U0.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async($)=>{try{await j5({dir:$.dir,format:$.format,output:$.output,verbose:$.verbose})}catch(J){console.error("-- Diagram generation failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async($,J)=>{try{console.log("-- Resetting database..."),await WG($,{dialect:J.dialect,state:J.state}),console.log("-- Generating fresh migrations..."),await x1($,{dialect:J.dialect,state:J.state,full:J.full}),console.log("-- Executing migrations..."),await jG()}catch(G){console.error("-- Migrate fresh failed:",G);let H=await import("process");H.default.exitCode=1}});U0.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async($,J)=>{try{await WG($,{dialect:J.dialect,state:J.state})}catch(G){console.error("-- Reset failed:",G);let H=await import("process");H.default.exitCode=1}});U0.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async($)=>{try{if($.class)await L5($.class,{verbose:$.verbose});else await RG({seedersDir:$.dir,verbose:$.verbose})}catch(J){console.error("-- Seeding failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async($)=>{try{if($.class)await L5($.class,{verbose:$.verbose});else await RG({seedersDir:$.dir,verbose:$.verbose})}catch(J){console.error("-- Seeding failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async($)=>{try{await m9($)}catch(J){console.error("-- Failed to create seeder:",J);let G=await import("process");G.default.exitCode=1}});U0.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async($)=>{try{await c9({modelsDir:$.models,seedersDir:$.seeders,verbose:$.verbose})}catch(J){console.error("-- Database fresh failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async($,J)=>{try{await Q9($,{table:J.table,dir:J.dir,timestamps:J.timestamps})}catch(G){console.error("-- Failed to create model:",G);let H=await import("process");H.default.exitCode=1}});U0.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async($,J)=>{try{await E5($,{dir:J.dir,json:J.json,verbose:J.verbose})}catch(G){console.error("-- Failed to show model:",G);let H=await import("process");H.default.exitCode=1}});U0.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await Z5()}catch($){console.error("-- Failed to get migration status:",$);let J=await import("process");J.default.exitCode=1}});U0.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await q9()}catch($){console.error("-- Failed to list migrations:",$);let J=await import("process");J.default.exitCode=1}});U0.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async($)=>{try{await T9({steps:Number($.steps),reverseSchema:$.reverseSchema,deleteFiles:Boolean($.deleteFiles)})}catch(J){console.error("-- Rollback failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async($,J)=>{try{await P9($,{dialect:J?.dialect,state:J?.state,apply:J?.apply,full:J?.full})}catch(G){console.error("-- Generate migration failed:",G);let H=await import("process");H.default.exitCode=1}});U0.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await sH()}catch($){console.error("-- Failed to get database info:",$);let J=await import("process");J.default.exitCode=1}});U0.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await z9()}catch($){console.error("-- Failed to get database stats:",$);let J=await import("process");J.default.exitCode=1}});U0.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async($)=>{try{await tH({dialect:$.dialect,force:$.force,verbose:$.verbose})}catch(J){console.error("-- Wipe failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async($)=>{try{await oH({dialect:$.dialect,aggressive:$.aggressive,tables:$.tables?$.tables.split(","):void 0,verbose:$.verbose})}catch(J){console.error("-- Optimize failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await lH()}catch($){console.error("-- Console failed:",$);let J=await import("process");J.default.exitCode=1}});U0.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await eA()}catch($){console.error("-- Tinker failed:",$);let J=await import("process");J.default.exitCode=1}});U0.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async($,J)=>{try{await aH($,{verbose:J.verbose})}catch(G){console.error("-- Failed to inspect table:",G);let H=await import("process");H.default.exitCode=1}});U0.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async($,J)=>{try{await X9($,{verbose:J.verbose})}catch(G){console.error("-- Failed to get table info:",G);let H=await import("process");H.default.exitCode=1}});U0.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await sA()}catch($){console.error("-- Failed to clear cache:",$);let J=await import("process");J.default.exitCode=1}});U0.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await oA()}catch($){console.error("-- Failed to get cache stats:",$);let J=await import("process");J.default.exitCode=1}});U0.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async($)=>{try{await tA({size:$.size})}catch(J){console.error("-- Failed to configure cache:",J);let G=await import("process");G.default.exitCode=1}});U0.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async($)=>{try{await iA({operations:$.operations,iterations:$.iterations?Number($.iterations):void 0})}catch(J){console.error("-- Benchmark failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async($)=>{try{await w5($)}catch(J){console.error("-- Validation failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async($)=>{try{await i9($)}catch(J){console.error("-- Check failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async($,J)=>{try{await J9($,{format:J.format,output:J.output,limit:J.limit?Number(J.limit):void 0})}catch(G){console.error("-- Export failed:",G);let H=await import("process");H.default.exitCode=1}});U0.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async($,J,G)=>{try{await G9($,J,{format:G.format,truncate:G.truncate})}catch(H){console.error("-- Import failed:",H);let A=await import("process");A.default.exitCode=1}});U0.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async($)=>{try{await H9({tables:$.tables,output:$.output})}catch(J){console.error("-- Dump failed:",J);let G=await import("process");G.default.exitCode=1}});U0.command("version","Show the version of the CLI").action(()=>{console.log(az)});U0.version(az);U0.help();U0.parse();
6
+ ${this.stack}`;return this.message}}function q4(z){if(z instanceof I)return!0;return!!z&&typeof z==="object"&&z.name==="ClappError"&&typeof z.message==="string"}function J4(){let{env:z}=z6,{TERM:q,TERM_PROGRAM:J}=z;if(z6.platform!=="win32")return q!=="linux";return Boolean(z.WT_SESSION)||Boolean(z.TERMINUS_SUBLIME)||z.ConEmuTask==="{cmd::Cmder}"||J==="Terminus-Sublime"||J==="vscode"||q==="xterm-256color"||q==="alacritty"||q==="rxvt-unicode"||q==="rxvt-unicode-256color"||z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var y="\x1B",L=`${y}[`;var P={to(z,q){if(!q)return`${L}${z+1}G`;return`${L}${q+1};${z+1}H`},move(z,q){let J="";if(z<0)J+=`${L}${-z}D`;else if(z>0)J+=`${L}${z}C`;if(q<0)J+=`${L}${-q}A`;else if(q>0)J+=`${L}${q}B`;return J},up:(z=1)=>`${L}${z}A`,down:(z=1)=>`${L}${z}B`,forward:(z=1)=>`${L}${z}C`,backward:(z=1)=>`${L}${z}D`,nextLine:(z=1)=>`${L}E`.repeat(z),prevLine:(z=1)=>`${L}F`.repeat(z),left:`${L}G`,hide:`${L}?25l`,show:`${L}?25h`,save:`${y}7`,restore:`${y}8`};var f={screen:`${L}2J`,up:(z=1)=>`${L}1J`.repeat(z),down:(z=1)=>`${L}J`.repeat(z),line:`${L}2K`,lineEnd:`${L}K`,lineStart:`${L}1K`,lines(z){let q="";for(let J=0;J<z;J++)q+=this.line+(J<z-1?P.up():"");if(z)q+=P.left;return q}},Xz={screen:`${y}c`};function Z4(z,q){let J=[];for(let Z=0;Z<=q.length;Z++)J[Z]=[Z];for(let Z=0;Z<=z.length;Z++)J[0][Z]=Z;for(let Z=1;Z<=q.length;Z++)for(let $=1;$<=z.length;$++)if(q.charAt(Z-1)===z.charAt($-1))J[Z][$]=J[Z-1][$-1];else J[Z][$]=Math.min(J[Z-1][$-1]+1,J[Z][$-1]+1,J[Z-1][$]+1);return J[q.length][z.length]}function X6(z,q,J=2,Z=3){return q.map(($)=>({cmd:$,distance:Z4(z,$)})).filter(({distance:$})=>$<=J).sort(($,Y)=>$.distance-Y.distance).slice(0,Z).map(({cmd:$})=>$)}function $4(z,q={}){let J={_:[]},Z=q.alias||{},$=new Set(q.boolean||[]),Y={};for(let X of Object.keys(Z))for(let Q of Z[X])Y[Q]=X;for(let X of $)if(Z[X])for(let Q of Z[X])$.add(Q);function F(X,Q){let j=Y[X]||X;if(J[j]=Q,Z[j])for(let U of Z[j])J[U]=Q;if(Y[X]&&Z[Y[X]])for(let U of Z[Y[X]])J[U]=Q;J[X]=Q}for(let X=0;X<z.length;X++){let Q=z[X];if(Q==="--"){J._.push(...z.slice(X+1));break}if(Q.startsWith("--")){let j=Q.indexOf("=");if(j!==-1){let U=C(Q.slice(2,j)),H=Q.slice(j+1);F(U,H)}else{let U=Q.slice(2);if(U.startsWith("no-")){let w=C(U.slice(3));F(w,!1);continue}let H=C(U),V=Y[H]||H;if($.has(V)||$.has(H))F(H,!0);else{let w=z[X+1];if(w!==void 0&&!w.startsWith("-"))F(H,w),X++;else F(H,!0)}}}else if(Q.startsWith("-")&&Q.length>1){let j=Q.slice(1);for(let U=0;U<j.length;U++){let H=j[U],V=Y[H]||H;if(U===j.length-1&&!$.has(V)&&!$.has(H)){let w=z[X+1];if(w!==void 0&&!w.startsWith("-"))F(H,w),X++;else F(H,!0)}else F(H,!0)}}else J._.push(Q)}return J}class U6{rawName;description;name;names;isBoolean;required;config;negated;constructor(z,q,J){if(this.rawName=z,this.description=q,this.config=Object.assign({},J),z=z.replace(/\.\*/g,""),this.negated=!1,this.names=m(z).split(",").map((Z)=>{let $=Z.trim().replace(/^-{1,2}/,"");if($.startsWith("no-"))this.negated=!0,$=$.replace(/^no-/,"");return b($)}).sort((Z,$)=>Z.length>$.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(z.includes("<"))this.required=!0;else if(z.includes("["))this.required=!1;else this.isBoolean=!0}}var Fz=d.argv,Q4=`${d.platform}-${d.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,J6=k.argv,Y4=`${k.platform}-${k.arch} node-${k.version}`;class u{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(z,q,J,Z){this.rawName=z,this.description=q,this.config=J,this.cli=Z,this.options=[],this.aliasNames=[],this.name=m(z);let $=m(z),Y=$.indexOf(":");if(Y>0)this.namespace=$.substring(0,Y),this.name=$.substring(Y+1);if(this.args=s6(z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!J)this.config={}}usage(z){return this.usageText=z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(z,q="-v, --version"){return this.versionNumber=z,this.option(q,"Display version number"),this}example(z){return this.examples.push(z),this}option(z,q,J){let Z=new U6(z,q,J);return this.options.push(Z),this}alias(z){return this.aliasNames.push(z),this}action(z){return this.commandAction=z,this}before(z){return this.beforeHooks.push(z),this}after(z){return this.afterHooks.push(z),this}use(z){return this.middleware.push(z),this}isMatched(z){if(this.aliasNames.includes(z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===z;return this.name===z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof i}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(z){let q=b(z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Z)=>b(Z)===q)})}outputHelp(){let{name:z,commands:q}=this.cli,{versionNumber:J,options:Z,helpCallback:$}=this.cli.globalCommand,Y=[{body:`${z}${J?`/${J}`:""}`}];if(Y.push({title:"Usage",body:` $ ${z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&q.length>0){let j=q6(q.map((M)=>M.rawName)),U=new Map,H=[];for(let M of q)if(M.namespace){if(!U.has(M.namespace))U.set(M.namespace,[]);U.get(M.namespace).push(M)}else H.push(M);let V="";if(H.sort((M,A)=>M.rawName<A.rawName?-1:M.rawName>A.rawName?1:0),H.length>0)V+=H.map((M)=>{return` ${_(M.rawName,j.length)} ${M.description}`}).join(`
7
+ `);let w=Array.from(U.keys()).sort();for(let M of w){let A=U.get(M);if(V.length>0)V+=`
8
+
9
+ `;V+=` ${M}:
10
+ `,V+=A.map((o)=>{return` ${_(o.rawName,j.length-2)} ${o.description}`}).join(`
11
+ `)}Y.push({title:"Commands",body:V}),Y.push({body:`Run \`${z} <command> --help\` for command details.`})}let X=new Set(this.options.flatMap((j)=>j.names)),Q=this.isGlobalCommand?Z:[...this.options,...(Z||[]).filter((j)=>!j.names.some((U)=>X.has(U)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)Q=Q.filter((j)=>j.name!=="version");if(Q.length>0){let j=q6(Q.map((U)=>U.rawName));Y.push({title:"Options",body:Q.map((U)=>{return` ${_(U.rawName,j.length)} ${U.description} ${U.config.default===void 0?"":`(default: ${U.config.default})`}`}).join(`
12
+ `)})}if(this.examples.length>0)Y.push({title:"Examples",body:this.examples.map((j)=>{if(typeof j==="function")return j(z);return j}).join(`
13
+ `)});if($)Y=$(Y)||Y;console.log(Y.map((j)=>{return j.title?`${j.title}:
14
+ ${j.body}`:j.body}).join(`
15
+
16
+ `))}outputVersion(){let{name:z}=this.cli,{versionNumber:q}=this.cli.globalCommand;if(q)console.log(`${z}/${q} ${typeof Bun<"u"?Q4:Y4}`)}get usageLine(){return`$ ${this.cli.name} ${this.usageText||this.rawName}`}checkRequiredArgs(){let z=this.args.filter((q)=>q.required).length;if(this.cli.args.length<z){let J=this.args.filter(($)=>$.required).slice(this.cli.args.length),Z=J.map(($)=>`<${$.value}>`).join(" ");throw new I(`Missing required argument${J.length>1?"s":""}: ${Z}
17
+
18
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:z,globalCommand:q}=this.cli;if(!this.config.allowUnknownOptions){for(let J of Object.keys(z))if(J!=="--"&&!this.hasOption(J)&&!q.hasOption(J)){let $=[...q.options,...this.options].flatMap((j)=>j.names),Y=b(J.split(".")[0]),F=J.length>1?`--${J}`:`-${J}`,X=X6(Y,$),Q=`Unknown option \`${F}\``;if(X.length>0)Q+=`
19
+
20
+ Did you mean one of these?`,X.forEach((j)=>{let U=j.length>1?`--${j}`:`-${j}`;Q+=`
21
+ \u2022 ${U}`});throw Q+=`
22
+
23
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new I(Q,this.usageLine)}}}checkOptionValue(){let{options:z,globalCommand:q}=this.cli,J=[...q.options,...this.options];for(let Z of J){let $=z[Z.name.split(".")[0]];if(Z.required){let Y=J.some((F)=>F.negated&&F.names.includes(Z.name));if($===!0||$===!1&&!Y)throw new I(`Option \`${Z.rawName}\` requires a value.
24
+
25
+ Example: ${this.cli.name} ${this.rawName} ${Z.rawName} <value>`,this.usageLine)}}}}class i extends u{constructor(z){super("@@global@@","",{},z)}}var j4=u,O={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var x={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function X4(){return!0}function U4(){let z={};z.supportsColor=X4();function q(Z,$=[]){let Y=Z===""?[]:[...$,Z],F=function(Q){if(!z.supportsColor)return Q;let j="",U="";for(let H of Y)if(H in x&&x[H]in O){let V=x[H];j+=O[V][0],U=O[V][1]+U}else if(H in O)j+=O[H][0],U=O[H][1]+U;return j+Q+U},X=[...Object.keys(O),...Object.keys(x)];for(let Q of X)if(!(Q in F))Object.defineProperty(F,Q,{get(){return q(Q,Y)}});return F}let J=[...Object.keys(O),...Object.keys(x)];for(let Z of J)if(!(Z in z))Object.defineProperty(z,Z,{get(){return q(Z)}});return z}var B=U4();class c extends a6{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(z=""){super();this.name=z,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new i(this),this.globalCommand.usage("<command> [options]")}handleSignals(z){if(this.signalHandlersSet)return this;let q=async(J)=>{if(console.log(`
26
+
27
+ Received ${J}, cleaning up...`),z)try{await z()}catch(Z){console.error("Error during cleanup:",Z)}N.exit(0)};return N.on("SIGINT",()=>q("SIGINT")),N.on("SIGTERM",()=>q("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(z=!0){return this.enableDidYouMean=z,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(z){return this.globalCommand.usage(z),this}command(z,q,J){if(!J)J={};let Z=new j4(z,q||"",J,this);return Z.globalCommand=this.globalCommand,this.commands.push(Z),Z}option(z,q,J){return this.globalCommand.option(z,q,J),this}help(z){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=z,this.showHelpOnExit=!0,this}version(z,q="-v, --version"){return this.globalCommand.version(z,q),this.showVersionOnExit=!0,this}example(z){return this.globalCommand.example(z),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:z,options:q},J,Z){if(this.args=z,this.options=q,J)this.matchedCommand=J;if(Z)this.matchedCommandName=Z;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(z){if(console.log(B.red(`
28
+ \u2717 Command "${z}" not found.
29
+ `)),this.enableDidYouMean){let q=[];for(let Z of this.commands){if(Z.displayName)q.push(Z.displayName);if(Z.aliasNames)q.push(...Z.aliasNames)}let J=X6(z,q);if(J.length>0)console.log(B.yellow("Did you mean one of these?")),J.forEach((Z)=>console.log(` ${B.dim("\u2022")} ${this.name} ${Z}`)),console.log("")}console.log(B.dim("Run"),`${this.name} --help`,B.dim("to see all available commands")),N.exit(1)}async parse(z=J6,q={}){let{run:J=!0,exitOnError:Z=!1}=q;if(Z)try{return await this.parse(z,{run:J})}catch(Q){throw this.handleUsageError(Q),Q}if(this.rawArgs=z,!this.name)this.name=z[1]?z4(z[1]):"cli";let $=!0,Y=z.slice(2),F=Y[0];if(F&&!F.startsWith("-")){for(let Q of this.commands)if(Q.isMatched(F)){let j=this.mri(Y,Q);$=!1;let U={...j,args:j.args.slice(1)};this.setParsedInfo(U,Q,F),this.emit(`command:${F}`,Q);break}if($){let Q=Y[1];if(Q&&!Q.startsWith("-")){let j=`${F}:${Q}`;for(let U of this.commands)if(U.isMatched(j)){let H=this.mri(Y,U);$=!1;let V={...H,args:H.args.slice(2)};this.setParsedInfo(V,U,j),this.emit(`command:${j}`,U);break}}}}if($){for(let Q of this.commands)if(Q.name===""){$=!1;let j=this.mri(Y,Q);this.setParsedInfo(j,Q),this.emit("command:!",Q);break}}if($){let Q=this.mri(z.slice(2));this.setParsedInfo(Q)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),J=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),J=!1,this.unsetMatchedCommand();let X={args:this.args,options:this.options};if(J)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return X}mri(z,q){let J=[...this.globalCommand.options,...q?q.options:[]],Z=t6(J),$=[],Y=z.indexOf("--");if(Y>-1)$=z.slice(Y+1),z=z.slice(0,Y);let F=$4(z,Z),X={_:F._};for(let V of Object.keys(F))if(V!=="_")X[b(V)]=F[V];let Q=X._,j={"--":$},U=q&&q.config.ignoreOptionDefaultValue?q.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,H=Object.create(null);for(let V of J){if(!U&&V.config.default!==void 0)for(let w of V.names)j[w]=V.config.default;if(Array.isArray(V.config.type)){if(H[V.name]===void 0)H[V.name]={shouldTransform:!0,transformFunction:V.config.type[0]}}}for(let V of Object.keys(X))if(V!=="_"){let w=V.split(".");o6(j,w,X[V]),e6(j,H)}return{args:Q,options:j}}async run(z=J6){return this.parse(z,{run:!0,exitOnError:!0})}handleUsageError(z){if(!q4(z)||z.isUsageError===!1)return;let q=z.message||"command-line error",J=this.name?`${this.name}: `:"",Z=/--help/.test(q)?"":z.usage?`
30
+ Usage: ${z.usage}`:`
31
+ Run \`${this.name??"cli"} --help\` for usage.`;N.stderr.write(`${J}${q}${Z}
32
+ `),N.exit(z.exitCode??2)}async runMatchedCommand(){let{args:z,options:q,matchedCommand:J}=this;if(!J||!J.commandAction)return;J.checkUnknownOptions(),J.checkOptionValue(),J.checkRequiredArgs();let Z=[];J.args.forEach((X,Q)=>{if(X.variadic)Z.push(z.slice(Q));else Z.push(z[Q])}),Z.push(q);let $={command:J,args:Z,options:q};for(let X of J.beforeHooks)await X($);let Y,F=async()=>{let X=J.commandAction.apply(this,Z);if(X instanceof Promise)Y=await X;else Y=X;return Y};if(J.middleware.length>0){let X=0,Q=async()=>{if(X<J.middleware.length){let j=J.middleware[X++];await j({...$,next:Q})}else await F()};await Q()}else await F();for(let X of J.afterHooks)await X($);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return N.removeAllListeners("SIGINT"),N.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class F6{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(z){if(!this.enabled){this.misses++;return}let q=this.cache.get(z);if(!q){this.misses++;return}if(Date.now()-q.timestamp>q.ttl){this.cache.delete(z),this.misses++;return}return this.hits++,q.value}set(z,q,J=5000){if(!this.enabled)return;this.cache.set(z,{value:q,timestamp:Date.now(),ttl:J})}has(z){if(!this.enabled)return!1;let q=this.cache.get(z);if(!q)return!1;if(Date.now()-q.timestamp>q.ttl)return this.cache.delete(z),!1;return!0}delete(z){this.cache.delete(z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let z=Date.now();for(let[q,J]of this.cache.entries())if(z-J.timestamp>J.ttl)this.cache.delete(q)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Hz=new F6;function F4(){if("FORCE_COLOR"in E.env)return E.env.FORCE_COLOR!=="0";if("NO_COLOR"in E.env||E.env.TERM==="dumb")return!1;if(E.platform==="win32")return!0;return Z6.isatty(1)&&Z6.isatty(2)}var G6=F4();function D(z,q){if(!G6)return(J)=>J;return(J)=>z+J+q}var G4=D("\x1B[0m","\x1B[0m"),H4=D("\x1B[31m","\x1B[39m"),K4=D("\x1B[32m","\x1B[39m"),V4=D("\x1B[33m","\x1B[39m"),W4=D("\x1B[34m","\x1B[39m"),D4=D("\x1B[35m","\x1B[39m"),L4=D("\x1B[36m","\x1B[39m"),M4=D("\x1B[37m","\x1B[39m"),w4=D("\x1B[90m","\x1B[39m"),P4=D("\x1B[1m","\x1B[22m"),N4=D("\x1B[3m","\x1B[23m"),O4=D("\x1B[4m","\x1B[24m"),T4=D("\x1B[2m","\x1B[22m"),x4=D("\x1B[7m","\x1B[27m"),B4=D("\x1B[8m","\x1B[28m"),E4=D("\x1B[9m","\x1B[29m"),b4=D("\x1B[41m","\x1B[49m"),I4=D("\x1B[42m","\x1B[49m"),A4=D("\x1B[43m","\x1B[49m"),R4=D("\x1B[44m","\x1B[49m"),C4=D("\x1B[45m","\x1B[49m"),k4=D("\x1B[46m","\x1B[49m"),h4=D("\x1B[47m","\x1B[49m"),v4=G6,y4={reset:G4,red:H4,green:K4,yellow:V4,blue:W4,magenta:D4,cyan:L4,white:M4,gray:w4,bold:P4,italic:N4,underline:O4,dim:T4,inverse:x4,hidden:B4,strikethrough:E4,bgRed:b4,bgGreen:I4,bgYellow:A4,bgBlue:R4,bgMagenta:C4,bgCyan:k4,bgWhite:h4,isColorSupported:v4},h=y4,g4=["up","down","left","right","space","enter","cancel"],v={actions:new Set(g4),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function H6(z,q){if(typeof z==="string")return v.aliases.get(z)===q;for(let J of z){if(J===void 0)continue;if(H6(J,q))return!0}return!1}function _4(z,q){if(z===q)return[];let J=z.split(`
33
+ `),Z=q.split(`
34
+ `),$=[];for(let Y=0;Y<Math.max(J.length,Z.length);Y++)if(J[Y]!==Z[Y])$.push(Y);return $}var Mz=S4.platform.startsWith("win"),$6=Symbol("clapp:cancel");function R(z,q){let J=z;if(J.isTTY)J.setRawMode(q)}function u4(z){return z.replace(/\x1b\[[0-9;]*m/g,"")}function i4(z){return u4(z).length}function Y6(z,q,J){if(!q||q<1)return z;let Z=J?.hard??!1,$=J?.trim??!0,Y=z.split(`
35
+ `),F=[];for(let X of Y){if(i4(X)<=q){F.push($?X.trimEnd():X);continue}if(Z){let Q="",j=0,U=0;while(U<X.length){let H=X.slice(U).match(/^\x1b\[[0-9;]*m/);if(H){Q+=H[0],U+=H[0].length;continue}if(j>=q)F.push($?Q.trimEnd():Q),Q="",j=0;Q+=X[U],j++,U++}if(Q)F.push($?Q.trimEnd():Q)}else F.push($?X.trimEnd():X)}return F.join(`
36
+ `)}class n{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(z,q=!0){let{input:J=f4,output:Z=m4,render:$,signal:Y,...F}=z;this.opts=F,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=$.bind(this),this._track=q,this._abortSignal=Y,this.input=J,this.output=Z}unsubscribe(){this._subscribers.clear()}setSubscriber(z,q){let J=this._subscribers.get(z)??[];J.push(q),this._subscribers.set(z,J)}on(z,q){return this.setSubscriber(z,{cb:q}),this}once(z,q){return this.setSubscriber(z,{cb:q,once:!0}),this}emit(z,...q){let J=this._subscribers.get(z)??[],Z=[];for(let $ of J)if($.cb(...q),$.once)Z.push(()=>J.splice(J.indexOf($),1));for(let $ of Z)$();return this}prompt(){return new Promise((z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),z($6);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=d4.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),R(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(P.show),this.output.off("resize",this.render),R(this.input,!1),z(this.value)}),this.once("cancel",()=>{this.output.write(P.show),this.output.off("resize",this.render),R(this.input,!1),z($6)})})}_isActionKey(z,q){return z==="\t"}_setValue(z){this.value=z,this.emit("value",this.value)}_setUserInput(z,q){if(this.userInput=z??"",this.emit("userInput",this.userInput),q&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(z,q){if(this._track&&q.name!=="return"){if(q.name&&this._isActionKey(z,q))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let J=q.name==="tab"||q.name==="escape"||q.name==="backspace"||q.name==="delete"||q.name==="enter"||q.name==="return"||q.name&&["up","down","left","right"].includes(q.name);if(z&&!J&&z.length===1&&z>=" ")this._manualLine+=z;else if(q.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Z=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Z)}if(this.state==="error")this.state="active",this.error="";if(q?.name){if(!this._track&&v.aliases.has(q.name))this.emit("cursor",v.aliases.get(q.name));if(v.actions.has(q.name))this.emit("cursor",q.name)}if(z&&(z.toLowerCase()==="y"||z.toLowerCase()==="n"))this.emit("confirm",z.toLowerCase()==="y");if(this.emit("key",z?.toLowerCase(),q),q?.name==="return"){if(this.opts.validate){let J=this.opts.validate(this.value);if(J)this.error=J instanceof Error?J.message:J,this.state="error"}if(this.state!=="error")this.state="submit"}if(H6([z,q?.name,q?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
37
+ `),R(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let z=Y6(this._prevFrame,Q6.stdout.columns,{hard:!0,trim:!1}).split(`
38
+ `).length-1;this.output.write(P.move(-999,z*-1))}render(){let z=Y6(this._render(this)??"",Q6.stdout.columns,{hard:!0,trim:!1});if(z===this._prevFrame)return;if(this.state==="initial")this.output.write(P.hide);else{let q=_4(this._prevFrame,z);if(this.restoreCursor(),q&&q?.length===1){let J=q[0];this.output.write(P.move(0,J)),this.output.write(f.lines(1));let Z=z.split(`
39
+ `);this.output.write(Z[J]),this._prevFrame=z,this.output.write(P.move(0,Z.length-J-1));return}if(q&&q?.length>1){let J=q[0];this.output.write(P.move(0,J)),this.output.write(f.down());let $=z.split(`
40
+ `).slice(J);this.output.write($.join(`
41
+ `)),this._prevFrame=z;return}this.output.write(f.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function c4(z,q){if(z===void 0)return 0;if(q.length===0)return 0;let Z=q.findIndex(($)=>$.value===z);return Z!==-1?Z:0}function n4(z,q){return(q.label??String(q.value)).toLowerCase().includes(z.toLowerCase())}function p4(z,q){if(!q)return;if(z)return q;return q[0]}class l4 extends n{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#J="";#Z;#q;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return h.inverse(h.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let z=this.userInput.slice(0,this._cursor),[q,...J]=this.userInput.slice(this._cursor);return`${z}${h.inverse(q)}${J.join("")}`}get options(){if(typeof this.#q==="function")return this.#q();return this.#q}constructor(z){super(z);this.#q=z.options;let q=this.options;this.filteredOptions=[...q],this.multiple=z.multiple===!0,this.#Z=z.filter??n4;let J;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)J=z.initialValue;else J=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Z of J){let $=q.findIndex((Y)=>Y.value===Z);if($!==-1)this.toggleSelected(Z),this.#z=$}this.focusedValue=this.options[this.#z]?.value,this.on("key",(Z,$)=>this.#$(Z,$)),this.on("userInput",(Z)=>this.#Q(Z))}_isActionKey(z,q){return z==="\t"||this.multiple&&this.isNavigating&&q.name==="space"&&z!==void 0&&z!==""}#$(z,q){let J=q.name==="up",Z=q.name==="down",$=q.name==="return";if(J||Z){if(this.#z=Math.max(0,Math.min(this.#z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if($)this.value=p4(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(q.name==="tab"||this.isNavigating&&q.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter((q)=>q!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#Q(z){if(z!==this.#J){this.#J=z;let q=this.options;if(z)this.filteredOptions=q.filter((J)=>this.#Z(z,J));else this.filteredOptions=[...q];if(this.#z=c4(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class r4 extends n{options;cursor=0;#z;getGroupItems(z){return this.options.filter((q)=>q.group===z)}isGroupSelected(z){let q=this.getGroupItems(z),J=this.value;if(J===void 0)return!1;return q.every((Z)=>J.includes(Z.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let q=String(z.value),J=this.getGroupItems(q);if(this.isGroupSelected(q))this.value=this.value.filter((Z)=>J.findIndex(($)=>$.value===Z)===-1);else this.value=[...this.value,...J.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let q=this.value.includes(z.value);this.value=q?this.value.filter((J)=>J!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:q}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries(q).flatMap(([J,Z])=>[{value:J,group:!0,label:J},...Z.map(($)=>({...$,group:J}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===z.cursorAt),this.#z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var a4=J4();var W=(z,q)=>a4?z:q,Nz=W("\u25C6","*"),Oz=W("\u25A0","x"),Tz=W("\u25B2","x"),xz=W("\u25C7","o"),Bz=W("\u250C","T"),s4=W("\u2502","|"),Ez=W("\u2514","\u2014"),bz=W("\u25CF",">"),Iz=W("\u25CB"," "),Az=W("\u25FB","[\u2022]"),Rz=W("\u25FC","[+]"),Cz=W("\u25FB","[ ]"),kz=W("\u25AA","\u2022"),hz=W("\u2500","-"),vz=W("\u256E","+"),yz=W("\u251C","+"),Sz=W("\u256F","+"),gz=W("\u25CF","\u2022"),_z=W("\u25C6","*"),fz=W("\u25B2","!"),mz=W("\u25A0","x");var dz={light:W("\u2500","-"),heavy:W("\u2501","="),block:W("\u2588","#")};function t4(){return`${h.gray(s4)} `}var uz=t4();var p="0.2.54";var G=new c("query-builder");G.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(z,q)=>{await R6(z,q)});G.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(z)=>{let q=z?.table,J=q?Array.isArray(q)?q:[q]:void 0,Z=await C6({tables:J});console.log(`import { defineModel } from 'bun-query-builder'
42
+
43
+ ${Z.map(($)=>$.source).join(`
44
+ `)}`)});G.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(z,q,J)=>{await i6(z,q,J)});G.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await _6()});G.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(z)=>{try{await l6(z)}catch{let q=await import("process");q.default.exitCode=1}});G.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(z,q)=>{await c6(z,q)});G.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(z,q)=>{await b6(z,q)});G.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate ./app/Models --dialect postgres").action(async(z,q)=>{try{await l(z,{dialect:q.dialect,state:q.state,apply:q.apply,full:q.full}),await r()}catch(J){console.error("-- Migration failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(z)=>{await E6(z)});G.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(z,q)=>{try{await f6(z,{verbose:q.verbose,json:q.json})}catch(J){console.error("-- Explain all failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(z)=>{try{await m6({dir:z.dir,format:z.format,output:z.output,verbose:z.verbose})}catch(q){console.error("-- Diagram generation failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(z,q)=>{try{console.log("-- Resetting database..."),await a(z,{dialect:q.dialect,state:q.state}),console.log("-- Generating fresh migrations..."),await l(z,{dialect:q.dialect,state:q.state,full:q.full}),console.log("-- Executing migrations..."),await r()}catch(J){console.error("-- Migrate fresh failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(z,q)=>{try{await a(z,{dialect:q.dialect,state:q.state})}catch(J){console.error("-- Reset failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(z)=>{try{if(z.class)await t(z.class,{verbose:z.verbose});else await s({seedersDir:z.dir,verbose:z.verbose})}catch(q){console.error("-- Seeding failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(z)=>{try{if(z.class)await t(z.class,{verbose:z.verbose});else await s({seedersDir:z.dir,verbose:z.verbose})}catch(q){console.error("-- Seeding failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(z)=>{try{await d6(z)}catch(q){console.error("-- Failed to create seeder:",q);let J=await import("process");J.default.exitCode=1}});G.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(z)=>{try{await u6({modelsDir:z.models,seedersDir:z.seeders,verbose:z.verbose})}catch(q){console.error("-- Database fresh failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(z,q)=>{try{await k6(z,{table:q.table,dir:q.dir,timestamps:q.timestamps})}catch(J){console.error("-- Failed to create model:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(z,q)=>{try{await g6(z,{dir:q.dir,json:q.json,verbose:q.verbose})}catch(J){console.error("-- Failed to show model:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await y6()}catch(z){console.error("-- Failed to get migration status:",z);let q=await import("process");q.default.exitCode=1}});G.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await S6()}catch(z){console.error("-- Failed to list migrations:",z);let q=await import("process");q.default.exitCode=1}});G.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(z)=>{try{await v6({steps:Number(z.steps),reverseSchema:z.reverseSchema,deleteFiles:Boolean(z.deleteFiles)})}catch(q){console.error("-- Rollback failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(z,q)=>{try{await h6(z,{dialect:q?.dialect,state:q?.state,apply:q?.apply,full:q?.full})}catch(J){console.error("-- Generate migration failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await O6()}catch(z){console.error("-- Failed to get database info:",z);let q=await import("process");q.default.exitCode=1}});G.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await T6()}catch(z){console.error("-- Failed to get database stats:",z);let q=await import("process");q.default.exitCode=1}});G.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(z)=>{try{await B6({dialect:z.dialect,force:z.force,verbose:z.verbose})}catch(q){console.error("-- Wipe failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(z)=>{try{await x6({dialect:z.dialect,aggressive:z.aggressive,tables:z.tables?z.tables.split(","):void 0,verbose:z.verbose})}catch(q){console.error("-- Optimize failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await L6()}catch(z){console.error("-- Console failed:",z);let q=await import("process");q.default.exitCode=1}});G.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await M6()}catch(z){console.error("-- Tinker failed:",z);let q=await import("process");q.default.exitCode=1}});G.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(z,q)=>{try{await I6(z,{verbose:q.verbose})}catch(J){console.error("-- Failed to inspect table:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(z,q)=>{try{await A6(z,{verbose:q.verbose})}catch(J){console.error("-- Failed to get table info:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await V6()}catch(z){console.error("-- Failed to clear cache:",z);let q=await import("process");q.default.exitCode=1}});G.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await W6()}catch(z){console.error("-- Failed to get cache stats:",z);let q=await import("process");q.default.exitCode=1}});G.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(z)=>{try{await D6({size:z.size})}catch(q){console.error("-- Failed to configure cache:",q);let J=await import("process");J.default.exitCode=1}});G.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(z)=>{try{await K6({operations:z.operations,iterations:z.iterations?Number(z.iterations):void 0})}catch(q){console.error("-- Benchmark failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(z)=>{try{await n6(z)}catch(q){console.error("-- Validation failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(z)=>{try{await p6(z)}catch(q){console.error("-- Check failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(z,q)=>{try{await w6(z,{format:q.format,output:q.output,limit:q.limit?Number(q.limit):void 0})}catch(J){console.error("-- Export failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(z,q,J)=>{try{await P6(z,q,{format:J.format,truncate:J.truncate})}catch(Z){console.error("-- Import failed:",Z);let $=await import("process");$.default.exitCode=1}});G.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(z)=>{try{await N6({tables:z.tables,output:z.output})}catch(q){console.error("-- Dump failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("version","Show the version of the CLI").action(()=>{console.log(p)});G.version(p);G.help();G.parse();