bun-query-builder 0.2.59 → 0.2.61
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 +31 -40
- package/dist/browser.d.ts +2 -2
- package/dist/chunk-1nqz3kbp.js +40 -0
- package/dist/chunk-3s6cme8m.js +3 -0
- package/dist/chunk-79cr4zy3.js +7 -0
- package/dist/chunk-rvr97jpq.js +2 -0
- package/dist/{chunk-739qq8wk.js → chunk-w49dhqgq.js} +1 -1
- package/dist/chunk-x8e0e418.js +446 -0
- package/dist/client.d.ts +19 -1
- package/dist/orm.d.ts +23 -2
- package/dist/sql-fragments.d.ts +30 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4q37wh0k.js +0 -445
- package/dist/chunk-asdkg5va.js +0 -3
- package/dist/chunk-cggx9cr8.js +0 -2
- package/dist/chunk-d2b8tt64.js +0 -40
- package/dist/chunk-j9778t8e.js +0 -7
package/dist/chunk-asdkg5va.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{rc as T}from"./chunk-739qq8wk.js";function I(z){K={...K,...z}}function R(){return K}function P(){return typeof window<"u"&&typeof document<"u"}async function D(){if(K.getToken){let z=K.getToken();return z instanceof Promise?z:z}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function W(){let z={"Content-Type":"application/json",Accept:"application/json",...K.headers},F=await D();if(F)z.Authorization=`Bearer ${F}`;return z}async function X(z){if(z.status===401)throw K.onUnauthorized?.(),new Y("Unauthorized",401);if(!z.ok){let G=await z.json().catch(()=>({message:"Request failed"}));throw new Y(G.message||`HTTP ${z.status}`,z.status)}let F=await z.json();if(K.transformResponse)return K.transformResponse(F);return F}class x{state;constructor(z){this.state={table:z,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...z){return this.state.selectColumns=z,this}where(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}andWhere(z,F,G){return G===void 0?this.where(z,F):this.where(z,F,G)}whereNull(z){return this.where(z,"is",null)}whereNotNull(z){return this.where(z,"is not",null)}whereIn(z,F){return this.where(z,"in",F)}whereNotIn(z,F){return this.where(z,"not in",F)}orderBy(z,F="asc"){return this.state.orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}latest(z="created_at"){return this.orderBy(z,"desc")}oldest(z="created_at"){return this.orderBy(z,"asc")}limit(z){return this.state.limitValue=z,this}offset(z){return this.state.offsetValue=z,this}skip(z){return this.offset(z)}take(z){return this.limit(z)}with(...z){return this.state.withRelations.push(...z),this}buildQueryParams(){let z=new URLSearchParams;for(let F of this.state.wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this.state.orderBy.length>0){let F=this.state.orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this.state.limitValue!==void 0)z.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)z.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))z.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)z.append("include",this.state.withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.state.table}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return Array.isArray(G)?G:G.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this.state.table} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G);return"data"in J&&!Array.isArray(J.data)?J.data:J}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this.state.table} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.state.table}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async create(z){let F=`${K.baseUrl}/${this.state.table}`,G=K.transformRequest?K.transformRequest(z):z,J=await fetch(F,{method:"POST",headers:await W(),body:JSON.stringify(G)}),L=await X(J);return"data"in L&&!Array.isArray(L.data)?L.data:L}async insert(z){return this.create(z)}async update(z,F){let G=`${K.baseUrl}/${this.state.table}/${z}`,J=K.transformRequest?K.transformRequest(F):F,L=await fetch(G,{method:"PATCH",headers:await W(),body:JSON.stringify(J)}),U=await X(L);return"data"in U&&!Array.isArray(U.data)?U.data:U}async delete(z){let F=`${K.baseUrl}/${this.state.table}/${z}`;return(await fetch(F,{method:"DELETE",headers:await W()})).ok}async destroy(z){return this.delete(z)}async paginate(z=1,F=15){this.limit(F).offset((z-1)*F);let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.state.table}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()});return X(L)}toState(){return{...this.state}}}function q(z){return new x(z)}function H(){return new Proxy({},{get:(z,F)=>{return()=>q(F)}})}class j{_attributes;_definition;constructor(z,F={}){this._definition=z,this._attributes={...F}}get(z){return this._attributes[z]}set(z,F){this._attributes[z]=F}get attributes(){return{...this._attributes}}get id(){let z=this._definition.primaryKey||"id";return this._attributes[z]}toJSON(){let z=new Set;for(let[G,J]of Object.entries(this._definition.attributes))if(J.hidden)z.add(G);let F={};for(let[G,J]of Object.entries(this._attributes))if(!z.has(G))F[G]=J;return F}}class N{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(z){this._definition=z}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this._wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this._wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}whereIn(z,F){return this._wheres.push({column:z,operator:"in",value:F,boolean:"and"}),this}whereNotIn(z,F){return this._wheres.push({column:z,operator:"not in",value:F,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not",value:null,boolean:"and"}),this}whereLike(z,F){return this._wheres.push({column:z,operator:"like",value:F,boolean:"and"}),this}orderBy(z,F="asc"){return this._orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}orderByAsc(z){return this.orderBy(z,"asc")}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}select(...z){return this._select=z,this}with(...z){return this._withRelations.push(...z),this}latest(z="created_at"){return this.orderByDesc(z)}oldest(z="created_at"){return this.orderByAsc(z)}buildQueryParams(){let z=new URLSearchParams;for(let F of this._wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this._orderBy.length>0){let F=this._orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this._limit!==void 0)z.append("limit",String(this._limit));if(this._offset!==void 0)z.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))z.append("fields",this._select.join(","));if(this._withRelations.length>0)z.append("include",this._withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.getTablePath()}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return(Array.isArray(G)?G:G.data).map((L)=>new j(this._definition,L))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this._definition.name} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G),L="data"in J&&!Array.isArray(J.data)?J.data:J;return new j(this._definition,L)}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this._definition.name} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.getTablePath()}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async pluck(z){return this._select=[z],(await this.get()).map((G)=>G.get(z))}async paginate(z=1,F=15){this._limit=F,this._offset=(z-1)*F;let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.getTablePath()}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()}),U=await X(L);return{...U,data:U.data.map((Z)=>new j(this._definition,Z))}}}function k(z){return new Proxy({query:()=>new N(z),where(G,J,L){return new N(z).where(G,J,L)},orWhere(G,J,L){return new N(z).orWhere(G,J,L)},whereIn(G,J){return new N(z).whereIn(G,J)},whereNotIn(G,J){return new N(z).whereNotIn(G,J)},whereNull(G){return new N(z).whereNull(G)},whereNotNull(G){return new N(z).whereNotNull(G)},whereLike(G,J){return new N(z).whereLike(G,J)},orderBy(G,J="asc"){return new N(z).orderBy(G,J)},orderByDesc(G){return new N(z).orderByDesc(G)},select(...G){return new N(z).select(...G)},limit:(G)=>new N(z).limit(G),take:(G)=>new N(z).take(G),skip:(G)=>new N(z).skip(G),latest:(G="created_at")=>new N(z).latest(G),oldest:(G="created_at")=>new N(z).oldest(G),async find(G){return new N(z).find(G)},async findOrFail(G){return new N(z).findOrFail(G)},async all(){return new N(z).get()},async first(){return new N(z).first()},async firstOrFail(){return new N(z).firstOrFail()},async count(){return new N(z).count()},async exists(){return new N(z).exists()},async paginate(G,J){return new N(z).paginate(G,J)},async pluck(G){return new N(z).pluck(G)},async create(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}`,U=K.transformRequest?K.transformRequest(G):G,Z=await fetch(L,{method:"POST",headers:await W(),body:JSON.stringify(U)}),_=await X(Z),$="data"in _&&!Array.isArray(_.data)?_.data:_;return new j(z,$)},async update(G,J){let L=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,U=`${K.baseUrl}/${L}/${G}`,Z=K.transformRequest?K.transformRequest(J):J,_=await fetch(U,{method:"PATCH",headers:await W(),body:JSON.stringify(Z)}),$=await X(_),A="data"in $&&!Array.isArray($.data)?$.data:$;return new j(z,A)},async delete(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}/${G}`;return(await fetch(L,{method:"DELETE",headers:await W()})).ok},async destroy(G){return this.delete(G)},getDefinition:()=>z,getTable:()=>z.table},{get(G,J){if(typeof J==="string"&&J.startsWith("where")&&J.length>5){let L=J.slice(5),U=L.charAt(0).toLowerCase()+L.slice(1);if(U in z.attributes||U==="id"||U===z.primaryKey)return(Z)=>new N(z).where(U,Z)}return Reflect.get(G,J)}})}var K,Y,E,V;var S=T(()=>{K={baseUrl:""};Y=class Y extends Error{status;constructor(z,F){super(z);this.name="BrowserQueryError",this.status=F}};E={async login(z){let F=await fetch(`${K.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Login failed"}));throw new Y(L.message||"Login failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async register(z){let F=await fetch(`${K.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Registration failed"}));throw new Y(L.message||"Registration failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async logout(){if(await D())try{await fetch(`${K.baseUrl}/logout`,{method:"POST",headers:await W()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await D())return null;try{let F=await fetch(`${K.baseUrl}/user`,{method:"GET",headers:await W()});if(F.status===401)return K.onUnauthorized?.(),null;if(!F.ok)return null;let G=await F.json();return G.user||G}catch{return null}},async check(){return await this.user()!==null},getToken:D},V=q});
|
|
3
|
-
export{I as Mb,R as Nb,P as Ob,Y as Pb,x as Qb,q as Rb,H as Sb,k as Tb,E as Ub,V as Vb,S as Wb};
|
package/dist/chunk-cggx9cr8.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{da as a,ea as b,fa as c,ga as d,ha as e,ia as f,ja as g}from"./chunk-4q37wh0k.js";import"./chunk-asdkg5va.js";import"./chunk-j9778t8e.js";import"./chunk-739qq8wk.js";export{a as saveMigrationSnapshot,d as resetDatabase,b as generateMigration,c as executeMigration,e as deleteMigrationFiles,f as copyModelsToGenerated,g as clearGeneratedDirectory};
|
package/dist/chunk-d2b8tt64.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{rc as Nt,sc as B}from"./chunk-739qq8wk.js";import{existsSync as tr}from"fs";import{join as rr}from"path";import ar from"process";import{existsSync as ut,statSync as dt}from"fs";import{join as ir,relative as nr,resolve as ft}from"path";import Ee from"process";import{Buffer as M}from"buffer";import{createCipheriv as or,createDecipheriv as sr,randomBytes as We}from"crypto";import{closeSync as Ie,createReadStream as gt,createWriteStream as lr,existsSync as pe,fsyncSync as pt,openSync as yt,writeFileSync as cr}from"fs";import{access as hr,constants as bt,mkdir as mr,readdir as ye,rename as wt,stat as L,unlink as be,writeFile as Je}from"fs/promises";import{isAbsolute as ur,join as F,resolve as dr}from"path";import g from"process";import{pipeline as fr}from"stream/promises";import{createGzip as Ct}from"zlib";import D from"process";import $ from"process";import we from"process";import{existsSync as Ce}from"fs";import{resolve as ze}from"path";import{existsSync as gr}from"fs";import{existsSync as Ye,mkdirSync as pr,readdirSync as yr,readFileSync as br,writeFileSync as wr}from"fs";import{homedir as H}from"os";import{dirname as vt,resolve as w}from"path";import R from"process";import{existsSync as Cr,readdirSync as vr}from"fs";import{extname as _e,resolve as St}from"path";import Sr from"process";import{spawnSync as fa}from"child_process";import{existsSync as O,readFileSync as ga}from"fs";import{join as j}from"path";import qt from"process";function Ar(e,t){this[e]=kr.bind(null,t)}class at{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!ut(e))return!0;return dt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=ut(r)?dt(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class it{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Pr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Nr(e){return e.getStats().size*2}function xr(e,t={}){let r=Ee.cwd();while(r.includes("storage"))r=ft(r,"..");let a=ft(r,e||"");if(t?.relative)return nr(Ee.cwd(),a);return a}function p(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Rr(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $<"u"){let e=$.type;if(e==="renderer"||e==="worker")return!1;return!!($.versions&&($.versions.node||$.versions.bun))}return!1}class Rt{async format(e){let t=await Rr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:D.pid,hostname:t(),environment:D.env.NODE_ENV||"development",platform:D.platform,version:D.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D.env.NODE_ENV||D.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class He{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(e,t={}){this.name=e,this.config={...V},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Rt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Se,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Se};return{...Se,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:V.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await hr(this.config.logDirectory,bt.F_OK|bt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await mr(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!pe(this.currentLogFile))await Je(this.currentLogFile,"",{mode:420});if(a=yt(this.currentLogFile,"a",420),cr(a,l,{flag:"a"}),pt(a),a!==void 0)Ie(a),a=void 0;if((await L(this.currentLogFile)).size===0){if(await Je(this.currentLogFile,l,{flag:"w",mode:420}),(await L(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Ie(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,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 F(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 F(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return F(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return We(16).toString("hex")}generateKey(){return We(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=We(16),a=or("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=Ct(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await L(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ye(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await L(r).catch(()=>null))try{if(await wt(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await be(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Je(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await L(r).catch(()=>null))await wt(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await ye(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await be(F(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=gt(e),a=lr(t),i=Ct();await fr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pe(this.currentLogFile))try{let e=yt(this.currentLogFile,"r+");pt(e),Ie(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ye(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await be(F(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ur(t)||t.startsWith("./")||t.startsWith("../"))t=dr(t);else return null;return pe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Lt[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
3
|
-
`);for(let b of S)if(b.trim()&&!b.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:f.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
|
|
4
|
-
`;if(l)h+=`${l}
|
|
5
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(i,n)=>{},finish:(i)=>{},interrupt:(i,n)=>{}};if(!this.enabled)return r;let a=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:a,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,n="info")=>{if(!p()&&g.stdout.isTTY)g.stdout.write(`
|
|
6
|
-
`);if(this[n==="warning"?"warn":n](i),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",a=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":f.blue("\u25D0"),tag:r,message:`${f.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let a=performance.now(),i=Math.round(a-t),n=`${e} completed in ${i}ms`,o=new Date,l=this.formatConsoleTimestamp(o),s=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${n}`;if(r)s+=` ${JSON.stringify(r)}`;if(s+=`
|
|
7
|
-
`,s=s.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":f.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!p())console.error(s.trim());if(this.shouldWriteToFile())await this.writeToFile(s)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new He(t,{...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(r),r}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!pe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return gt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let a=M.isBuffer(e)?e:M.from(e,"base64"),i=a.subarray(0,16),n=a.subarray(a.length-16),o=a.subarray(16,a.length-16),l=sr("aes-256-gcm",r,i);l.setAuthTag(n);let s=l.update(o),c=l.final(),h=s.length+c.length,m=M.allocUnsafe(h);return s.copy(m,0),c.copy(m,s.length),m.toString("utf8")}catch(a){throw Error(`Decryption failed: ${a instanceof Error?a.message:String(a)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),a=this.formatFileTimestamp(t),{consoleText:i,fileText:n}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=i.split(`
|
|
8
|
-
`),s=Math.max(...l.map((u)=>u.length))+2,c=`\u250C${"\u2500".repeat(s)}\u2510`,h=`\u2514${"\u2500".repeat(s)}\u2518`,m=l.map((u)=>{return this.formatConsoleMessage({timestamp:r,message:f.cyan(u),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:f.cyan(c),showTimestamp:!1})),m.forEach((u)=>console.error(u)),console.error(this.formatConsoleMessage({timestamp:r,message:f.cyan(h),showTimestamp:!1}))}else if(!p())console.error(`${a} ${this.environment}.INFO: [BOX] ${n}`);let o=`${a} ${this.environment}.INFO: [BOX] ${n}
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(p())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${f.cyan("?")} ${e} (y/n) `);let r=(a)=>{let i=a.toString().trim().toLowerCase();g.stdin.removeListener("data",r);try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!1)}catch{}g.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!0)}catch{}g.stdin.resume(),g.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,l=0;if(r=e.replace(o,(s,c)=>{if(c==="%")return"%";if(l>=t.length)return s;let h=t[l++];switch(c){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 s}}),l<t.length)r+=` ${t.slice(l).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}let{consoleText:a,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${f.blue("\u25D0")} `;console.error(`${l}${o} ${f.cyan(a)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(n)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!g.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),a=Math.round(e.barLength*r/100),i=e.barLength-a,n=f.green("\u2501".repeat(a)),o=f.gray("\u2501".repeat(i)),l=`[${n}${o}]`,s=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=this.options.showIcons===!1?"":t||r===100?f.green("\u2713"):f.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${f.gray(this.formatTag(this.name))}`:"",u=`\r${h}${m} ${l} ${s}${c}`,d=g.stdout.columns||80,S=" ".repeat(Math.max(0,d-u.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${u}${S}`,g.stdout.write(e.lastRenderedLine),t)g.stdout.write(`
|
|
11
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||p()||!g.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ye(this.config.logDirectory),r=[];for(let a of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(a):a.startsWith(this.name))||!a.endsWith(".log"))continue;let i=F(this.config.logDirectory,a);if(e.before)try{if((await L(i)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${i}:`,n);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let a of r)try{await be(a),console.warn(`Deleted log file: ${a}`)}catch(i){console.error(`Failed to delete log file ${a}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ft(e,t={}){let{maxRetries:r=3,retryDelay:a=1000,isRetryable:i=()=>!0,fallback:n}=t,o=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(s){if(o=s instanceof Error?s:Error(String(s)),l===r||!i(o))break;if(a>0)await new Promise((c)=>setTimeout(c,a))}if(n!==void 0)return n;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Dt(e){return e instanceof C}function Yr(e){return e instanceof ke}function qr(e){if(Dt(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class Oe{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:a,useCamelCase:i=!0,useBackwardCompatibility:n=!0,customParsers:o={},verbose:l=!1,trackPerformance:s=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=a||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],h,{useCamelCase:i,useBackwardCompatibility:n,customParsers:o,verbose:l,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(s)return fe.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,a){for(let[i,n]of Object.entries(e)){let o=[...t,i],l=o.map((h)=>this.formatEnvKey(h,a.useCamelCase)),s=`${r}_${l.join("_")}`,c=a.useBackwardCompatibility?`${r}_${o.map((h)=>h.toUpperCase()).join("_")}`:null;if(a.verbose);if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.processObject(n,o,r,a);else{let h=we.env[s]||(c?we.env[c]:void 0);if(h!==void 0){if(a.verbose){let m=we.env[s]?s:c}try{e[i]=this.parseEnvironmentValue(h,typeof n,s,a.customParsers,a.configName)}catch(m){if(m instanceof Ae)throw m;throw x.envVar(s,h,typeof n,a.configName)}}}}}parseEnvironmentValue(e,t,r,a,i){for(let[n,o]of Object.entries(a))try{return o(e)}catch{continue}for(let n of this.defaultParsers)if(n.canParse(e,t))try{return n.parse(e)}catch{throw x.envVar(r,e,`${t} (via ${n.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[a,i]of Object.entries(we.env))if(a.startsWith(r)&&i!==void 0)t[a]=i;return t}validateEnvironmentVariable(e,t,r){let a=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))a.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){a.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:a.length===0,errors:a}}generateEnvVarDocs(e,t,r={}){let{prefix:a,format:i="text"}=r,n=a||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],n,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,a){for(let[i,n]of Object.entries(e)){let o=[...t,i],l=`${r}_${o.map((s)=>this.formatEnvKey(s,!0)).join("_")}`;if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.extractEnvVarInfo(n,o,r,a);else a.push({key:l,type:Array.isArray(n)?"array":typeof n,description:`Configuration for ${o.join(".")}`,example:this.generateExample(n)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
12
|
-
|
|
13
|
-
`;for(let a of e)r+=`${a.key}
|
|
14
|
-
`,r+=` Type: ${a.type}
|
|
15
|
-
`,r+=` Description: ${a.description}
|
|
16
|
-
`,r+=` Example: ${a.example}
|
|
17
|
-
|
|
18
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
19
|
-
|
|
20
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
21
|
-
`,r+=`|----------|------|-------------|----------|
|
|
22
|
-
`;for(let a of e)r+=`| \`${a.key}\` | ${a.type} | ${a.description} | \`${a.example}\` |
|
|
23
|
-
`;return r}}function Zr(e,t){let r=$r("process");if(typeof r>"u"||!r.env)return t;let a=r.env[e];return a!==void 0?a:t}function Ot(e,t,r={}){return jt(e,t,r,new WeakMap)}function jt(e,t,r,a){let{arrayMergeMode:i="replace",skipNullish:n=!1,customMerger:o}=r;if(t===null||t===void 0)return n?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Gt(e,t,i,a);if(!k(t)||!k(e))return t;return ta(e,t,r,a)}function Gt(e,t,r,a){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Xr(e,t);case"smart":return Qr(e,t,a);default:return t}return t}function Xr(e,t){let r=[...t];for(let a of e)if(!r.some((i)=>rt(i,a)))r.push(a);return r}function Qr(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(k(t[0])&&k(e[0]))return ea(e,t,r);if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let i of e)if(!a.includes(i))a.push(i);return a}return t}function ea(e,t,r){let a=[...t];for(let i of e){if(!k(i)){a.push(i);continue}let n=["id","name","key","path","type"],o=!1;for(let l of n)if(l in i){if(a.find((s)=>k(s)&&(l in s)&&s[l]===i[l])){o=!0;break}}if(!o)a.push(i)}return a}function ta(e,t,r,a){let i=t;if(k(i)&&a.has(i))return a.get(i);let n={...e};if(k(i))a.set(i,n);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let l=i[o],s=n[o];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){n[o]=l;continue}if(k(l)&&k(s))n[o]=jt(s,l,r,a);else if(Array.isArray(l)||Array.isArray(s))n[o]=Gt(s,l,r.arrayMergeMode||"smart",a);else n[o]=l}return n}function nt(e,t,r="replace"){return Ot(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function rt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!rt(e[r],t[r]))return!1;return!0}if(k(e)&&k(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!rt(e[i],t[i]))return!1}return!0}return!1}function k(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class je{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:a="replace",useCache:i=!0,cacheTtl:n,trackPerformance:o=!0,verbose:l=!1}=r;if(i){let c=I.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let s=async()=>{if(!Ce(e))return null;try{let c=`?t=${Date.now()}`,h=await import(e+c),m=h.default||h,u="default"in h,d=Object.keys(h).length>0;if(!u&&!d)throw new he(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new he(e,Error("Configuration must export a valid object"),"unknown");let S={config:nt(t,m,a),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)I.setWithFileCheck("file",S,e,n);return S}catch(c){throw c instanceof Error?x.configLoad(e,c):x.configLoad(e,Error(String(c)))}};if(o)return fe.track("loadFromPath",s,{path:e});return s()}async tryLoadFromPaths(e,t,r={}){for(let a of e)try{let i=await this.loadFromPath(a,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${a}:`,i)}return null}generateConfigPaths(e,t,r){let a=this.generateNamePatterns(e,r),i=[];for(let n of a)for(let o of this.extensions)i.push(ze(t,`${n}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let a=t===void 0?[]:Array.isArray(t)?t:[t];for(let n of a){if(!n)continue;if(r.push(n,`.${n}.config`,`${n}.config`,`.${n}`),e)r.push(`${e}.${n}.config`,`.${e}.${n}.config`)}let i=new Set;return r.filter((n)=>{if(!n||i.has(n))return!1;return i.add(n),!0})}checkFileAccess(e){return Ft(async()=>{return Ce(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let a=[];if(!Ce(e))return a;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let n of i)for(let o of this.extensions){let l=ze(e,`${n}${o}`);if(await this.checkFileAccess(l))a.push(l)}}else try{let{readdirSync:i}=await import("fs"),n=i(e);for(let o of n)if(this.looksLikeConfigFile(o)){let l=ze(e,o);if(await this.checkFileAccess(l))a.push(l)}}catch{return[]}return a}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Ce(e))return t.push("Configuration file does not exist"),t;let r=await import(e),a=r.default||r;if(a===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof a!=="object"||a===null)t.push("Configuration must be an object");else if(Array.isArray(a))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),n=i(e,"utf8");JSON.parse(n)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(a)=>{try{let i=await this.loadFromPath(a,{},t);if(i)r.set(a,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${a}:`,i)}})),r}}class st{async validateConfiguration(e,t,r={}){let{stopOnFirstError:a=!1,validateRequired:i=!0,validateTypes:n=!0,customRules:o=[],trackPerformance:l=!0,verbose:s=!1}=r,c=async()=>{let h=[],m=[],u={stopOnFirstError:a,validateRequired:i,validateTypes:n,customRules:o,trackPerformance:l,verbose:s};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,u);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],u);else return this.validateWithJSONSchema(e,t,u)}catch(d){return h.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:h,warnings:m}}};if(l)return await fe.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!gr(t))throw new me(t,[{path:"",message:"Schema file does not exist"}]);let a=await import(t),i=a.default||a;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(a){throw new me(t,[{path:"",message:`Failed to load schema: ${a}`}])}}validateWithJSONSchema(e,t,r){let a=[],i=[];return this.validateObjectAgainstSchema(e,t,"",a,i,r),{isValid:a.length===0,errors:a,warnings:i}}validateObjectAgainstSchema(e,t,r,a,i,n){if(n.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(a.push({path:r,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),n.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(a.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),n.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)a.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)a.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))a.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)a.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)a.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,a,i,n),n.stopOnFirstError&&a.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(n.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(a.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),n.stopOnFirstError)return}}if(t.properties){for(let[l,s]of Object.entries(t.properties))if(l in o){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],s,c,a,i,n),n.stopOnFirstError&&a.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let s of Object.keys(o))if(!l.has(s))i.push({path:r?`${r}.${s}`:s,message:`Additional property '${s}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let a=[],i=[];for(let n of t)try{let o=this.getValueByPath(e,n.path),l=this.validateWithRule(o,n,n.path);if(a.push(...l),r.stopOnFirstError&&a.length>0)break}catch(o){a.push({path:n.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:a.length===0,errors:a,warnings:i}}validateWithRule(e,t,r){let a=[];if(t.required&&(e===void 0||e===null))return a.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),a;if(e===void 0||e===null)return a;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)a.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)a.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)a.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))a.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))a.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)a.push({path:r,message:t.message||i,rule:"custom"})}return a}getValueByPath(e,t){if(!t)return e;let r=t.split("."),a=e;for(let i of r)if(a&&typeof a==="object"&&i in a)a=a[i];else return;return a}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let a of r){let[,i,n,o]=a;t.push({path:i,required:!n,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Jt},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function ra(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class lt{fileLoader=new je;envProcessor=new Oe;validator=new st;async loadConfig(e){let t=Date.now(),{cache:r,performance:a,schema:i,validate:n,...o}=e;try{if(r?.enabled){let s=this.checkCache(o.name||"",o);if(s)return s}let l;try{l=await this.loadConfigurationStrategies(o,!0,r)}catch(s){let c=o.__strictErrorHandling;if(s instanceof Error&&s.name==="ConfigNotFoundError"){if(c)throw s;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(s instanceof Error&&s.name==="ConfigLoadError"){let h=s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"),m=!h&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")||s.message.includes("errors building")),u=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");if(c&&(u||h))throw s;if(m&&(!c||!u))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${s.message}`]};else throw s}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${s instanceof Error?s.message:String(s)}`]}}if(i||n)await this.validateConfiguration(l.config,i,n,o.name);if(r?.enabled&&l)this.cacheResult(o.name||"",l,r,o);if(a?.enabled){let s={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(a.onMetrics)a.onMetrics(s);if(a.slowThreshold&&s.duration>a.slowThreshold)E.warn(`Slow configuration loading detected: ${s.duration}ms for ${o.name}`);l.metrics=s}return l}catch(l){let s=Date.now()-t;throw E.error(`Configuration loading failed after ${s}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:a="",alias:i,cwd:n,configDir:o,defaultConfig:l,checkEnv:s=!0,arrayStrategy:c="replace",verbose:h=!1}=e,m=n||R.cwd(),u=[],d=await this.loadLocalConfiguration(a,i,m,o,l,c,h,s,r);if(d)return u.push(...this.getLocalSearchPaths(a,i,m,o)),this.finalizeResult(d,u,s,a,h);let S=await this.loadHomeConfiguration(a,i,l,c,h,s);if(S)return u.push(...this.getHomeSearchPaths(a,i)),this.finalizeResult(S,u,s,a,h);let b=await this.loadPackageJsonConfiguration(a,i,m,l,c,h,s);if(b)return u.push(w(m,"package.json")),this.finalizeResult(b,u,s,a,h);if(u.push(...this.getAllSearchPaths(a,i,m,o)),t)throw x.configNotFound(a,u,i);return{...await this.applyEnvironmentVariables(a,l,s,h),warnings:[`No configuration file found for "${a}"${ra(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,a,i,n,o,l,s){let c=l?_(e,i,o):i,h=this.getLocalDirectories(r,a);for(let m of h){if(o)E.info(`Searching for configuration in: ${m}`);let u=this.fileLoader.generateConfigPaths(e,m,t),d=await this.fileLoader.tryLoadFromPaths(u,c,{arrayStrategy:n,verbose:o,cacheTtl:s?.ttl,useCache:!s?.ttl||s.ttl>100});if(d){if(o)E.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,a,i,n){if(!e)return null;let o=n?_(e,r,i):r,l=[w(H(),".config",e),w(H(),".config"),H()];for(let s of l){if(i)E.info(`Checking home directory: ${s}`);let c=this.fileLoader.generateConfigPaths(e,s,t),h=await this.fileLoader.tryLoadFromPaths(c,o,{arrayStrategy:a,verbose:i});if(h){if(i)E.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,r,a,i,n,o){let l=o?_(e,a,n):a;try{let s=w(r,"package.json");if(!Ye(s))return null;let c={};try{c=JSON.parse(br(s,"utf8"))}catch(u){if(n)E.warn("Failed to parse package.json:",[u instanceof Error?u:Error(String(u))]);return null}let h=c[e],m=e;if(!h&&t){let u=Array.isArray(t)?t:[t];for(let d of u){if(!d)continue;if(c[d]){h=c[d],m=d;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(n)E.success(`Configuration loaded from package.json: ${m}`);return{config:nt(l,h,i),source:{type:"package.json",path:s,priority:30,timestamp:new Date}}}}catch(s){if(n)E.warn("Failed to load package.json:",[s instanceof Error?s:Error(String(s))])}return null}async applyEnvironmentVariables(e,t,r,a){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:_(e,t,a),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,a,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,a){let i=[];if(r){let n=r(e);if(n)i.push(...n)}if(t){let n=await this.validator.validateConfiguration(e,t);if(!n.isValid)i.push(...n.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw x.configValidation(a||"unknown",i,a)}checkCache(e,t){let r=this.generateCacheKey(e,t);return I.get(r)||null}cacheResult(e,t,r,a){let i=this.generateCacheKey(e,a);I.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let a=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${a}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,w(e,"config"),w(e,".config"),t?w(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,a){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,a)),i.push(...this.getHomeSearchPaths(e,t)),i.push(w(r,"package.json")),i}getLocalSearchPaths(e,t,r,a){let i=this.getLocalDirectories(r,a),n=[];for(let o of i)n.push(...this.fileLoader.generateConfigPaths(e,o,t));return n}getHomeSearchPaths(e,t){if(!e)return[];let r=[w(H(),".config",e),w(H(),".config"),H()],a=[];for(let i of r)a.push(...this.fileLoader.generateConfigPaths(e,i,t));return a}async loadConfigWithResult(e){return this.loadConfig(e)}}function Tt(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function aa(e){return T.loadConfig({...e,__strictErrorHandling:!0})}async function ct(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let a;if(r)a=await T.loadConfig(e);else a=await T.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return a?.config??t}catch(a){let i=a instanceof Error?a.name:"UnknownError",n=a instanceof Error?a.message:String(a);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||n.includes("config"))&&e.verbose)E.warn("Unexpected error loading config, using defaults:",[a instanceof Error?a:Error(String(a))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await T.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function ia(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await T.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Tt(r)))return(await T.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await T.loadConfig({...e,cwd:e.cwd||R.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Tt(t)))return(await T.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function na(e,t,r="replace"){let a=new je;try{let i=await a.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function _(e,t,r=!1){let a=new Oe,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function n(o,l=[]){let s={...o};for(let[c,h]of Object.entries(o)){let m=[...l,c],u=[`${i}_${m.join("_").toUpperCase()}`,`${i}_${m.map((b)=>b.toUpperCase()).join("")}`,`${i}_${m.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,S;for(let b of u)if(d=R.env[b],d!==void 0){S=b;break}if(d!==void 0&&S)if(typeof h==="boolean")s[c]=["true","1","yes"].includes(d.toLowerCase());else if(typeof h==="number"){let b=Number(d);if(!Number.isNaN(b))s[c]=b}else if(Array.isArray(h))try{s[c]=JSON.parse(d)}catch{s[c]=d.split(",").map((b)=>b.trim())}else s[c]=d;else if(h&&typeof h==="object"&&!Array.isArray(h))s[c]=n(h,m)}return s}return n(t)}function oa(e){let t=w(R.cwd(),e.configDir),r=w(R.cwd(),e.generatedDir),a=w(r,"config-types.ts");if(!Ye(vt(a)))pr(vt(a),{recursive:!0,mode:511});let i=Ye(t)?yr(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],n=`// Generated by bunfig v${Ur}
|
|
24
|
-
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
25
|
-
`;wr(a,n,{mode:438})}function sa(e){let t=null,r=null,a=()=>{if(!r)r=ct(e).then((n)=>{return t=n,n},(n)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)E.warn("Config loading failed, using defaults:",[n instanceof Error?n:Error(String(n))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,a(),new Proxy({},{get(n,o){if(t)return t[o];let l=i[o];return a(),l},has(n,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(n,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(n,o,l){if(!t)t={...i};return t[o]=l,!0}})}function ca(e){let t=St(Sr.cwd(),e?.configDir||"./config");function r(){if(!Cr(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),n=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=vr(t).filter((s)=>i.has(_e(s))).map((s)=>({base:s.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:s})),l=new Map;for(let{base:s,file:c}of o){let h=_e(c).toLowerCase(),m=l.get(s);if(!m){l.set(s,c);continue}let u=_e(m).toLowerCase();if(n.indexOf(h)<n.indexOf(u))l.set(s,c)}return Array.from(l.entries()).map(([s,c])=>({base:s,file:c})).sort((s,c)=>s.base.localeCompare(c.base))}function a(){let i=r(),n=i.map((s)=>s.base),o=n.length?n.map((s)=>`'${s}'`).join(" | "):"string",l=i.length?`{
|
|
26
|
-
${i.map((s)=>{let c=St(t,s.file).replace(/\\/g,"/");return` '${s.base}': typeof import('${c}').default`}).join(`,
|
|
27
|
-
`)}
|
|
28
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
29
|
-
export type ConfigByName = ${l}
|
|
30
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
31
|
-
export type ConfigOf = Config
|
|
32
|
-
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(n)=>{return{path:n.path,namespace:"bunfig-virtual"}}),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:a(),loader:"ts"}})}}}async function ma(){if(!Ke)Ke=await ct({name:"faker",alias:"mock",defaultConfig:ht});return Ke}function G(e){let t=e.replace(/-/g,"_").split("_"),r=t[0].toLowerCase(),a=t[1]?.toUpperCase(),i=a?`${r}-${a.toLowerCase()}`:r;return{full:e,language:r,region:a,packageName:i,normalized:a?`${r}_${a}`:r}}function ua(e){let t=G(e);if(t.region)return[t.normalized,t.language];return[t.language]}function da(e){return`@mock-locale/${G(e).packageName}`}function Yt(e,t){let r={...e};for(let a in t){let i=t[a],n=e[a];if(i===void 0)continue;if(typeof i==="object"&&i!==null&&!Array.isArray(i)&&typeof n==="object"&&n!==null&&!Array.isArray(n))r[a]=Yt(n,i);else r[a]=i}return r}function W(){let e=qt.cwd(),t=j(e,"package.json");if(!O(t))return!1;try{let r=JSON.parse(ga(t,"utf-8"));return!!(r.workspaces||r.workspace)}catch{return!1}}function Zt(){let e=qt.cwd();if(O(j(e,"bun.lockb"))||O(j(e,"bun.lock")))return"bun";if(O(j(e,"pnpm-lock.yaml")))return"pnpm";if(O(j(e,"yarn.lock")))return"yarn";if(O(j(e,"package-lock.json")))return"npm";return"bun"}function Xt(e,t={}){let r=Zt(),{silent:a=!1}=t;if(!a)console.log(`
|
|
33
|
-
\uD83D\uDCE6 Installing ${e} using ${r}...`);let i={bun:{cmd:"bun",args:["add",e]},npm:{cmd:"npm",args:["install",e]},yarn:{cmd:"yarn",args:["add",e]},pnpm:{cmd:"pnpm",args:["add",e]}},{cmd:n,args:o}=i[r];try{let l=fa(n,o,{stdio:"pipe",shell:!0}),s=l.stdout?.toString()||"",c=l.stderr?.toString()||"",h=s+c;if(!a){if(s)console.log(s);if(c)console.error(c)}if(l.status===0){if(!a)console.log(`\u2713 Successfully installed ${e}`);return!0}else{let m=h;if(m.toLowerCase().includes("dependency loop")||m.includes("DependencyLoop")||m.includes("has a dependency loop")||m.includes("An internal error occurred (DependencyLoop)")){if(!a){if(console.log(`
|
|
34
|
-
\u26A0\uFE0F Package ${e} is already available in the workspace and cannot be installed separately due to a dependency loop.`),W())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!a)console.error(`\u2717 Failed to install ${e}`);return!1}}catch(l){if(!a)console.error(`\u2717 Error installing ${e}:`,l);return!1}}function ue(e,t){let r=[];for(let a of t.rules)if(!a.validator(e)){let i=a.errorMessage||`Validation failed for value: ${e}`;if(r.push(i),t.strict)throw Error(i)}return{isValid:r.length===0,errors:r}}function de(e,t){let{items:r}=t;if(r.length===0)throw Error("Cannot select from empty weighted items array");let a=r.reduce((o,l)=>o+l.weight,0);if(a<=0)throw Error("Total weight must be greater than 0");let i=e.number()*a,n=0;for(let o of r)if(n+=o.weight,i<=n)return o.item;return r[r.length-1].item}function pa(e,t){return e.filter((r)=>{if(t.gender&&r.gender&&r.gender!==t.gender)return!1;if(t.country){let a=Array.isArray(t.country)?t.country:[t.country];if(r.country&&!a.includes(r.country))return!1}if(t.region){let a=Array.isArray(t.region)?t.region:[t.region];if(r.region&&!a.includes(r.region))return!1}if(t.locale&&r.locale&&r.locale!==t.locale)return!1;if(t.ageRange&&r.age){let{min:a,max:i}=t.ageRange;if(r.age<a||r.age>i)return!1}for(let[a,i]of Object.entries(t))if(a!=="gender"&&a!=="country"&&a!=="region"&&a!=="locale"&&a!=="ageRange"&&r[a]!==void 0){if(!(Array.isArray(i)?i:[i]).includes(r[a]))return!1}return!0})}function N(e,t){let r={...e};for(let a of t){let{field:i,dependsOn:n,mapping:o}=a;if(r[n]&&o[r[n]])r[i]=o[r[n]]}return r}function ya(e,t={}){let r=e();if(t.relationships)return N(r,t.relationships);return r}class mt{providers=new Map;register(e){let{category:t,name:r}=e;if(!this.providers.has(t))this.providers.set(t,new Map);this.providers.get(t).set(r,e)}get(e,t){return this.providers.get(e)?.get(t)}getProvidersInCategory(e){let t=this.providers.get(e);return t?Array.from(t.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove(e,t){let r=this.providers.get(e);if(r)return r.delete(t);return!1}clear(){this.providers.clear()}}class U{random;locale;constructor(e,t){this.random=e,this.locale=t}street(){let e=this.random.arrayElement(this.locale.address.street),t=this.streetSuffix();return`${e} ${t}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress(e){let t=this.buildingNumber(),r=this.street();if(e?.useFullAddress)return`${t} ${r}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${t} ${r}`}buildingNumber(){let e=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols(e)}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 e=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols(e)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude(e){let t=e?.min??-90,r=e?.max??90,a=e?.precision??4;return this.random.float(t,r,a)}longitude(e){let t=e?.min??-180,r=e?.max??180,a=e?.precision??4;return this.random.float(t,r,a)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced(e){let t;if(e?.constraints?.country){let r=e.constraints.country,a=Array.isArray(r)?r:[r];t=this.city()}else t=this.city();if(e?.weighted)t=de(this.random,e.weighted);if(e?.relationships)t=N({city:t,country:e?.constraints?.country},e.relationships).city||t;if(e?.validation){let r=ue(t,e.validation);if(!r.isValid){if(e.validation.strict)throw Error(`Validation failed: ${r.errors.join(", ")}`);t=this.city()}}return t}countryAdvanced(e){let t;if(e?.constraints?.country){let r=e.constraints.country,a=Array.isArray(r)?r:[r];t=this.random.arrayElement(a)}else t=this.country();if(e?.weighted)t=de(this.random,e.weighted);if(e?.relationships)t=N({country:t},e.relationships).country||t;if(e?.validation){let r=ue(t,e.validation);if(!r.isValid){if(e.validation.strict)throw Error(`Validation failed: ${r.errors.join(", ")}`);t=this.country()}}return t}addressAdvanced(e){let t=this.countryAdvanced(e),r=this.cityAdvanced(e),a=this.state(),i=this.stateAbbr(),n=this.zipCode(),o=this.street(),l=this.latitude(),s=this.longitude(),c={street:o,city:r,state:a,stateAbbr:i,country:t,countryCode:this.countryCode(),zipCode:n,latitude:l,longitude:s};if(e?.relationships)return N(c,e.relationships);return c}neighborhood(e){let t=e?.size||this.random.int(3,10),r=this.cityAdvanced(e),a=this.state(),i=this.zipCode(),n=[];for(let o=0;o<t;o++)n.push({street:this.street(),city:r,state:a,zipCode:i,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 n}}class K{random;locale;constructor(e,t){this.random=e,this.locale=t}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let e=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement(e)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let e=["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(e)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let e=["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(e)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let e=["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(e)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let e=["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(e)}bear(){let e=["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(e)}cetacean(){let e=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement(e)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let e=["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(e)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let e=["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(e)}lion(){let e=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement(e)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let e=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement(e)}snake(){let e=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement(e)}}class Y{random;locale;constructor(e,t){this.random=e,this.locale=t}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let e=["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(e)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let e=["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(e)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let e=["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(e)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let e=["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(e)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let e=["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(e)}isbn(){if(this.random.boolean(0.5)){let n=Array.from({length:9},()=>this.random.int(0,9)),o=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${n.slice(0,1).join("")}-${n.slice(1,4).join("")}-${n.slice(4,9).join("")}-${o}`}let e="978",t=this.random.int(0,9),r=Array.from({length:3},()=>this.random.int(0,9)).join(""),a=Array.from({length:5},()=>this.random.int(0,9)).join(""),i=this.random.int(0,9);return`${e}-${t}-${r}-${a}-${i}`}format(){let e=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement(e)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let e=["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(e)}}class q{random;locale;constructor(e,t){this.random=e,this.locale=t}hex(e){let t=e?.prefix??"#",r=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return t+r}rgb(e){let t=this.random.int(0,255),r=this.random.int(0,255),a=this.random.int(0,255);if(e?.alpha){let i=this.random.float(0,1,2);if(e?.format==="array")return[t,r,a,i];return`rgba(${t}, ${r}, ${a}, ${i})`}if(e?.format==="array")return[t,r,a];return`rgb(${t}, ${r}, ${a})`}hsl(e){let t=this.random.int(0,360),r=this.random.int(0,100),a=this.random.int(0,100);if(e?.alpha){let i=this.random.float(0,1,2);if(e?.format==="array")return[t,r,a,i];return`hsla(${t}, ${r}%, ${a}%, ${i})`}if(e?.format==="array")return[t,r,a];return`hsl(${t}, ${r}%, ${a}%)`}css(e){let t=e?.format??this.random.arrayElement(["hex","rgb","hsl"]);if(t==="hex")return this.hex();if(t==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let e=["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(e)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class Z{random;locale;constructor(e,t){this.random=e,this.locale=t}product(){let e=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"],t=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],r=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(e)} ${this.random.arrayElement(t)} ${this.random.arrayElement(r)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let e=["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(e)}price(e){let t=e?.min??1,r=e?.max??1000,a=e?.dec??2,i=e?.symbol??"",n=this.random.float(t,r,a);return i+n.toFixed(a)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let e=["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(e)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let e=["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(e)}productDescription(){let e=["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}."],t=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],r=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement(e).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement(t)).replace("{benefit}",this.random.arrayElement(r))}review(){let e=["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(e)}discountCode(){let e=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],t=this.random.int(10,99);return`${this.random.arrayElement(e)}${t}`}sku(){let e=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),t=this.random.int(1e4,99999),r=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${e}-${t}-${r}`}}class X{random;locale;constructor(e,t){this.random=e,this.locale=t}name(){let e=this.random.arrayElement(this.locale.company.name??["Company"]),t=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${e} ${t}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let e=this.random.arrayElement(this.locale.company.adjective??["innovative"]),t=this.random.arrayElement(this.locale.company.descriptor??["digital"]),r=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${e} ${t} ${r}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let e=this.buzzword(),t=this.random.arrayElement(this.locale.company.descriptor??["digital"]),r=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${e} ${t} ${r}`}}class Me{random;constructor(e){this.random=e}engine(){let e=["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(e)}type(){let e=["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(e)}collation(){let e=["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(e)}column(){let e=["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(e)}table(){let e=["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(e)}mongodbObjectId(){let e="";for(let t=0;t<24;t++)e+="0123456789abcdef"[this.random.int(0,15)];return e}constraint(){let e=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement(e)}queryType(){let e=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement(e)}connectionString(e){let t=e?.engine??this.engine().toLowerCase().replace(/ /g,""),r="user",a="password",i="localhost",n=this.random.int(3000,9999),o=this.table(),l={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[t]||"jdbc";if(t==="mongodb")return`${l}://user:password@localhost:${n}/${o}`;return`${l}://user:password@localhost:${n}/${o}`}}class $e{random;constructor(e){this.random=e}past(e){let t=e?.years??1,r=e?.to??new Date,a=e?.from??new Date(r.getTime()-t*365*24*60*60*1000);return this.between({from:a,to:r})}future(e){let t=e?.years??1,r=e?.from??new Date,a=e?.to??new Date(r.getTime()+t*365*24*60*60*1000);return this.between({from:r,to:a})}between(e){let t=e.from??new Date(Date.now()-31536000000),r=e.to??new Date,a=t.getTime(),i=r.getTime(),n=this.random.int(a,i);return new Date(n)}recent(e){let t=e?.days??1,r=new Date,a=new Date(r.getTime()-t*24*60*60*1000);return this.between({from:a,to:r})}soon(e){let t=e?.days??1,r=new Date,a=new Date(r.getTime()+t*24*60*60*1000);return this.between({from:r,to:a})}month(){let e=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement(e)}weekday(){let e=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement(e)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween(e){return this.between(e)}birthdate(e){let t=e?.mode??"age",r=e?.refDate??new Date;if(t==="year"){let s=e?.min??1900,c=e?.max??r.getUTCFullYear(),h=new Date(Date.UTC(s,0,1)),m=new Date(Date.UTC(c,11,31,23,59,59,999));return this.between({from:h,to:m})}let a=Math.max(0,e?.min??18),i=Math.max(a,e?.max??80),n=(s)=>s*365.25*24*60*60*1000,o=new Date(r.getTime()-n(i)),l=new Date(r.getTime()-n(a));return this.between({from:o,to:l})}}class Te{random;constructor(e){this.random=e}amount(e){let t=e?.min??0,r=e?.max??1e4,a=e?.dec??2,i=e?.symbol??"",n=this.random.float(t,r,a);return i+n.toFixed(a)}account(e=8){let t="";for(let r=0;r<e;r++)t+=this.random.int(0,9);return t}accountName(){let e=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement(e)} Account`}routingNumber(){return this.account(9)}creditCardNumber(e){let t=e?.formatted??!0,r=e?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),a="",i=16;switch(r){case"visa":a="4",i=16;break;case"mastercard":a=`5${this.random.int(1,5)}`,i=16;break;case"amex":a=`3${this.random.arrayElement(["4","7"])}`,i=15;break;case"discover":a="6011",i=16;break}let n=a;while(n.length<i)n+=this.random.int(0,9);if(t){if(r==="amex")return`${n.slice(0,4)}-${n.slice(4,10)}-${n.slice(10)}`;return n.match(/.{1,4}/g)?.join("-")??n}return n}cvv(){return this.account(3)}iban(e){let t=e?.countryCode??"GB",r=e?.formatted??!1,a=this.random.int(10,99).toString(),i="WEST",n=this.account(14),o=t+a+"WEST"+n;if(r)return o.match(/.{1,4}/g)?.join(" ")??o;return o}bic(){let e="";for(let t=0;t<4;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let t=0;t<2;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let t=0;t<2;t++)e+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(r,a)=>a.toString())]);return e}bitcoin(){let e=this.random.arrayElement(["1","3"]);for(let t=0;t<33;t++)e+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return e}ethereum(){let e="0x";for(let t=0;t<40;t++)e+="0123456789abcdef"[this.random.int(0,15)];return e}currencyCode(){let e=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement(e)}currencyName(){let e=["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(e)}currencySymbol(){let e=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement(e)}transactionType(){let e=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement(e)}}class Q{random;locale;constructor(e,t){this.random=e,this.locale=t}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let e=["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(e)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let e=["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(e)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let e=["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(e)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let e=["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(e)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let e=["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(e)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let e=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement(e)}seafood(){let e=["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(e)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let e=["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(e)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let e=["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(e)}description(){let e=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],t=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement(e)} ${this.random.arrayElement(t)}`}}class Pe{random;constructor(e){this.random=e}branch(){let e=["feature","bugfix","hotfix","refactor","chore","docs","test"],t=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],r=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],a=this.random.arrayElement(e),i=this.random.arrayElement(t),n=this.random.arrayElement(r);return`${a}/${i}-${n}`}commitMessage(){let e=["feat","fix","docs","style","refactor","test","chore","perf"],t=["api","ui","auth","db","config","deps","core","utils"],r=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],a=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],i=this.random.arrayElement(e),n=this.random.boolean(0.5)?`(${this.random.arrayElement(t)})`:"",o=this.random.arrayElement(r),l=this.random.arrayElement(a);return`${i}${n}: ${o} ${l}`}commitSha(e){let t=e?.short?7:40,r="0123456789abcdef",a="";for(let i=0;i<t;i++)a+="0123456789abcdef"[this.random.int(0,15)];return a}commitEntry(){let e=this.commitSha({short:!0}),t=this.commitMessage();return`${e} ${t}`}commitAuthor(e){let t=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],r=e?.name??this.random.arrayElement(t),a=e?.email??`${r.toLowerCase().replace(" ",".")}@example.com`;return`${r} <${a}>`}remote(e){let t=e?.protocol??this.random.arrayElement(["https","ssh"]),r=e?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),a=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),i=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),n={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if(t==="ssh")return`git@${n[r]}:${a}/${i}.git`;return`https://${n[r]}/${a}/${i}.git`}tag(){let e=this.random.int(0,5),t=this.random.int(0,20),r=this.random.int(0,50),a=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${e}.${t}.${r}${a}`}}class ee{random;locale;constructor(e,t){this.random=e,this.locale=t}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let e=["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(e)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let e=["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(e)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let e=["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(e)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let e=["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(e)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let e=["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(e)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let e=["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(e).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 Ne{random;constructor(e){this.random=e}randomElement(e){return this.random.arrayElement(e)}arrayElement(e){return this.random.arrayElement(e)}arrayElements(e,t){return this.random.arrayElements(e,t)}shuffle(e){return this.random.shuffle(e)}numerify(e){return e.replace(/#/g,()=>String(this.random.int(0,9)))}lexify(e){return e.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify(e){return this.numerify(this.lexify(e))}replaceSymbols(e){return this.random.replaceSymbols(e)}boolean(e=0.5){return this.random.boolean(e)}objectKey(e){let t=Object.keys(e);return this.random.arrayElement(t)}objectValue(e){let t=this.objectKey(e);return e[t]}multiple(e,t=3){return Array.from({length:t},e)}maybe(e,t=0.5){return this.random.boolean(t)?e():void 0}unique(e,t=50){let r=new Set,a=0;while(a<t){let i=e();if(!r.has(i))return r.add(i),i;a++}throw Error(`Failed to generate unique value after ${t} retries`)}replaceCreditCardSymbols(e="####-####-####-####",t="#"){return this.random.replaceCreditCardSymbols(e,t)}regexify(e){return e.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,(t,r)=>{return""})}}class xe{random;constructor(e){this.random=e}url(e){let t=e?.width??640,r=e?.height??480;return`https://via.placeholder.com/${t}x${r}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr(e){let t=e?.width??640,r=e?.height??480,a=e?.category??"";if(a)return`https://loremflickr.com/${t}/${r}/${a}`;return`https://loremflickr.com/${t}/${r}`}urlPicsumPhotos(e){let t=e?.width??640,r=e?.height??480,a=`https://picsum.photos/${t}/${r}`;if(e?.grayscale)a+="?grayscale";if(e?.blur)a+=e?.grayscale?`&blur=${e.blur}`:`?blur=${e.blur}`;return a}dataUri(e){let t=e?.width??640,r=e?.height??480,a=e?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),i=`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${r}"><rect width="${t}" height="${r}" fill="#${a}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(i)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let e=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement(e)}imageType(){let e=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement(e)}}class te{random;locale;domainWordsCache=null;constructor(e,t){this.random=e,this.locale=t}getDomainWords(){if(!this.domainWordsCache){let e=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=e.map((t)=>t.toLowerCase().replace(/[^a-z0-9]/g,"")).filter((t)=>t.length>0)}return this.domainWordsCache}email(e){let t;if(e?.firstName)t=e.firstName.toLowerCase();else{let o=this.locale.person.firstNameMale.length,l=this.locale.person.firstNameFemale.length,s=this.locale.person.firstNameNeutral?.length||0,c=o+l+s,h=this.random.int(0,c-1);if(h<o)t=this.locale.person.firstNameMale[h].toLowerCase();else if(h<o+l)t=this.locale.person.firstNameFemale[h-o].toLowerCase();else t=this.locale.person.firstNameNeutral[h-o-l].toLowerCase()}let r=e?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),a=e?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),i=this.random.arrayElement(Sa),n=this.random.arrayElement(this.getDomainWords());return`${t}${i}${r}@${n}.${a}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let e=this.locale.person.firstNameMale.length,t=this.locale.person.firstNameFemale.length,r=this.locale.person.firstNameNeutral?.length||0,a=e+t+r,i=this.random.int(0,a-1),n;if(i<e)n=this.locale.person.firstNameMale[i].toLowerCase();else if(i<e+t)n=this.locale.person.firstNameFemale[i-e].toLowerCase();else n=this.locale.person.firstNameNeutral[i-e-t].toLowerCase();let o=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),l=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),s=[".","_",""],c=this.random.arrayElement(s);return`${n}${c}${o}@${l}`}username(e){let t;if(e?.firstName)t=e.firstName.toLowerCase();else{let i=this.locale.person.firstNameMale.length,n=this.locale.person.firstNameFemale.length,o=this.locale.person.firstNameNeutral?.length||0,l=i+n+o,s=this.random.int(0,l-1);if(s<i)t=this.locale.person.firstNameMale[s].toLowerCase();else if(s<i+n)t=this.locale.person.firstNameFemale[s-i].toLowerCase();else t=this.locale.person.firstNameNeutral[s-i-n].toLowerCase()}let r=e?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),a=[`${t}${r}`,`${t}_${r}`,`${t}.${r}`,`${t}${this.random.int(10,999)}`,`${t}_${r}${this.random.int(10,99)}`];return this.random.arrayElement(a)}password(e){let t=e?.length??12,r=e?.memorable??!1,a=e?.prefix??"";if(r){let o=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],l=[];for(let s=0;s<3;s++)l.push(this.random.arrayElement(o));return a+l.join("-")+this.random.int(10,999)}let i="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",n=a;for(let o=a.length;o<t;o++)n+=i[this.random.int(0,i.length-1)];return n}url(e){let t=e?.protocol??this.random.arrayElement(["http","https"]),r=e?.domain??this.domainName();return`${t}://${r}`}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 e=[];for(let t=0;t<8;t++)e.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return e.join(":")}mac(e=":"){let t=[];for(let r=0;r<6;r++)t.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return t.join(e)}userAgent(){let e=["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(e)}slug(e=3){let t=[];for(let r=0;r<e;r++)t.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return t.join("-").toLowerCase()}ip(){return this.ipv4()}}class Re{random;constructor(e){this.random=e}word(){return this.random.arrayElement(Ea)}words(e=3){let t=[];for(let r=0;r<e;r++)t.push(this.word());return t.join(" ")}sentence(e){let t=e??this.random.int(3,10),r=this.words(t);return`${r.charAt(0).toUpperCase()+r.slice(1)}.`}sentences(e=3,t=" "){let r=[];for(let a=0;a<e;a++)r.push(this.sentence());return r.join(t)}paragraph(e){let t=e??this.random.int(3,7);return this.sentences(t)}paragraphs(e=3,t=`
|
|
35
|
-
|
|
36
|
-
`){let r=[];for(let a=0;a<e;a++)r.push(this.paragraph());return r.join(t)}text(e){let t=e??200,r="";while(r.length<t)r+=`${this.paragraph()} `;return r.trim().slice(0,t)}slug(e=3){return this.words(e).replace(/ /g,"-")}lines(e=3){let t=[];for(let r=0;r<e;r++)t.push(this.sentence());return t.join(`
|
|
37
|
-
`)}}class re{random;locale;constructor(e,t){this.random=e,this.locale=t}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let e=["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(e)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let e=["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(e)}albumName(){let e=["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(e)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let e=["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(e)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let e=["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(e)}note(){let e=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement(e)}chord(){let e=this.note(),t=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${e}${t}`}tempo(){return this.random.int(60,200)}key(){let e=this.note(),t=this.random.arrayElement(["Major","Minor"]);return`${e} ${t}`}timeSignature(){let e=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement(e)}}class Le{random;constructor(e){this.random=e}int(e){let t=e?.min??0,r=e?.max??100;return this.random.int(t,r)}float(e){let t=e?.min??0,r=e?.max??1,a=e?.precision??2;return this.random.float(t,r,a)}bigInt(e){let t=e?.min??0n,r=(e?.max??1000000n)-t+1n,a=BigInt(Math.floor(this.random.number()*Number(r)));return t+a}binary(e){let t=e?.length??8,r="";for(let a=0;a<t;a++)r+=this.random.int(0,1);return r}octal(e){let t=e?.length??3,r="";for(let a=0;a<t;a++)r+=this.random.int(0,7);return r}hex(e){let t=e?.length??6,r="0123456789ABCDEF",a="";for(let i=0;i<t;i++)a+="0123456789ABCDEF"[this.random.int(0,15)];return a}randomNumber(e){return this.int(e)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class ae{random;locale;constructor(e,t){this.random=e,this.locale=t}firstName(e){if(e?.gender==="male")return this.firstNameMale();if(e?.gender==="female")return this.firstNameFemale();if(e?.gender==="neutral")return this.firstNameNeutral();let t=this.locale.person.firstNameMale.length,r=this.locale.person.firstNameFemale.length,a=this.locale.person.firstNameNeutral?.length||0,i=t+r+a,n=this.random.int(0,i-1);if(n<t)return this.locale.person.firstNameMale[n];if(n<t+r)return this.locale.person.firstNameFemale[n-t];return this.locale.person.firstNameNeutral[n-t-r]}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 e=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement(e)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName(e){if(!e)return`${this.firstName()} ${this.lastName()}`;let t=this.firstName({gender:e.gender}),r=this.lastName();if(e.prefix&&e.suffix)return`${this.prefix()} ${t} ${r} ${this.suffix()}`;if(e.prefix)return`${this.prefix()} ${t} ${r}`;if(e.suffix)return`${t} ${r} ${this.suffix()}`;return`${t} ${r}`}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(e){let t;if(e?.constraints)t=this.firstName({gender:e.constraints.gender});else t=this.firstName({gender:e?.gender});if(e?.weighted)t=de(this.random,e.weighted);if(e?.relationships)t=N({firstName:t,gender:e?.gender||e?.constraints?.gender},e.relationships).firstName||t;if(e?.validation){let r=ue(t,e.validation);if(!r.isValid){if(e.validation.strict)throw Error(`Validation failed: ${r.errors.join(", ")}`);t=this.firstName({gender:e?.gender||e?.constraints?.gender})}}return t}fullNameAdvanced(e){let t;if(e?.constraints)t=this.fullName({gender:e.constraints.gender,prefix:e.prefix,suffix:e.suffix});else t=this.fullName(e);if(e?.weighted)t=de(this.random,e.weighted);if(e?.relationships)t=N({fullName:t,gender:e?.gender||e?.constraints?.gender},e.relationships).fullName||t;if(e?.validation){let r=ue(t,e.validation);if(!r.isValid){if(e.validation.strict)throw Error(`Validation failed: ${r.errors.join(", ")}`);t=this.fullName({gender:e?.gender||e?.constraints?.gender,prefix:e?.prefix,suffix:e?.suffix})}}return t}profile(e){let t=e?.constraints?.gender||e?.gender||this.gender(),r=this.firstNameAdvanced({...e,gender:t}),a=this.lastName(),i=`${r} ${a}`,n={firstName:r,lastName:a,fullName:i,gender:t,jobTitle:this.jobTitle(),age:e?.constraints?.ageRange?this.random.int(e.constraints.ageRange.min,e.constraints.ageRange.max):this.random.int(18,80)};if(e?.relationships)return N(n,e.relationships);return n}family(e){let t=e?.size||this.random.int(2,6),r=this.lastName(),a=["parent","parent","child","child","child","grandparent"],i=[];for(let n=0;n<t;n++){let o=a[n]||"relative",l=o==="parent"||o==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",s=this.firstNameAdvanced({...e,gender:l,constraints:{...e?.constraints,gender:l}});i.push({firstName:s,lastName:r,fullName:`${s} ${r}`,gender:l,relationship:o})}return{members:i,lastName:r}}}class ie{random;locale;constructor(e,t){this.random=e,this.locale=t}number(e){let t=e??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols(t)}phoneNumber(e){return this.number(e)}}class ne{random;locale;constructor(e,t){this.random=e,this.locale=t}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let e=["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(e)}chemicalElementSymbol(){let e=["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(e)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let e=["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(e)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let e=["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(e)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let e=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement(e)}dnaSequence(e=12){let t=["A","T","C","G"],r="";for(let a=0;a<e;a++)r+=this.random.arrayElement(t);return r}rnaSequence(e=12){let t=["A","U","C","G"],r="";for(let a=0;a<e;a++)r+=this.random.arrayElement(t);return r}hypothesis(){let e=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],t=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement(e)}, then ${this.random.arrayElement(t)}`}}class oe{random;locale;constructor(e,t){this.random=e,this.locale=t}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let e=["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(e)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let e=["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(e)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let e=["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(e)}position(){let e=["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(e)}event(){let e=["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(e)}league(){let e=["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(e)}quote(){let e=["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(e)}equipment(){let e=["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(e)}}class Fe{random;constructor(e){this.random=e}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let e="0123456789abcdef",t="";for(let r=0;r<36;r++)if(r===8||r===13||r===18||r===23)t+="-";else if(r===14)t+="4";else if(r===19){let a=this.random.int(0,15);t+=e[a&3|8]}else t+=e[this.random.int(0,15)];return t}nanoid(e=21){let t="";for(let r=0;r<e;r++)t+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return t}alpha(e){let t=e?.length??10,r=e?.casing??"mixed",a="abcdefghijklmnopqrstuvwxyz",i="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n="";if(r==="lower")n="abcdefghijklmnopqrstuvwxyz";else if(r==="upper")n="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else n="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let o="";for(let l=0;l<t;l++)o+=n[this.random.int(0,n.length-1)];return o}alphanumeric(e){let t=e?.length??10,r=e?.casing??"mixed",a="abcdefghijklmnopqrstuvwxyz",i="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n="0123456789",o="0123456789";if(r==="lower")o+="abcdefghijklmnopqrstuvwxyz";else if(r==="upper")o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let l="";for(let s=0;s<t;s++)l+=o[this.random.int(0,o.length-1)];return l}numeric(e=10){if(!this.random.isSeeded()){let r="";for(let a=0;a<e;a++)r+=Math.floor(Math.random()*10);return r}let t="";for(let r=0;r<e;r++)t+=this.random.int(0,9);return t}sample(e=10){return this.alphanumeric({length:e})}symbol(e=5){let t="";for(let r=0;r<e;r++)t+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return t}hexadecimal(e){let t=e?.length??6,r=e?.prefix??"",a="0123456789abcdef",i=r;for(let n=0;n<t;n++)i+="0123456789abcdef"[this.random.int(0,15)];return i}}class se{random;locale;constructor(e,t){this.random=e,this.locale=t}fileName(e){let t;if(this.locale?.system?.fileName)t=this.locale.system.fileName;else t=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let r=this.random.arrayElement(t),a=e?.extension??this.fileExtension();return`${r}.${a}`}fileExtension(){let e=["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(e)}commonFileName(){let e=["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(e)}mimeType(){let e=["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(e)}commonMimeType(){let e=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement(e)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let e=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement(e)}directoryPath(){let e=["/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(e)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let e=this.random.int(0,10),t=this.random.int(0,20),r=this.random.int(0,50);return`${e}.${t}.${r}`}networkInterface(){let e=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement(e)}cron(){let e=this.random.boolean(0.5)?"*":this.random.int(0,59),t=this.random.boolean(0.5)?"*":this.random.int(0,23),r=this.random.boolean(0.5)?"*":this.random.int(1,31),a=this.random.boolean(0.5)?"*":this.random.int(1,12),i=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${e} ${t} ${r} ${a} ${i}`}}class le{random;locale;constructor(e,t){this.random=e,this.locale=t}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(ka)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(Aa)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(Ma)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement($a)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(Ta)}vin(){let e="";for(let t=0;t<17;t++)e+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return e}registration(){let e=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement(e).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let e=this.random.int(2000,2024),t=this.manufacturer(),r=this.model();return`${e} ${t} ${r}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let e=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement(e)}}class ce{random;locale;constructor(e,t){this.random=e,this.locale=t}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let e=["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(e)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let e=["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(e)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let e=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement(e)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let e=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement(e)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let e=["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(e)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let e=["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(e)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let e=["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(e)}sample(){let e=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],t=this.random.arrayElement(e);return this[t]()}words(e=3){let t=[];for(let r=0;r<e;r++)t.push(this.sample());return t.join(" ")}}class De{seed;constructor(e){this.seed=e}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(e=0,t=100){return Math.floor(this.number()*(t-e+1))+e}float(e=0,t=1,r=2){let a=this.number()*(t-e)+e;return Number.parseFloat(a.toFixed(r))}arrayElement(e){if(e.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return e[Math.floor(Math.random()*e.length)];return e[this.int(0,e.length-1)]}arrayElements(e,t){if(e.length===0)return[];let r=t??this.int(1,e.length);return[...e].sort(()=>this.number()-0.5).slice(0,Math.min(r,e.length))}shuffle(e){let t=[...e];for(let r=t.length-1;r>0;r--){let a=this.int(0,r);[t[r],t[a]]=[t[a],t[r]]}return t}boolean(e=0.5){return this.number()<e}replaceSymbols(e){if(this.seed===void 0){let t="";for(let r=0;r<e.length;r++){let a=e[r];if(a==="#")t+="0123456789"[Math.floor(Math.random()*10)];else if(a==="?")t+=Pt[Math.floor(Math.random()*26)];else t+=a}return t}return e.replace(/[#?]/g,(t)=>{if(t==="#")return String(this.int(0,9));return this.arrayElement(Pt)})}replaceCreditCardSymbols(e="####-####-####-####",t="#"){return e.replace(new RegExp(t,"g"),()=>String(this.int(0,9)))}weightedArrayElement(e){if(e.length===0)throw Error("Cannot pick from empty weighted items array");let t=e.reduce((i,n)=>i+n.weight,0);if(t<=0)throw Error("Total weight must be greater than 0");let r=this.number()*t,a=0;for(let i of e)if(a+=i.weight,r<=a)return i.item;return e[e.length-1].item}weightedArrayElements(e,t,r=!1){if(e.length===0)return[];let a=t??this.int(1,e.length),i=[],n=[...e];for(let o=0;o<a&&n.length>0;o++){let l=this.weightedArrayElement(n);if(i.push(l),!r){let s=n.findIndex((c)=>c.item===l);if(s!==-1)n.splice(s,1)}}return i}weightedBoolean(e=0.5){return this.number()<e}weightedInt(e,t,r){let a=t-e+1;if(r){if(r.length!==a)throw Error("Weights array length must match the range size");let i=r.map((n,o)=>({item:e+o,weight:n}));return this.weightedArrayElement(i)}return this.int(e,t)}}class Ge{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(e){let t=e?.locale??"en",r=e?.seed;if(this._autoInstallLocales=e?.autoInstallLocales??!1,t!=="en"&&!v.isCached(t))console.warn(`[ts-mocker] Locale '${t}' requires async loading. Use 'await Faker.create({ locale: "${t}" })' for better performance. Falling back to English.`),this._locale=v.loadSync("en");else this._locale=v.loadSync(t);this.random=new De(r),this.person=new ae(this.random,this._locale),this.address=new U(this.random,this._locale),this.internet=new te(this.random,this._locale),this.phone=new ie(this.random,this._locale),this.company=new X(this.random,this._locale),this.lorem=new Re(this.random),this.date=new $e(this.random),this.number=new Le(this.random),this.string=new Fe(this.random),this.color=new q(this.random,this._locale),this.finance=new Te(this.random),this.helpers=new Ne(this.random),this.image=new xe(this.random),this.git=new Pe(this.random),this.science=new ne(this.random,this._locale),this.music=new re(this.random,this._locale),this.database=new Me(this.random),this.food=new Q(this.random,this._locale),this.commerce=new Z(this.random,this._locale),this.book=new Y(this.random,this._locale),this.animal=new K(this.random,this._locale),this.sport=new oe(this.random,this._locale),this.hacker=new ee(this.random,this._locale),this.system=new se(this.random,this._locale),this.word=new ce(this.random,this._locale),this.vehicle=new le(this.random,this._locale)}static async create(e){let t=e?.locale??"en";return await v.load(t),new Ge(e)}seed(e){return this.random=new De(e),Object.assign(this.person,new ae(this.random,this._locale)),Object.assign(this.address,new U(this.random,this._locale)),Object.assign(this.internet,new te(this.random,this._locale)),Object.assign(this.phone,new ie(this.random,this._locale)),Object.assign(this.company,new X(this.random,this._locale)),Object.assign(this.lorem,new Re(this.random)),Object.assign(this.date,new $e(this.random)),Object.assign(this.number,new Le(this.random)),Object.assign(this.string,new Fe(this.random)),Object.assign(this.color,new q(this.random,this._locale)),Object.assign(this.finance,new Te(this.random)),Object.assign(this.helpers,new Ne(this.random)),Object.assign(this.image,new xe(this.random)),Object.assign(this.git,new Pe(this.random)),Object.assign(this.science,new ne(this.random,this._locale)),Object.assign(this.music,new re(this.random,this._locale)),Object.assign(this.database,new Me(this.random)),Object.assign(this.food,new Q(this.random,this._locale)),Object.assign(this.commerce,new Z(this.random,this._locale)),Object.assign(this.book,new Y(this.random,this._locale)),Object.assign(this.animal,new K(this.random,this._locale)),Object.assign(this.sport,new oe(this.random,this._locale)),Object.assign(this.hacker,new ee(this.random,this._locale)),Object.assign(this.system,new se(this.random,this._locale)),Object.assign(this.word,new ce(this.random,this._locale)),Object.assign(this.vehicle,new le(this.random,this._locale)),this}async setLocale(e){return this._locale=await v.load(e),this.reinitializeLocaleModules(),this}setLocaleSync(e){if(!v.isCached(e)&&e!=="en")return console.warn(`[ts-mocker] Locale '${e}' is not loaded. Use 'await faker.setLocale("${e}")' or preload it first.`),this;return this._locale=v.loadSync(e),this.reinitializeLocaleModules(),this}async preloadLocales(e){return await v.preload(e),this}reinitializeLocaleModules(){Object.assign(this.person,new ae(this.random,this._locale)),Object.assign(this.address,new U(this.random,this._locale)),Object.assign(this.internet,new te(this.random,this._locale)),Object.assign(this.phone,new ie(this.random,this._locale)),Object.assign(this.company,new X(this.random,this._locale)),Object.assign(this.food,new Q(this.random,this._locale)),Object.assign(this.animal,new K(this.random,this._locale)),Object.assign(this.sport,new oe(this.random,this._locale)),Object.assign(this.music,new re(this.random,this._locale)),Object.assign(this.commerce,new Z(this.random,this._locale)),Object.assign(this.book,new Y(this.random,this._locale)),Object.assign(this.vehicle,new le(this.random,this._locale)),Object.assign(this.word,new ce(this.random,this._locale)),Object.assign(this.hacker,new ee(this.random,this._locale)),Object.assign(this.system,new se(this.random,this._locale)),Object.assign(this.color,new q(this.random,this._locale)),Object.assign(this.science,new ne(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return v.getAvailableLocales()}static isLocaleLoaded(e){return v.isCached(e)}static async preloadLocales(e){await v.preload(e)}name(){return this.person.name()}email(){return this.internet.email()}}var Er,kr=(e)=>e,Mr=(e,t)=>{for(var r in t)Er(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ar.bind(t,r)})},P=(e,t)=>()=>(e&&(t=e(e=0)),t),$r,I,fe,xt,ge,Et,Be,V,Lr,y,f,Fr,kt,Dr,At,Hr,Or,Ve,jr,Mt,$t,Gr,Ue,Wr,Ir,Jr,zr,_r,Se,Lt,Br,Vr,Ur="0.15.9",Kr=()=>{},C,ke,he,qe,Ze,Ae,Xe,Qe,me,et,tt,x,J,Ht,Wt,ot,It,Jt,zt,E,T,_t,Bt,la,ha=()=>{},Vt,Ut,ht,Ke=null,Kt,ve,A,z,v,ba,wa,Ca,va,Sa,Ea,ka,Aa,Ma,$a,Ta,Pt,Qt,Pa;var er=Nt(()=>{Er=Object.defineProperty;$r=import.meta.require;ge=P(()=>{I=new at,fe=new it,xt={createKey:Tr,isEquivalent:Pr,estimateMemoryUsage:Nr}});Vr=P(()=>{Et=Ee.env.CLARITY_LOG_DIR||ir(xr(),"logs"),Be={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Et,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},V={...Be},Lr=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(Ut(),Vt)),t=await e({name:"clarity",alias:"logging",defaultConfig:Be,cwd:Ee.cwd()});if(t)Object.assign(V,t)}catch{}return V})(),y={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},f=y,Fr=y.red,kt=y.green,Dr=y.yellow,At=y.blue,Hr=y.magenta,Or=y.cyan,Ve=y.white,jr=y.gray,Mt=y.bgRed,$t=y.bgYellow,Gr=y.bgGray,Ue=y.bold,Wr=y.dim,Ir=y.italic,Jr=y.underline,zr=y.strikethrough,_r=y.reset,Se={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Lt={debug:"\uD83D\uDD0D",info:At("\u2139"),success:kt("\u2713"),warning:$t(Ve(Ue(" WARN "))),error:Mt(Ve(Ue(" ERROR ")))},Br=new He("stacks")});J=P(()=>{C=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},ke=class extends C{code="CONFIG_NOT_FOUND";constructor(e,t,r){let a=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(a.length===1)i=` or alias "${a[0]}"`;else if(a.length>1)i=` or aliases ${a.map((n)=>`"${n}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},he=class extends C{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},qe=class extends C{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ze=class extends C{code="CONFIG_MERGE_ERROR";constructor(e,t,r,a){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:a,originalError:r.name,originalMessage:r.message});this.cause=r}},Ae=class extends C{code="ENV_VAR_ERROR";constructor(e,t,r,a){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:a})}},Xe=class extends C{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Qe=class extends C{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},me=class extends C{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},et=class extends C{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,a){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:a})}},tt=class extends C{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},x={configNotFound(e,t,r){return new ke(e,t,r)},configLoad(e,t,r){return new he(e,t,r)},configValidation(e,t,r){return new qe(e,t,r)},configMerge(e,t,r,a){return new Ze(e,t,r,a)},envVar(e,t,r,a){return new Ae(e,t,r,a)},fileSystem(e,t,r){return new Xe(e,t,r)},typeGeneration(e,t,r){return new Qe(e,t,r)},schemaValidation(e,t,r){return new me(e,t,r)},browserConfig(e,t,r,a){return new et(e,t,r,a)},plugin(e,t,r){return new tt(e,t,r)}}});Ht=P(()=>{ge(),J()});ot=P(()=>{Wt={replace:"replace",concat:"concat",smart:"smart"}});It=P(()=>{ge(),J(),ot()});zt=P(()=>{ge(),J(),Jt=/^https?:\/\//});la=P(()=>{Vr(),Kr(),ge(),J(),Ht(),It(),zt(),ot(),E=new He("bunfig",{showTags:!0}),T=new lt,_t=w(R.cwd(),"config"),Bt=w(R.cwd(),"src/generated")});Vt={};Mr(Vt,{withErrorRecovery:()=>Ft,tryLoadConfig:()=>na,loadConfigWithResult:()=>aa,loadConfig:()=>ct,isRetryableError:()=>qr,isConfigNotFoundError:()=>Yr,isBunfigError:()=>Dt,globalPerformanceMonitor:()=>fe,globalCache:()=>I,getEnvOrDefault:()=>Zr,generateConfigTypes:()=>oa,defaultGeneratedDir:()=>Bt,defaultConfigDir:()=>_t,deepMergeWithArrayStrategy:()=>nt,deepMerge:()=>Ot,createLibraryConfig:()=>sa,config:()=>ia,bunfigPlugin:()=>ca,applyEnvVarsToConfig:()=>_,TypeGenerationError:()=>Qe,SchemaValidationError:()=>me,PluginError:()=>tt,PerformanceMonitor:()=>it,FileSystemError:()=>Xe,ErrorFactory:()=>x,EnvVarError:()=>Ae,EnvProcessor:()=>Oe,ConfigValidator:()=>st,ConfigValidationError:()=>qe,ConfigNotFoundError:()=>ke,ConfigMergeError:()=>Ze,ConfigLoader:()=>lt,ConfigLoadError:()=>he,ConfigFileLoader:()=>je,ConfigCache:()=>at,CacheUtils:()=>xt,BunfigError:()=>C,BrowserConfigError:()=>et,ArrayMergeStrategies:()=>Wt});Ut=P(()=>{la(),J(),ge(),J(),ha(),Ht(),It(),zt(),ot()});Ut();ht={verbose:!1,locale:"en",autoInstallLocales:!1};Kt=ht,ve={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"]}};A=new Map,z=new Map;v=class v{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(e){let t=G(e).normalized;if(t==="en"){if(!A.has("en"))A.set("en",ve);return ve}if(A.has(t))return A.get(t);if(z.has(t))return z.get(t);let r=this.loadLocaleWithFallback(t);z.set(t,r);try{let a=await r;return A.set(t,a),a}finally{z.delete(t)}}static loadSync(e){let t=G(e).normalized;if(t==="en"){if(!A.has("en"))A.set("en",ve);return ve}if(A.has(t))return A.get(t);throw Error(`Locale '${e}' is not loaded. Please use async loading with faker.setLocale('${e}') or preload it.`)}static isCached(e){let t=G(e).normalized;return A.has(t)}static async preload(e){await Promise.all(e.map((t)=>this.load(t)))}static clearCache(){A.clear(),z.clear()}static async loadLocaleWithFallback(e){let t=ua(e);for(let r=0;r<t.length;r++){let a=t[r],i=r===0&&t.length>1,n=!i;try{if(i){let o=await this.loadLocaleModule(a),l=t[1];try{let s=await this.loadLocaleModule(l);return Yt(s,o)}catch{return o}}else return await this.loadLocaleModule(a)}catch(o){if(r===t.length-1)throw o;continue}}throw Error(`Failed to load locale '${e}' with fallback chain: ${t.join(" \u2192 ")}`)}static async tryWorkspaceImport(e,t){if(!W())return null;try{let r=await import(`../../${t.packageName}/dist/index.js`);return r[t.normalized]||r[t.language]||r.default}catch{try{let r=ar.cwd(),a=rr(r,"packages",t.packageName,"dist","index.js");if(!tr(a))return null;let i=await import(`file://${a}`);return i[t.normalized]||i[t.language]||i.default}catch{return null}}}static async loadLocaleModule(e){let t=da(e),r=G(e);try{let a=await import(t);return a[r.normalized]||a[r.language]||a.default}catch(a){let i=a instanceof Error?a.message:String(a);if(i.includes("Cannot find")||i.includes("not found")||i.includes("ModuleNotFound")){if(W()&&t.startsWith("@mock-locale/")){let n=await this.tryWorkspaceImport(e,r);if(n)return n}if(Kt.autoInstallLocales)if(console.log(`
|
|
38
|
-
\uD83D\uDD0D Locale '${e}' not found. Auto-installing ${t}...`),Xt(t)){if(W()&&t.startsWith("@mock-locale/")){let n=await this.tryWorkspaceImport(e,r);if(n)return n}try{let n=await import(t);return n[r.normalized]||n[r.language]||n.default}catch(n){if(W()&&t.startsWith("@mock-locale/")){let o=await this.tryWorkspaceImport(e,r);if(o)return o;throw Error(`Locale '${e}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${t.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${e}' after installation: ${n instanceof Error?n.message:String(n)}`)}}else throw Error(`Failed to auto-install locale '${e}'. Please install manually with: bun add ${t}`);throw Error(`Locale '${e}' is not installed. Install it with: bun add ${t}
|
|
39
|
-
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}
|
|
40
|
-
Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${e}': ${i}`)}}};ba=new mt,wa={email:(e)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(e)},phone:(e)=>{let t=/^\+?[1-9]\d{0,15}$/,r=e.replace(/[\s\-()]/g,"");return r.length>=7&&t.test(r)},name:(e)=>{return/^[a-z\s\-']+$/i.test(e)&&e.length>=2&&e.length<=50},age:(e)=>{return Number.isInteger(e)&&e>=0&&e<=150},url:(e)=>{try{let t=new URL(e);return e.startsWith("http://")||e.startsWith("https://")}catch{return!1}},regex:(e)=>(t)=>{return e.test(t)},length:(e,t)=>(r)=>{return r.length>=e&&r.length<=t},range:(e,t)=>(r)=>{return r>=e&&r<=t}},Ca={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"]}}},va={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}]}};Sa=[".","_","-",""];Ea=["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"];ka=["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"],Aa=["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"],Ma=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],$a=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],Ta=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"];Pt="abcdefghijklmnopqrstuvwxyz".split("");Qt=new Ge,Pa=Qt});var Na=Nt(()=>{er()});Na();export{ue as validateData,de as selectWeightedItem,W as isInWorkspace,Xt as installPackage,ba as globalProviderRegistry,ma as getConfig,ya as generateRealisticData,Qt as faker,Zt as detectPackageManager,ht as defaultConfig,Pa as default,Kt as config,N as applyRelationships,pa as applyConstraints,ce as WordModule,va as WeightedSelections,le as VehicleModule,wa as ValidationRules,se as SystemModule,Fe as StringModule,oe as SportModule,ne as ScienceModule,De as Random,ie as PhoneModule,ae as PersonModule,Le as NumberModule,re as MusicModule,Re as LoremModule,v as LocaleLoader,te as InternetModule,xe as ImageModule,Ne as HelpersModule,ee as HackerModule,Pe as GitModule,Q as FoodModule,Te as FinanceModule,Ge as Faker,$e as DateModule,Me as DatabaseModule,Ca as DataRelationships,mt as DataProviderRegistry,X as CompanyModule,Z as CommerceModule,q as ColorModule,Y as BookModule,K as AnimalModule,U as AddressModule};
|